diff --git a/javascript/solution/client-details/index.html b/javascript/solution/client-details/index.html index 0735a2d..b51120f 100644 --- a/javascript/solution/client-details/index.html +++ b/javascript/solution/client-details/index.html @@ -8,9 +8,7 @@ Client Details - - - + diff --git a/javascript/solution/client-details/index.js b/javascript/solution/client-details/index.js index f8b680b..704318a 100644 --- a/javascript/solution/client-details/index.js +++ b/javascript/solution/client-details/index.js @@ -1,3 +1,6 @@ +import IOBrowser from '@interopio/browser'; +import IOWorkspaces from '@interopio/workspaces-api'; + const setFields = (client) => { const elementName = document.querySelectorAll("[data-name]")[0]; elementName.innerText = client.name; diff --git a/javascript/solution/client-details/lib/browser.umd.js b/javascript/solution/client-details/lib/browser.umd.js deleted file mode 100644 index a5e6fcb..0000000 --- a/javascript/solution/client-details/lib/browser.umd.js +++ /dev/null @@ -1,17399 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.browser = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs$1 (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) - }; - - function isNonNullObject(value) { - return !!value && typeof value === 'object' - } - - function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); - - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) - } - - // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 - var canUseSymbol = typeof Symbol === 'function' && Symbol.for; - var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; - - function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE - } - - function emptyTarget(val) { - return Array.isArray(val) ? [] : {} - } - - function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value - } - - function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) - } - - function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge - } - - function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return Object.propertyIsEnumerable.call(target, symbol) - }) - : [] - } - - function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) - } - - function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } - } - - // Protects from prototype poisoning and unexpected merging up the prototype chain. - function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. - } - - function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } - - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination - } - - function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; - - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } - } - - deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } - - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) - }; - - var deepmerge_1 = deepmerge; - - var cjs = deepmerge_1; - - var deepmerge$1 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$2 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$2 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$2 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$2 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$2 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$2 = function (f, r) { - return r.ok === true ? ok$2(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$2(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$2 = function (f, r) { - return r.ok === true ? r : err$2(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$2 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$2 = function() { - __assign$2 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - - function __rest$2(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$2(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$2(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$2(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$2 = function (json) { return Array.isArray(json); }; - var isJsonObject$2 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$2(json); - }; - var typeString$2 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$2 = function (expected, got) { - return "expected " + expected + ", got " + typeString$2(got); - }; - var printPath$2 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$2 = function (newAt, _a) { - var at = _a.at, rest = __rest$2(_a, ["at"]); - return (__assign$2({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$2 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$2(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$2(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$2(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$2(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$2(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$2(json) - : err$2({ message: expectedGot$2('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$2(json) - : err$2({ message: expectedGot$2('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$2(json) - : err$2({ message: expectedGot$2('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$2(json, value) - ? ok$2(value) - : err$2({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$2(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$2({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else if (isJsonObject$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$2(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$2(function (err$$1) { return prependAt$2("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$2([])); - } - else if (isJsonArray$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$2(json)) { - if (json.length !== decoders.length) { - return err$2({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$2(prependAt$2("[" + i + "]", nth.error)); - } - } - return ok$2(result); - } - else { - return err$2({ message: expectedGot$2("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$2(Object.assign, acc, decoder.decode(json)); }, ok$2({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$2(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$2(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$2(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$2(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$2({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$2(withDefault$2(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$2(function (error) { - return jsonAtPath === undefined - ? { at: printPath$2(paths), message: 'path does not exist' } - : prependAt$2(printPath$2(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$2(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$2({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$2 = Decoder$2.string; - /** See `Decoder.number` */ - var number$2 = Decoder$2.number; - /** See `Decoder.boolean` */ - var boolean$2 = Decoder$2.boolean; - /** See `Decoder.anyJson` */ - var anyJson$2 = Decoder$2.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$2.unknownJson; - /** See `Decoder.constant` */ - var constant$2 = Decoder$2.constant; - /** See `Decoder.object` */ - var object$2 = Decoder$2.object; - /** See `Decoder.array` */ - var array$2 = Decoder$2.array; - /** See `Decoder.tuple` */ - Decoder$2.tuple; - /** See `Decoder.dict` */ - Decoder$2.dict; - /** See `Decoder.optional` */ - var optional$2 = Decoder$2.optional; - /** See `Decoder.oneOf` */ - var oneOf$1 = Decoder$2.oneOf; - /** See `Decoder.union` */ - var union$1 = Decoder$2.union; - /** See `Decoder.intersection` */ - var intersection = Decoder$2.intersection; - /** See `Decoder.withDefault` */ - Decoder$2.withDefault; - /** See `Decoder.valueAt` */ - Decoder$2.valueAt; - /** See `Decoder.succeed` */ - Decoder$2.succeed; - /** See `Decoder.fail` */ - Decoder$2.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder$2.lazy; - - const defaultConfig = { - gateway: { webPlatform: {} }, - libraries: [], - exposeAPI: true, - }; - const defaultWidgetConfig = { - awaitFactory: true, - enable: false, - timeout: 5 * 1000, - restoreLastKnownPosition: true, - }; - const defaultModalsConfig = { - alerts: { - enabled: false - }, - dialogs: { - enabled: false - }, - awaitFactory: true, - timeout: 5 * 1000, - }; - const defaultIntentResolverConfig = { - enable: false, - timeout: 5 * 1000, - awaitFactory: true, - }; - - const Glue42CoreMessageTypes = { - platformUnload: { name: "platformUnload" }, - transportSwitchRequest: { name: "transportSwitchRequest" }, - transportSwitchResponse: { name: "transportSwitchResponse" }, - getCurrentTransport: { name: "getCurrentTransport" }, - getCurrentTransportResponse: { name: "getCurrentTransportResponse" }, - checkPreferredLogic: { name: "checkPreferredLogic" }, - checkPreferredConnection: { name: "checkPreferredConnection" }, - checkPreferredLogicResponse: { name: "checkPreferredLogicResponse" }, - checkPreferredConnectionResponse: { name: "checkPreferredConnectionResponse" } - }; - const webPlatformTransportName = "web-platform"; - const latestFDC3Type = "latest_fdc3_type"; - const errorChannel = new MessageChannel(); - const REQUEST_WIDGET_READY = "requestWidgetFactoryReady"; - const REQUEST_MODALS_UI_FACTORY_READY = "requestModalsUIFactoryReady"; - const MAX_SET_TIMEOUT_DELAY = 2147483647; - const REQUEST_INTENT_RESOLVER_UI_FACTORY_READY = "requestIntentResolverUIFactoryReady"; - const READONLY_PROPERTY_DESCRIPTOR = { - configurable: false, - enumerable: true, - writable: false, - }; - - const extractErrorMsg = (error) => { - if (typeof error === "string") { - return error; - } - if (error?.message) { - return typeof error.message === "string" ? error.message : JSON.stringify(error.message); - } - return JSON.stringify(error); - }; - const runDecoderWithIOError = (decoder, json) => { - try { - const result = decoder.runWithException(json); - return result; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const getSupportedOperationsNames = (operations) => { - return Object.keys(operations).filter((operation) => (operations)[operation].execute); - }; - const handleOperationCheck = (supportedOperations, operationName) => { - const isSupported = supportedOperations.some((operation) => operation.toLowerCase() === operationName.toLowerCase()); - return { isSupported }; - }; - const getSafeTimeoutDelay = (delay) => { - return Math.min(delay, MAX_SET_TIMEOUT_DELAY); - }; - const wrapPromise = () => { - let wrapperResolve; - let wrapperReject; - const promise = new Promise((resolve, reject) => { - wrapperResolve = resolve; - wrapperReject = reject; - }); - return { promise, resolve: wrapperResolve, reject: wrapperReject }; - }; - - class IOError { - raiseError(error, shouldThrowOriginalError) { - const errorMessage = extractErrorMsg(error); - errorChannel.port1.postMessage(errorMessage); - if (shouldThrowOriginalError) { - throw error; - } - throw new Error(errorMessage); - } - } - const ioError = new IOError(); - - const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"]; - const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"]; - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$1 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$1 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$1 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$1 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$1 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$1 = function (f, r) { - return r.ok === true ? ok$1(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$1 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$1(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$1 = function (f, r) { - return r.ok === true ? r : err$1(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$1 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$1 = function() { - __assign$1 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - - function __rest$1(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$1(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$1(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$1(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$1 = function (json) { return Array.isArray(json); }; - var isJsonObject$1 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$1(json); - }; - var typeString$1 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$1 = function (expected, got) { - return "expected " + expected + ", got " + typeString$1(got); - }; - var printPath$1 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$1 = function (newAt, _a) { - var at = _a.at, rest = __rest$1(_a, ["at"]); - return (__assign$1({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$1 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$1(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$1(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$1(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$1(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$1(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$1(json) - : err$1({ message: expectedGot$1('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$1(json) - : err$1({ message: expectedGot$1('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$1(json) - : err$1({ message: expectedGot$1('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$1(json, value) - ? ok$1(value) - : err$1({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$1(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$1({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else if (isJsonObject$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$1(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$1(function (err$$1) { return prependAt$1("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$1(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$1([])); - } - else if (isJsonArray$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$1(json)) { - if (json.length !== decoders.length) { - return err$1({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$1(prependAt$1("[" + i + "]", nth.error)); - } - } - return ok$1(result); - } - else { - return err$1({ message: expectedGot$1("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$1(Object.assign, acc, decoder.decode(json)); }, ok$1({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$1(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$1(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$1(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$1(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$1({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$1(withDefault$1(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$1(function (error) { - return jsonAtPath === undefined - ? { at: printPath$1(paths), message: 'path does not exist' } - : prependAt$1(printPath$1(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$1(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$1({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$1 = Decoder$1.string; - /** See `Decoder.number` */ - var number$1 = Decoder$1.number; - /** See `Decoder.boolean` */ - var boolean$1 = Decoder$1.boolean; - /** See `Decoder.anyJson` */ - var anyJson$1 = Decoder$1.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$1.unknownJson; - /** See `Decoder.constant` */ - var constant$1 = Decoder$1.constant; - /** See `Decoder.object` */ - var object$1 = Decoder$1.object; - /** See `Decoder.array` */ - var array$1 = Decoder$1.array; - /** See `Decoder.tuple` */ - Decoder$1.tuple; - /** See `Decoder.dict` */ - var dict = Decoder$1.dict; - /** See `Decoder.optional` */ - var optional$1 = Decoder$1.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder$1.oneOf; - /** See `Decoder.union` */ - Decoder$1.union; - /** See `Decoder.intersection` */ - Decoder$1.intersection; - /** See `Decoder.withDefault` */ - Decoder$1.withDefault; - /** See `Decoder.valueAt` */ - Decoder$1.valueAt; - /** See `Decoder.succeed` */ - Decoder$1.succeed; - /** See `Decoder.fail` */ - Decoder$1.fail; - /** See `Decoder.lazy` */ - Decoder$1.lazy; - - const nonEmptyStringDecoder$3 = string$1().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$3 = number$1().where((num) => num >= 0, "Expected a non-negative number"); - const regexDecoder = anyJson$1().andThen((value) => { - return value instanceof RegExp ? anyJson$1() : fail(`expected a regex, got a ${typeof value}`); - }); - - const intentDefinitionDecoder$1 = object$1({ - name: nonEmptyStringDecoder$3, - displayName: optional$1(string$1()), - contexts: optional$1(array$1(string$1())), - customConfig: optional$1(object$1()) - }); - const v2TypeDecoder = oneOf(constant$1("web"), constant$1("native"), constant$1("citrix"), constant$1("onlineNative"), constant$1("other")); - const v2DetailsDecoder = object$1({ - url: nonEmptyStringDecoder$3 - }); - const v2IconDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3) - }); - const v2ScreenshotDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3), - label: optional$1(nonEmptyStringDecoder$3) - }); - const v2ListensForIntentDecoder = object$1({ - contexts: array$1(nonEmptyStringDecoder$3), - displayName: optional$1(nonEmptyStringDecoder$3), - resultType: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(anyJson$1()) - }); - const v2IntentsDecoder = object$1({ - listensFor: optional$1(dict(v2ListensForIntentDecoder)), - raises: optional$1(dict(array$1(nonEmptyStringDecoder$3))) - }); - const v2UserChannelDecoder = object$1({ - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2AppChannelDecoder = object$1({ - name: nonEmptyStringDecoder$3, - description: optional$1(nonEmptyStringDecoder$3), - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2InteropDecoder = object$1({ - intents: optional$1(v2IntentsDecoder), - userChannels: optional$1(v2UserChannelDecoder), - appChannels: optional$1(array$1(v2AppChannelDecoder)) - }); - const glue42ApplicationDetailsDecoder = object$1({ - url: optional$1(nonEmptyStringDecoder$3), - top: optional$1(number$1()), - left: optional$1(number$1()), - width: optional$1(nonNegativeNumberDecoder$3), - height: optional$1(nonNegativeNumberDecoder$3) - }); - const glue42HostManifestsBrowserDecoder = object$1({ - name: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3.where((s) => s === "window", "Expected a value of window")), - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - customProperties: optional$1(anyJson$1()), - icon: optional$1(string$1()), - caption: optional$1(string$1()), - details: optional$1(glue42ApplicationDetailsDecoder), - intents: optional$1(array$1(intentDefinitionDecoder$1)), - hidden: optional$1(boolean$1()) - }); - const v1DefinitionDecoder = object$1({ - name: nonEmptyStringDecoder$3, - appId: nonEmptyStringDecoder$3, - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - manifest: nonEmptyStringDecoder$3, - manifestType: nonEmptyStringDecoder$3, - tooltip: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - images: optional$1(array$1(object$1({ url: optional$1(nonEmptyStringDecoder$3) }))), - icons: optional$1(array$1(object$1({ icon: optional$1(nonEmptyStringDecoder$3) }))), - customConfig: anyJson$1(), - intents: optional$1(array$1(intentDefinitionDecoder$1)) - }); - const v2LocalizedDefinitionDecoder = object$1({ - appId: optional$1(nonEmptyStringDecoder$3), - name: optional$1(nonEmptyStringDecoder$3), - details: optional$1(v2DetailsDecoder), - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder) - }); - const v2DefinitionDecoder = object$1({ - appId: nonEmptyStringDecoder$3, - name: optional$1(nonEmptyStringDecoder$3), - type: v2TypeDecoder, - details: v2DetailsDecoder, - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder), - localizedVersions: optional$1(dict(v2LocalizedDefinitionDecoder)) - }); - const allDefinitionsDecoder = oneOf(v1DefinitionDecoder, v2DefinitionDecoder); - - const parseDecoderErrorToStringMessage = (error) => { - return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`; - }; - - class FDC3Service { - fdc3ToDesktopDefinitionType = { - web: "window", - native: "exe", - citrix: "citrix", - onlineNative: "clickonce", - other: "window" - }; - toApi() { - return { - isFdc3Definition: this.isFdc3Definition.bind(this), - parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this), - parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this) - }; - } - isFdc3Definition(definition) { - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - return { isFdc3: false, reason: parseDecoderErrorToStringMessage(decodeRes.error) }; - } - if (definition.appId && definition.details) { - return { isFdc3: true, version: "2.0" }; - } - if (definition.manifest) { - return { isFdc3: true, version: "1.2" }; - } - return { isFdc3: false, reason: "The passed definition is not FDC3" }; - } - parseToBrowserBaseAppData(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - const userProperties = this.getUserPropertiesFromDefinition(definition, version); - const createOptions = { url: this.getUrl(definition, version) }; - const baseApplicationData = { - name: definition.appId, - type: "window", - createOptions, - userProperties: { - ...userProperties, - intents: version === "1.2" - ? userProperties.intents - : this.getIntentsFromV2AppDefinition(definition), - details: createOptions - }, - title: definition.title, - version: definition.version, - icon: this.getIconFromDefinition(definition, version), - caption: definition.description, - fdc3: version === "2.0" ? { ...definition, definitionVersion: "2.0" } : undefined, - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return baseApplicationData; - } - const ioDefinitionDecodeRes = glue42HostManifestsBrowserDecoder.run(ioConnectDefinition); - if (!ioDefinitionDecodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(ioDefinitionDecodeRes.error)}`); - } - if (!Object.keys(ioDefinitionDecodeRes.result).length) { - return baseApplicationData; - } - return this.mergeBaseAppDataWithGlueManifest(baseApplicationData, ioDefinitionDecodeRes.result); - } - parseToDesktopAppConfig(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - if (version === "1.2") { - const fdc3v1Definition = definition; - return { - name: fdc3v1Definition.appId, - type: "window", - details: { - url: this.getUrl(definition, version) - }, - version: fdc3v1Definition.version, - title: fdc3v1Definition.title, - tooltip: fdc3v1Definition.tooltip, - caption: fdc3v1Definition.description, - icon: fdc3v1Definition.icons?.[0].icon, - intents: fdc3v1Definition.intents, - customProperties: { - manifestType: fdc3v1Definition.manifestType, - images: fdc3v1Definition.images, - contactEmail: fdc3v1Definition.contactEmail, - supportEmail: fdc3v1Definition.supportEmail, - publisher: fdc3v1Definition.publisher, - icons: fdc3v1Definition.icons, - customConfig: fdc3v1Definition.customConfig - } - }; - } - const fdc3v2Definition = definition; - const desktopDefinition = { - name: fdc3v2Definition.appId, - type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type], - details: fdc3v2Definition.details, - version: fdc3v2Definition.version, - title: fdc3v2Definition.title, - tooltip: fdc3v2Definition.tooltip, - caption: fdc3v2Definition.description, - icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"), - intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition), - fdc3: { ...fdc3v2Definition, definitionVersion: "2.0" } - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return desktopDefinition; - } - if (typeof ioConnectDefinition !== "object" || Array.isArray(ioConnectDefinition)) { - throw new Error(`Invalid '${definition.hostManifests.ioConnect ? "hostManifests.ioConnect" : "hostManifests['Glue42']"}' key`); - } - return this.mergeDesktopConfigWithGlueManifest(desktopDefinition, ioConnectDefinition); - } - getUserPropertiesFromDefinition(definition, version) { - if (version === "1.2") { - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key))); - } - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key))); - } - getUrl(definition, version) { - let url; - if (version === "1.2") { - const parsedManifest = JSON.parse(definition.manifest); - url = parsedManifest.details?.url || parsedManifest.url; - } - else { - url = definition.details?.url; - } - if (!url || typeof url !== "string") { - throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`); - } - return url; - } - getIntentsFromV2AppDefinition(definition) { - const fdc3Intents = definition.interop?.intents?.listensFor; - if (!fdc3Intents) { - return; - } - const intents = Object.entries(fdc3Intents).map((fdc3Intent) => { - const [intentName, intentData] = fdc3Intent; - return { - name: intentName, - ...intentData - }; - }); - return intents; - } - getIconFromDefinition(definition, version) { - if (version === "1.2") { - return definition.icons?.find((iconDef) => iconDef.icon)?.icon || undefined; - } - return definition.icons?.find((iconDef) => iconDef.src)?.src || undefined; - } - mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) { - let baseApplicationDefinition = baseAppData; - if (hostManifestDefinition.customProperties) { - baseApplicationDefinition.userProperties = { ...baseAppData.userProperties, ...hostManifestDefinition.customProperties }; - } - if (hostManifestDefinition.details) { - const details = { ...baseAppData.createOptions, ...hostManifestDefinition.details }; - baseApplicationDefinition.createOptions = details; - baseApplicationDefinition.userProperties.details = details; - } - if (Array.isArray(hostManifestDefinition.intents)) { - baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents); - } - baseApplicationDefinition = { ...baseApplicationDefinition, ...hostManifestDefinition }; - delete baseApplicationDefinition.details; - delete baseApplicationDefinition.intents; - return baseApplicationDefinition; - } - mergeDesktopConfigWithGlueManifest(config, desktopDefinition) { - const appConfig = Object.assign({}, config, desktopDefinition, { details: { ...config.details, ...desktopDefinition.details } }); - if (Array.isArray(desktopDefinition.intents)) { - appConfig.intents = (config.intents || []).concat(desktopDefinition.intents); - } - return appConfig; - } - } - - const decoders$1 = { - common: { - nonEmptyStringDecoder: nonEmptyStringDecoder$3, - nonNegativeNumberDecoder: nonNegativeNumberDecoder$3, - regexDecoder - }, - fdc3: { - allDefinitionsDecoder, - v1DefinitionDecoder, - v2DefinitionDecoder - } - }; - - var INTENTS_ERRORS; - (function (INTENTS_ERRORS) { - INTENTS_ERRORS["USER_CANCELLED"] = "User Closed Intents Resolver UI without choosing a handler"; - INTENTS_ERRORS["CALLER_NOT_DEFINED"] = "Caller Id is not defined"; - INTENTS_ERRORS["TIMEOUT_HIT"] = "Timeout hit"; - INTENTS_ERRORS["INTENT_NOT_FOUND"] = "Cannot find Intent"; - INTENTS_ERRORS["HANDLER_NOT_FOUND"] = "Cannot find Intent Handler"; - INTENTS_ERRORS["TARGET_INSTANCE_UNAVAILABLE"] = "Cannot start Target Instance"; - INTENTS_ERRORS["INTENT_DELIVERY_FAILED"] = "Target Instance did not add a listener"; - INTENTS_ERRORS["RESOLVER_UNAVAILABLE"] = "Intents Resolver UI unavailable"; - INTENTS_ERRORS["RESOLVER_TIMEOUT"] = "User did not choose a handler"; - INTENTS_ERRORS["INVALID_RESOLVER_RESPONSE"] = "Intents Resolver UI returned invalid response"; - INTENTS_ERRORS["INTENT_HANDLER_REJECTION"] = "Intent Handler function processing the raised intent threw an error or rejected the promise it returned"; - })(INTENTS_ERRORS || (INTENTS_ERRORS = {})); - - let IoC$1 = class IoC { - _fdc3; - _decoders = decoders$1; - _errors = { - intents: INTENTS_ERRORS - }; - get fdc3() { - if (!this._fdc3) { - this._fdc3 = new FDC3Service().toApi(); - } - return this._fdc3; - } - get decoders() { - return this._decoders; - } - get errors() { - return this._errors; - } - }; - - const ioc = new IoC$1(); - ioc.fdc3; - const decoders = ioc.decoders; - ioc.errors; - - const nonEmptyStringDecoder$2 = string$2().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$2 = number$2().where((num) => num >= 0, "Expected a non-negative number"); - const optionalNonEmptyStringDecoder = optional$2(nonEmptyStringDecoder$2); - const libDomainDecoder = oneOf$1(constant$2("system"), constant$2("windows"), constant$2("appManager"), constant$2("layouts"), constant$2("intents"), constant$2("notifications"), constant$2("channels"), constant$2("extension"), constant$2("themes"), constant$2("prefs"), constant$2("ui")); - const windowOperationTypesDecoder = oneOf$1(constant$2("openWindow"), constant$2("windowHello"), constant$2("windowAdded"), constant$2("windowRemoved"), constant$2("getBounds"), constant$2("getFrameBounds"), constant$2("getUrl"), constant$2("moveResize"), constant$2("focus"), constant$2("close"), constant$2("getTitle"), constant$2("setTitle"), constant$2("focusChange"), constant$2("getChannel"), constant$2("notifyChannelsChanged"), constant$2("setZoomFactor"), constant$2("zoomFactorChange"), constant$2("refresh"), constant$2("operationCheck")); - const appManagerOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("appDirectoryStateChange"), constant$2("instanceStarted"), constant$2("instanceStopped"), constant$2("applicationStart"), constant$2("instanceStop"), constant$2("clear"), constant$2("operationCheck")); - const layoutsOperationTypesDecoder = oneOf$1(constant$2("layoutAdded"), constant$2("layoutChanged"), constant$2("layoutRemoved"), constant$2("layoutRenamed"), constant$2("get"), constant$2("getAll"), constant$2("export"), constant$2("import"), constant$2("remove"), constant$2("rename"), constant$2("clientSaveRequest"), constant$2("getGlobalPermissionState"), constant$2("checkGlobalActivated"), constant$2("requestGlobalPermission"), constant$2("getDefaultGlobal"), constant$2("setDefaultGlobal"), constant$2("clearDefaultGlobal"), constant$2("updateMetadata"), constant$2("operationCheck"), constant$2("getCurrent"), constant$2("defaultLayoutChanged"), constant$2("layoutRestored")); - const notificationsOperationTypesDecoder = oneOf$1(constant$2("raiseNotification"), constant$2("requestPermission"), constant$2("notificationShow"), constant$2("notificationClick"), constant$2("getPermission"), constant$2("list"), constant$2("notificationRaised"), constant$2("notificationClosed"), constant$2("click"), constant$2("clear"), constant$2("clearAll"), constant$2("configure"), constant$2("getConfiguration"), constant$2("configurationChanged"), constant$2("setState"), constant$2("clearOld"), constant$2("activeCountChange"), constant$2("stateChange"), constant$2("operationCheck"), constant$2("getActiveCount")); - const systemOperationTypesDecoder = oneOf$1(constant$2("getEnvironment"), constant$2("getBase"), constant$2("platformShutdown"), constant$2("isFdc3DataWrappingSupported"), constant$2("clientError"), constant$2("systemHello"), constant$2("operationCheck")); - const windowRelativeDirectionDecoder = oneOf$1(constant$2("top"), constant$2("left"), constant$2("right"), constant$2("bottom")); - const windowBoundsDecoder = object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }); - const windowOpenSettingsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - context: optional$2(anyJson$2()), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - windowId: optional$2(nonEmptyStringDecoder$2), - layoutComponentId: optional$2(nonEmptyStringDecoder$2) - })); - const openWindowConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2, - options: windowOpenSettingsDecoder - }); - const windowHelloDecoder = object$2({ - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const coreWindowDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleWindowDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const helloSuccessDecoder = object$2({ - windows: array$2(coreWindowDataDecoder), - isWorkspaceFrame: boolean$2() - }); - const windowTitleConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - title: string$2() - }); - const focusEventDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - hasFocus: boolean$2() - }); - const windowMoveResizeConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relative: optional$2(boolean$2()) - }); - const windowBoundsResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const frameWindowBoundsResultDecoder = object$2({ - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const windowUrlResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2 - }); - const windowZoomFactorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - factorIndex: nonNegativeNumberDecoder$2 - }); - const anyDecoder = anyJson$2(); - const boundsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2) - }); - const instanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - applicationName: nonEmptyStringDecoder$2 - }); - const iframePermissionsPolicyConfigDecoder = object$2({ - flags: string$2() - }); - const workspacesSandboxDecoder = object$2({ - flags: string$2() - }); - const requestChannelSelectorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelsNames: array$2(nonEmptyStringDecoder$2) - }); - const channelSelectorDecoder$1 = object$2({ - enabled: boolean$2(), - }); - const applicationDetailsDecoder = object$2({ - url: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - workspacesSandbox: optional$2(workspacesSandboxDecoder), - channelSelector: optional$2(channelSelectorDecoder$1), - iframePermissionsPolicy: optional$2(iframePermissionsPolicyConfigDecoder) - }); - const intentDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - displayName: optional$2(string$2()), - contexts: optional$2(array$2(string$2())), - customConfig: optional$2(object$2()), - resultType: optional$2(string$2()) - }); - const applicationDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - customProperties: optional$2(anyJson$2()), - icon: optional$2(string$2()), - caption: optional$2(string$2()), - details: applicationDetailsDecoder, - intents: optional$2(array$2(intentDefinitionDecoder)), - hidden: optional$2(boolean$2()), - fdc3: optional$2(decoders.fdc3.v2DefinitionDecoder) - }); - const appRemoveConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const appsExportOperationDecoder = object$2({ - definitions: array$2(applicationDefinitionDecoder) - }); - const applicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - instances: array$2(instanceDataDecoder), - userProperties: optional$2(anyJson$2()), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const baseApplicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - userProperties: anyJson$2(), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const appDirectoryStateChangeDecoder = object$2({ - appsAdded: array$2(baseApplicationDataDecoder), - appsChanged: array$2(baseApplicationDataDecoder), - appsRemoved: array$2(baseApplicationDataDecoder) - }); - const appHelloSuccessDecoder = object$2({ - apps: array$2(applicationDataDecoder), - initialChannelId: optional$2(nonEmptyStringDecoder$2) - }); - const basicInstanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const layoutTypeDecoder = oneOf$1(constant$2("Global"), constant$2("Activity"), constant$2("ApplicationDefault"), constant$2("Swimlane"), constant$2("Workspace")); - const componentTypeDecoder = oneOf$1(constant$2("application"), constant$2("activity")); - const windowComponentStateDecoder = object$2({ - context: optional$2(anyJson$2()), - bounds: windowBoundsDecoder, - createArgs: object$2({ - name: optional$2(nonEmptyStringDecoder$2), - url: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - instanceId: nonEmptyStringDecoder$2, - isCollapsed: optional$2(boolean$2()), - isSticky: optional$2(boolean$2()), - restoreSettings: object$2({ - groupId: optional$2(nonEmptyStringDecoder$2), - groupZOrder: optional$2(number$2()) - }), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const windowLayoutComponentDecoder = object$2({ - type: constant$2("window"), - componentType: optional$2(componentTypeDecoder), - application: nonEmptyStringDecoder$2, - state: windowComponentStateDecoder - }); - const windowLayoutItemDecoder = object$2({ - type: constant$2("window"), - config: object$2({ - appName: nonEmptyStringDecoder$2, - url: optional$2(nonEmptyStringDecoder$2), - title: optional$2(string$2()), - allowExtract: optional$2(boolean$2()), - allowReorder: optional$2(boolean$2()), - showCloseButton: optional$2(boolean$2()), - isMaximized: optional$2(boolean$2()) - }) - }); - const groupLayoutItemDecoder = object$2({ - type: constant$2("group"), - config: anyJson$2(), - children: array$2(oneOf$1(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object$2({ - type: constant$2("column"), - config: anyJson$2(), - children: array$2(oneOf$1(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object$2({ - type: constant$2("row"), - config: anyJson$2(), - children: array$2(oneOf$1(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutComponentStateDecoder = object$2({ - config: anyJson$2(), - context: anyJson$2(), - children: array$2(oneOf$1(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }); - const workspaceLayoutComponentDecoder = object$2({ - type: constant$2("Workspace"), - application: optional$2(nonEmptyStringDecoder$2), - state: workspaceLayoutComponentStateDecoder - }); - const workspaceFrameComponentStateDecoder = object$2({ - bounds: windowBoundsDecoder, - instanceId: nonEmptyStringDecoder$2, - selectedWorkspace: nonNegativeNumberDecoder$2, - workspaces: array$2(workspaceLayoutComponentStateDecoder), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }); - const workspaceFrameComponentDecoder = object$2({ - type: constant$2("workspaceFrame"), - application: nonEmptyStringDecoder$2, - componentType: optional$2(componentTypeDecoder), - state: workspaceFrameComponentStateDecoder - }); - const glueLayoutDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()) - }); - const renamedLayoutNotificationDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()), - prevName: nonEmptyStringDecoder$2 - }); - const newLayoutOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - instances: optional$2(array$2(nonEmptyStringDecoder$2)), - ignoreInstances: optional$2(array$2(nonEmptyStringDecoder$2)), - setAsCurrent: optional$2(boolean$2()), - ignoreContexts: optional$2(boolean$2()) - }); - const restoreOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - closeRunningInstance: optional$2(boolean$2()), - closeMe: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2) - }); - const layoutSummaryDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()) - }); - const simpleLayoutConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder - }); - const saveLayoutConfigDecoder = object$2({ - layout: newLayoutOptionsDecoder - }); - const renameLayoutConfigDecoder = object$2({ - layout: glueLayoutDecoder, - newName: nonEmptyStringDecoder$2 - }); - const layoutResultDecoder = object$2({ - status: nonEmptyStringDecoder$2 - }); - const updateLayoutMetadataConfigDecoder = object$2({ - layout: glueLayoutDecoder, - }); - const restoreLayoutConfigDecoder = object$2({ - layout: restoreOptionsDecoder - }); - const getAllLayoutsConfigDecoder = object$2({ - type: layoutTypeDecoder - }); - const allLayoutsFullConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder) - }); - const defaultGlobalChangedDecoder = optional$2(object$2({ - name: nonEmptyStringDecoder$2 - })); - const importModeDecoder = oneOf$1(constant$2("replace"), constant$2("merge")); - const layoutsImportConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder), - mode: importModeDecoder, - skipManagerRequest: optional$2(boolean$2()) - }); - const allLayoutsSummariesResultDecoder = object$2({ - summaries: array$2(layoutSummaryDecoder) - }); - const simpleLayoutResultDecoder = object$2({ - layout: glueLayoutDecoder - }); - const optionalSimpleLayoutResult = object$2({ - layout: optional$2(glueLayoutDecoder) - }); - const setDefaultGlobalConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const intentsOperationTypesDecoder = oneOf$1(constant$2("findIntent"), constant$2("getIntents"), constant$2("getIntentsByHandler"), constant$2("raise"), constant$2("filterHandlers")); - const intentHandlerDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2, - applicationTitle: optional$2(string$2()), - applicationDescription: optional$2(string$2()), - applicationIcon: optional$2(string$2()), - type: oneOf$1(constant$2("app"), constant$2("instance")), - displayName: optional$2(string$2()), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - instanceId: optional$2(string$2()), - instanceTitle: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - object$2({ - applicationName: string$2(), - applicationIcon: optional$2(string$2()), - instanceId: optional$2(string$2()), - }); - object$2({ - intent: nonEmptyStringDecoder$2, - handler: intentHandlerDecoder - }); - const intentDecoder = object$2({ - name: nonEmptyStringDecoder$2, - handlers: array$2(intentHandlerDecoder) - }); - const intentTargetDecoder = oneOf$1(constant$2("startNew"), constant$2("reuse"), object$2({ - app: optional$2(nonEmptyStringDecoder$2), - instance: optional$2(nonEmptyStringDecoder$2) - })); - const intentContextDecoder = object$2({ - type: optional$2(nonEmptyStringDecoder$2), - data: optional$2(anyJson$2()) - }); - const intentsDecoder = array$2(intentDecoder); - const wrappedIntentsDecoder = object$2({ - intents: intentsDecoder - }); - const intentFilterDecoder = object$2({ - name: optional$2(nonEmptyStringDecoder$2), - contextType: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const findFilterDecoder = oneOf$1(nonEmptyStringDecoder$2, intentFilterDecoder); - const wrappedIntentFilterDecoder = object$2({ - filter: optional$2(intentFilterDecoder) - }); - const applicationStartOptionsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const intentRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - target: optional$2(intentTargetDecoder), - context: optional$2(intentContextDecoder), - options: optional$2(applicationStartOptionsDecoder), - handlers: optional$2(array$2(intentHandlerDecoder)), - timeout: optional$2(nonNegativeNumberDecoder$2), - waitUserResponseIndefinitely: optional$2(boolean$2()), - clearSavedHandler: optional$2(boolean$2()) - }); - const originAppDecoder = object$2({ - interopInstance: nonEmptyStringDecoder$2, - name: optional$2(nonEmptyStringDecoder$2) - }); - const startReasonDecoder = object$2({ - originApp: originAppDecoder, - intentRequest: optional$2(intentRequestDecoder) - }); - const applicationStartConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - waitForAGMReady: boolean$2(), - id: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()), - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - forceChromeTab: optional$2(boolean$2()), - layoutComponentId: optional$2(nonEmptyStringDecoder$2), - channelId: optional$2(nonEmptyStringDecoder$2), - startReason: startReasonDecoder - }); - const raiseRequestDecoder = oneOf$1(nonEmptyStringDecoder$2, intentRequestDecoder); - const resolverConfigDecoder = object$2({ - enabled: boolean$2(), - appName: nonEmptyStringDecoder$2, - waitResponseTimeout: number$2() - }); - const handlerExclusionCriteriaApplicationNameDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaInstanceIdDecoder = object$2({ - instanceId: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaDecoder = oneOf$1(handlerExclusionCriteriaApplicationNameDecoder, handlerExclusionCriteriaInstanceIdDecoder); - const handlerFilterDecoder = object$2({ - title: optional$2(nonEmptyStringDecoder$2), - openResolver: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2), - intent: optional$2(nonEmptyStringDecoder$2), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - resultType: optional$2(nonEmptyStringDecoder$2), - applicationNames: optional$2(array$2(nonEmptyStringDecoder$2)), - excludeList: optional$2(array$2(handlerExclusionCriteriaDecoder)) - }); - const embeddedResolverConfigDecoder = object$2({ - enabled: boolean$2(), - initialCaller: object$2({ instanceId: nonEmptyStringDecoder$2 }), - }); - const raiseIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const intentResultDecoder = object$2({ - request: intentRequestDecoder, - handler: intentHandlerDecoder, - result: anyJson$2() - }); - const filterHandlersResultDecoder = object$2({ - handlers: array$2(intentHandlerDecoder) - }); - const filterHandlersWithResolverConfigDecoder = object$2({ - filterHandlersRequest: handlerFilterDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const AddIntentListenerRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - displayName: optional$2(string$2()), - icon: optional$2(string$2()), - description: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - const AddIntentListenerDecoder = oneOf$1(nonEmptyStringDecoder$2, AddIntentListenerRequestDecoder); - const intentInfoDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - description: optional$2(nonEmptyStringDecoder$2), - displayName: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const getIntentsResultDecoder = object$2({ - intents: array$2(intentInfoDecoder) - }); - const channelNameDecoder = (channelNames) => { - return nonEmptyStringDecoder$2.where(s => channelNames.includes(s), "Expected a valid channel name"); - }; - const fdc3OptionsDecoder = object$2({ - contextType: optional$2(nonEmptyStringDecoder$2) - }); - const publishOptionsDecoder = optional$2(oneOf$1(nonEmptyStringDecoder$2, object$2({ - name: optional$2(nonEmptyStringDecoder$2), - fdc3: optional$2(boolean$2()) - }))); - const leaveChannelsConfig = object$2({ - windowId: optionalNonEmptyStringDecoder, - channel: optionalNonEmptyStringDecoder - }); - const fdc3ContextDecoder = anyJson$2().where((value) => typeof value.type === "string", "Expected a valid FDC3 Context with compulsory 'type' field"); - const interopActionSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$2, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("all"), constant$2("best"))) - }); - const glue42NotificationActionDecoder = object$2({ - action: string$2(), - title: nonEmptyStringDecoder$2, - icon: optional$2(string$2()), - interop: optional$2(interopActionSettingsDecoder) - }); - const notificationStateDecoder = oneOf$1(constant$2("Active"), constant$2("Acknowledged"), constant$2("Seen"), constant$2("Closed"), constant$2("Stale"), constant$2("Snoozed"), constant$2("Processing")); - const activeNotificationsCountChangeDecoder = object$2({ - count: number$2() - }); - const notificationDefinitionDecoder = object$2({ - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())) - }); - const glue42NotificationOptionsDecoder = object$2({ - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const notificationSetStateRequestDecoder = object$2({ - id: nonEmptyStringDecoder$2, - state: notificationStateDecoder - }); - object$2().where((value) => value.fdc3 ? typeof value.fdc3.type === "string" : true, "Expected a valid FDC3 Context with compulsory 'type' field"); - const channelFDC3DisplayMetadataDecoder = object$2({ - color: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - name: optional$2(nonEmptyStringDecoder$2), - glyph: optional$2(nonEmptyStringDecoder$2) - }); - const channelFdc3MetaDecoder = object$2({ - id: nonEmptyStringDecoder$2, - displayMetadata: optional$2(channelFDC3DisplayMetadataDecoder) - }); - const channelMetaDecoder = object$2({ - color: nonEmptyStringDecoder$2, - fdc3: optional$2(channelFdc3MetaDecoder) - }); - const channelDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - meta: channelMetaDecoder, - data: optional$2(object$2()), - }); - const pathValueDecoder = object$2({ - path: nonEmptyStringDecoder$2, - value: anyJson$2() - }); - const pathsValueDecoder = array$2(pathValueDecoder); - const removeChannelDataDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const channelRestrictionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const channelRestrictionConfigWithWindowIdDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: nonEmptyStringDecoder$2 - }); - const restrictionConfigDataDecoder = object$2({ - config: channelRestrictionConfigWithWindowIdDecoder - }); - const restrictionsDecoder = object$2({ - channels: array$2(channelRestrictionsDecoder) - }); - const getRestrictionsDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const restrictionsConfigDecoder = object$2({ - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const restrictAllDataDecoder = object$2({ - restrictions: restrictionsConfigDecoder - }); - const raiseNotificationDecoder = object$2({ - settings: glue42NotificationOptionsDecoder, - id: nonEmptyStringDecoder$2 - }); - const raiseNotificationResultDecoder = object$2({ - settings: glue42NotificationOptionsDecoder - }); - const permissionRequestResultDecoder = object$2({ - permissionGranted: boolean$2() - }); - const permissionQueryResultDecoder = object$2({ - permission: oneOf$1(constant$2("default"), constant$2("granted"), constant$2("denied")) - }); - const notificationEventPayloadDecoder = object$2({ - definition: notificationDefinitionDecoder, - action: optional$2(string$2()), - id: optional$2(nonEmptyStringDecoder$2) - }); - const notificationFilterDecoder = object$2({ - allowed: optional$2(array$2(nonEmptyStringDecoder$2)), - blocked: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const notificationsConfigurationDecoder = object$2({ - enable: optional$2(boolean$2()), - enableToasts: optional$2(boolean$2()), - sourceFilter: optional$2(notificationFilterDecoder), - showNotificationBadge: optional$2(boolean$2()) - }); - const notificationsConfigurationProtocolDecoder = object$2({ - configuration: notificationsConfigurationDecoder - }); - const strictNotificationsConfigurationProtocolDecoder = object$2({ - configuration: object$2({ - enable: boolean$2(), - enableToasts: boolean$2(), - sourceFilter: object$2({ - allowed: array$2(nonEmptyStringDecoder$2), - blocked: array$2(nonEmptyStringDecoder$2) - }) - }) - }); - const platformSaveRequestConfigDecoder = object$2({ - layoutType: oneOf$1(constant$2("Global"), constant$2("Workspace")), - layoutName: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()) - }); - const saveRequestClientResponseDecoder = object$2({ - windowContext: optional$2(anyJson$2()), - }); - const permissionStateResultDecoder = object$2({ - state: oneOf$1(constant$2("prompt"), constant$2("denied"), constant$2("granted")) - }); - const simpleAvailabilityResultDecoder = object$2({ - isAvailable: boolean$2() - }); - const simpleItemIdDecoder = object$2({ - itemId: nonEmptyStringDecoder$2 - }); - const operationCheckResultDecoder = object$2({ - isSupported: boolean$2() - }); - const operationCheckConfigDecoder = object$2({ - operation: nonEmptyStringDecoder$2 - }); - const workspaceFrameBoundsResultDecoder = object$2({ - bounds: windowBoundsDecoder - }); - const themeDecoder = object$2({ - displayName: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleThemeResponseDecoder = object$2({ - theme: themeDecoder - }); - const allThemesResponseDecoder = object$2({ - themes: array$2(themeDecoder) - }); - const selectThemeConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const notificationsDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const simpleNotificationDataDecoder = object$2({ - notification: notificationsDataDecoder - }); - const allNotificationsDataDecoder = object$2({ - notifications: array$2(notificationsDataDecoder) - }); - const simpleNotificationSelectDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelResultDecoder = object$2({ - windowIds: array$2(nonEmptyStringDecoder$2) - }); - const channelsOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("addChannel"), constant$2("getMyChannel"), constant$2("getWindowIdsOnChannel"), constant$2("getWindowIdsWithChannels"), constant$2("joinChannel"), constant$2("restrict"), constant$2("getRestrictions"), constant$2("restrictAll"), constant$2("notifyChannelsChanged"), constant$2("leaveChannel"), constant$2("getMode"), constant$2("operationCheck")); - const modeDecoder = oneOf$1(constant$2("single"), constant$2("multi")); - const getChannelsModeDecoder = object$2({ - mode: modeDecoder - }); - const channelsAppHelloDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const channelsAppHelloSuccessDecoder = object$2({ - mode: modeDecoder, - channels: array$2(nonEmptyStringDecoder$2), - restrictions: array$2(channelRestrictionsDecoder) - }); - const getMyChanelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2) - }); - const windowWithChannelFilterDecoder = object$2({ - application: optional$2(nonEmptyStringDecoder$2), - channels: optional$2(array$2(nonEmptyStringDecoder$2)), - windowIds: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const wrappedWindowWithChannelFilterDecoder = object$2({ - filter: optional$2(windowWithChannelFilterDecoder) - }); - const getWindowIdsWithChannelsResultDecoder = object$2({ - windowIdsWithChannels: array$2(object$2({ - application: nonEmptyStringDecoder$2, - channel: optional$2(nonEmptyStringDecoder$2), - windowId: nonEmptyStringDecoder$2 - })) - }); - const startApplicationContextDecoder = optional$2(anyJson$2()); - const startApplicationOptionsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - reuseId: optional$2(nonEmptyStringDecoder$2), - originIntentRequest: optional$2(intentRequestDecoder) - })); - const joinChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2, - windowId: nonEmptyStringDecoder$2 - }); - const leaveChannelDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelName: optional$2(nonEmptyStringDecoder$2) - }); - const channelsChangedDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelNames: array$2(nonEmptyStringDecoder$2) - }); - const windowChannelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2), - }); - const prefsOperationTypesDecoder = oneOf$1(constant$2("clear"), constant$2("clearAll"), constant$2("get"), constant$2("getAll"), constant$2("set"), constant$2("update"), constant$2("prefsChanged"), constant$2("prefsHello"), constant$2("operationCheck"), constant$2("registerSubscriber")); - const appPreferencesDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - lastUpdate: optional$2(nonEmptyStringDecoder$2), - }); - const basePrefsConfigDecoder = object$2({ - app: nonEmptyStringDecoder$2, - }); - const getPrefsResultDecoder = object$2({ - prefs: appPreferencesDecoder, - }); - const getAllPrefsResultDecoder = object$2({ - all: array$2(appPreferencesDecoder), - }); - const subscriberRegisterConfigDecoder = object$2({ - interopId: nonEmptyStringDecoder$2, - appName: optional$2(nonEmptyStringDecoder$2) - }); - const changePrefsDataDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - }); - const prefsHelloSuccessDecoder = object$2({ - platform: object$2({ - app: nonEmptyStringDecoder$2, - }), - validNonExistentApps: optional$2(array$2(nonEmptyStringDecoder$2)), - }); - const clientErrorDataDecoder = object$2({ - message: nonEmptyStringDecoder$2 - }); - const systemHelloSuccessDecoder = object$2({ - isClientErrorOperationSupported: boolean$2() - }); - - const nonEmptyStringDecoder$1 = decoders.common.nonEmptyStringDecoder; - const nonNegativeNumberDecoder$1 = decoders.common.nonNegativeNumberDecoder; - const widgetSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const modalsSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const intentResolverSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const channelSelectorTypeDecoder = oneOf$1(constant$2("directional"), constant$2("default")); - const channelSelectorDecoder = object$2({ - type: optional$2(channelSelectorTypeDecoder), - enable: optional$2(boolean$2()) - }); - const positionDecoder = oneOf$1(constant$2("top-left"), constant$2("top-center"), constant$2("top-right"), constant$2("center-left"), constant$2("center-right"), constant$2("bottom-left"), constant$2("bottom-center"), constant$2("bottom-right")); - const displayModeDecoder = oneOf$1(constant$2("all"), constant$2("fdc3")); - const widgetChannelsDecoder = object$2({ - selector: optional$2(channelSelectorDecoder), - displayMode: optional$2(displayModeDecoder) - }); - const platformWidgetDefaultConfigDecoder = object$2({ - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const widgetConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const modalsConfigDecoder = object$2({ - alerts: optional$2(object$2({ - enabled: boolean$2() - })), - dialogs: optional$2(object$2({ - enabled: boolean$2() - })), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - }); - const uiOperationTypesDecoder = oneOf$1(constant$2("getResources"), constant$2("operationCheck"), constant$2("showAlert"), constant$2("showDialog"), constant$2("alertInteropAction"), constant$2("showResolver")); - const getResourcesDataDecoder = object$2({ - origin: nonEmptyStringDecoder$1 - }); - const blockedResourcesDecoder = object$2({ - blockedOrigin: constant$2(true) - }); - const availableWidgetResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - config: platformWidgetDefaultConfigDecoder, - sources: widgetSourcesDecoder - }); - const widgetResourcesDecoder = union$1(blockedResourcesDecoder, availableWidgetResourcesDecoder); - const availableModalsResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: modalsSourcesDecoder - }); - const modalsResourcesDecoder = union$1(blockedResourcesDecoder, availableModalsResourcesDecoder); - const availableIntentResolverResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: intentResolverSourcesDecoder - }); - const intentResolverResourcesDecoder = union$1(blockedResourcesDecoder, availableIntentResolverResourcesDecoder); - const resourcesDecoder = object$2({ - widget: optional$2(widgetResourcesDecoder), - modals: optional$2(modalsResourcesDecoder), - intentResolver: optional$2(intentResolverResourcesDecoder) - }); - const getResourcesResultDecoder = object$2({ - resources: resourcesDecoder, - }); - const alertsInteropSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$1, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("best"), constant$2("all"), nonEmptyStringDecoder$1)) - }); - const modalRequestTargetDecoder = oneOf$1(constant$2("Global"), constant$2("WindowContainer"), nonEmptyStringDecoder$1); - const modalRequestMessageTargetDecoder = object$2({ - instance: nonEmptyStringDecoder$1, - container: optional$2(oneOf$1(constant$2("Global"), constant$2("WindowContainer"))) - }); - const alertRequestConfigDecoder = object$2({ - variant: oneOf$1(constant$2("default"), constant$2("success"), constant$2("critical"), constant$2("info"), constant$2("warning")), - text: nonEmptyStringDecoder$1, - showCloseButton: optional$2(boolean$2()), - clickInterop: optional$2(alertsInteropSettingsDecoder), - onCloseInterop: optional$2(alertsInteropSettingsDecoder), - actions: optional$2(array$2(object$2({ - id: nonEmptyStringDecoder$1, - title: nonEmptyStringDecoder$1, - clickInterop: alertsInteropSettingsDecoder - }))), - data: optional$2(anyJson$2()), - ttl: optional$2(nonNegativeNumberDecoder$1), - target: optional$2(modalRequestTargetDecoder) - }); - const uiAlertRequestMessageDecoder = object$2({ - config: alertRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const dialogRequestConfigDecoder = object$2({ - templateName: nonEmptyStringDecoder$1, - variables: anyJson$2(), - target: optional$2(modalRequestTargetDecoder), - timer: optional$2(object$2({ - duration: nonNegativeNumberDecoder$1 - })), - size: optional$2(object$2({ - width: nonNegativeNumberDecoder$1, - height: nonNegativeNumberDecoder$1 - })), - movable: optional$2(boolean$2()), - transparent: optional$2(boolean$2()) - }); - const dialogResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - isEnterPressed: optional$2(boolean$2()), - responseButtonClicked: optional$2(object$2({ - id: nonEmptyStringDecoder$1, - text: nonEmptyStringDecoder$1 - })), - inputs: optional$2(array$2(object$2({ - type: oneOf$1(constant$2("checkbox"), constant$2("email"), constant$2("number"), constant$2("password"), constant$2("text")), - id: nonEmptyStringDecoder$1, - checked: optional$2(boolean$2()), - value: optional$2(string$2()) - }))) - }); - object$2({ - result: dialogResponseDecoder - }); - const uiDialogRequestMessageDecoder = object$2({ - config: dialogRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const openAlertResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const openDialogResultDecoder = object$2({ - id: nonEmptyStringDecoder$1, - responsePromise: anyJson$2() - }); - const dialogOnCompletionConfigDecoder = object$2({ - response: dialogResponseDecoder - }); - const alertInteropActionDecoder = object$2({ - name: nonEmptyStringDecoder$1, - settings: alertsInteropSettingsDecoder - }); - const alertOnClickConfigDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const alertInteropActionDataDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const intentResolverConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1) - }); - const openResolverResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const userSettingsDecoder = object$2({ - preserveChoice: boolean$2() - }); - const userChoiceResponseDecoder = object$2({ - intent: nonEmptyStringDecoder$1, - handler: intentHandlerDecoder, - userSettings: userSettingsDecoder - }); - const intentResolverResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - userChoice: optional$2(userChoiceResponseDecoder) - }); - const onUserResponseResponseDecoder = object$2({ - response: intentResolverResponseDecoder - }); - const openConfigWithIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder - }); - const openConfigWithHandlerFilterDecoder = object$2({ - handlerFilter: handlerFilterDecoder - }); - const intentResolverOpenConfigDecoder = union$1(openConfigWithIntentRequestDecoder, openConfigWithHandlerFilterDecoder); - const uiResolverRequestMessageConfigDecoder = intersection(intentResolverOpenConfigDecoder, object$2({ timeout: nonNegativeNumberDecoder$1 })); - const uiResolverRequestMessageDecoder = object$2({ - config: uiResolverRequestMessageConfigDecoder - }); - const uiResolverResponseMessageDecoder = object$2({ - result: intentResolverResponseDecoder - }); - - const parseConfig = (config = {}) => { - const isPlatformInternal = !!config?.gateway?.webPlatform?.port; - const decodedWidgetConfigResult = optional$2(widgetConfigDecoder).run(config.widget); - if (!decodedWidgetConfigResult.ok) { - throw ioError.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(decodedWidgetConfigResult.error)}`); - } - const decodedModalsConfigResult = optional$2(modalsConfigDecoder).run(config.modals); - if (!decodedModalsConfigResult.ok) { - throw ioError.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(decodedModalsConfigResult.error)}`); - } - const decodedIntentResolverConfigResult = optional$2(intentResolverConfigDecoder).run(config.intentResolver); - if (!decodedIntentResolverConfigResult.ok) { - throw ioError.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(decodedIntentResolverConfigResult.error)}`); - } - const combined = { - ...defaultConfig, - ...config, - isPlatformInternal, - logger: config.systemLogger?.level ?? "info", - customLogger: config.systemLogger?.customLogger, - widget: deepmerge$1(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}), - modals: deepmerge$1(defaultModalsConfig, decodedModalsConfigResult.result ?? {}), - intentResolver: deepmerge$1(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}), - }; - return combined; - }; - - const checkSingleton = () => { - const ioConnectBrowserNamespace = window.glue42core || window.iobrowser; - if (ioConnectBrowserNamespace && ioConnectBrowserNamespace.webStarted) { - return ioError.raiseError("IoConnect Browser has already been started for this application."); - } - if (!ioConnectBrowserNamespace) { - window.iobrowser = { webStarted: true }; - return; - } - ioConnectBrowserNamespace.webStarted = true; - }; - - const enterprise = (config) => { - const enterpriseConfig = { - windows: true, - layouts: "full", - appManager: "full", - channels: true, - libraries: config?.libraries ?? [], - logger: config?.systemLogger?.level ?? "warn" - }; - const injectedFactory = window.IODesktop || window.Glue; - return injectedFactory(enterpriseConfig); - }; - - const operations$a = { - openWindow: { name: "openWindow", dataDecoder: openWindowConfigDecoder, resultDecoder: coreWindowDataDecoder }, - windowHello: { name: "windowHello", dataDecoder: windowHelloDecoder, resultDecoder: helloSuccessDecoder }, - windowAdded: { name: "windowAdded", dataDecoder: coreWindowDataDecoder }, - windowRemoved: { name: "windowRemoved", dataDecoder: simpleWindowDecoder }, - getBounds: { name: "getBounds", dataDecoder: simpleWindowDecoder, resultDecoder: windowBoundsResultDecoder }, - getFrameBounds: { name: "getFrameBounds", dataDecoder: simpleWindowDecoder, resultDecoder: frameWindowBoundsResultDecoder }, - getUrl: { name: "getUrl", dataDecoder: simpleWindowDecoder, resultDecoder: windowUrlResultDecoder }, - moveResize: { name: "moveResize", dataDecoder: windowMoveResizeConfigDecoder }, - focus: { name: "focus", dataDecoder: simpleWindowDecoder }, - close: { name: "close", dataDecoder: simpleWindowDecoder }, - getTitle: { name: "getTitle", dataDecoder: simpleWindowDecoder, resultDecoder: windowTitleConfigDecoder }, - setTitle: { name: "setTitle", dataDecoder: windowTitleConfigDecoder }, - focusChange: { name: "focusChange", dataDecoder: focusEventDataDecoder }, - getChannel: { name: "getChannel", dataDecoder: simpleWindowDecoder, resultDecoder: windowChannelResultDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - setZoomFactor: { name: "setZoomFactor", dataDecoder: windowZoomFactorConfigDecoder }, - zoomFactorChange: { name: "zoomFactorChange", dataDecoder: windowZoomFactorConfigDecoder }, - refresh: { name: "refresh", dataDecoder: simpleWindowDecoder }, - operationCheck: { name: "operationCheck" } - }; - - function createRegistry$1(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry$1.default = createRegistry$1; - var lib$1 = createRegistry$1; - - - var CallbackRegistryFactory$1 = /*@__PURE__*/getDefaultExportFromCjs$1(lib$1); - - const ZOOM_FACTORS = Object.freeze({ - 0: 24, - 1: 33, - 2: 50, - 3: 67, - 4: 75, - 5: 80, - 6: 90, - 7: 100, - 8: 110, - 9: 125, - 10: 150, - 11: 175, - 12: 200, - 13: 250, - 14: 300, - 15: 400, - 16: 500 - }); - - class WebWindowModel { - _id; - _name; - _bridge; - _logger; - registry = CallbackRegistryFactory$1(); - myCtxKey; - ctxUnsubscribe; - zoomFactorIndex = 7; - me; - constructor(_id, _name, _bridge, _logger) { - this._id = _id; - this._name = _name; - this._bridge = _bridge; - this._logger = _logger; - this.myCtxKey = `___window___${this.id}`; - } - get id() { - return this._id.slice(); - } - get name() { - return this._name.slice(); - } - get zoomFactor() { - return ZOOM_FACTORS[this.zoomFactorIndex]; - } - clean() { - if (this.ctxUnsubscribe) { - this.ctxUnsubscribe(); - } - } - processSelfFocusEvent(hasFocus) { - this.me.isFocused = hasFocus; - this.registry.execute("focus-change", this.me); - } - processChannelsChangedEvent(channelNames) { - this.registry.execute("channels-changed", channelNames); - } - processSelfZoomFactorChangedEvent(factorIndex) { - this.zoomFactorIndex = factorIndex; - this.registry.execute("zoom-factor-changed", this.me); - } - async toApi() { - this.ctxUnsubscribe = await this._bridge.contextLib.subscribe(this.myCtxKey, (data) => this.registry.execute("context-updated", data)); - this.me = { - id: this.id, - name: this.name, - isFocused: false, - zoomFactor: this.zoomFactor, - getURL: this.getURL.bind(this), - moveResize: this.moveResize.bind(this), - resizeTo: this.resizeTo.bind(this), - moveTo: this.moveTo.bind(this), - focus: this.focus.bind(this), - close: this.close.bind(this), - getTitle: this.getTitle.bind(this), - setTitle: this.setTitle.bind(this), - getBounds: this.getBounds.bind(this), - getContext: this.getContext.bind(this), - updateContext: this.updateContext.bind(this), - setContext: this.setContext.bind(this), - refresh: this.refresh.bind(this), - onContextUpdated: this.onContextUpdated.bind(this), - onFocusChanged: this.onFocusChanged.bind(this), - getChannel: this.getChannel.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - zoomIn: this.zoomIn.bind(this), - zoomOut: this.zoomOut.bind(this), - setZoomFactor: this.setZoomFactor.bind(this), - onZoomFactorChanged: this.onZoomFactorChanged.bind(this), - }; - Object.defineProperties(this.me, { - id: READONLY_PROPERTY_DESCRIPTOR, - name: READONLY_PROPERTY_DESCRIPTOR, - zoomFactor: { - get: () => { - return this.zoomFactor; - }, - enumerable: true, - }, - }); - return this.me; - } - async getURL() { - const result = await this._bridge.send("windows", operations$a.getUrl, { windowId: this.id }); - return result.url; - } - onFocusChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - return this.registry.add("focus-change", callback); - } - async moveResize(dimension) { - const targetBounds = runDecoderWithIOError(boundsDecoder, dimension); - const commandArgs = Object.assign({}, targetBounds, { windowId: this.id, relative: false }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async resizeTo(width, height) { - if (typeof width === "undefined" && typeof height === "undefined") { - return this.me; - } - if (typeof width !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, width); - } - if (typeof height !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, height); - } - const commandArgs = Object.assign({}, { width, height }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async moveTo(top, left) { - if (typeof top === "undefined" && typeof left === "undefined") { - return this.me; - } - if (typeof top !== "undefined") { - runDecoderWithIOError(number$2(), top); - } - if (typeof left !== "undefined") { - runDecoderWithIOError(number$2(), left); - } - const commandArgs = Object.assign({}, { top, left }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async focus() { - if (this.name === "Platform") { - window.open(undefined, this.id); - } - else { - await this._bridge.send("windows", operations$a.focus, { windowId: this.id }); - } - return this.me; - } - async close() { - await this._bridge.send("windows", operations$a.close, { windowId: this.id }); - return this.me; - } - async getTitle() { - const result = await this._bridge.send("windows", operations$a.getTitle, { windowId: this.id }); - return result.title; - } - async setTitle(title) { - const ttl = runDecoderWithIOError(nonEmptyStringDecoder$2, title); - await this._bridge.send("windows", operations$a.setTitle, { windowId: this.id, title: ttl }); - return this.me; - } - async getBounds() { - const result = await this._bridge.send("windows", operations$a.getBounds, { windowId: this.id }); - return result.bounds; - } - async getContext() { - const ctx = await this._bridge.contextLib.get(this.myCtxKey); - const { ___io___, ...rest } = ctx; - return rest; - } - async updateContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - await this._bridge.contextLib.update(this.myCtxKey, ctx); - return this.me; - } - async setContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - const current = await this._bridge.contextLib.get(this.myCtxKey); - const newCtx = current.___io___ ? { ...ctx, ___io___: current.___io___ } : ctx; - await this._bridge.contextLib.set(this.myCtxKey, newCtx); - return this.me; - } - onContextUpdated(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - const wrappedCallback = (data) => { - const { ___io___, ...rest } = data; - callback(rest, this.me); - }; - return this.registry.add("context-updated", wrappedCallback); - } - async getChannel() { - const result = await this._bridge.send("windows", operations$a.getChannel, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return result.channel; - } - onChannelsChanged(callback) { - return this.registry.add("channels-changed", callback); - } - getClosestZoomFactorIndex(factor) { - const closestIndex = Object.entries(ZOOM_FACTORS).reduce((closestIndex, [currentIndex, currentValue]) => { - return (Math.abs(currentValue - factor) <= Math.abs(ZOOM_FACTORS[closestIndex] - factor) ? parseInt(currentIndex) : closestIndex); - }, 0); - const closestFactor = ZOOM_FACTORS[closestIndex]; - if (closestFactor !== factor) { - this._logger.warn(`Zoom factor ${factor} is not available, using closest value ${closestFactor} instead.`); - } - return closestIndex; - } - async zoom(factorIndex) { - if (factorIndex === this.zoomFactorIndex || !(factorIndex in ZOOM_FACTORS)) { - return; - } - await this._bridge.send("windows", operations$a.setZoomFactor, { windowId: this.id, factorIndex }, undefined, { includeOperationCheck: true }); - this.zoomFactorIndex = factorIndex; - } - async zoomIn() { - await this.zoom(this.zoomFactorIndex + 1); - return this.me; - } - async zoomOut() { - await this.zoom(this.zoomFactorIndex - 1); - return this.me; - } - async setZoomFactor(factor) { - const targetZoomFactor = runDecoderWithIOError(number$2(), factor); - const closestZoomFactorIndex = this.getClosestZoomFactorIndex(targetZoomFactor); - await this.zoom(closestZoomFactorIndex); - return this.me; - } - onZoomFactorChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"); - } - return this.registry.add("zoom-factor-changed", callback); - } - async refresh() { - await this._bridge.send("windows", operations$a.refresh, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return this.me; - } - } - - const commonOperations = { - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - getWorkspaceWindowFrameBounds: { name: "getWorkspaceWindowFrameBounds", resultDecoder: workspaceFrameBoundsResultDecoder, dataDecoder: simpleItemIdDecoder } - }; - - const PromiseWrap = (callback, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - callback() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - const PromisePlus$1 = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WindowsController { - supportedOperationsNames = []; - focusEventHandler; - registry = CallbackRegistryFactory$1(); - platformRegistration; - ioc; - bridge; - publicWindowId; - allWindowProjections = []; - me; - logger; - isWorkspaceFrame; - instanceId; - channelsController; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("windows.controller.web"); - this.logger.trace("starting the web windows controller"); - this.publicWindowId = ioc.publicWindowId; - this.addWindowOperationExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.instanceId = coreGlue.interop.instance.instance; - this.channelsController = ioc.channelsController; - this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`); - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - await this.initializeFocusTracking(); - this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning"); - const api = this.toApi(); - coreGlue.windows = api; - } - handlePlatformShutdown() { - this.registry.clear(); - this.allWindowProjections = []; - if (!this.focusEventHandler) { - return; - } - document.removeEventListener("visibilityChange", this.focusEventHandler); - window.removeEventListener("focus", this.focusEventHandler); - window.removeEventListener("blur", this.focusEventHandler); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(windowOperationTypesDecoder, args.operation); - const operation = operations$a[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async open(name, url, options) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(nonEmptyStringDecoder$2, url); - const settings = runDecoderWithIOError(windowOpenSettingsDecoder, options); - const windowSuccess = await this.bridge.send("windows", operations$a.openWindow, { name, url, options: settings }); - return this.waitForWindowAdded(windowSuccess.windowId); - } - list() { - return this.allWindowProjections.map((projection) => projection.api); - } - findById(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - return this.allWindowProjections.find((projection) => projection.id === id)?.api; - } - toApi() { - return { - open: this.open.bind(this), - my: this.my.bind(this), - list: this.list.bind(this), - findById: this.findById.bind(this), - onWindowAdded: this.onWindowAdded.bind(this), - onWindowRemoved: this.onWindowRemoved.bind(this), - onWindowGotFocus: this.onWindowGotFocus.bind(this), - onWindowLostFocus: this.onWindowLostFocus.bind(this) - }; - } - addWindowOperationExecutors() { - operations$a.focusChange.execute = this.handleFocusChangeEvent.bind(this); - operations$a.windowAdded.execute = this.handleWindowAdded.bind(this); - operations$a.windowRemoved.execute = this.handleWindowRemoved.bind(this); - operations$a.getBounds.execute = this.handleGetBounds.bind(this); - operations$a.getFrameBounds.execute = this.handleGetBounds.bind(this); - operations$a.getTitle.execute = this.handleGetTitle.bind(this); - operations$a.getUrl.execute = this.handleGetUrl.bind(this); - operations$a.moveResize.execute = this.handleMoveResize.bind(this); - operations$a.setTitle.execute = this.handleSetTitle.bind(this); - operations$a.getChannel.execute = this.handleGetChannel.bind(this); - operations$a.notifyChannelsChanged.execute = this.handleChannelsChanged.bind(this); - operations$a.setZoomFactor.execute = this.handleSetZoomFactor.bind(this); - operations$a.zoomFactorChange.execute = this.handleZoomFactorChanged.bind(this); - operations$a.refresh.execute = this.handleRefresh.bind(this); - operations$a.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$a); - } - my() { - return Object.assign({}, this.me); - } - onWindowAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"); - } - return this.registry.add("window-added", callback); - } - onWindowRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"); - } - return this.registry.add("window-removed", callback); - } - onWindowGotFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-got-focus", callback); - } - onWindowLostFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-lost-focus", callback); - } - async sayHello() { - const helloSuccess = await this.bridge.send("windows", operations$a.windowHello, { windowId: this.publicWindowId }); - return helloSuccess; - } - async registerWithPlatform() { - const { windows, isWorkspaceFrame } = await this.sayHello(); - this.isWorkspaceFrame = isWorkspaceFrame; - this.logger.trace("the platform responded to the hello message"); - if (!this.isWorkspaceFrame && this.publicWindowId) { - this.logger.trace("i am not treated as a workspace frame, setting my window"); - const myWindow = windows.find((w) => w.windowId === this.publicWindowId); - if (!myWindow) { - const windowsInfo = windows.map(w => `${w.windowId}:${w.name}`).join(", "); - return ioError.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${windowsInfo}`); - } - const myProjection = await this.ioc.buildWebWindow(this.publicWindowId, myWindow.name, this.logger); - this.me = myProjection.api; - this.allWindowProjections.push(myProjection); - } - const currentWindows = await Promise.all(windows - .filter((w) => w.windowId !== this.publicWindowId) - .map((w) => this.ioc.buildWebWindow(w.windowId, w.name, this.logger))); - this.logger.trace("all windows projections are completed, building the list collection"); - this.allWindowProjections.push(...currentWindows); - } - async handleFocusChangeEvent(focusData) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === focusData.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfFocusEvent(focusData.hasFocus); - const keyToExecute = focusData.hasFocus ? "window-got-focus" : "window-lost-focus"; - this.registry.execute(keyToExecute, foundProjection.api); - } - async handleWindowAdded(data) { - if (this.allWindowProjections.some((projection) => projection.id === data.windowId)) { - return; - } - const webWindowProjection = await this.ioc.buildWebWindow(data.windowId, data.name, this.logger); - this.allWindowProjections.push(webWindowProjection); - this.registry.execute("window-added", webWindowProjection.api); - } - async handleWindowRemoved(data) { - const removed = this.allWindowProjections.find((w) => w.id === data.windowId); - if (!removed) { - return; - } - this.allWindowProjections = this.allWindowProjections.filter((w) => w.id !== data.windowId); - removed.model.clean(); - this.registry.execute("window-removed", removed.api); - } - async handleGetBounds() { - if (!this.me && !this.isWorkspaceFrame) { - return ioError.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.isWorkspaceFrame ? "noop" : this.me.id, - bounds: { - top: window.screenTop, - left: window.screenLeft, - width: window.innerWidth, - height: window.innerHeight - } - }; - } - async handleGetTitle() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - title: document.title - }; - } - async handleGetUrl() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - url: window.location.href - }; - } - async handleMoveResize(config) { - const targetTop = typeof config.top === "number" ? config.top : - config.relative ? 0 : window.screenTop; - const targetLeft = typeof config.left === "number" ? config.left : - config.relative ? 0 : window.screenLeft; - const targetHeight = typeof config.height === "number" ? config.height : - config.relative ? 0 : window.innerHeight; - const targetWidth = typeof config.width === "number" ? config.width : - config.relative ? 0 : window.innerWidth; - const moveMethod = config.relative ? window.moveBy : window.moveTo; - const resizeMethod = config.relative ? window.resizeBy : window.resizeTo; - moveMethod(targetLeft, targetTop); - resizeMethod(targetWidth, targetHeight); - } - async handleSetTitle(config) { - document.title = config.title; - } - async initializeFocusTracking() { - if (this.isWorkspaceFrame) { - this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame"); - return; - } - try { - await this.bridge.send("windows", commonOperations.operationCheck, { operation: "focusChange" }); - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client."); - return; - } - const hasFocus = document.hasFocus(); - await this.transmitFocusChange(true); - if (!hasFocus) { - await this.transmitFocusChange(false); - } - this.defineEventListeners(); - } - processFocusEvent() { - const hasFocus = document.hasFocus(); - this.transmitFocusChange(hasFocus); - } - waitForWindowAdded(windowId) { - const foundWindow = this.allWindowProjections.find((projection) => projection.id === windowId); - if (foundWindow) { - return Promise.resolve(foundWindow.api); - } - return PromisePlus$1((resolve) => { - const unsubscribe = this.onWindowAdded((addedWindow) => { - if (addedWindow.id === windowId) { - unsubscribe(); - resolve(addedWindow); - } - }); - }, 30000, `Timed out waiting for ${windowId} to be announced`); - } - async transmitFocusChange(hasFocus) { - const eventData = { - windowId: this.me?.id || `iframe-${this.instanceId}`, - hasFocus - }; - if (this.me) { - this.me.isFocused = hasFocus; - } - await this.bridge.send("windows", operations$a.focusChange, eventData); - } - defineEventListeners() { - this.focusEventHandler = this.processFocusEvent.bind(this); - document.addEventListener("visibilityChange", this.focusEventHandler); - window.addEventListener("focus", this.focusEventHandler); - window.addEventListener("blur", this.focusEventHandler); - } - async handleGetChannel() { - if (!this.me) { - return ioError.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe"); - } - const channel = this.channelsController.my(); - return { - ...(channel ? { channel } : {}), - }; - } - async handleRefresh() { - if (!this.me) { - return ioError.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe"); - } - setTimeout(() => { - window.location.reload(); - }, 0); - } - async handleChannelsChanged(data) { - const windowProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - windowProjection?.model.processChannelsChangedEvent(data.channelNames); - } - async handleSetZoomFactor(config) { - if (!this.me) { - return ioError.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe"); - } - document.body.style.zoom = `${ZOOM_FACTORS[config.factorIndex]}%`; - } - async handleZoomFactorChanged(data) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfZoomFactorChangedEvent(data.factorIndex); - } - } - - const GlueWebPlatformControlName = "T42.Web.Platform.Control"; - const GlueWebPlatformStreamName = "T42.Web.Platform.Stream"; - const GlueClientControlName = "T42.Web.Client.Control"; - const GlueCorePlusThemesStream = "T42.Core.Plus.Themes.Stream"; - - class GlueBridge { - coreGlue; - communicationId; - platformMethodTimeoutMs = 10000; - controllers; - sub; - running; - constructor(coreGlue, communicationId) { - this.coreGlue = coreGlue; - this.communicationId = communicationId; - } - get contextLib() { - return this.coreGlue.contexts; - } - get interopInstance() { - return this.coreGlue.interop.instance.instance; - } - async stop() { - this.running = false; - this.sub.close(); - await this.coreGlue.interop.unregister(GlueClientControlName); - } - async start(controllers) { - this.running = true; - this.controllers = controllers; - await Promise.all([ - this.checkWaitMethod(GlueWebPlatformControlName), - this.checkWaitMethod(GlueWebPlatformStreamName) - ]); - const systemId = this.communicationId; - const [sub] = await Promise.all([ - this.coreGlue.interop.subscribe(GlueWebPlatformStreamName, systemId ? { target: { instance: this.communicationId } } : undefined), - this.coreGlue.interop.registerAsync(GlueClientControlName, (args, _, success, error) => this.passMessageController(args, success, error)) - ]); - this.sub = sub; - this.sub.onData((pkg) => this.passMessageController(pkg.data)); - } - getInteropInstance(windowId) { - const result = this.coreGlue.interop.servers().find((s) => s.windowId && s.windowId === windowId); - return { - application: result?.application, - applicationName: result?.applicationName, - peerId: result?.peerId, - instance: result?.instance, - windowId: result?.windowId - }; - } - async send(domain, operation, operationData, options, webOptions) { - if (operation.dataDecoder) { - try { - operation.dataDecoder.runWithException(operationData); - } - catch (error) { - return ioError.raiseError(`Unexpected Web->Platform outgoing validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - } - const operationSupported = webOptions?.includeOperationCheck ? - (await this.checkOperationSupported(domain, operation)).isSupported : - true; - if (!operationSupported) { - return ioError.raiseError(`Cannot complete operation: ${operation.name} for domain: ${domain} because this client is connected to a platform which does not support it`); - } - try { - const operationResult = await this.transmitMessage(domain, operation, operationData, options); - if (operation.resultDecoder) { - operation.resultDecoder.runWithException(operationResult); - } - return operationResult; - } - catch (error) { - if (error?.kind) { - return ioError.raiseError(`Unexpected Web<-Platform incoming validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - return ioError.raiseError(error); - } - } - async createNotificationsSteam() { - const streamExists = this.coreGlue.interop.methods().some((method) => method.name === GlueCorePlusThemesStream); - if (!streamExists) { - return ioError.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus."); - } - return this.coreGlue.interop.subscribe(GlueCorePlusThemesStream, this.communicationId ? { target: { instance: this.communicationId } } : undefined); - } - async checkOperationSupported(domain, operation) { - try { - const result = await this.send(domain, commonOperations.operationCheck, { operation: operation.name }); - return result; - } - catch (error) { - return { isSupported: false }; - } - } - checkWaitMethod(name) { - return PromisePlus$1((resolve) => { - const hasMethod = this.coreGlue.interop.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = this.communicationId ? - method.getServers().some((server) => server.instance === this.communicationId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - return resolve(); - } - const unSub = this.coreGlue.interop.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = this.communicationId ? - server.instance === this.communicationId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }, this.platformMethodTimeoutMs, `Cannot initiate Glue Web, because a system method's discovery timed out: ${name}`); - } - passMessageController(args, success, error) { - const decodeResult = libDomainDecoder.run(args.domain); - if (!decodeResult.ok) { - if (error) { - error(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(decodeResult.error)}`); - } - return; - } - const domain = decodeResult.result; - this.controllers[domain] - .handleBridgeMessage(args) - .then((resolutionData) => { - if (success) { - success(resolutionData); - } - }) - .catch((err) => { - if (error) { - error(err); - } - console.warn(err); - }); - } - async transmitMessage(domain, operation, data, options) { - const messageData = { domain, data, operation: operation.name }; - let invocationResult; - const baseErrorMessage = `Internal Platform Communication Error. Attempted operation: ${JSON.stringify(operation.name)} with data: ${JSON.stringify(data)}. `; - const systemId = this.communicationId; - try { - if (!this.running) { - throw new Error("Cannot send a control message, because the platform shut down"); - } - invocationResult = await this.coreGlue.interop.invoke(GlueWebPlatformControlName, messageData, systemId ? { instance: this.communicationId } : undefined, options); - if (!invocationResult) { - throw new Error("Received unsupported result from the platform - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from the platform - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - } - - const operations$9 = { - appHello: { name: "appHello", dataDecoder: windowHelloDecoder, resultDecoder: appHelloSuccessDecoder }, - appDirectoryStateChange: { name: "appDirectoryStateChange", dataDecoder: appDirectoryStateChangeDecoder }, - instanceStarted: { name: "instanceStarted", dataDecoder: instanceDataDecoder }, - instanceStopped: { name: "instanceStopped", dataDecoder: instanceDataDecoder }, - applicationStart: { name: "applicationStart", dataDecoder: applicationStartConfigDecoder, resultDecoder: instanceDataDecoder }, - instanceStop: { name: "instanceStop", dataDecoder: basicInstanceDataDecoder }, - import: { name: "import" }, - remove: { name: "remove", dataDecoder: appRemoveConfigDecoder }, - export: { name: "export", resultDecoder: appsExportOperationDecoder }, - clear: { name: "clear" }, - operationCheck: { name: "operationCheck" } - }; - - class AppManagerController { - me; - supportedOperationsNames = []; - baseApplicationsTimeoutMS = 60000; - appImportTimeoutMS = 20; - registry = CallbackRegistryFactory$1(); - ioc; - bridge; - publicWindowId; - applications = []; - instances = []; - platformRegistration; - logger; - channelsController; - interop; - initialChannelId; - handlePlatformShutdown() { - this.registry.clear(); - this.applications = []; - this.instances = []; - delete this.me; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("appManger.controller.web"); - this.logger.trace("starting the web appManager controller"); - this.publicWindowId = ioc.publicWindowId; - this.addOperationsExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.interop = coreGlue.interop; - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning"); - const api = this.toApi(); - coreGlue.appManager = api; - } - async postStart() { - if (!this.initialChannelId) { - return; - } - await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(appManagerOperationTypesDecoder, args.operation); - const operation = operations$9[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStarted requires a single argument of type function"); - } - return this.registry.add("instance-started", callback, this.instances); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStopped requires a single argument of type function"); - } - return this.registry.add("instance-stopped", callback); - } - async startApplication(appName, context, options) { - const channels = await this.channelsController.all(); - if (options?.channelId && !channels.includes(options.channelId)) { - return ioError.raiseError(`The channel with name "${options.channelId}" doesn't exist!`); - } - const startOptions = { - name: appName, - waitForAGMReady: options?.waitForAGMReady ?? true, - context, - top: options?.top, - left: options?.left, - width: options?.width, - height: options?.height, - relativeTo: options?.relativeTo, - relativeDirection: options?.relativeDirection, - id: options?.reuseId, - forceChromeTab: options?.forceTab, - layoutComponentId: options?.layoutComponentId, - channelId: options?.channelId, - startReason: { - originApp: { - name: this.me?.application.name, - interopInstance: this.interop.instance.instance - } - } - }; - if (options?.originIntentRequest) { - startOptions.startReason.intentRequest = options.originIntentRequest; - } - const openResult = await this.bridge.send("appManager", operations$9.applicationStart, startOptions); - const app = this.applications.find((a) => a.name === openResult.applicationName); - return this.ioc.buildInstance(openResult, app); - } - getApplication(name) { - const verifiedName = runDecoderWithIOError(nonEmptyStringDecoder$2, name); - return this.applications.find((app) => app.name === verifiedName); - } - getInstances() { - return this.instances.slice(); - } - onAppAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppAdded requires a single argument of type function"); - } - return this.registry.add("application-added", callback, this.applications); - } - onAppRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppRemoved requires a single argument of type function"); - } - return this.registry.add("application-removed", callback); - } - toApi() { - const api = { - myInstance: this.me, - inMemory: { - import: this.importApps.bind(this), - remove: this.remove.bind(this), - export: this.exportApps.bind(this), - clear: this.clear.bind(this) - }, - application: this.getApplication.bind(this), - applications: this.getApplications.bind(this), - instances: this.getInstances.bind(this), - onAppAdded: this.onAppAdded.bind(this), - onAppChanged: this.onAppChanged.bind(this), - onAppRemoved: this.onAppRemoved.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - return api; - } - addOperationsExecutors() { - operations$9.appDirectoryStateChange.execute = this.handleAppDirectoryStateChange.bind(this); - operations$9.instanceStarted.execute = this.handleInstanceStartedMessage.bind(this); - operations$9.instanceStopped.execute = this.handleInstanceStoppedMessage.bind(this); - operations$9.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$9); - } - async handleAppDirectoryStateChange(data) { - data.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)); - data.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)); - data.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this)); - } - onAppChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppChanged requires a single argument of type function"); - } - return this.registry.add("application-changed", callback); - } - async handleApplicationAddedMessage(appData) { - if (this.applications.some((app) => app.name === appData.name)) { - return; - } - const app = await this.ioc.buildApplication(appData, []); - const instances = this.instances.filter((instance) => instance.application.name === app.name); - app.instances.push(...instances); - this.applications.push(app); - this.registry.execute("application-added", app); - } - async handleApplicationRemovedMessage(appData) { - const appIndex = this.applications.findIndex((app) => app.name === appData.name); - if (appIndex < 0) { - return; - } - const app = this.applications[appIndex]; - this.applications.splice(appIndex, 1); - this.registry.execute("application-removed", app); - } - async handleApplicationChangedMessage(appData) { - const app = this.applications.find((app) => app.name === appData.name); - if (!app) { - return this.handleApplicationAddedMessage(appData); - } - app.title = appData.title; - app.version = appData.version; - app.icon = appData.icon; - app.caption = appData.caption; - app.userProperties = appData.userProperties; - this.registry.execute("application-changed", app); - } - async handleInstanceStartedMessage(instanceData) { - if (this.instances.some((instance) => instance.id === instanceData.id)) { - return; - } - const application = this.applications.find((app) => app.name === instanceData.applicationName); - if (!application) { - return ioError.raiseError(`Cannot add instance: ${instanceData.id}, because there is no application definition associated with it`); - } - const instance = this.ioc.buildInstance(instanceData, application); - this.instances.push(instance); - application.instances.push(instance); - this.registry.execute("instance-started", instance); - } - async handleInstanceStoppedMessage(instanceData) { - const instance = this.instances.find((i) => i.id === instanceData.id); - if (instance) { - const instIdx = this.instances.findIndex((inst) => inst.id === instanceData.id); - this.instances.splice(instIdx, 1); - } - const application = this.applications.find((app) => app.instances.some((inst) => inst.id === instanceData.id)); - if (application) { - const instIdxApps = application.instances.findIndex((inst) => inst.id === instanceData.id); - application.instances.splice(instIdxApps, 1); - } - if (!instance) { - return; - } - this.registry.execute("instance-stopped", instance); - } - async importApps(definitions, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(definitions)) { - return ioError.raiseError("Import must be called with an array of definitions"); - } - if (definitions.length > 10000) { - return ioError.raiseError("Cannot import more than 10000 app definitions in Glue42 Core."); - } - const parseResult = definitions.reduce((soFar, definition) => { - const { isValid, error } = this.isValidDefinition(definition); - if (!isValid) { - soFar.invalid.push({ app: definition?.name, error: error ?? `Provided definition is invalid ${JSON.stringify(definition)}` }); - } - else { - soFar.valid.push(definition); - } - return soFar; - }, { valid: [], invalid: [] }); - const responseTimeout = this.baseApplicationsTimeoutMS + this.appImportTimeoutMS * parseResult.valid.length; - await this.bridge.send("appManager", operations$9.import, { definitions: parseResult.valid, mode }, { methodResponseTimeoutMs: responseTimeout }); - return { - imported: parseResult.valid.map((valid) => valid.name), - errors: parseResult.invalid - }; - } - isValidDefinition(definition) { - const isFdc3V2Definition = definition?.appId && definition?.details; - if (isFdc3V2Definition) { - const decodeResult = decoders.fdc3.v2DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v2 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const isFdc3V1Definition = definition?.appId && definition?.manifest; - if (isFdc3V1Definition) { - const decodeResult = decoders.fdc3.v1DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v1 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const decodeResult = applicationDefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("appManager", operations$9.remove, { name }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async clear() { - await this.bridge.send("appManager", operations$9.clear, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async exportApps() { - const response = await this.bridge.send("appManager", operations$9.export, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - return response.definitions; - } - getApplications() { - return this.applications.slice(); - } - async registerWithPlatform() { - const result = await this.bridge.send("appManager", operations$9.appHello, { windowId: this.publicWindowId }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - this.logger.trace("the platform responded to the hello message with a full list of apps"); - this.applications = await Promise.all(result.apps.map((app) => this.ioc.buildApplication(app, app.instances))); - this.instances = this.applications.reduce((instancesSoFar, app) => { - instancesSoFar.push(...app.instances); - return instancesSoFar; - }, []); - this.me = this.findMyInstance(); - this.logger.trace(`all applications were parsed and saved. I am ${this.me ? "NOT a" : "a"} valid instance`); - this.initialChannelId = result.initialChannelId; - } - findMyInstance() { - for (const app of this.applications) { - const foundInstance = app.instances.find((instance) => instance.id === this.publicWindowId); - if (foundInstance) { - return foundInstance; - } - } - return undefined; - } - } - - class InstanceModel { - data; - bridge; - application; - me; - myCtxKey; - constructor(data, bridge, application) { - this.data = data; - this.bridge = bridge; - this.application = application; - this.myCtxKey = `___instance___${this.data.id}`; - } - toApi() { - const agm = this.bridge.getInteropInstance(this.data.id); - const api = { - id: this.data.id, - agm, - application: this.application, - stop: this.stop.bind(this), - getContext: this.getContext.bind(this) - }; - this.me = Object.freeze(api); - return this.me; - } - async getContext() { - return this.bridge.contextLib.get(this.myCtxKey); - } - async stop() { - await this.bridge.send("appManager", operations$9.instanceStop, { id: this.data.id }); - } - } - - class ApplicationModel { - data; - instances; - controller; - me; - constructor(data, instances, controller) { - this.data = data; - this.instances = instances; - this.controller = controller; - } - toApi() { - const api = { - name: this.data.name, - title: this.data.title, - version: this.data.version, - icon: this.data.icon, - caption: this.data.caption, - userProperties: this.data.userProperties, - instances: this.instances, - start: this.start.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - this.me = api; - return this.me; - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStarted((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStopped((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - async start(context, options) { - const verifiedContext = runDecoderWithIOError(startApplicationContextDecoder, context); - const verifiedOptions = runDecoderWithIOError(startApplicationOptionsDecoder, options); - return this.controller.startApplication(this.data.name, verifiedContext, verifiedOptions); - } - } - - const operations$8 = { - layoutAdded: { name: "layoutAdded", dataDecoder: glueLayoutDecoder }, - layoutChanged: { name: "layoutChanged", dataDecoder: glueLayoutDecoder }, - layoutRemoved: { name: "layoutRemoved", dataDecoder: glueLayoutDecoder }, - layoutRestored: { name: "layoutRestored", dataDecoder: glueLayoutDecoder }, - defaultLayoutChanged: { name: "defaultLayoutChanged", dataDecoder: defaultGlobalChangedDecoder }, - layoutRenamed: { name: "layoutRenamed", dataDecoder: renamedLayoutNotificationDecoder }, - get: { name: "get", dataDecoder: simpleLayoutConfigDecoder, resultDecoder: optionalSimpleLayoutResult }, - getAll: { name: "getAll", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsSummariesResultDecoder }, - export: { name: "export", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsFullConfigDecoder }, - import: { name: "import", dataDecoder: layoutsImportConfigDecoder }, - remove: { name: "remove", dataDecoder: simpleLayoutConfigDecoder }, - rename: { name: "rename", dataDecoder: renameLayoutConfigDecoder, resultDecoder: layoutResultDecoder }, - save: { name: "save", dataDecoder: saveLayoutConfigDecoder, resultDecoder: simpleLayoutResultDecoder }, - restore: { name: "restore", dataDecoder: restoreLayoutConfigDecoder }, - clientSaveRequest: { name: "clientSaveRequest", dataDecoder: platformSaveRequestConfigDecoder, resultDecoder: saveRequestClientResponseDecoder }, - getGlobalPermissionState: { name: "getGlobalPermissionState", resultDecoder: permissionStateResultDecoder }, - requestGlobalPermission: { name: "requestGlobalPermission", resultDecoder: simpleAvailabilityResultDecoder }, - checkGlobalActivated: { name: "checkGlobalActivated", resultDecoder: simpleAvailabilityResultDecoder }, - getDefaultGlobal: { name: "getDefaultGlobal", resultDecoder: optionalSimpleLayoutResult }, - setDefaultGlobal: { name: "setDefaultGlobal", dataDecoder: setDefaultGlobalConfigDecoder }, - clearDefaultGlobal: { name: "clearDefaultGlobal" }, - getCurrent: { name: "getCurrent", resultDecoder: optionalSimpleLayoutResult }, - updateMetadata: { name: "updateMetadata", dataDecoder: updateLayoutMetadataConfigDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class LayoutsController { - supportedOperationsNames = []; - defaultLayoutRestoreTimeoutMS = 120000; - registry = CallbackRegistryFactory$1(); - bridge; - logger; - windowsController; - saveRequestSubscription; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("layouts.controller.web"); - this.logger.trace("starting the web layouts controller"); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.addOperationsExecutors(); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"); - coreGlue.layouts = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(layoutsOperationTypesDecoder, args.operation); - const operation = operations$8[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - get: this.get.bind(this), - getAll: this.getAll.bind(this), - getCurrentLayout: this.getCurrentLayout.bind(this), - export: this.exportLayouts.bind(this), - import: this.importLayouts.bind(this), - save: this.save.bind(this), - restore: this.restore.bind(this), - remove: this.remove.bind(this), - onAdded: this.onAdded.bind(this), - onChanged: this.onChanged.bind(this), - onRemoved: this.onRemoved.bind(this), - onDefaultGlobalChanged: this.onDefaultGlobalChanged.bind(this), - onSaveRequested: this.subscribeOnSaveRequested.bind(this), - getMultiScreenPermissionState: this.getGlobalPermissionState.bind(this), - requestMultiScreenPermission: this.requestGlobalPermission.bind(this), - getGlobalTypeState: this.checkGlobalActivated.bind(this), - getDefaultGlobal: this.getDefaultGlobal.bind(this), - setDefaultGlobal: this.setDefaultGlobal.bind(this), - clearDefaultGlobal: this.clearDefaultGlobal.bind(this), - rename: this.rename.bind(this), - onRenamed: this.onRenamed.bind(this), - onRestored: this.onRestored.bind(this), - updateMetadata: this.updateMetadata.bind(this) - }; - return Object.freeze(api); - } - addOperationsExecutors() { - operations$8.layoutAdded.execute = this.handleOnAdded.bind(this); - operations$8.layoutChanged.execute = this.handleOnChanged.bind(this); - operations$8.layoutRemoved.execute = this.handleOnRemoved.bind(this); - operations$8.layoutRenamed.execute = this.handleOnRenamed.bind(this); - operations$8.layoutRestored.execute = this.handleOnRestored.bind(this); - operations$8.defaultLayoutChanged.execute = this.handleOnDefaultChanged.bind(this); - operations$8.clientSaveRequest.execute = this.handleSaveRequest.bind(this); - operations$8.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$8); - } - async get(name, type) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.get, { name, type }); - return result.layout; - } - async getCurrentLayout() { - const result = await this.bridge.send("layouts", operations$8.getCurrent, undefined); - return result.layout; - } - async getAll(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.getAll, { type }); - return result.summaries; - } - async exportLayouts(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.export, { type }); - return result.layouts; - } - async importLayouts(layouts, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(layouts)) { - return ioError.raiseError("Import must be called with an array of layouts"); - } - if (layouts.length > 1000) { - return ioError.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core."); - } - const parseResult = layouts.reduce((soFar, layout) => { - const decodeResult = glueLayoutDecoder.run(layout); - if (decodeResult.ok) { - soFar.valid.push(layout); - } - else { - this.logger.warn(`A layout with name: ${layout.name} was not imported, because of error: ${JSON.stringify(decodeResult.error)}`); - } - return soFar; - }, { valid: [] }); - const layoutsToImport = layouts.filter((layout) => parseResult.valid.some((validLayout) => validLayout.name === layout.name)); - await this.bridge.send("layouts", operations$8.import, { layouts: layoutsToImport, mode }); - } - async save(layout) { - runDecoderWithIOError(newLayoutOptionsDecoder, layout); - const saveResult = await this.bridge.send("layouts", operations$8.save, { layout }); - return saveResult.layout; - } - async restore(options) { - runDecoderWithIOError(restoreOptionsDecoder, options); - const invocationTimeout = options.timeout ? options.timeout * 2 : this.defaultLayoutRestoreTimeoutMS; - await this.bridge.send("layouts", operations$8.restore, { layout: options }, { methodResponseTimeoutMs: invocationTimeout }); - } - async remove(type, name) { - runDecoderWithIOError(layoutTypeDecoder, type); - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.remove, { type, name }); - } - async handleSaveRequest(config) { - const response = {}; - if (this.saveRequestSubscription) { - try { - const onSaveRequestResponse = this.saveRequestSubscription(config); - response.windowContext = onSaveRequestResponse?.windowContext; - } - catch (error) { - this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(error)}`); - } - } - return response; - } - async getGlobalPermissionState() { - const requestResult = await this.bridge.send("layouts", operations$8.getGlobalPermissionState, undefined); - return requestResult; - } - async requestGlobalPermission() { - const currentState = (await this.getGlobalPermissionState()).state; - if (currentState === "denied") { - return { permissionGranted: false }; - } - if (currentState === "granted") { - return { permissionGranted: true }; - } - const myWindow = this.windowsController.my(); - const globalNamespace = window.glue42core || window.iobrowser; - const amIWorkspaceFrame = globalNamespace.isPlatformFrame; - if (myWindow.name !== "Platform" && !amIWorkspaceFrame) { - return ioError.raiseError("Cannot request permission for multi-window placement from any app other than the Platform."); - } - const requestResult = await this.bridge.send("layouts", operations$8.requestGlobalPermission, undefined, { methodResponseTimeoutMs: 180000 }); - return { permissionGranted: requestResult.isAvailable }; - } - async checkGlobalActivated() { - const requestResult = await this.bridge.send("layouts", operations$8.checkGlobalActivated, undefined); - return { activated: requestResult.isAvailable }; - } - async getDefaultGlobal() { - const requestResult = await this.bridge.send("layouts", operations$8.getDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - return requestResult.layout; - } - async setDefaultGlobal(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.setDefaultGlobal, { name }, undefined, { includeOperationCheck: true }); - } - async clearDefaultGlobal() { - await this.bridge.send("layouts", operations$8.clearDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - } - async rename(layout, newName) { - runDecoderWithIOError(glueLayoutDecoder, layout); - runDecoderWithIOError(nonEmptyStringDecoder$2, newName); - const result = await this.bridge.send("layouts", operations$8.rename, { layout, newName }, undefined, { includeOperationCheck: true }); - return result; - } - async updateMetadata(layout) { - runDecoderWithIOError(glueLayoutDecoder, layout); - await this.bridge.send("layouts", operations$8.updateMetadata, { layout }, undefined, { includeOperationCheck: true }); - } - onAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"); - } - this.exportLayouts("Global").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - this.exportLayouts("Workspace").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - return this.registry.add(operations$8.layoutAdded.name, callback); - } - onChanged(callback) { - return this.registry.add(operations$8.layoutChanged.name, callback); - } - onDefaultGlobalChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"); - } - this.getDefaultGlobal().then((layout) => callback(layout ? { name: layout.name } : undefined)).catch(() => { }); - return this.registry.add(operations$8.defaultLayoutChanged.name, callback); - } - onRemoved(callback) { - return this.registry.add(operations$8.layoutRemoved.name, callback); - } - onRenamed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRenamed.name, callback); - } - onRestored(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRestored.name, callback); - } - subscribeOnSaveRequested(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."); - } - if (this.saveRequestSubscription) { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."); - } - this.saveRequestSubscription = callback; - return () => { - delete this.saveRequestSubscription; - }; - } - async handleOnAdded(layout) { - this.registry.execute(operations$8.layoutAdded.name, layout); - } - async handleOnChanged(layout) { - this.registry.execute(operations$8.layoutChanged.name, layout); - } - async handleOnDefaultChanged(layout) { - this.registry.execute(operations$8.defaultLayoutChanged.name, layout); - } - async handleOnRemoved(layout) { - this.registry.execute(operations$8.layoutRemoved.name, layout); - } - async handleOnRestored(layout) { - this.registry.execute(operations$8.layoutRestored.name, layout); - } - async handleOnRenamed(renamedData) { - const { prevName, ...layout } = renamedData; - this.registry.execute(operations$8.layoutRenamed.name, layout, { name: prevName }); - } - } - - const operations$7 = { - raiseNotification: { name: "raiseNotification", dataDecoder: raiseNotificationDecoder, resultDecoder: raiseNotificationResultDecoder }, - requestPermission: { name: "requestPermission", resultDecoder: permissionRequestResultDecoder }, - notificationShow: { name: "notificationShow", dataDecoder: notificationEventPayloadDecoder }, - notificationClick: { name: "notificationClick", dataDecoder: notificationEventPayloadDecoder }, - getPermission: { name: "getPermission", resultDecoder: permissionQueryResultDecoder }, - list: { name: "list", resultDecoder: allNotificationsDataDecoder }, - notificationRaised: { name: "notificationRaised", dataDecoder: simpleNotificationDataDecoder }, - notificationClosed: { name: "notificationClosed", dataDecoder: simpleNotificationSelectDecoder }, - click: { name: "click" }, - clear: { name: "clear" }, - clearAll: { name: "clearAll" }, - clearOld: { name: "clearOld" }, - configure: { name: "configure", dataDecoder: notificationsConfigurationProtocolDecoder }, - getConfiguration: { name: "getConfiguration", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - getActiveCount: { name: "getActiveCount", resultDecoder: activeNotificationsCountChangeDecoder }, - configurationChanged: { name: "configurationChanged", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - setState: { name: "setState", dataDecoder: notificationSetStateRequestDecoder }, - activeCountChange: { name: "activeCountChange", resultDecoder: activeNotificationsCountChangeDecoder }, - stateChange: { name: "stateChange", resultDecoder: notificationSetStateRequestDecoder }, - operationCheck: { name: "operationCheck" } - }; - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet$1 = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid$1 = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet$1[(Math.random() * 64) | 0]; - } - return id - }; - - class NotificationsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - bridge; - notificationsSettings; - notifications = {}; - coreGlue; - buildNotificationFunc; - notificationsConfiguration; - notificationsActiveCount = 0; - handlePlatformShutdown() { - this.notifications = {}; - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("notifications.controller.web"); - this.logger.trace("starting the web notifications controller"); - this.bridge = ioc.bridge; - this.coreGlue = coreGlue; - this.notificationsSettings = ioc.config.notifications; - this.buildNotificationFunc = ioc.buildNotification; - this.notificationsConfiguration = await this.getConfiguration(); - this.notificationsActiveCount = await this.getActiveCount(); - const api = this.toApi(); - this.addOperationExecutors(); - coreGlue.notifications = api; - this.logger.trace("notifications are ready"); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(notificationsOperationTypesDecoder, args.operation); - const operation = operations$7[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - requestPermission: this.requestPermission.bind(this), - getPermission: this.getPermission.bind(this), - list: this.list.bind(this), - onRaised: this.onRaised.bind(this), - onClosed: this.onClosed.bind(this), - click: this.click.bind(this), - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearOld: this.clearOld.bind(this), - configure: this.configure.bind(this), - getConfiguration: this.getConfiguration.bind(this), - getFilter: this.getFilter.bind(this), - setFilter: this.setFilter.bind(this), - setState: this.setState.bind(this), - onConfigurationChanged: this.onConfigurationChanged.bind(this), - onActiveCountChanged: this.onActiveCountChanged.bind(this), - onCounterChanged: this.onActiveCountChanged.bind(this), - onStateChanged: this.onStateChanged.bind(this) - }; - return Object.freeze(api); - } - async getPermission() { - const queryResult = await this.bridge.send("notifications", operations$7.getPermission, undefined); - return queryResult.permission; - } - async requestPermission() { - const permissionResult = await this.bridge.send("notifications", operations$7.requestPermission, undefined); - return permissionResult.permissionGranted; - } - async raise(options) { - const settings = runDecoderWithIOError(glue42NotificationOptionsDecoder, options); - settings.showToast = typeof settings.showToast === "boolean" ? settings.showToast : true; - settings.showInPanel = typeof settings.showInPanel === "boolean" ? settings.showInPanel : true; - const permissionGranted = await this.requestPermission(); - if (!permissionGranted) { - return ioError.raiseError("Cannot raise the notification, because the user has declined the permission request"); - } - const id = nanoid$1(10); - const raiseResult = await this.bridge.send("notifications", operations$7.raiseNotification, { settings, id }); - const notification = this.buildNotificationFunc(raiseResult.settings, id); - this.notifications[id] = notification; - return notification; - } - async list() { - const bridgeResponse = await this.bridge.send("notifications", operations$7.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.notifications; - } - onRaised(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onRaised expects a callback of type function"); - } - return this.registry.add("notification-raised", callback); - } - onClosed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onClosed expects a callback of type function"); - } - return this.registry.add("notification-closed", callback); - } - async click(id, action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - if (action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, action); - } - await this.bridge.send("notifications", operations$7.click, { id, action }, undefined, { includeOperationCheck: true }); - } - async clear(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - await this.bridge.send("notifications", operations$7.clear, { id }, undefined, { includeOperationCheck: true }); - } - async clearAll() { - await this.bridge.send("notifications", operations$7.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearOld() { - await this.bridge.send("notifications", operations$7.clearOld, undefined, undefined, { includeOperationCheck: true }); - } - async configure(config) { - const verifiedConfig = runDecoderWithIOError(notificationsConfigurationDecoder, config); - await this.bridge.send("notifications", operations$7.configure, { configuration: verifiedConfig }, undefined, { includeOperationCheck: true }); - } - async getConfiguration() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration; - } - async getActiveCount() { - try { - const response = await this.bridge.send("notifications", operations$7.getActiveCount, undefined, undefined, { includeOperationCheck: true }); - return response.count; - } - catch (error) { - console.warn("Failed to get accurate active notifications count", error); - return 0; - } - } - async getFilter() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration.sourceFilter; - } - async setFilter(filter) { - const verifiedFilter = runDecoderWithIOError(notificationFilterDecoder, filter); - await this.bridge.send("notifications", operations$7.configure, { configuration: { sourceFilter: verifiedFilter } }, undefined, { includeOperationCheck: true }); - return verifiedFilter; - } - async setState(id, state) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - runDecoderWithIOError(notificationStateDecoder, state); - await this.bridge.send("notifications", operations$7.setState, { id, state }, undefined, { includeOperationCheck: true }); - } - onConfigurationChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"); - } - setTimeout(() => callback(this.notificationsConfiguration), 0); - return this.registry.add("notifications-config-changed", callback); - } - onActiveCountChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"); - } - setTimeout(() => callback({ count: this.notificationsActiveCount }), 0); - return this.registry.add("notifications-active-count-changed", callback); - } - onStateChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"); - } - return this.registry.add("notification-state-changed", callback); - } - addOperationExecutors() { - operations$7.notificationShow.execute = this.handleNotificationShow.bind(this); - operations$7.notificationClick.execute = this.handleNotificationClick.bind(this); - operations$7.notificationRaised.execute = this.handleNotificationRaised.bind(this); - operations$7.notificationClosed.execute = this.handleNotificationClosed.bind(this); - operations$7.configurationChanged.execute = this.handleConfigurationChanged.bind(this); - operations$7.activeCountChange.execute = this.handleActiveCountChanged.bind(this); - operations$7.stateChange.execute = this.handleNotificationStateChanged.bind(this); - operations$7.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$7); - } - async handleConfigurationChanged(data) { - this.notificationsConfiguration = data.configuration; - this.registry.execute("notifications-config-changed", data.configuration); - } - async handleActiveCountChanged(data) { - this.notificationsActiveCount = data.count; - this.registry.execute("notifications-active-count-changed", data); - } - async handleNotificationStateChanged(data) { - this.registry.execute("notification-state-changed", { id: data.id }, data.state); - } - async handleNotificationShow(data) { - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onshow) { - notification.onshow(); - } - } - async handleNotificationClick(data) { - if (!data.action && this.notificationsSettings?.defaultClick) { - this.notificationsSettings.defaultClick(this.coreGlue, data.definition); - } - if (data.action && this.notificationsSettings?.actionClicks?.some((actionDef) => actionDef.action === data.action)) { - const foundHandler = this.notificationsSettings?.actionClicks?.find((actionDef) => actionDef.action === data.action); - foundHandler.handler(this.coreGlue, data.definition); - } - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onclick) { - notification.onclick(); - delete this.notifications[data.id]; - } - } - async handleNotificationRaised(data) { - this.registry.execute("notification-raised", data.notification); - } - async handleNotificationClosed(data) { - this.registry.execute("notification-closed", data); - } - } - - const operations$6 = { - getIntents: { name: "getIntents", resultDecoder: wrappedIntentsDecoder }, - findIntent: { name: "findIntent", dataDecoder: wrappedIntentFilterDecoder, resultDecoder: wrappedIntentsDecoder }, - raise: { name: "raise", dataDecoder: raiseIntentRequestDecoder, resultDecoder: intentResultDecoder }, - filterHandlers: { name: "filterHandlers", dataDecoder: filterHandlersWithResolverConfigDecoder, resultDecoder: filterHandlersResultDecoder }, - getIntentsByHandler: { name: "getIntentsByHandler", dataDecoder: intentHandlerDecoder, resultDecoder: getIntentsResultDecoder } - }; - - const GLUE42_FDC3_INTENTS_METHOD_PREFIX = "Tick42.FDC3.Intents."; - const INTENTS_RESOLVER_APP_NAME = "intentsResolver"; - const DEFAULT_RESOLVER_RESPONSE_TIMEOUT = 60 * 1000; - const ADDITIONAL_BRIDGE_OPERATION_TIMEOUT = 30 * 1000; - const DEFAULT_PICK_HANDLER_BY_TIMEOUT = 90 * 1000; - - class IntentsController { - bridge; - logger; - interop; - appManagerController; - windowsController; - myIntents = new Set(); - prefsController; - uiController; - useIntentsResolverUI = true; - intentsResolverAppName; - intentResolverResponseTimeout = DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - unregisterIntentPromises = []; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("intents.controller.web"); - this.logger.trace("starting the web intents controller"); - this.bridge = ioc.bridge; - this.interop = coreGlue.interop; - this.appManagerController = ioc.appManagerController; - this.windowsController = ioc.windowsController; - this.prefsController = ioc.prefsController; - this.uiController = ioc.uiController; - this.checkIfIntentsResolverIsEnabled(ioc.config); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"); - coreGlue.intents = api; - } - handlePlatformShutdown() { - this.myIntents = new Set(); - this.unregisterIntentPromises = []; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(intentsOperationTypesDecoder, args.operation); - const operation = operations$6[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - all: this.all.bind(this), - addIntentListener: this.addIntentListener.bind(this), - register: this.register.bind(this), - find: this.find.bind(this), - filterHandlers: this.filterHandlers.bind(this), - getIntents: this.getIntentsByHandler.bind(this), - clearSavedHandlers: this.clearSavedHandlers.bind(this), - onHandlerAdded: this.onHandlerAdded.bind(this), - onHandlerRemoved: this.onHandlerRemoved.bind(this) - }; - return api; - } - async raise(request) { - const validatedIntentRequest = runDecoderWithIOError(raiseRequestDecoder, request); - const intentRequest = typeof validatedIntentRequest === "string" - ? { intent: validatedIntentRequest } - : validatedIntentRequest; - await Promise.all(this.unregisterIntentPromises); - if (intentRequest.clearSavedHandler) { - this.logger.trace(`User removes saved handler for intent ${intentRequest.intent}`); - await this.removeRememberedHandler(intentRequest.intent); - } - const resultFromRememberedHandler = await this.checkHandleRaiseWithRememberedHandler(intentRequest); - if (resultFromRememberedHandler) { - return resultFromRememberedHandler; - } - const requestWithResolverInfo = { - intentRequest, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - const methodResponseTimeoutMs = intentRequest.waitUserResponseIndefinitely - ? MAX_SET_TIMEOUT_DELAY - : (intentRequest.timeout || this.intentResolverResponseTimeout) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(request)} and method response timeout of ${methodResponseTimeoutMs}ms`); - const response = await this.bridge.send("intents", operations$6.raise, requestWithResolverInfo, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }); - this.logger.trace(`Raise operation completed with response: ${JSON.stringify(response)}`); - return response; - } - getLegacyResolverConfigByRequest(filter) { - if (filter.handlerFilter) { - return { - enabled: typeof filter.handlerFilter?.openResolver === "boolean" ? filter.handlerFilter?.openResolver : this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout: filter.handlerFilter?.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT - }; - } - const waitResponseTimeout = filter.intentRequest?.waitUserResponseIndefinitely ? MAX_SET_TIMEOUT_DELAY : this.intentResolverResponseTimeout; - return { - enabled: this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout - }; - } - getEmbeddedResolverConfig() { - return { - enabled: this.uiController.isIntentResolverEnabled(), - initialCaller: { instanceId: this.interop.instance.instance } - }; - } - async all() { - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.getIntents, undefined); - return result.intents; - } - addIntentListener(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - let registerPromise; - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - const result = { - unsubscribe: () => { - this.myIntents.delete(intentName); - registerPromise - .then(() => this.interop.unregister(methodName)) - .catch((err) => this.logger.trace(`Unregistration of a method with name ${methodName} failed with reason: ${err}`)); - } - }; - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - registerPromise = this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - return handler(rest); - } - }); - registerPromise.catch(err => { - this.myIntents.delete(intentName); - this.logger.warn(`Registration of a method with name ${methodName} failed with reason: ${err}`); - }); - return result; - } - async register(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - await Promise.all(this.unregisterIntentPromises); - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - try { - await this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - const caller = this.interop.servers().find((server) => server.instance === _initialCallerId); - return handler(rest, caller); - } - }); - } - catch (err) { - this.myIntents.delete(intentName); - return ioError.raiseError(`Registration of a method with name ${methodName} failed with reason: ${JSON.stringify(err)}`); - } - return { - unsubscribe: () => this.unsubscribeIntent(intentName) - }; - } - async find(intentFilter) { - let data = undefined; - if (typeof intentFilter !== "undefined") { - const intentFilterObj = runDecoderWithIOError(findFilterDecoder, intentFilter); - if (typeof intentFilterObj === "string") { - data = { - filter: { - name: intentFilterObj - } - }; - } - else if (typeof intentFilterObj === "object") { - data = { - filter: intentFilterObj - }; - } - } - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.findIntent, data); - return result.intents; - } - onHandlerAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!"); - } - const unOnAppAdded = this.subscribeForAppEvent("onAppAdded", callback); - const unOnServerMethodAdded = this.subscribeForServerMethodEvent("serverMethodAdded", callback); - return () => { - unOnAppAdded(); - unOnServerMethodAdded(); - }; - } - onHandlerRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!"); - } - const unOnAppRemoved = this.subscribeForAppEvent("onAppRemoved", callback); - const unOnServerMethodRemoved = this.subscribeForServerMethodEvent("serverMethodRemoved", callback); - return () => { - unOnAppRemoved(); - unOnServerMethodRemoved(); - }; - } - subscribeForAppEvent(method, callback) { - return this.appManagerController[method]((app) => { - const appIntents = app.userProperties.intents; - if (!appIntents?.length) { - return; - } - appIntents.forEach((intent) => { - const handler = this.buildIntentHandlerFromApp(app, intent); - callback(handler, intent.name); - }); - }); - } - subscribeForServerMethodEvent(eventMethod, callback) { - return this.interop[eventMethod](async ({ server, method }) => { - if (!method.name.startsWith(GLUE42_FDC3_INTENTS_METHOD_PREFIX)) { - return; - } - const intentName = method.name.replace(GLUE42_FDC3_INTENTS_METHOD_PREFIX, ""); - const handler = await this.buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName); - callback(handler, intentName); - }); - } - buildIntentHandlerFromApp(app, intent) { - const handler = { - applicationName: app.name, - type: "app", - applicationDescription: app.caption, - applicationIcon: app.icon, - applicationTitle: app.title, - contextTypes: intent.contexts, - displayName: intent.displayName, - resultType: intent.resultType, - customConfig: intent.customConfig - }; - return handler; - } - async buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName) { - const info = method.flags.intent; - const app = this.appManagerController.getApplication(server.application || server.applicationName); - let title; - if (eventMethod === "serverMethodAdded" && server.windowId) { - title = await (this.windowsController.findById(server.windowId))?.getTitle(); - } - const appIntent = app?.userProperties?.intents?.find((intent) => intent.name === intentName); - const handler = { - applicationName: server.application || server.applicationName || "", - instanceId: server.windowId || server.instance, - type: "instance", - applicationIcon: info?.icon || app?.icon, - applicationTitle: app?.title, - applicationDescription: info?.description || app?.caption, - contextTypes: info?.contextTypes || appIntent?.contexts, - instanceTitle: title, - displayName: info?.displayName || appIntent?.displayName, - resultType: info?.resultType || appIntent?.resultType, - customConfig: info?.customConfig - }; - return handler; - } - async clearSavedHandlers() { - this.logger.trace("Removing all saved handlers from prefs storage for current app"); - await this.prefsController.update({ intents: undefined }); - } - checkIfIntentsResolverIsEnabled(options) { - this.useIntentsResolverUI = typeof options.intents?.enableIntentsResolverUI === "boolean" - ? options.intents.enableIntentsResolverUI - : true; - this.intentsResolverAppName = options.intents?.intentsResolverAppName ?? INTENTS_RESOLVER_APP_NAME; - this.intentResolverResponseTimeout = options.intents?.methodResponseTimeoutMs ?? DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - } - clearUnregistrationPromise(promiseToRemove) { - this.unregisterIntentPromises = this.unregisterIntentPromises.filter(promise => promise !== promiseToRemove); - } - buildInteropMethodName(intentName) { - return `${GLUE42_FDC3_INTENTS_METHOD_PREFIX}${intentName}`; - } - unsubscribeIntent(intentName) { - this.myIntents.delete(intentName); - const methodName = this.buildInteropMethodName(intentName); - const unregisterPromise = this.interop.unregister(methodName); - this.unregisterIntentPromises.push(unregisterPromise); - unregisterPromise - .then(() => { - this.clearUnregistrationPromise(unregisterPromise); - }) - .catch((err) => { - this.logger.error(`Unregistration of a method with name ${methodName} failed with reason: ${err}`); - this.clearUnregistrationPromise(unregisterPromise); - }); - } - async filterHandlers(handlerFilter) { - runDecoderWithIOError(handlerFilterDecoder, handlerFilter); - this.checkIfAtLeastOneFilterIsPresent(handlerFilter); - const embeddedResolverConfig = this.getEmbeddedResolverConfig(); - if (handlerFilter.openResolver && !this.useIntentsResolverUI && !embeddedResolverConfig.enabled) { - return ioError.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled"); - } - const methodResponseTimeoutMs = (handlerFilter.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - const filterHandlersRequestWithResolverConfig = { - filterHandlersRequest: handlerFilter, - resolverConfig: this.getLegacyResolverConfigByRequest({ handlerFilter }), - embeddedResolverConfig - }; - const result = await this.bridge.send("intents", operations$6.filterHandlers, filterHandlersRequestWithResolverConfig, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }, { includeOperationCheck: true }); - return result; - } - checkIfAtLeastOneFilterIsPresent(filter) { - const errorMsg = "Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'"; - if (!Object.keys(filter).length) { - return ioError.raiseError(errorMsg); - } - const { intent, resultType, contextTypes, applicationNames } = filter; - const existingValidContextTypes = contextTypes?.length; - const existingValidApplicationNames = applicationNames?.length; - if (!intent && !resultType && !existingValidContextTypes && !existingValidApplicationNames) { - return ioError.raiseError(errorMsg); - } - } - async getIntentsByHandler(handler) { - runDecoderWithIOError(intentHandlerDecoder, handler); - const result = await this.bridge.send("intents", operations$6.getIntentsByHandler, handler, undefined, { includeOperationCheck: true }); - return result; - } - async removeRememberedHandler(intentName) { - this.logger.trace(`Removing saved handler from prefs storage for intent ${intentName}`); - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const intentPrefs = prefs.data?.intents; - if (!intentPrefs) { - this.logger.trace("No app prefs found for current app"); - return; - } - delete intentPrefs[intentName]; - const updatedPrefs = { - ...prefs.data, - intents: intentPrefs - }; - try { - await this.prefsController.update(updatedPrefs); - } - catch (error) { - this.logger.warn(`prefs.update() threw the following error: ${error}`); - return; - } - this.logger.trace(`Handler saved choice for intent ${intentName} removed successfully`); - } - async checkForRememberedHandler(intentRequest) { - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const prefsForIntent = prefs.data?.intents?.[intentRequest.intent]; - return prefsForIntent?.handler; - } - async checkHandleRaiseWithRememberedHandler(intentRequest) { - if (intentRequest.target) { - return; - } - const rememberedHandler = await this.checkForRememberedHandler(intentRequest); - if (!rememberedHandler) { - return; - } - const operationData = { - intentRequest: { - ...intentRequest, - target: { - app: rememberedHandler.applicationName, - instance: rememberedHandler.instanceId - } - }, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - try { - const response = await this.bridge.send("intents", operations$6.raise, operationData); - return response; - } - catch (error) { - this.logger.trace(`Could not raise intent to remembered handler. Reason: ${error}. Removing it from Prefs store`); - await this.removeRememberedHandler(intentRequest.intent); - } - } - } - - const operations$5 = { - appHello: { name: "appHello", dataDecoder: channelsAppHelloDataDecoder, resultDecoder: channelsAppHelloSuccessDecoder }, - addChannel: { name: "addChannel", dataDecoder: channelDefinitionDecoder }, - removeChannel: { name: "removeChannel", dataDecoder: removeChannelDataDecoder }, - getMyChannel: { name: "getMyChannel", resultDecoder: getMyChanelResultDecoder }, - getWindowIdsOnChannel: { name: "getWindowIdsOnChannel", dataDecoder: getWindowIdsOnChannelDataDecoder, resultDecoder: getWindowIdsOnChannelResultDecoder }, - getWindowIdsWithChannels: { name: "getWindowIdsWithChannels", dataDecoder: wrappedWindowWithChannelFilterDecoder, resultDecoder: getWindowIdsWithChannelsResultDecoder }, - joinChannel: { name: "joinChannel", dataDecoder: joinChannelDataDecoder }, - restrict: { name: "restrict", dataDecoder: restrictionConfigDataDecoder }, - getRestrictions: { name: "getRestrictions", dataDecoder: getRestrictionsDataDecoder, resultDecoder: restrictionsDecoder }, - restrictAll: { name: "restrictAll", dataDecoder: restrictAllDataDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - leaveChannel: { name: "leaveChannel", dataDecoder: leaveChannelDataDecoder }, - requestChannelSelector: { name: "requestChannelSelector", dataDecoder: requestChannelSelectorConfigDecoder }, - getMode: { name: "getMode", resultDecoder: getChannelsModeDecoder }, - operationCheck: { name: "operationCheck" }, - }; - - const DEFAULT_MODE = "single"; - const CHANNELS_PREFIX = "___channel___"; - const SUBS_KEY = "subs"; - const CHANGED_KEY = "changed"; - const CHANNELS_CHANGED = "channels_changed"; - const STORAGE_NAMESPACE = "io_connect_channels"; - const DEFAULT_STORAGE_MODE = "inMemory"; - - class ChannelsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - contexts; - interop; - bridge; - windowsController; - _mode; - myWindowId; - storage; - handlePlatformShutdown() { - this.registry.clear(); - this.storage.clear(); - } - addOperationsExecutors() { - operations$5.getMyChannel.execute = this.handleGetMyChannel.bind(this); - operations$5.joinChannel.execute = this.handleJoinChannel.bind(this); - operations$5.leaveChannel.execute = this.handleLeaveChannel.bind(this); - operations$5.restrict.execute = this.handleRestrict.bind(this); - operations$5.getRestrictions.execute = ({ windowId }) => this.getRestrictions(windowId); - operations$5.restrictAll.execute = this.handleRestrictAll.bind(this); - operations$5.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$5); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("channels.controller.web"); - this.logger.trace("starting the web channels controller"); - this.contexts = coreGlue.contexts; - this.interop = coreGlue.interop; - this.addOperationsExecutors(); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.storage = ioc.channelsStorage; - this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"); - this.myWindowId = this.windowsController.my().id ?? this.interop.instance.instance; - await this.initialize(); - const api = this.toApi(); - coreGlue.channels = api; - } - async postStart(io, ioc) { - try { - await this.requestChannelSelector(io.appManager.myInstance); - } - catch (error) { - this.logger.warn(`Failed to display channel selector: ${extractErrorMsg(error)}`); - } - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(channelsOperationTypesDecoder, args.operation); - const operation = operations$5[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async list() { - const channelNames = this.getAllChannelNames(); - const channelContexts = await Promise.all(channelNames.map((channelName) => this.get(channelName))); - return channelContexts; - } - my() { - return this.current(); - } - async handleGetMyChannel() { - const channel = this.my(); - return channel ? { channel } : {}; - } - async join(name, windowId) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const joinData = { channel: name, windowId: windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.joinChannel, joinData, undefined, { includeOperationCheck: true }); - } - handleJoinChannel({ channel }) { - if (this._mode === "single") { - return this.switchToChannel(channel); - } - return this.joinAdditionalChannel(channel); - } - onChanged(callback) { - return this.changed(callback); - } - async leave(config = {}) { - runDecoderWithIOError(leaveChannelsConfig, config); - if (config.channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.channel); - } - const leaveData = { channelName: config.channel, windowId: config.windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.leaveChannel, leaveData, undefined, { includeOperationCheck: true }); - } - async handleAppManagerInitialChannelId(channel) { - if (this.storage.mode === "inMemory") { - return; - } - if (this.storage.getSessionStorageData()) { - return; - } - return this.handleJoinChannel({ channel, windowId: this.myWindowId }); - } - async handleLeaveChannel({ channelName }) { - const channelNamesToLeave = channelName ? [channelName] : this.storage.channels; - channelNamesToLeave.forEach((name) => this.storage.invokeUnsubscribes(name)); - this.storage.channels = this.storage.channels.filter((channelName) => !channelNamesToLeave.includes(channelName)); - this.executeChangedEvents(); - await this.notifyChannelsChanged(); - } - toApi() { - const api = { - mode: this._mode, - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - publish: this.publish.bind(this), - all: this.all.bind(this), - list: this.list.bind(this), - get: this.get.bind(this), - getMyChannels: this.getMyChannels.bind(this), - myChannels: this.myChannels.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - join: this.join.bind(this), - leave: this.leave.bind(this), - current: this.current.bind(this), - my: this.my.bind(this), - changed: this.changed.bind(this), - onChanged: this.onChanged.bind(this), - add: this.add.bind(this), - remove: this.remove.bind(this), - getMy: this.getMy.bind(this), - getWindowsOnChannel: this.getWindowsOnChannel.bind(this), - getWindowsWithChannels: this.getWindowsWithChannels.bind(this), - restrict: this.restrict.bind(this), - getRestrictions: this.getRestrictions.bind(this), - restrictAll: this.restrictAll.bind(this), - clearChannelData: this.clearChannelData.bind(this), - setPath: this.setPath.bind(this), - setPaths: this.setPaths.bind(this) - }; - return Object.freeze(api); - } - createContextName(channelName) { - return `${CHANNELS_PREFIX}${channelName}`; - } - getAllChannelNames() { - const contextNames = this.contexts.all(); - const channelContextNames = contextNames.filter((contextName) => contextName.startsWith(CHANNELS_PREFIX)); - const channelNames = channelContextNames.map((channelContextName) => channelContextName.replace(CHANNELS_PREFIX, "")); - return channelNames; - } - async joinAdditionalChannel(name) { - if (this.storage.channels.includes(name)) { - return; - } - this.storage.channels = [...this.storage.channels, name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - async switchToChannel(name) { - const currentChannel = this.storage.channels[0]; - if (name === currentChannel) { - return; - } - this.storage.invokeUnsubscribes(currentChannel); - this.storage.channels = [name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - executeChangedEvents(name) { - this.registry.execute(CHANGED_KEY, name); - this.registry.execute(CHANNELS_CHANGED, this.storage.channels); - } - async notifyChannelsChanged() { - const windowId = this.windowsController.my().id; - if (!windowId) { - return; - } - try { - await this.bridge.send("channels", operations$5.notifyChannelsChanged, { channelNames: this.storage.channels, windowId }, undefined, { includeOperationCheck: true }); - } - catch (error) { - this.logger.warn(`Failed to notify channel changed: ${extractErrorMsg(error)}`); - } - } - async updateData(name, data) { - const contextName = this.createContextName(name); - const fdc3Type = this.getFDC3Type(data); - if (this.contexts.setPathSupported) { - const pathValues = Object.keys(data).map((key) => { - return { - path: `data.${key}`, - value: data[key] - }; - }); - if (fdc3Type) { - pathValues.push({ path: latestFDC3Type, value: fdc3Type }); - } - await this.contexts.setPaths(contextName, pathValues); - } - else { - if (fdc3Type) { - data[latestFDC3Type] = fdc3Type; - } - await this.contexts.update(contextName, { data }); - } - } - getFDC3Type(data) { - const fdc3PropsArr = Object.keys(data).filter((key) => key.indexOf("fdc3_") === 0); - if (fdc3PropsArr.length === 0) { - return; - } - if (fdc3PropsArr.length > 1) { - return ioError.raiseError("FDC3 does not support updating of multiple context keys"); - } - return fdc3PropsArr[0].split("_").slice(1).join("_"); - } - subscribe(callback, options) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels, because the provided callback is not a function!"); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const currentChannel = this.current(); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - if (currentChannel) { - this.replaySubscribe(wrappedCallback, currentChannel); - } - return this.registry.add(SUBS_KEY, wrappedCallback); - } - async subscribeFor(name, callback, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (typeof callback !== "function") { - return ioError.raiseError(`Cannot subscribe to channel ${name}, because the provided callback is not a function!`); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - wrappedCallback(context.data, context, delta, extraData?.updaterId); - }); - } - async publish(data, options) { - if (typeof data !== "object") { - return ioError.raiseError("Cannot publish to channel, because the provided data is not an object!"); - } - runDecoderWithIOError(publishOptionsDecoder, options); - if (typeof options === "object") { - return this.publishWithOptions(data, options); - } - if (typeof options === "string") { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options); - } - if (!options && this.storage.channels.length > 1) { - return this.publishOnMultipleChannels(data); - } - const channelName = typeof options === "string" ? options : this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - return this.updateData(channelName, data); - } - async all() { - const channelNames = this.getAllChannelNames(); - return channelNames; - } - async get(name, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const channelContext = await this.contexts.get(contextName); - if (options?.contextType) { - return this.getContextForFdc3Type(channelContext, options.contextType); - } - if (channelContext.latest_fdc3_type) { - return this.getContextWithFdc3Data(channelContext); - } - return channelContext; - } - async getMyChannels() { - return Promise.all(this.storage.channels.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.get(contextName); - })); - } - myChannels() { - return this.storage.channels; - } - getContextForFdc3Type(channelContext, searchedType) { - const encodedType = `fdc3_${searchedType.split(".").join("&")}`; - if (!channelContext.data[encodedType]) { - return { - name: channelContext.name, - meta: channelContext.meta, - data: {} - }; - } - const fdc3Context = { type: searchedType, ...channelContext.data[encodedType] }; - return { - name: channelContext.name, - meta: channelContext.meta, - data: { fdc3: fdc3Context } - }; - } - getContextWithFdc3Data(channelContext) { - const { latest_fdc3_type, ...rest } = channelContext; - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Context = { type: parsedType, ...rest.data[`fdc3_${latest_fdc3_type}`] }; - delete rest.data[`fdc3_${latest_fdc3_type}`]; - const context = { - name: channelContext.name, - meta: channelContext.meta, - data: { - ...rest.data, - fdc3: fdc3Context - } - }; - return context; - } - current() { - return this.storage.channels[0]; - } - changed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"); - } - return this.registry.add(CHANGED_KEY, callback); - } - async add(info) { - const channelContext = runDecoderWithIOError(channelDefinitionDecoder, info); - const channelWithSuchNameExists = this.getAllChannelNames().includes(channelContext.name); - if (channelWithSuchNameExists) { - return ioError.raiseError("There's an already existing channel with such name"); - } - await this.bridge.send("channels", operations$5.addChannel, channelContext); - return { - name: channelContext.name, - meta: channelContext.meta, - data: channelContext.data || {} - }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - const channelWithSuchNameExists = this.getAllChannelNames().includes(name); - if (!channelWithSuchNameExists) { - return ioError.raiseError("There's no channel with such name"); - } - await this.bridge.send("channels", operations$5.removeChannel, { name }, undefined, { includeOperationCheck: true }); - } - replaySubscribe = (callback, channelId) => { - this.get(channelId) - .then((channelContext) => { - if (!channelContext) { - return undefined; - } - const contextName = this.createContextName(channelContext.name); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - callback(context.data, context, delta, extraData?.updaterId); - }); - }) - .then((un) => un?.()) - .catch(err => this.logger.trace(err)); - }; - async getMy(options) { - if (!this.storage.channels.length) { - return; - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - return this.get(this.storage.channels[this.storage.channels.length - 1], options); - } - async getWindowsOnChannel(channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), channel); - const { windowIds } = await this.bridge.send("channels", operations$5.getWindowIdsOnChannel, { channel }, undefined, { includeOperationCheck: true }); - const result = windowIds.reduce((windows, windowId) => { - const window = this.windowsController.findById(windowId); - return window ? [...windows, window] : windows; - }, []); - return result; - } - async getWindowsWithChannels(filter) { - const operationData = filter !== undefined - ? { filter: runDecoderWithIOError(windowWithChannelFilterDecoder, filter) } - : {}; - const { windowIdsWithChannels } = await this.bridge.send("channels", operations$5.getWindowIdsWithChannels, operationData, undefined, { includeOperationCheck: true }); - const result = windowIdsWithChannels.reduce((windowsWithChannels, { application, channel, windowId }) => { - const window = this.windowsController.findById(windowId); - return window ? [...windowsWithChannels, { application, channel, window }] : windowsWithChannels; - }, []); - return result; - } - async clearChannelData(name) { - const paths = [ - { path: "data", value: {} }, - { path: "latest_fdc3_type", value: null }, - ]; - await this.handleSetPaths("clearChannelData", paths, name); - } - async restrict(config) { - runDecoderWithIOError(channelRestrictionsDecoder, config); - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.name); - const configData = { - config: { - ...config, - windowId: config.windowId ?? this.myWindowId - } - }; - await this.bridge.send("channels", operations$5.restrict, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrict({ config }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateRestriction(config); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateRestriction(config); - const isForCurrentChannel = config.name === currentChannel.name; - if (!isForCurrentChannel || prevReadAllowed || !config.read) { - return; - } - this.replaySubscribeCallback(config.name); - } - updateRestriction(config) { - const exists = this.storage.restrictions.some((r) => r.name === config.name); - this.storage.restrictions = exists - ? this.storage.restrictions.map((restriction) => restriction.name === config.name ? config : restriction) - : this.storage.restrictions.concat(config); - } - updateAllRestrictions(config) { - const allChannelNames = this.getAllChannelNames(); - this.storage.restrictions = allChannelNames.map((name) => ({ name, ...config })); - } - async getRestrictions(windowId) { - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const forAnotherClient = windowId && windowId !== this.interop.instance.instance; - if (windowId && forAnotherClient) { - return this.bridge.send("channels", operations$5.getRestrictions, { windowId }, undefined, { includeOperationCheck: true }); - } - return { channels: this.storage.restrictions }; - } - async restrictAll(restrictions) { - runDecoderWithIOError(restrictionsConfigDecoder, restrictions); - const configData = { - restrictions: { - ...restrictions, - windowId: restrictions.windowId ?? this.myWindowId - } - }; - return this.bridge.send("channels", operations$5.restrictAll, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrictAll({ restrictions }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateAllRestrictions(restrictions); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateAllRestrictions(restrictions); - if (prevReadAllowed || !restrictions.read) { - return; - } - this.replaySubscribeCallback(currentChannel.name); - } - async setPath(path, name) { - const validatedPath = runDecoderWithIOError(pathValueDecoder, path); - const paths = [{ path: `data.${validatedPath.path}`, value: validatedPath.value }]; - await this.handleSetPaths("setPath", paths, name); - } - async setPaths(paths, name) { - const validatedPaths = runDecoderWithIOError(pathsValueDecoder, paths); - const dataPaths = validatedPaths.map(({ path, value }) => ({ path: `data.${path}`, value })); - await this.handleSetPaths("setPaths", dataPaths, name); - } - async handleSetPaths(operation, paths, name) { - const channelNamesToUpdate = name ? [name] : this.storage.channels; - if (!channelNamesToUpdate.length) { - return ioError.raiseError(`Cannot complete ${operation} operation, because channel is not specified. Either join one or pass a channel name as second argument!`); - } - this.validateChannelNames(channelNamesToUpdate); - const { allowed, forbidden } = this.groupChannelsByPermission("write", channelNamesToUpdate); - if (channelNamesToUpdate.length === forbidden.length) { - return ioError.raiseError(`Cannot complete ${operation} operation due to write restrictions to the following channels: ${channelNamesToUpdate.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Cannot set paths on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} due to write restrictions`); - } - await Promise.all(allowed.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.setPaths(contextName, paths); - })); - } - validateChannelNames(names) { - const allChannelNames = this.getAllChannelNames(); - names.forEach((name) => runDecoderWithIOError(channelNameDecoder(allChannelNames), name)); - } - groupChannelsByPermission(action, channelNames) { - return channelNames.reduce((byFar, channelName) => { - const isAllowed = this.isAllowedByRestrictions(channelName, action); - if (isAllowed) { - byFar.allowed.push(channelName); - } - else { - byFar.forbidden.push(channelName); - } - return byFar; - }, { allowed: [], forbidden: [] }); - } - isAllowedByRestrictions(channelName, action) { - const restriction = this.storage.restrictions.find((restriction) => restriction.name === channelName); - return restriction ? restriction[action] : true; - } - replaySubscribeCallback(channelName) { - const contextName = this.createContextName(channelName); - this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }).then((unsub) => { - if (unsub && typeof unsub === "function") { - unsub(); - } - }).catch(err => this.logger.error(err)); - } - async publishWithOptions(data, options) { - if (options.name) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options.name); - } - const publishOnMultipleChannels = options.name ? false : this.storage.channels.length > 1; - if (publishOnMultipleChannels) { - return this.publishOnMultipleChannels(data, options.fdc3); - } - const channelName = options.name || this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - if (!options.fdc3) { - return this.updateData(channelName, data); - } - return this.publishFdc3Data(channelName, data); - } - async publishOnMultipleChannels(data, isFdc3) { - const { allowed, forbidden } = this.groupChannelsByPermission("write", this.storage.channels); - if (this.storage.channels.length === forbidden.length) { - return ioError.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Data on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} won't be published due to write restrictions`); - } - const publishMethod = isFdc3 ? this.publishFdc3Data.bind(this) : this.updateData.bind(this); - await Promise.all(allowed.map((channelName) => publishMethod(channelName, data))); - } - async publishFdc3Data(channelName, data) { - runDecoderWithIOError(fdc3ContextDecoder, data); - const { type, ...rest } = data; - const parsedType = type.split(".").join("&"); - const fdc3DataToPublish = { [`fdc3_${parsedType}`]: rest }; - return this.updateData(channelName, fdc3DataToPublish); - } - getWrappedSubscribeCallback(callback) { - const wrappedCallback = (channelData, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const latestTypePropName = `fdc3_${latest_fdc3_type}`; - if (!latest_fdc3_type || (delta.data && !delta.data[latestTypePropName])) { - callback(channelData, context, updaterId); - return; - } - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Data = { type: parsedType, ...data[latestTypePropName] }; - const { [latestTypePropName]: latestFDC3Type, ...rest } = channelData; - callback({ ...rest, fdc3: fdc3Data }, context, updaterId); - }; - return wrappedCallback; - } - getWrappedSubscribeCallbackWithFdc3Type(callback, fdc3Type) { - const didReplay = { replayed: false }; - const wrappedCallback = (_, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const searchedType = `fdc3_${fdc3Type.split(".").join("&")}`; - if (!data[searchedType] || (delta.data && !delta.data[searchedType])) { - return; - } - if (didReplay.replayed) { - return this.parseDataAndInvokeSubscribeCallback({ latestFdc3TypeEncoded: latest_fdc3_type, searchedType: fdc3Type, callback, context, updaterId }); - } - const fdc3Data = { type: fdc3Type, ...data[searchedType] }; - callback({ fdc3: fdc3Data }, context, updaterId); - didReplay.replayed = true; - }; - return wrappedCallback; - } - parseDataAndInvokeSubscribeCallback(args) { - const { latestFdc3TypeEncoded, searchedType, callback, context, updaterId } = args; - const latestPublishedType = latestFdc3TypeEncoded.split("&").join("."); - if (latestPublishedType !== searchedType) { - return; - } - const fdc3Data = { type: searchedType, ...context.data[`fdc3_${latestFdc3TypeEncoded}`] }; - callback({ fdc3: fdc3Data }, context, updaterId); - } - async requestChannelSelector(myInstance) { - if (!myInstance) { - return; - } - const myApplicationData = myInstance.application; - const myAppDetails = myApplicationData.userProperties?.details; - if (!myAppDetails) { - return; - } - if (!myAppDetails?.channelSelector?.enabled) { - return; - } - const windowId = myInstance.id; - const requestChannelSelectorConfig = { windowId, channelsNames: this.storage.channels }; - await this.bridge.send("channels", operations$5.requestChannelSelector, requestChannelSelectorConfig, undefined, { includeOperationCheck: true }); - } - async getPlatformChannelsMode() { - try { - const result = await this.bridge.send("channels", operations$5.getMode, {}, undefined, { includeOperationCheck: true }); - return result.mode; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - return DEFAULT_MODE; - } - } - onChannelsChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"); - } - return this.registry.add(CHANNELS_CHANGED, callback); - } - async initialize() { - const isAppHelloSupported = await this.checkIfAppHelloSupported(); - if (!isAppHelloSupported) { - return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions"); - } - const { success, error } = await this.sendAppHello(); - if (error) { - return this.handleAppHelloFailure(error); - } - this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(success)}`); - const { mode, channels, restrictions } = success; - this.storage.mode = "inMemory"; - this._mode = mode; - this.storage.channels = channels; - this.storage.restrictions = restrictions; - } - async handleAppHelloFailure(errorMsg) { - this.logger.trace(errorMsg); - this.storage.mode = "sessionStorage"; - this._mode = await this.getPlatformChannelsMode(); - } - async sendAppHello() { - try { - const result = await this.bridge.send("channels", operations$5.appHello, { windowId: this.myWindowId }, undefined, { includeOperationCheck: true }); - return { success: result, error: undefined }; - } - catch (error) { - return { error: `Failed to get initial state from platform. Error: ${extractErrorMsg(error)}`, success: undefined }; - } - } - async checkIfAppHelloSupported() { - try { - const { isSupported } = await this.bridge.send("channels", operations$5.operationCheck, { operation: operations$5.appHello.name }, undefined, { includeOperationCheck: true }); - return isSupported; - } - catch (error) { - this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${extractErrorMsg(error)}`); - return false; - } - } - } - - const operations$4 = { - getEnvironment: { name: "getEnvironment", resultDecoder: anyDecoder }, - getBase: { name: "getBase", resultDecoder: anyDecoder }, - platformShutdown: { name: "platformShutdown" }, - isFdc3DataWrappingSupported: { name: "isFdc3DataWrappingSupported" }, - clientError: { name: "clientError", dataDecoder: clientErrorDataDecoder }, - systemHello: { name: "systemHello", resultDecoder: systemHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class SystemController { - supportedOperationsNames = []; - bridge; - ioc; - logger; - errorPort = errorChannel.port2; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("system.controller.web"); - this.logger.trace("starting the web system controller"); - this.bridge = ioc.bridge; - this.ioc = ioc; - this.addOperationsExecutors(); - let isClientErrorOperationSupported = false; - try { - const systemHelloSuccess = await this.bridge.send("system", operations$4.systemHello, undefined, undefined, { includeOperationCheck: true }); - isClientErrorOperationSupported = systemHelloSuccess.isClientErrorOperationSupported; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support some system operations."); - } - this.errorPort.onmessage = async (event) => { - if (!isClientErrorOperationSupported) { - return; - } - await this.bridge.send("system", operations$4.clientError, { message: event.data }, undefined, { includeOperationCheck: true }); - }; - await this.setEnvironment(); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(systemOperationTypesDecoder, args.operation); - const operation = operations$4[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async processPlatformShutdown() { - Object.values(this.ioc.controllers).forEach((controller) => controller.handlePlatformShutdown ? controller.handlePlatformShutdown() : null); - this.ioc.preferredConnectionController.stop(); - this.ioc.eventsDispatcher.stop(); - await this.bridge.stop(); - } - async setEnvironment() { - const environment = await this.bridge.send("system", operations$4.getEnvironment, undefined); - const base = await this.bridge.send("system", operations$4.getBase, undefined); - const globalNamespace = window.glue42core || window.iobrowser; - const globalNamespaceName = window.glue42core ? "glue42core" : "iobrowser"; - const globalObj = Object.assign({}, globalNamespace, base, { environment }); - window[globalNamespaceName] = globalObj; - } - addOperationsExecutors() { - operations$4.platformShutdown.execute = this.processPlatformShutdown.bind(this); - operations$4.isFdc3DataWrappingSupported.execute = this.handleIsFdc3DataWrappingSupported.bind(this); - operations$4.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$4); - } - async handleIsFdc3DataWrappingSupported() { - return { isSupported: true }; - } - } - - class Notification { - onclick = () => { }; - onshow = () => { }; - id; - title; - badge; - body; - data; - dir; - icon; - image; - lang; - renotify; - requireInteraction; - silent; - tag; - timestamp; - vibrate; - clickInterop; - actions; - focusPlatformOnDefaultClick; - severity; - showToast; - showInPanel; - state; - constructor(config, id) { - this.id = id; - this.badge = config.badge; - this.body = config.body; - this.data = config.data; - this.dir = config.dir; - this.icon = config.icon; - this.image = config.image; - this.lang = config.lang; - this.renotify = config.renotify; - this.requireInteraction = config.requireInteraction; - this.silent = config.silent; - this.tag = config.tag; - this.timestamp = config.timestamp; - this.vibrate = config.vibrate; - this.title = config.title; - this.clickInterop = config.clickInterop; - this.actions = config.actions; - this.focusPlatformOnDefaultClick = config.focusPlatformOnDefaultClick; - this.severity = config.severity; - this.showToast = config.showToast; - this.showInPanel = config.showInPanel; - this.state = config.state; - } - } - - oneOf$1(constant$2("clientHello")); - const extensionConfigDecoder = object$2({ - widget: object$2({ - inject: boolean$2() - }) - }); - - const operations$3 = { - clientHello: { name: "clientHello", resultDecoder: extensionConfigDecoder } - }; - - class ExtController { - windowId; - logger; - bridge; - eventsDispatcher; - channelsController; - config; - channels = []; - unsubFuncs = []; - contentCommands = { - widgetVisualizationPermission: { name: "widgetVisualizationPermission", handle: this.handleWidgetVisualizationPermission.bind(this) }, - changeChannel: { name: "changeChannel", handle: this.handleChangeChannel.bind(this) } - }; - handlePlatformShutdown() { - this.unsubFuncs.forEach((unsub) => unsub()); - this.channels = []; - this.unsubFuncs = []; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("extension.controller.web"); - this.windowId = ioc.publicWindowId; - this.logger.trace("starting the extension web controller"); - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.eventsDispatcher = ioc.eventsDispatcher; - try { - await this.registerWithPlatform(); - } - catch (error) { - return; - } - this.channels = await this.channelsController.list(); - const unsubDispatcher = this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)); - const unsubChannels = this.channelsController.onChanged((channel) => { - this.eventsDispatcher.sendContentMessage({ command: "channelChange", newChannel: channel }); - }); - this.unsubFuncs.push(unsubDispatcher); - this.unsubFuncs.push(unsubChannels); - } - async handleBridgeMessage(_) { - } - handleContentMessage(message) { - if (!message || typeof message.command !== "string") { - return; - } - const foundHandler = this.contentCommands[message.command]; - if (!foundHandler) { - return; - } - foundHandler.handle(message); - } - async registerWithPlatform() { - this.logger.trace("registering with the platform"); - this.config = await this.bridge.send("extension", operations$3.clientHello, { windowId: this.windowId }); - this.logger.trace("the platform responded to the hello message with a valid extension config"); - } - async handleWidgetVisualizationPermission() { - if (!this.config?.widget.inject) { - return this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: false }); - } - const currentChannel = this.channels.find((channel) => channel.name === this.channelsController.my()); - this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: true, channels: this.channels, currentChannel }); - } - async handleChangeChannel(message) { - if (message.name === "no-channel") { - await this.channelsController.leave(); - return; - } - await this.channelsController.join(message.name); - } - } - - class EventsDispatcher { - config; - glue; - registry = CallbackRegistryFactory$1(); - glue42EventName = "Glue42"; - _handleMessage; - _resolveWidgetReadyPromise; - _resolveModalsUIFactoryReadyPromise; - _resolveIntentResolverUIFactoryReadyPromise; - constructor(config) { - this.config = config; - } - events = { - notifyStarted: { name: "notifyStarted", handle: this.handleNotifyStarted.bind(this) }, - contentInc: { name: "contentInc", handle: this.handleContentInc.bind(this) }, - requestGlue: { name: "requestGlue", handle: this.handleRequestGlue.bind(this) }, - widgetFactoryReady: { name: "widgetFactoryReady", handle: this.handleWidgetReady.bind(this) }, - modalsUIFactoryReady: { name: "modalsUIFactoryReady", handle: this.handleModalsUIFactoryReady.bind(this) }, - intentResolverUIFactoryReady: { name: "intentResolverUIFactoryReady", handle: this.handleIntentResolverUIFactoryReady.bind(this) }, - }; - stop() { - window.removeEventListener(this.glue42EventName, this._handleMessage); - } - start(glue) { - this.glue = glue; - this.wireCustomEventListener(); - this.announceStarted(); - } - sendContentMessage(message) { - this.send("contentOut", "glue42core", message); - } - onContentMessage(callback) { - return this.registry.add("content-inc", callback); - } - async widgetReady() { - const widgetReadyPromise = new Promise((resolve) => { - this._resolveWidgetReadyPromise = resolve; - }); - this.requestWidgetReady(); - return widgetReadyPromise; - } - async modalsUIFactoryReady() { - const modalsUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveModalsUIFactoryReadyPromise = resolve; - }); - this.requestModalsUIFactoryReady(); - return modalsUIFactoryReadyPromise; - } - async intentResolverUIFactoryReady() { - const intentResolverUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveIntentResolverUIFactoryReadyPromise = resolve; - }); - this.requestIntentResolverUIFactoryReady(); - return intentResolverUIFactoryReadyPromise; - } - wireCustomEventListener() { - this._handleMessage = this.handleMessage.bind(this); - window.addEventListener(this.glue42EventName, this._handleMessage); - } - handleMessage(event) { - const data = event.detail; - const namespace = data?.glue42 ?? data?.glue42core; - if (!namespace) { - return; - } - const glue42Event = namespace.event; - const foundHandler = this.events[glue42Event]; - if (!foundHandler) { - return; - } - foundHandler.handle(namespace.message); - } - announceStarted() { - this.send("start", "glue42"); - } - handleRequestGlue() { - if (!this.config.exposeAPI) { - this.send("requestGlueResponse", "glue42", { error: "Will not give access to the underlying Glue API, because it was explicitly denied upon initialization." }); - return; - } - this.send("requestGlueResponse", "glue42", { glue: this.glue }); - } - handleNotifyStarted() { - this.announceStarted(); - } - handleContentInc(message) { - this.registry.execute("content-inc", message); - } - requestWidgetReady() { - this.send(REQUEST_WIDGET_READY, "glue42"); - } - handleWidgetReady() { - this._resolveWidgetReadyPromise?.(); - } - requestModalsUIFactoryReady() { - this.send(REQUEST_MODALS_UI_FACTORY_READY, "glue42"); - } - handleModalsUIFactoryReady() { - this._resolveModalsUIFactoryReadyPromise?.(); - } - requestIntentResolverUIFactoryReady() { - this.send(REQUEST_INTENT_RESOLVER_UI_FACTORY_READY, "glue42"); - } - handleIntentResolverUIFactoryReady() { - this._resolveIntentResolverUIFactoryReadyPromise?.(); - } - send(eventName, namespace, message) { - const payload = {}; - payload[namespace] = { event: eventName, message }; - const event = new CustomEvent(this.glue42EventName, { detail: payload }); - window.dispatchEvent(event); - } - } - - class PreferredConnectionController { - coreGlue; - transactionTimeout = 15000; - transactionLocks = {}; - webPlatformTransport; - webPlatformMessagesUnsubscribe; - reconnectCounter = 0; - logger; - constructor(coreGlue) { - this.coreGlue = coreGlue; - this.logger = this.coreGlue.logger.subLogger("web.preferred.connection.controller"); - } - stop() { - if (!this.webPlatformMessagesUnsubscribe) { - return; - } - this.webPlatformMessagesUnsubscribe(); - } - async start(coreConfig) { - if (coreConfig.isPlatformInternal) { - this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic."); - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - if (!isConnectedToPlatform) { - return ioError.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport."); - } - if (!this.coreGlue.connection.transport.isPreferredActivated) { - this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization."); - return; - } - this.webPlatformTransport = this.coreGlue.connection.transport; - this.webPlatformMessagesUnsubscribe = this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this)); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - handleWebPlatformMessage(msg) { - if (typeof msg === "string") { - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - const type = msg.type; - const args = msg.args; - const transactionId = msg.transactionId; - if (type === Glue42CoreMessageTypes.transportSwitchRequest.name) { - return this.handleTransportSwitchRequest(args, transactionId); - } - if (type === Glue42CoreMessageTypes.platformUnload.name && !isConnectedToPlatform) { - return this.handlePlatformUnload(); - } - if (type === Glue42CoreMessageTypes.getCurrentTransportResponse.name) { - return this.handleGetCurrentTransportResponse(args, transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredLogic.name) { - return this.handleCheckPreferredLogic(transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredConnection.name) { - return this.handleCheckPreferredConnection(args, transactionId); - } - } - async reEstablishPlatformPort() { - try { - await this.webPlatformTransport.connect(); - } - catch (error) { - this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(error)}`); - --this.reconnectCounter; - if (this.reconnectCounter > 0) { - return this.reEstablishPlatformPort(); - } - this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform."); - } - this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."); - this.reconnectCounter = 0; - this.webPlatformTransport.close(); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - async checkSwitchTransport(config) { - const myCurrentTransportName = this.coreGlue.connection.transport.name(); - if (myCurrentTransportName === config.transportName) { - this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary"); - return; - } - this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${myCurrentTransportName}, but it should reconnect to ${JSON.stringify(config)}`); - const result = await this.coreGlue.connection.switchTransport(config); - this.setConnected(); - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - } - async getCurrentPlatformTransportState() { - this.logger.trace("Requesting the current transport state of the platform."); - const transaction = this.setTransaction(Glue42CoreMessageTypes.getCurrentTransport.name); - this.sendPlatformMessage(Glue42CoreMessageTypes.getCurrentTransport.name, transaction.id); - const transportState = await transaction.lock; - this.logger.trace(`The platform responded with transport state: ${JSON.stringify(transportState)}`); - return transportState; - } - setTransaction(operation) { - const transaction = {}; - const transactionId = nanoid$1(10); - const transactionLock = new Promise((resolve, reject) => { - let transactionLive = true; - transaction.lift = (args) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - resolve(args); - }; - transaction.fail = (reason) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - reject(reason); - }; - setTimeout(() => { - if (!transactionLive) { - return; - } - transactionLive = false; - this.logger.warn(`Transaction for operation: ${operation} timed out.`); - delete this.transactionLocks[transactionId]; - reject(`Transaction for operation: ${operation} timed out.`); - }, this.transactionTimeout); - }); - transaction.lock = transactionLock; - transaction.id = transactionId; - this.transactionLocks[transactionId] = transaction; - return transaction; - } - sendPlatformMessage(type, transactionId, args) { - this.logger.trace(`Sending a platform message of type: ${type}, id: ${transactionId} and args: ${JSON.stringify(args)}`); - this.webPlatformTransport.sendObject({ - glue42core: { type, args, transactionId } - }); - } - handleTransportSwitchRequest(args, transactionId) { - this.logger.trace(`Received a transport switch request with id: ${transactionId} and data: ${JSON.stringify(args)}`); - this.coreGlue.connection.switchTransport(args.switchSettings) - .then((result) => { - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - this.setConnected(); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: result.success }); - }) - .catch((error) => { - this.logger.error(error); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: false }); - }); - } - handlePlatformUnload() { - this.reconnectCounter = 5; - this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."); - this.reEstablishPlatformPort(); - } - handleGetCurrentTransportResponse(args, transactionId) { - this.logger.trace(`Got a current transport response from the platform with id: ${transactionId} and data: ${JSON.stringify(args)}`); - const transportState = args.transportState; - const transaction = this.transactionLocks[transactionId]; - transaction?.lift(transportState); - } - handleCheckPreferredLogic(transactionId) { - setTimeout(() => this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredLogicResponse.name, transactionId), 0); - } - handleCheckPreferredConnection(args, transactionId) { - const url = args.url; - this.logger.trace(`Testing the possible connection to: ${url}`); - this.checkPreferredConnection(url) - .then((result) => { - this.logger.trace(`The connection to ${url} is possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, result); - }) - .catch((error) => { - this.logger.trace(`The connection to ${url} is not possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, { error }); - }); - } - checkPreferredConnection(url) { - return new Promise((resolve) => { - const ws = new WebSocket(url); - ws.onerror = () => resolve({ live: false }); - ws.onopen = () => { - ws.close(); - resolve({ live: true }); - }; - }); - } - setConnected() { - this.webPlatformTransport.manualSetReadyState(); - } - } - - const operations$2 = { - getCurrent: { name: "getCurrent", resultDecoder: simpleThemeResponseDecoder }, - list: { name: "list", resultDecoder: allThemesResponseDecoder }, - select: { name: "select", dataDecoder: selectThemeConfigDecoder } - }; - - class ThemesController { - logger; - bridge; - registry = CallbackRegistryFactory$1(); - themesSubscription; - activeThemeSubs = 0; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("themes.controller.web"); - this.logger.trace("starting the web themes controller"); - this.bridge = ioc.bridge; - const api = this.toApi(); - coreGlue.themes = api; - this.logger.trace("themes are ready"); - } - handlePlatformShutdown() { - this.registry.clear(); - this.activeThemeSubs = 0; - this.themesSubscription?.close(); - delete this.themesSubscription; - } - async handleBridgeMessage() { - } - toApi() { - const api = { - getCurrent: this.getCurrent.bind(this), - list: this.list.bind(this), - select: this.select.bind(this), - onChanged: this.onChanged.bind(this) - }; - return Object.freeze(api); - } - async getCurrent() { - const bridgeResponse = await this.bridge.send("themes", operations$2.getCurrent, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.theme; - } - async list() { - const bridgeResponse = await this.bridge.send("themes", operations$2.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.themes; - } - async select(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("themes", operations$2.select, { name }, undefined, { includeOperationCheck: true }); - } - async onChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onChanged requires a callback of type function"); - } - const subReady = this.themesSubscription ? - Promise.resolve() : - this.configureThemeSubscription(); - await subReady; - ++this.activeThemeSubs; - const unsubFunc = this.registry.add("on-theme-change", callback); - return () => this.themeUnsub(unsubFunc); - } - async configureThemeSubscription() { - if (this.themesSubscription) { - return; - } - this.themesSubscription = await this.bridge.createNotificationsSteam(); - this.themesSubscription.onData((data) => { - const eventData = data.data; - const validation = simpleThemeResponseDecoder.run(eventData); - if (!validation.ok) { - this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`); - return; - } - const themeChanged = validation.result; - this.registry.execute("on-theme-change", themeChanged.theme); - }); - this.themesSubscription.onClosed(() => { - this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"); - this.registry.clear(); - this.activeThemeSubs = 0; - delete this.themesSubscription; - }); - } - themeUnsub(registryUnsub) { - registryUnsub(); - --this.activeThemeSubs; - if (this.activeThemeSubs) { - return; - } - this.themesSubscription?.close(); - delete this.themesSubscription; - } - } - - class ChannelsStorage { - sessionStorage = window.sessionStorage; - _mode = DEFAULT_STORAGE_MODE; - inMemoryChannels = []; - inMemoryRestrictions = []; - _unsubscribeDict = {}; - clear() { - this._mode = DEFAULT_STORAGE_MODE; - this.inMemoryChannels = []; - this.inMemoryRestrictions = []; - this._unsubscribeDict = {}; - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify([])); - } - get mode() { - return this._mode; - } - set mode(mode) { - this._mode = mode; - } - get channels() { - if (this.mode === "inMemory") { - return this.inMemoryChannels.slice(); - } - return this.getSessionStorageData()?.channels ?? []; - } - set channels(channels) { - if (this.mode === "inMemory") { - this.inMemoryChannels = channels; - } - this.setSessionStorageChannels(channels); - } - get restrictions() { - if (this.mode === "inMemory") { - return this.inMemoryRestrictions.slice(); - } - return this.getSessionStorageData()?.restrictions ?? []; - } - set restrictions(restrictions) { - if (this.mode === "inMemory") { - this.inMemoryRestrictions = restrictions; - } - this.setSessionStorageRestrictions(restrictions); - } - getSessionStorageData() { - return JSON.parse(this.sessionStorage.getItem(STORAGE_NAMESPACE) || "null"); - } - addUnsubscribe(channel, unsubscribe) { - this._unsubscribeDict[channel] = unsubscribe; - } - invokeUnsubscribes(channel) { - if (channel) { - this._unsubscribeDict[channel]?.(); - delete this._unsubscribeDict[channel]; - return; - } - Object.values(this._unsubscribeDict).forEach((unsub) => unsub()); - this._unsubscribeDict = {}; - } - setSessionStorageChannels(channels) { - const data = this.getSessionStorageData(); - if (data?.channels) { - data.channels = channels; - return this.setSessionStorageData(data); - } - const newData = { channels, restrictions: data?.restrictions ?? [] }; - return this.setSessionStorageData(newData); - } - setSessionStorageRestrictions(restrictions) { - const data = this.getSessionStorageData(); - if (data?.restrictions) { - data.restrictions = restrictions; - return this.setSessionStorageData(data); - } - const newData = { channels: data?.channels ?? [], restrictions }; - return this.setSessionStorageData(newData); - } - setSessionStorageData(data) { - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify(data)); - } - } - - const operations$1 = { - clear: { name: "clear", dataDecoder: basePrefsConfigDecoder }, - clearAll: { name: "clearAll" }, - get: { name: "get", dataDecoder: basePrefsConfigDecoder, resultDecoder: getPrefsResultDecoder }, - getAll: { name: "getAll", resultDecoder: getAllPrefsResultDecoder }, - set: { name: "set", dataDecoder: changePrefsDataDecoder }, - update: { name: "update", dataDecoder: changePrefsDataDecoder }, - prefsChanged: { name: "prefsChanged", dataDecoder: getPrefsResultDecoder }, - prefsHello: { name: "prefsHello", resultDecoder: prefsHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" }, - registerSubscriber: { name: "registerSubscriber", dataDecoder: subscriberRegisterConfigDecoder }, - }; - - class PrefsController { - supportedOperationsNames = []; - bridge; - config; - logger; - appManagerController; - platformAppName; - registry = CallbackRegistryFactory$1(); - validNonExistentApps; - signaledSubscription = false; - interopId; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("prefs.controller.web"); - this.logger.trace("starting the web prefs controller"); - this.addOperationsExecutors(); - this.interopId = coreGlue.interop.instance.instance; - this.bridge = ioc.bridge; - this.config = ioc.config; - this.appManagerController = ioc.appManagerController; - try { - const prefsHelloSuccess = await this.bridge.send("prefs", operations$1.prefsHello, undefined, undefined, { includeOperationCheck: true }); - this.platformAppName = prefsHelloSuccess.platform.app; - this.validNonExistentApps = prefsHelloSuccess.validNonExistentApps ?? []; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support Prefs API."); - return; - } - this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning"); - const api = this.toApi(); - coreGlue.prefs = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(prefsOperationTypesDecoder, args.operation); - const operation = operations$1[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async get(app) { - const verifiedApp = app === undefined || app === null ? this.getMyAppName() : runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const { prefs } = await this.bridge.send("prefs", operations$1.get, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - return prefs; - } - async update(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.updateFor(app, data); - } - addOperationsExecutors() { - operations$1.prefsChanged.execute = this.handleOnChanged.bind(this); - operations$1.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$1); - } - toApi() { - const api = { - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearFor: this.clearFor.bind(this), - get: this.get.bind(this), - getAll: this.getAll.bind(this), - set: this.set.bind(this), - setFor: this.setFor.bind(this), - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - update: this.update.bind(this), - updateFor: this.updateFor.bind(this), - }; - return api; - } - async clear() { - const app = this.getMyAppName(); - await this.clearFor(app); - } - async clearAll() { - await this.bridge.send("prefs", operations$1.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearFor(app) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - await this.bridge.send("prefs", operations$1.clear, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - } - async getAll() { - const result = await this.bridge.send("prefs", operations$1.getAll, undefined, undefined, { includeOperationCheck: true }); - return result; - } - async set(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.setFor(app, data); - } - async setFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.set, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - subscribe(callback) { - const app = this.getMyAppName(); - return this.subscribeFor(app, callback); - } - subscribeFor(app, callback) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const applications = this.appManagerController.getApplications(); - const isValidApp = verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp); - if (!isValidApp) { - return ioError.raiseError(`The provided app name "${app}" is not valid.`); - } - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!"); - } - if (!this.signaledSubscription) { - this.bridge.send("prefs", operations$1.registerSubscriber, { interopId: this.interopId, appName: verifiedApp }, undefined, { includeOperationCheck: true }) - .catch((error) => { - this.logger.warn("Failed to register subscriber for prefs"); - this.logger.error(error); - }); - this.signaledSubscription = true; - } - const subscriptionKey = this.getSubscriptionKey(verifiedApp); - this.get(verifiedApp).then(callback); - return this.registry.add(subscriptionKey, callback); - } - async updateFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.update, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - getMyAppName() { - const myAppName = this.config.isPlatformInternal ? this.platformAppName : this.appManagerController.me?.application.name; - if (!myAppName) { - return ioError.raiseError("App Preferences operations can not be executed for windows that do not have app!"); - } - return myAppName; - } - getSubscriptionKey(app) { - return `prefs-changed-${app}`; - } - async handleOnChanged({ prefs }) { - const subscriptionKey = this.getSubscriptionKey(prefs.app); - this.registry.execute(subscriptionKey, prefs); - } - } - - const operations = { - getResources: { name: "getResources", dataDecoder: getResourcesDataDecoder, resultDecoder: getResourcesResultDecoder }, - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - showAlert: { name: "showAlert", dataDecoder: uiAlertRequestMessageDecoder }, - showDialog: { name: "showDialog", dataDecoder: uiDialogRequestMessageDecoder }, - alertInteropAction: { name: "alertInteropAction", dataDecoder: alertInteropActionDataDecoder }, - showResolver: { name: "showResolver", dataDecoder: uiResolverRequestMessageDecoder, resultDecoder: uiResolverResponseMessageDecoder }, - }; - - const DEFAULT_ALERT_TTL = 5 * 1000; - const MODALS_SHADOW_HOST_ID = "io-modals-shadow-host"; - const MODALS_ROOT_ELEMENT_ID = "io-modals-root"; - const WIDGET_SHADOW_HOST_ID = "io-widget-shadow-host"; - const WIDGET_ROOT_ELEMENT_ID = "io-widget-root"; - const INTENT_RESOLVER_SHADOW_HOST_ID = "io-intent-resolver-shadow-host"; - const INTENT_RESOLVER_ROOT_ELEMENT_ID = "io-intent-resolver-root"; - const SHADOW_ROOT_ELEMENT_CLASSNAME = "io-body io-variables"; - - class UIController { - ioc; - supportedOperationsNames = []; - logger; - bridge; - config; - zIndexDictionary = { - [WIDGET_SHADOW_HOST_ID]: "100", - [MODALS_SHADOW_HOST_ID]: "101", - [INTENT_RESOLVER_SHADOW_HOST_ID]: "100" - }; - widgetResources; - modalsResources; - intentResolverResources; - modalsUiApi; - isDialogOpen = false; - intentResolverUiApi; - isIntentResolverOpen = false; - constructor(ioc) { - this.ioc = ioc; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("ui.controller.web"); - this.logger.trace("starting the ui controller"); - this.bridge = ioc.bridge; - this.config = ioc.config; - this.addOperationsExecutors(); - const resources = await this.getResources(); - if (!resources) { - this.logger.trace("No UI elements to display - platform is not initialized with any UI resources"); - return; - } - this.logger.trace(`Received UI resources from platform: ${JSON.stringify(resources)}`); - this.setResources(resources); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(uiOperationTypesDecoder, args.operation); - const operation = operations[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async showComponents(io) { - const initializeWidgetPromise = this.widgetResources ? this.initializeWidget(io, this.widgetResources) : Promise.resolve(); - const initializeModalsPromise = this.modalsResources ? this.initializeModalsUi(io, this.modalsResources) : Promise.resolve(); - const initializeIntentResolverPromise = this.intentResolverResources ? this.initializeIntentResolverUI(io, this.intentResolverResources) : Promise.resolve(); - await Promise.all([ - this.config.widget.awaitFactory ? initializeWidgetPromise : Promise.resolve(), - this.config.modals.awaitFactory ? initializeModalsPromise : Promise.resolve(), - this.config.intentResolver.awaitFactory ? initializeIntentResolverPromise : Promise.resolve(), - ]); - } - isIntentResolverEnabled() { - return !!this.intentResolverResources && this.config.intentResolver.enable; - } - addOperationsExecutors() { - operations.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - operations.showAlert.execute = this.handleShowAlert.bind(this); - operations.showDialog.execute = this.handleShowDialog.bind(this); - operations.showResolver.execute = this.handleShowResolver.bind(this); - this.supportedOperationsNames = getSupportedOperationsNames(operations); - } - async handleShowAlert({ config }) { - if (!this.config.modals.alerts.enabled) { - return ioError.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showAlert operation because modalsUiApi is missing."); - } - const { promise: closePromise, resolve: resolveClosePromise } = wrapPromise(); - const onClick = (config) => { - const decodedConfig = alertOnClickConfigDecoder.run(config); - if (!decodedConfig.ok) { - this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(decodedConfig.error)}.`); - return; - } - const { interopAction } = decodedConfig.result; - this.bridge.send("ui", operations.alertInteropAction, { interopAction }, undefined, { includeOperationCheck: true }) - .catch((error) => this.logger.warn(extractErrorMsg(error))); - }; - let result; - try { - this.logger.trace(`Open alert with config: ${JSON.stringify(config)}`); - result = modalsUiApi.alerts.open({ ...config, onClick, onClose: resolveClosePromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openAlertResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - const timeoutId = setTimeout(() => { - resolveClosePromise(); - }, getSafeTimeoutDelay(config.ttl ?? DEFAULT_ALERT_TTL)); - closePromise.then(() => { - clearTimeout(timeoutId); - try { - modalsUiApi.alerts.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close alert with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - }); - } - async handleShowDialog({ config }) { - if (!this.config.modals.dialogs.enabled) { - return ioError.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showDialog operation because modalsUiApi is missing."); - } - if (this.isDialogOpen) { - return ioError.raiseError("Cannot open a dialog because another one is already open."); - } - const { promise: completionPromise, resolve: resolveCompletionPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open dialog with config: ${JSON.stringify(config)}`); - result = modalsUiApi.dialogs.open({ ...config, onCompletion: resolveCompletionPromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openDialogResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - this.isDialogOpen = true; - let timeoutId; - if (config.timer) { - timeoutId = setTimeout(() => { - resolveCompletionPromise({ response: { isExpired: true } }); - }, getSafeTimeoutDelay(config.timer.duration)); - } - const response = await completionPromise; - clearTimeout(timeoutId); - this.isDialogOpen = false; - try { - modalsUiApi.dialogs.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close dialog with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodeResponse = dialogOnCompletionConfigDecoder.run(response); - if (!decodeResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodeResponse.error)}.`); - } - return { result: decodeResponse.result.response }; - } - async handleShowResolver({ config }) { - this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(config)}`); - if (!this.config.intentResolver.enable) { - return ioError.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config."); - } - const intentResolverApi = this.intentResolverUiApi; - if (!intentResolverApi) { - return ioError.raiseError("Unable to perform showResolver operation because intentResolverApi is missing."); - } - if (this.isIntentResolverOpen) { - return ioError.raiseError("Cannot open the intent resolver because another one is already open."); - } - const { promise: completionPromise, resolve: resolveIntentResolverPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open intent resolver with config: ${JSON.stringify(config)}`); - result = intentResolverApi.open({ ...config, onUserResponse: resolveIntentResolverPromise }); - } - catch (error) { - return ioError.raiseError(`intentResolverUI.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodedOpenResult = openResolverResultDecoder.run(result); - if (!decodedOpenResult.ok) { - return ioError.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(decodedOpenResult.error)}.`); - } - const timer = setTimeout(() => resolveIntentResolverPromise({ response: { isExpired: true } }), getSafeTimeoutDelay(config.timeout)); - const response = await completionPromise; - clearTimeout(timer); - this.isIntentResolverOpen = false; - try { - intentResolverApi.close({ id: decodedOpenResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close intent resolver with id ${decodedOpenResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodedResponse = onUserResponseResponseDecoder.run(response); - if (!decodedResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodedResponse.error)}.`); - } - return { result: decodedResponse.result.response }; - } - async getResources() { - const data = { - origin: window.origin - }; - try { - const result = await this.bridge.send("ui", operations.getResources, data, undefined, { includeOperationCheck: true }); - return result.resources; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - } - } - appendModalsResources(resources) { - this.logger.trace("Appending modals resources"); - return this.appendResources(MODALS_SHADOW_HOST_ID, MODALS_ROOT_ELEMENT_ID, resources.sources); - } - appendWidgetResources(resources) { - this.logger.trace("Appending widget resources"); - return this.appendResources(WIDGET_SHADOW_HOST_ID, WIDGET_ROOT_ELEMENT_ID, resources.sources); - } - appendIntentResolverResources(resources) { - this.logger.trace("Appending intent resolver resources"); - return this.appendResources(INTENT_RESOLVER_SHADOW_HOST_ID, INTENT_RESOLVER_ROOT_ELEMENT_ID, resources.sources); - } - appendResources(shadowHostId, rootElementId, sources) { - const { bundle, fonts = [], styles } = sources; - const shadowHost = document.createElement("div"); - shadowHost.id = shadowHostId; - shadowHost.style.position = "fixed"; - shadowHost.style.zIndex = this.zIndexDictionary[shadowHostId]; - const shadowRoot = shadowHost.attachShadow({ mode: "open" }); - const script = document.createElement("script"); - script.src = bundle; - script.type = "module"; - shadowRoot.appendChild(script); - const rootElement = document.createElement("div"); - rootElement.id = rootElementId; - rootElement.className = SHADOW_ROOT_ELEMENT_CLASSNAME; - shadowRoot.appendChild(rootElement); - styles.forEach((style) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = style; - shadowRoot.appendChild(link); - }); - fonts.forEach((font) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = font; - document.head.insertBefore(link, document.head.firstChild); - }); - document.body.appendChild(shadowHost); - return { rootElement }; - } - async initializeWidget(io, resources) { - this.logger.trace("Initializing IOBrowserWidget."); - const { rootElement } = this.appendWidgetResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...deepmerge$1(resources.config, this.config.widget), - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.widgetReady(); - this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(config)}`); - await window.IOBrowserWidget(io, config); - this.logger.trace("IOBrowserWidget was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserWidget to initialize.`); - } - async initializeModalsUi(io, resources) { - this.logger.trace("Initializing IOBrowserModalsUI."); - const { rootElement } = this.appendModalsResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.modals, - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.modalsUIFactoryReady(); - this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.modalsUiApi = await window.IOBrowserModalsUI(io, config); - this.logger.trace("IOBrowserModalsUI was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`); - } - async initializeIntentResolverUI(io, resources) { - this.logger.trace("Initializing IOBrowserIntentResolverUI."); - const { rootElement } = this.appendIntentResolverResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.intentResolver, - rootElement - }; - const timeout = config.timeout; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(); - this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.intentResolverUiApi = await window.IOBrowserIntentResolverUI(io, config); - this.logger.trace("IOBrowserIntentResolverUI initialized successfully."); - }, timeout, `Timeout of ${timeout}ms hit waiting for IOBrowserIntentResolverUI to initialize.`); - } - setResources(resources) { - this.setWidgetResources(resources.widget); - this.setModalsUiResources(resources.modals); - this.setIntentResolverResources(resources.intentResolver); - } - setWidgetResources(resources) { - const baseMsg = "Widget won't be displayed. Reason: "; - const decodedConfig = widgetConfigDecoder.run(this.config.widget); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid widget config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.widget.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'widget: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`); - return; - } - this.widgetResources = resources; - } - setModalsUiResources(resources) { - const baseMsg = "Modals won't be displayed. Reason: "; - const decodedConfig = modalsConfigDecoder.run(this.config.modals); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid modals config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.modals.alerts.enabled && !this.config.modals.dialogs.enabled) { - this.logger.trace(`${baseMsg} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`); - return; - } - this.modalsResources = resources; - } - setIntentResolverResources(resources) { - const baseMsg = "Intent Resolver UI won't be displayed. Reason: "; - const decodedConfig = intentResolverConfigDecoder.run(this.config.intentResolver); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid intent resolver config. Error: ${JSON.stringify(decodedConfig.error)}`); - return; - } - if (!this.config.intentResolver.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'intentResolver: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`); - return; - } - this.intentResolverResources = resources; - } - subscribeForThemeChanges(io, element) { - const themesApi = io.themes; - if (!themesApi) { - return; - } - const changeTheme = async (theme) => { - if (element.classList.contains(theme.name)) { - return; - } - const allThemes = await themesApi.list(); - element.classList.remove(...allThemes.map(({ name }) => name)); - element.classList.add(theme.name); - }; - themesApi.onChanged(changeTheme); - themesApi.getCurrent().then(changeTheme); - } - } - - class IoC { - _coreGlue; - _communicationId; - _publicWindowId; - _webConfig; - _windowsControllerInstance; - _appManagerControllerInstance; - _layoutsControllerInstance; - _notificationsControllerInstance; - _intentsControllerInstance; - _channelsControllerInstance; - _themesControllerInstance; - _extensionController; - _systemControllerInstance; - _bridgeInstance; - _eventsDispatcher; - _preferredConnectionController; - _channelsStorage; - _prefsControllerInstance; - _uiController; - controllers = { - windows: this.windowsController, - appManager: this.appManagerController, - layouts: this.layoutsController, - notifications: this.notificationsController, - intents: this.intentsController, - channels: this.channelsController, - system: this.systemController, - extension: this.extensionController, - themes: this.themesController, - prefs: this.prefsController, - ui: this.uiController - }; - get communicationId() { - return this._communicationId; - } - get publicWindowId() { - return this._publicWindowId; - } - get windowsController() { - if (!this._windowsControllerInstance) { - this._windowsControllerInstance = new WindowsController(); - } - return this._windowsControllerInstance; - } - get uiController() { - if (!this._uiController) { - this._uiController = new UIController(this); - } - return this._uiController; - } - get appManagerController() { - if (!this._appManagerControllerInstance) { - this._appManagerControllerInstance = new AppManagerController(); - } - return this._appManagerControllerInstance; - } - get layoutsController() { - if (!this._layoutsControllerInstance) { - this._layoutsControllerInstance = new LayoutsController(); - } - return this._layoutsControllerInstance; - } - get themesController() { - if (!this._themesControllerInstance) { - this._themesControllerInstance = new ThemesController(); - } - return this._themesControllerInstance; - } - get notificationsController() { - if (!this._notificationsControllerInstance) { - this._notificationsControllerInstance = new NotificationsController(); - } - return this._notificationsControllerInstance; - } - get intentsController() { - if (!this._intentsControllerInstance) { - this._intentsControllerInstance = new IntentsController(); - } - return this._intentsControllerInstance; - } - get systemController() { - if (!this._systemControllerInstance) { - this._systemControllerInstance = new SystemController(); - } - return this._systemControllerInstance; - } - get channelsController() { - if (!this._channelsControllerInstance) { - this._channelsControllerInstance = new ChannelsController(); - } - return this._channelsControllerInstance; - } - get prefsController() { - if (!this._prefsControllerInstance) { - this._prefsControllerInstance = new PrefsController(); - } - return this._prefsControllerInstance; - } - get extensionController() { - if (!this._extensionController) { - this._extensionController = new ExtController(); - } - return this._extensionController; - } - get eventsDispatcher() { - if (!this._eventsDispatcher) { - this._eventsDispatcher = new EventsDispatcher(this.config); - } - return this._eventsDispatcher; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new GlueBridge(this._coreGlue, this.communicationId); - } - return this._bridgeInstance; - } - get preferredConnectionController() { - if (!this._preferredConnectionController) { - this._preferredConnectionController = new PreferredConnectionController(this._coreGlue); - } - return this._preferredConnectionController; - } - get channelsStorage() { - if (!this._channelsStorage) { - this._channelsStorage = new ChannelsStorage(); - } - return this._channelsStorage; - } - get config() { - return this._webConfig; - } - defineGlue(coreGlue) { - this._coreGlue = coreGlue; - this._publicWindowId = coreGlue.connection.transport.publicWindowId; - const globalNamespace = window.glue42core || window.iobrowser; - this._communicationId = coreGlue.connection.transport.communicationId || globalNamespace.communicationId; - } - defineConfig(config) { - this._webConfig = config; - } - async buildWebWindow(id, name, logger) { - const model = new WebWindowModel(id, name, this.bridge, logger); - const api = await model.toApi(); - return { id, model, api }; - } - buildNotification(config, id) { - return new Notification(config, id); - } - async buildApplication(app, applicationInstances) { - const application = (new ApplicationModel(app, [], this.appManagerController)).toApi(); - const instances = applicationInstances.map((instanceData) => this.buildInstance(instanceData, application)); - application.instances.push(...instances); - return application; - } - buildInstance(instanceData, app) { - return (new InstanceModel(instanceData, this.bridge, app)).toApi(); - } - } - - var version$1 = "4.2.4"; - - const setupGlobalSystem = (io, bridge) => { - return { - getContainerInfo: async () => { - if (window === window.parent) { - return; - } - if (window.name.includes("#wsp")) { - return { - workspaceFrame: { - id: "N/A" - } - }; - } - return window.parent === window.top ? - { top: {} } : - { parent: {} }; - }, - getProfileData: async () => { - if (!bridge) { - throw new Error("Bridge is not available and cannot fetch the profile data"); - } - const data = await bridge.send("system", { name: "getProfileData" }, undefined); - return data; - } - }; - }; - - const createFactoryFunction = (coreFactoryFunction) => { - let cachedApiPromise; - const initAPI = async (config) => { - const ioc = new IoC(); - const glue = await PromiseWrap(() => coreFactoryFunction(config, { version: version$1 }), 30000, "Glue Web initialization timed out, because core didn't resolve"); - const logger = glue.logger.subLogger("web.main.controller"); - ioc.defineGlue(glue); - await ioc.preferredConnectionController.start(config); - await ioc.bridge.start(ioc.controllers); - ioc.defineConfig(config); - logger.trace("the bridge has been started, initializing all controllers"); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.start(glue, ioc))); - logger.trace("all controllers reported started, starting all additional libraries"); - try { - await Promise.all(config.libraries.map((lib) => lib(glue, config))); - logger.trace("all libraries were started"); - ioc.eventsDispatcher.start(glue); - logger.trace("start event dispatched, glue is ready, returning it"); - await ioc.uiController.showComponents(glue).catch((err) => logger.warn(err?.message ? err.message : JSON.stringify(err))); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.postStart ? controller.postStart(glue, ioc) : Promise.resolve())); - window.iobrowser.system = setupGlobalSystem(glue, ioc.bridge); - window.iobrowser = Object.freeze({ ...window.iobrowser }); - return glue; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const factory = (userConfig) => { - if (window.glue42gd || window.iodesktop) { - return enterprise(userConfig); - } - const config = parseConfig(userConfig); - try { - checkSingleton(); - } - catch (error) { - return typeof cachedApiPromise === "undefined" ? Promise.reject(new Error(error)) : cachedApiPromise; - } - const apiPromise = initAPI(config); - cachedApiPromise = userConfig?.memoizeAPI ? apiPromise : undefined; - return apiPromise; - }; - return factory; - }; - - var MetricTypes = { - STRING: 1, - NUMBER: 2, - TIMESTAMP: 3, - OBJECT: 4 - }; - - function getMetricTypeByValue(metric) { - if (metric.type === MetricTypes.TIMESTAMP) { - return "timestamp"; - } - else if (metric.type === MetricTypes.NUMBER) { - return "number"; - } - else if (metric.type === MetricTypes.STRING) { - return "string"; - } - else if (metric.type === MetricTypes.OBJECT) { - return "object"; - } - return "unknown"; - } - function getTypeByValue(value) { - if (value.constructor === Date) { - return "timestamp"; - } - else if (typeof value === "number") { - return "number"; - } - else if (typeof value === "string") { - return "string"; - } - else if (typeof value === "object") { - return "object"; - } - else { - return "string"; - } - } - function serializeMetric(metric) { - const serializedMetrics = {}; - const type = getMetricTypeByValue(metric); - if (type === "object") { - const values = Object.keys(metric.value).reduce((memo, key) => { - const innerType = getTypeByValue(metric.value[key]); - if (innerType === "object") { - const composite = defineNestedComposite(metric.value[key]); - memo[key] = { - type: "object", - description: "", - context: {}, - composite, - }; - } - else { - memo[key] = { - type: innerType, - description: "", - context: {}, - }; - } - return memo; - }, {}); - serializedMetrics.composite = values; - } - serializedMetrics.name = normalizeMetricName(metric.path.join("/") + "/" + metric.name); - serializedMetrics.type = type; - serializedMetrics.description = metric.description; - serializedMetrics.context = {}; - return serializedMetrics; - } - function defineNestedComposite(values) { - return Object.keys(values).reduce((memo, key) => { - const type = getTypeByValue(values[key]); - if (type === "object") { - memo[key] = { - type: "object", - description: "", - context: {}, - composite: defineNestedComposite(values[key]), - }; - } - else { - memo[key] = { - type, - description: "", - context: {}, - }; - } - return memo; - }, {}); - } - function normalizeMetricName(name) { - if (typeof name !== "undefined" && name.length > 0 && name[0] !== "/") { - return "/" + name; - } - else { - return name; - } - } - function getMetricValueByType(metric) { - const type = getMetricTypeByValue(metric); - if (type === "timestamp") { - return Date.now(); - } - else { - return publishNestedComposite(metric.value); - } - } - function publishNestedComposite(values) { - if (typeof values !== "object") { - return values; - } - return Object.keys(values).reduce((memo, key) => { - const value = values[key]; - if (typeof value === "object" && value.constructor !== Date) { - memo[key] = publishNestedComposite(value); - } - else if (value.constructor === Date) { - memo[key] = new Date(value).getTime(); - } - else if (value.constructor === Boolean) { - memo[key] = value.toString(); - } - else { - memo[key] = value; - } - return memo; - }, {}); - } - function flatten(arr) { - return arr.reduce((flat, toFlatten) => { - return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); - }, []); - } - function getHighestState(arr) { - return arr.sort((a, b) => { - if (!a.state) { - return 1; - } - if (!b.state) { - return -1; - } - return b.state - a.state; - })[0]; - } - function aggregateDescription(arr) { - let msg = ""; - arr.forEach((m, idx, a) => { - const path = m.path.join("."); - if (idx === a.length - 1) { - msg += path + "." + m.name + ": " + m.description; - } - else { - msg += path + "." + m.name + ": " + m.description + ","; - } - }); - if (msg.length > 100) { - return msg.slice(0, 100) + "..."; - } - else { - return msg; - } - } - function composeMsgForRootStateMetric(system) { - const aggregatedState = system.root.getAggregateState(); - const merged = flatten(aggregatedState); - const highestState = getHighestState(merged); - const aggregateDesc = aggregateDescription(merged); - return { - description: aggregateDesc, - value: highestState.state, - }; - } - - function gw3 (connection, config) { - if (!connection || typeof connection !== "object") { - throw new Error("Connection is required parameter"); - } - let joinPromise; - let session; - const init = (repo) => { - let resolveReadyPromise; - joinPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - session = connection.domain("metrics"); - session.onJoined((reconnect) => { - if (!reconnect && resolveReadyPromise) { - resolveReadyPromise(); - resolveReadyPromise = undefined; - } - const rootStateMetric = { - name: "/State", - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const defineRootMetricsMsg = { - type: "define", - metrics: [rootStateMetric], - }; - session.sendFireAndForget(defineRootMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(err)}`); - }); - if (reconnect) { - replayRepo(repo); - } - }); - session.join({ - system: config.system, - service: config.service, - instance: config.instance - }); - }; - const replayRepo = (repo) => { - replaySystem(repo.root); - }; - const replaySystem = (system) => { - createSystem(system); - system.metrics.forEach((m) => { - createMetric(m); - }); - system.subSystems.forEach((ss) => { - replaySystem(ss); - }); - }; - const createSystem = async (system) => { - if (system.parent === undefined) { - return; - } - await joinPromise; - const metric = { - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const createMetricsMsg = { - type: "define", - metrics: [metric], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const updateSystem = async (system, state) => { - await joinPromise; - const shadowedUpdateMetric = { - type: "publish", - values: [{ - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - value: { - Description: state.description, - Value: state.state, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(shadowedUpdateMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - const stateObj = composeMsgForRootStateMetric(system); - const rootMetric = { - type: "publish", - peer_id: connection.peerId, - values: [{ - name: "/State", - value: { - Description: stateObj.description, - Value: stateObj.value, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(rootMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for root state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const createMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - const m = serializeMetric(metricClone); - const createMetricsMsg = { - type: "define", - metrics: [m], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for metric ${metric.name}: ${JSON.stringify(err)}`); - }); - if (typeof metricClone.value !== "undefined") { - updateMetricCore(metricClone); - } - }; - const updateMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - updateMetricCore(metricClone); - }; - const updateMetricCore = (metric) => { - if (canUpdate()) { - const value = getMetricValueByType(metric); - const publishMetricsMsg = { - type: "publish", - values: [{ - name: normalizeMetricName(metric.path.join("/") + "/" + metric.name), - value, - timestamp: Date.now(), - }], - }; - return session.sendFireAndForget(publishMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to publish metric ${metric.name}: ${JSON.stringify(err)}`); - }); - } - return Promise.resolve(); - }; - const cloneMetric = (metric) => { - const metricClone = { ...metric }; - if (typeof metric.value === "object" && metric.value !== null) { - metricClone.value = { ...metric.value }; - } - return metricClone; - }; - const canUpdate = () => { - try { - const func = config.canUpdateMetric ?? (() => true); - return func(); - } - catch { - return true; - } - }; - return { - init, - createSystem, - updateSystem, - createMetric, - updateMetric, - }; - } - - var Helpers = { - validate: (definition, parent, transport) => { - if (definition === null || typeof definition !== "object") { - throw new Error("Missing definition"); - } - if (parent === null || typeof parent !== "object") { - throw new Error("Missing parent"); - } - if (transport === null || typeof transport !== "object") { - throw new Error("Missing transport"); - } - }, - }; - - class BaseMetric { - definition; - system; - transport; - value; - type; - path = []; - name; - description; - get repo() { - return this.system?.repo; - } - get id() { return `${this.system.path}/${name}`; } - constructor(definition, system, transport, value, type) { - this.definition = definition; - this.system = system; - this.transport = transport; - this.value = value; - this.type = type; - Helpers.validate(definition, system, transport); - this.path = system.path.slice(0); - this.path.push(system.name); - this.name = definition.name; - this.description = definition.description; - transport.createMetric(this); - } - update(newValue) { - this.value = newValue; - return this.transport.updateMetric(this); - } - } - - class NumberMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.NUMBER); - } - incrementBy(num) { - this.update(this.value + num); - } - increment() { - this.incrementBy(1); - } - decrement() { - this.incrementBy(-1); - } - decrementBy(num) { - this.incrementBy(num * -1); - } - } - - class ObjectMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.OBJECT); - } - update(newValue) { - this.mergeValues(newValue); - return this.transport.updateMetric(this); - } - mergeValues(values) { - return Object.keys(this.value).forEach((k) => { - if (typeof values[k] !== "undefined") { - this.value[k] = values[k]; - } - }); - } - } - - class StringMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.STRING); - } - } - - class TimestampMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.TIMESTAMP); - } - now() { - this.update(new Date()); - } - } - - function system(name, repo, protocol, parent, description) { - if (!repo) { - throw new Error("Repository is required"); - } - if (!protocol) { - throw new Error("Transport is required"); - } - const _transport = protocol; - const _name = name; - const _description = description || ""; - const _repo = repo; - const _parent = parent; - const _path = _buildPath(parent); - let _state = {}; - const id = _arrayToString(_path, "/") + name; - const root = repo.root; - const _subSystems = []; - const _metrics = []; - function subSystem(nameSystem, descriptionSystem) { - if (!nameSystem || nameSystem.length === 0) { - throw new Error("name is required"); - } - const match = _subSystems.filter((s) => s.name === nameSystem); - if (match.length > 0) { - return match[0]; - } - const _system = system(nameSystem, _repo, _transport, me, descriptionSystem); - _subSystems.push(_system); - return _system; - } - function setState(state, stateDescription) { - _state = { state, description: stateDescription }; - _transport.updateSystem(me, _state); - } - function stringMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.STRING, value, (metricDef) => new StringMetric(metricDef, me, _transport, value)); - } - function numberMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.NUMBER, value, (metricDef) => new NumberMetric(metricDef, me, _transport, value)); - } - function objectMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.OBJECT, value, (metricDef) => new ObjectMetric(metricDef, me, _transport, value)); - } - function timestampMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.TIMESTAMP, value, (metricDef) => new TimestampMetric(metricDef, me, _transport, value)); - } - function _getOrCreateMetric(metricObject, expectedType, value, createMetric) { - let metricDef = { name: "" }; - if (typeof metricObject === "string") { - metricDef = { name: metricObject }; - } - else { - metricDef = metricObject; - } - const matching = _metrics.filter((shadowedMetric) => shadowedMetric.name === metricDef.name); - if (matching.length > 0) { - const existing = matching[0]; - if (existing.type !== expectedType) { - throw new Error(`A metric named ${metricDef.name} is already defined with different type.`); - } - if (typeof value !== "undefined") { - existing - .update(value) - .catch(() => { }); - } - return existing; - } - const metric = createMetric(metricDef); - _metrics.push(metric); - return metric; - } - function _buildPath(shadowedSystem) { - if (!shadowedSystem || !shadowedSystem.parent) { - return []; - } - const path = _buildPath(shadowedSystem.parent); - path.push(shadowedSystem.name); - return path; - } - function _arrayToString(path, separator) { - return ((path && path.length > 0) ? path.join(separator) : ""); - } - function getAggregateState() { - const aggState = []; - if (Object.keys(_state).length > 0) { - aggState.push({ - name: _name, - path: _path, - state: _state.state, - description: _state.description, - }); - } - _subSystems.forEach((shadowedSubSystem) => { - const result = shadowedSubSystem.getAggregateState(); - if (result.length > 0) { - aggState.push(...result); - } - }); - return aggState; - } - const me = { - get name() { - return _name; - }, - get description() { - return _description; - }, - get repo() { - return _repo; - }, - get parent() { - return _parent; - }, - path: _path, - id, - root, - get subSystems() { - return _subSystems; - }, - get metrics() { - return _metrics; - }, - subSystem, - getState: () => { - return _state; - }, - setState, - stringMetric, - timestampMetric, - objectMetric, - numberMetric, - getAggregateState, - }; - _transport.createSystem(me); - return me; - } - - class Repository { - root; - constructor(options, protocol) { - protocol.init(this); - this.root = system("", this, protocol); - this.addSystemMetrics(this.root, options.clickStream || options.clickStream === undefined); - } - addSystemMetrics(rootSystem, useClickStream) { - if (typeof navigator !== "undefined") { - rootSystem.stringMetric("UserAgent", navigator.userAgent); - } - if (useClickStream && typeof document !== "undefined") { - const clickStream = rootSystem.subSystem("ClickStream"); - const documentClickHandler = (e) => { - if (!e.target) { - return; - } - const target = e.target; - const className = target ? target.getAttribute("class") ?? "" : ""; - clickStream.objectMetric("LastBrowserEvent", { - type: "click", - timestamp: new Date(), - target: { - className, - id: target.id, - type: "<" + target.tagName.toLowerCase() + ">", - href: target.href || "", - }, - }); - }; - clickStream.objectMetric("Page", { - title: document.title, - page: window.location.href, - }); - if (document.addEventListener) { - document.addEventListener("click", documentClickHandler); - } - else { - document.attachEvent("onclick", documentClickHandler); - } - } - rootSystem.stringMetric("StartTime", (new Date()).toString()); - const urlMetric = rootSystem.stringMetric("StartURL", ""); - const appNameMetric = rootSystem.stringMetric("AppName", ""); - if (typeof window !== "undefined") { - if (typeof window.location !== "undefined") { - const startUrl = window.location.href; - urlMetric.update(startUrl); - } - if (typeof window.glue42gd !== "undefined") { - appNameMetric.update(window.glue42gd.appName); - } - } - } - } - - class NullProtocol { - init(repo) { - } - createSystem(system) { - return Promise.resolve(); - } - updateSystem(metric, state) { - return Promise.resolve(); - } - createMetric(metric) { - return Promise.resolve(); - } - updateMetric(metric) { - return Promise.resolve(); - } - } - - class PerfTracker { - api; - lastCount = 0; - initialPublishTimeout = 10 * 1000; - publishInterval = 60 * 1000; - system; - constructor(api, initialPublishTimeout, publishInterval) { - this.api = api; - this.initialPublishTimeout = initialPublishTimeout ?? this.initialPublishTimeout; - this.publishInterval = publishInterval ?? this.publishInterval; - this.scheduleCollection(); - this.system = this.api.subSystem("performance", "Performance data published by the web application"); - } - scheduleCollection() { - setTimeout(() => { - this.collect(); - setInterval(() => { - this.collect(); - }, this.publishInterval); - }, this.initialPublishTimeout); - } - collect() { - try { - this.collectMemory(); - this.collectEntries(); - } - catch { - } - } - collectMemory() { - const memory = window.performance.memory; - this.system.stringMetric("memory", JSON.stringify({ - totalJSHeapSize: memory.totalJSHeapSize, - usedJSHeapSize: memory.usedJSHeapSize - })); - } - collectEntries() { - const allEntries = window.performance.getEntries(); - if (allEntries.length <= this.lastCount) { - return; - } - this.lastCount = allEntries.length; - const jsonfiedEntries = allEntries.map((i) => i.toJSON()); - this.system.stringMetric("entries", JSON.stringify(jsonfiedEntries)); - } - } - - var metrics = (options) => { - let protocol; - if (!options.connection || typeof options.connection !== "object") { - protocol = new NullProtocol(); - } - else { - protocol = gw3(options.connection, options); - } - const repo = new Repository(options, protocol); - let rootSystem = repo.root; - if (!options.disableAutoAppSystem) { - rootSystem = rootSystem.subSystem("App"); - } - const api = addFAVSupport(rootSystem); - initPerf(api, options.pagePerformanceMetrics); - return api; - }; - function initPerf(api, config) { - if (typeof window === "undefined") { - return; - } - const perfConfig = window?.glue42gd?.metrics?.pagePerformanceMetrics; - if (perfConfig) { - config = perfConfig; - } - if (config?.enabled) { - new PerfTracker(api, config.initialPublishTimeout, config.publishInterval); - } - } - function addFAVSupport(system) { - const reportingSystem = system.subSystem("reporting"); - const def = { - name: "features" - }; - let featureMetric; - const featureMetricFunc = (name, action, payload) => { - if (typeof name === "undefined" || name === "") { - throw new Error("name is mandatory"); - } - else if (typeof action === "undefined" || action === "") { - throw new Error("action is mandatory"); - } - else if (typeof payload === "undefined" || payload === "") { - throw new Error("payload is mandatory"); - } - if (!featureMetric) { - featureMetric = reportingSystem.objectMetric(def, { name, action, payload }); - } - else { - featureMetric.update({ - name, - action, - payload - }); - } - }; - system.featureMetric = featureMetricFunc; - return system; - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackRegistryFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - class InProcTransport { - gw; - registry = CallbackRegistryFactory(); - client; - constructor(settings, logger) { - this.gw = settings.facade; - this.gw.connect((_client, message) => { - this.messageHandler(message); - }).then((client) => { - this.client = client; - }); - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - if (this.client) { - this.client.send(msg); - return Promise.resolve(undefined); - } - else { - return Promise.reject(`not connected`); - } - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "in-memory"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class SharedWorkerTransport { - logger; - worker; - registry = CallbackRegistryFactory(); - constructor(workerFile, logger) { - this.logger = logger; - this.worker = new SharedWorker(workerFile); - this.worker.port.onmessage = (e) => { - this.messageHandler(e.data); - }; - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - this.worker.port.postMessage(msg); - return Promise.resolve(); - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "shared-worker"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class Utils { - static isNode() { - if (typeof Utils._isNode !== "undefined") { - return Utils._isNode; - } - if (typeof window !== "undefined") { - Utils._isNode = false; - return false; - } - try { - Utils._isNode = Object.prototype.toString.call(global.process) === "[object process]"; - } - catch (e) { - Utils._isNode = false; - } - return Utils._isNode; - } - static _isNode; - } - - class PromiseWrapper { - static delay(time) { - return new Promise((resolve) => setTimeout(resolve, time)); - } - resolve; - reject; - promise; - rejected = false; - resolved = false; - get ended() { - return this.rejected || this.resolved; - } - constructor() { - this.promise = new Promise((resolve, reject) => { - this.resolve = (t) => { - this.resolved = true; - resolve(t); - }; - this.reject = (err) => { - this.rejected = true; - reject(err); - }; - }); - } - } - - const timers = {}; - function getAllTimers() { - return timers; - } - function timer (timerName) { - const existing = timers[timerName]; - if (existing) { - return existing; - } - const marks = []; - function now() { - return new Date().getTime(); - } - const startTime = now(); - mark("start", startTime); - let endTime; - let period; - function stop() { - endTime = now(); - mark("end", endTime); - period = endTime - startTime; - return period; - } - function mark(name, time) { - const currentTime = time ?? now(); - let diff = 0; - if (marks.length > 0) { - diff = currentTime - marks[marks.length - 1].time; - } - marks.push({ name, time: currentTime, diff }); - } - const timerObj = { - get startTime() { - return startTime; - }, - get endTime() { - return endTime; - }, - get period() { - return period; - }, - stop, - mark, - marks - }; - timers[timerName] = timerObj; - return timerObj; - } - - const WebSocketConstructor = Utils.isNode() ? null : window.WebSocket; - class WS { - ws; - logger; - settings; - startupTimer = timer("connection"); - _running = true; - _registry = CallbackRegistryFactory(); - wsRequests = []; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - if (!this.settings.ws) { - throw new Error("ws is missing"); - } - } - onMessage(callback) { - return this._registry.add("onMessage", callback); - } - send(msg, options) { - return new Promise((resolve, reject) => { - this.waitForSocketConnection(() => { - try { - this.ws?.send(msg); - resolve(); - } - catch (e) { - reject(e); - } - }, reject); - }); - } - open() { - this.logger.info("opening ws..."); - this._running = true; - return new Promise((resolve, reject) => { - this.waitForSocketConnection(resolve, reject); - }); - } - close() { - this._running = false; - if (this.ws) { - this.ws.close(); - } - return Promise.resolve(); - } - onConnectedChanged(callback) { - return this._registry.add("onConnectedChanged", callback); - } - name() { - return this.settings.ws; - } - reconnect() { - this.ws?.close(); - const pw = new PromiseWrapper(); - this.waitForSocketConnection(() => { - pw.resolve(); - }); - return pw.promise; - } - waitForSocketConnection(callback, failed) { - failed = failed ?? (() => { }); - if (!this._running) { - failed(`wait for socket on ${this.settings.ws} failed - socket closed by user`); - return; - } - if (this.ws?.readyState === 1) { - callback(); - return; - } - this.wsRequests.push({ callback, failed }); - if (this.wsRequests.length > 1) { - return; - } - this.openSocket(); - } - async openSocket(retryInterval, retriesLeft) { - this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${retryInterval}, retriesLeft: ${retriesLeft}...`); - this.startupTimer.mark("opening-socket"); - if (retryInterval === undefined) { - retryInterval = this.settings.reconnectInterval; - } - if (typeof retriesLeft === "undefined") { - retriesLeft = this.settings.reconnectAttempts; - } - if (retriesLeft !== undefined) { - if (retriesLeft === 0) { - this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`); - return; - } - this.logger.debug(`will retry ${retriesLeft} more times (every ${retryInterval} ms)`); - } - try { - await this.initiateSocket(); - this.startupTimer.mark("socket-initiated"); - this.notifyForSocketState(); - } - catch { - setTimeout(() => { - const retries = retriesLeft === undefined ? undefined : retriesLeft - 1; - this.openSocket(retryInterval, retries); - }, retryInterval); - } - } - initiateSocket() { - const pw = new PromiseWrapper(); - this.logger.debug(`initiating ws to ${this.settings.ws}...`); - this.ws = new WebSocketConstructor(this.settings.ws ?? ""); - let wasOpen = false; - this.ws.onerror = (err) => { - let reason; - try { - reason = JSON.stringify(err); - } - catch (error) { - const seen = new WeakSet(); - const replacer = (key, value) => { - if (typeof value === "object" && value !== null) { - if (seen.has(value)) { - return; - } - seen.add(value); - } - if (value instanceof Error) { - return { - message: value.message, - name: value.name, - stack: value.stack - }; - } - return value; - }; - reason = JSON.stringify(err, replacer); - } - this.logger.info(`ws error - reason: ${reason}`); - pw.reject("error"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("error"); - } - this.notifyStatusChanged(false, reason); - }; - this.ws.onclose = (err) => { - this.logger.info(`ws closed - code: ${err?.code} reason: ${err?.reason}`); - pw.reject("closed"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("closed"); - } - this.notifyStatusChanged(false); - }; - this.ws.onopen = () => { - this.startupTimer.mark("ws-opened"); - this.logger.info(`ws opened ${this.settings.identity?.application}`); - pw.resolve(); - wasOpen = true; - this.notifyStatusChanged(true); - }; - this.ws.onmessage = (message) => { - this._registry.execute("onMessage", message.data); - }; - return pw.promise; - } - notifyForSocketState(error) { - this.wsRequests.forEach((wsRequest) => { - if (error) { - if (wsRequest.failed) { - wsRequest.failed(error); - } - } - else { - wsRequest.callback(); - } - }); - this.wsRequests = []; - } - notifyStatusChanged(status, reason) { - this._registry.execute("onConnectedChanged", status, reason); - } - } - - class MessageReplayerImpl { - specs; - specsNames = []; - messages = {}; - isDone; - subs = {}; - subsRefCount = {}; - connection; - constructor(specs) { - this.specs = {}; - for (const spec of specs) { - this.specs[spec.name] = spec; - this.specsNames.push(spec.name); - } - } - init(connection) { - this.connection = connection; - for (const name of this.specsNames) { - for (const type of this.specs[name].types) { - let refCount = this.subsRefCount[type]; - if (!refCount) { - refCount = 0; - } - refCount += 1; - this.subsRefCount[type] = refCount; - if (refCount > 1) { - continue; - } - const sub = connection.on(type, (msg) => this.processMessage(type, msg)); - this.subs[type] = sub; - } - } - } - processMessage(type, msg) { - if (this.isDone || !msg) { - return; - } - for (const name of this.specsNames) { - if (this.specs[name].types.indexOf(type) !== -1) { - const messages = this.messages[name] || []; - this.messages[name] = messages; - messages.push(msg); - } - } - } - drain(name, callback) { - if (callback) { - (this.messages[name] || []).forEach(callback); - } - delete this.messages[name]; - for (const type of this.specs[name].types) { - this.subsRefCount[type] -= 1; - if (this.subsRefCount[type] <= 0) { - this.connection?.off(this.subs[type]); - delete this.subs[type]; - delete this.subsRefCount[type]; - } - } - delete this.specs[name]; - if (!this.specs.length) { - this.isDone = true; - } - } - } - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet[(Math.random() * 64) | 0]; - } - return id - }; - - const PromisePlus = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WebPlatformTransport { - settings; - logger; - identity; - isPreferredActivated; - _connectionProtocolVersion; - _communicationId; - publicWindowId; - selfAssignedWindowId; - iAmConnected = false; - parentReady = false; - rejected = false; - parentPingResolve; - parentPingInterval; - connectionResolve; - extConnectionResolve; - extConnectionReject; - connectionReject; - port; - myClientId; - extContentAvailable = false; - extContentConnecting = false; - extContentConnected = false; - parentWindowId; - parentInExtMode = false; - webNamespace = "g42_core_web"; - parent; - parentType; - parentPingTimeout = 5000; - connectionRequestTimeout = 7000; - defaultTargetString = "*"; - registry = CallbackRegistryFactory(); - messages = { - connectionAccepted: { name: "connectionAccepted", handle: this.handleConnectionAccepted.bind(this) }, - connectionRejected: { name: "connectionRejected", handle: this.handleConnectionRejected.bind(this) }, - connectionRequest: { name: "connectionRequest", handle: this.handleConnectionRequest.bind(this) }, - parentReady: { - name: "parentReady", handle: () => { - } - }, - parentPing: { name: "parentPing", handle: this.handleParentPing.bind(this) }, - platformPing: { name: "platformPing", handle: this.handlePlatformPing.bind(this) }, - platformReady: { name: "platformReady", handle: this.handlePlatformReady.bind(this) }, - clientUnload: { name: "clientUnload", handle: () => { } }, - manualUnload: { name: "manualUnload", handle: this.handleManualUnload.bind(this) }, - extConnectionResponse: { name: "extConnectionResponse", handle: this.handleExtConnectionResponse.bind(this) }, - extSetupRequest: { name: "extSetupRequest", handle: this.handleExtSetupRequest.bind(this) }, - gatewayDisconnect: { name: "gatewayDisconnect", handle: this.handleGatewayDisconnect.bind(this) }, - gatewayInternalConnect: { name: "gatewayInternalConnect", handle: this.handleGatewayInternalConnect.bind(this) } - }; - constructor(settings, logger, identity) { - this.settings = settings; - this.logger = logger; - this.identity = identity; - this.extContentAvailable = !!window.glue42ext; - this.setUpMessageListener(); - this.setUpUnload(); - this.setupPlatformUnloadListener(); - this.parentType = window.name.includes("#wsp") ? "workspace" : undefined; - } - manualSetReadyState() { - this.iAmConnected = true; - this.parentReady = true; - } - get transportWindowId() { - return this.publicWindowId; - } - get communicationId() { - return this._communicationId; - } - async sendObject(msg) { - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: msg }, window.origin); - } - if (!this.port) { - throw new Error("Cannot send message, because the port was not opened yet"); - } - this.port.postMessage(msg); - } - get isObjectBasedTransport() { - return true; - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - send() { - return Promise.reject("not supported"); - } - onConnectedChanged(callback) { - return this.registry.add("onConnectedChanged", callback); - } - async open() { - this.logger.debug("opening a connection to the web platform gateway."); - await this.connect(); - this.notifyStatusChanged(true); - } - close() { - this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId || "unknown"}, client connected: ${this.iAmConnected}`); - const message = { - glue42core: { - type: this.messages.gatewayDisconnect.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.port?.postMessage(message); - this.parentReady = false; - this.notifyStatusChanged(false, "manual reconnection"); - return Promise.resolve(); - } - name() { - return "web-platform"; - } - async reconnect() { - await this.close(); - return Promise.resolve(); - } - initiateInternalConnection() { - return new Promise((resolve, reject) => { - this.logger.debug("opening an internal web platform connection"); - this.port = this.settings.port; - if (this.iAmConnected) { - this.logger.warn("cannot open a new connection, because this client is currently connected"); - return; - } - this.port.onmessage = (event) => { - if (this.iAmConnected && !event.data?.glue42core) { - this.registry.execute("onMessage", event.data); - return; - } - const data = event.data?.glue42core; - if (!data) { - return; - } - if (data.type === this.messages.gatewayInternalConnect.name && data.success) { - this.publicWindowId = this.settings.windowId; - if (this.identity && this.publicWindowId) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.publicWindowId; - } - resolve(); - } - if (data.type === this.messages.gatewayInternalConnect.name && data.error) { - reject(data.error); - } - }; - this.port.postMessage({ - glue42core: { - type: this.messages.gatewayInternalConnect.name - } - }); - }); - } - initiateRemoteConnection(target) { - return PromisePlus((resolve, reject) => { - this.connectionResolve = resolve; - this.connectionReject = reject; - this.myClientId = this.myClientId ?? nanoid(10); - const bridgeInstanceId = this.getMyWindowId() || nanoid(10); - const request = { - glue42core: { - type: this.messages.connectionRequest.name, - clientId: this.myClientId, - clientType: "child", - bridgeInstanceId, - selfAssignedWindowId: this.selfAssignedWindowId - } - }; - this.logger.debug(`sending connection request - clientId: ${this.myClientId}`); - if (this.extContentConnecting) { - request.glue42core.clientType = "child"; - request.glue42core.bridgeInstanceId = this.myClientId; - request.glue42core.parentWindowId = this.parentWindowId; - return window.postMessage(request, window.origin); - } - if (!target) { - throw new Error("Cannot send a connection request, because no glue target was specified!"); - } - target.postMessage(request, this.defaultTargetString); - }, this.connectionRequestTimeout, "The connection to the target glue window timed out"); - } - async isParentCheckSuccess(parentCheck) { - try { - await parentCheck; - return { success: true }; - } - catch (error) { - return { success: false }; - } - } - setUpMessageListener() { - if (this.settings.port) { - this.logger.debug("skipping generic message listener, because this is an internal client"); - return; - } - this.logger.debug("setting up window message listener"); - window.addEventListener("message", (event) => { - const data = event.data?.glue42core; - if (!data || this.rejected) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - if (!this.checkMessageTypeValid(data.type)) { - this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${data.type}`); - return; - } - const messageType = data.type; - this.logger.debug(`received valid glue42core message of type: ${messageType}`); - this.messages[messageType].handle(event); - }); - } - setUpUnload() { - if (this.settings.port) { - this.logger.debug("skipping unload event listener, because this is an internal client"); - return; - } - this.logger.debug("setting up unload event listeners"); - window.addEventListener("beforeunload", () => { - if (this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - window.addEventListener("pagehide", () => { - if (!this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - } - signalClientDisappearing() { - if (this.extContentConnected) { - return; - } - this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.parent?.postMessage(message, this.defaultTargetString); - this.port?.postMessage(message); - } - handlePlatformReady(event) { - this.logger.debug("the web platform gave the ready signal"); - this.parentReady = true; - if (this.parentPingResolve) { - this.parentPingResolve(); - delete this.parentPingResolve; - } - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - this.parent = event.source; - this.parentType = window.name.includes("#wsp") ? "workspace" : "window"; - } - handleConnectionAccepted(event) { - const data = event.data?.glue42core; - if (this.myClientId !== data.clientId) { - return this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${data.clientId}`); - } - return this.handleAcceptanceOfMyRequest(data); - } - handleAcceptanceOfMyRequest(data) { - this.logger.debug("handling a connection accepted signal targeted at me."); - this.isPreferredActivated = data.isPreferredActivated; - if (this.extContentConnecting) { - return this.processExtContentConnection(data); - } - if (!data.port) { - this.logger.error("cannot set up my connection, because I was not provided with a port"); - return; - } - this._connectionProtocolVersion = data.connectionProtocolVersion; - this.publicWindowId = this.getMyWindowId(); - if (this.identity) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.identity.instance ? this.identity.instance : this.publicWindowId || nanoid(10); - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - this._communicationId = data.communicationId; - this.port = data.port; - this.port.onmessage = (e) => this.registry.execute("onMessage", e.data); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - this.logger.error("unable to call the connection resolve, because no connection promise was found"); - } - processExtContentConnection(data) { - this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."); - this.extContentConnecting = false; - this.extContentConnected = true; - this.publicWindowId = this.parentWindowId || this.myClientId; - if (this.extContentConnecting && this.identity) { - this.identity.windowId = this.publicWindowId; - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - window.addEventListener("message", (event) => { - const extData = event.data?.glue42ExtInc; - if (!extData) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - this.registry.execute("onMessage", extData); - }); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - } - handleConnectionRejected(event) { - this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"); - if (!this.connectionReject) { - return; - } - const errorMsg = typeof event.data.glue42core?.error === "string" - ? `Connection was rejected. ${event.data.glue42core?.error}` - : "The platform connection was rejected. Most likely because this window was not created by a glue API call"; - this.connectionReject(errorMsg); - delete this.connectionReject; - } - handleConnectionRequest() { - if (this.extContentConnecting) { - this.logger.debug("This connection request event is targeted at the extension content"); - return; - } - } - handleParentPing(event) { - if (!this.parentReady) { - this.logger.debug("my parent is not ready, I am ignoring the parent ping"); - return; - } - if (!this.iAmConnected) { - this.logger.debug("i am not fully connected yet, I am ignoring the parent ping"); - return; - } - const message = { - glue42core: { - type: this.messages.parentReady.name - } - }; - if (this.extContentConnected) { - message.glue42core.extMode = { windowId: this.myClientId }; - } - const source = event.source; - this.logger.debug("responding to a parent ping with a ready message"); - source.postMessage(message, event.origin); - } - setupPlatformUnloadListener() { - this.logger.debug("setting up platform unload listener"); - this.onMessage((msg) => { - if (msg.type === "platformUnload") { - this.logger.debug("detected a web platform unload"); - this.parentReady = false; - this.notifyStatusChanged(false, "Gateway unloaded"); - } - }); - } - handleManualUnload() { - this.logger.debug("handling manual unload"); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: message }, window.origin); - } - this.port?.postMessage(message); - } - handlePlatformPing() { - return; - } - notifyStatusChanged(status, reason) { - this.logger.debug(`status changed - connected: ${status}, reason: ${reason || "none"}`); - this.iAmConnected = status; - this.registry.execute("onConnectedChanged", status, reason); - } - checkMessageTypeValid(typeToValidate) { - return typeof typeToValidate === "string" && !!this.messages[typeToValidate]; - } - requestConnectionPermissionFromExt() { - return this.waitForContentScript() - .then(() => PromisePlus((resolve, reject) => { - this.extConnectionResolve = resolve; - this.extConnectionReject = reject; - const message = { - glue42core: { - type: "extSetupRequest" - } - }; - this.logger.debug("permission request to the extension content script was sent"); - window.postMessage(message, window.origin); - }, this.parentPingTimeout, "Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")); - } - handleExtConnectionResponse(event) { - const data = event.data?.glue42core; - if (!data.approved) { - return this.extConnectionReject ? this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected") : undefined; - } - if (this.extConnectionResolve) { - this.extConnectionResolve(); - delete this.extConnectionResolve; - } - this.extContentConnecting = true; - this.parentType = "extension"; - this.logger.debug("The extension connection was approved, proceeding."); - } - handleExtSetupRequest() { - return; - } - handleGatewayDisconnect() { - return; - } - handleGatewayInternalConnect() { - return; - } - waitForContentScript() { - const contentReady = !!window.glue42ext?.content; - if (contentReady) { - return Promise.resolve(); - } - return PromisePlus((resolve) => { - window.addEventListener("Glue42EXTReady", () => { - resolve(); - }); - }, this.connectionRequestTimeout, "The content script was available, but was never heard to be ready"); - } - async connect() { - if (this.settings.port) { - await this.initiateInternalConnection(); - this.logger.debug("internal web platform connection completed"); - return; - } - this.logger.debug("opening a client web platform connection"); - await this.findParent(); - await this.initiateRemoteConnection(this.parent); - this.logger.debug("the client is connected"); - } - async findParent() { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const myInsideParents = this.getPossibleParentsInWindow(window); - const myOutsideParents = this.getPossibleParentsOutsideWindow(window.top?.opener, window.top); - const uniqueParents = new Set([...myInsideParents, ...myOutsideParents]); - if (!uniqueParents.size && !this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - if (!uniqueParents.size && this.extContentAvailable) { - await this.requestConnectionPermissionFromExt(); - return; - } - const defaultParentCheck = await this.isParentCheckSuccess(this.confirmParent(Array.from(uniqueParents))); - if (defaultParentCheck.success) { - this.logger.debug("The default parent was found!"); - return; - } - if (!this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - await this.requestConnectionPermissionFromExt(); - } - getPossibleParentsInWindow(currentWindow) { - return (!currentWindow?.parent || currentWindow === currentWindow.parent) ? [] : [currentWindow.parent, ...this.getPossibleParentsInWindow(currentWindow.parent)]; - } - getPossibleParentsOutsideWindow(opener, current) { - return (!opener || !current || opener === current) ? [] : [opener, ...this.getPossibleParentsInWindow(opener), ...this.getPossibleParentsOutsideWindow(opener.opener, opener)]; - } - confirmParent(targets) { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const parentCheck = PromisePlus((resolve) => { - this.parentPingResolve = resolve; - const message = { - glue42core: { - type: this.messages.platformPing.name - } - }; - this.parentPingInterval = setInterval(() => { - targets.forEach((target) => { - target.postMessage(message, this.defaultTargetString); - }); - }, 1000); - }, this.parentPingTimeout, connectionNotPossibleMsg); - parentCheck.catch(() => { - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - }); - return parentCheck; - } - getMyWindowId() { - if (this.parentType === "workspace") { - return window.name.substring(0, window.name.indexOf("#wsp")); - } - if (window !== window.top) { - return; - } - if (window.name?.includes("g42")) { - return window.name; - } - this.selfAssignedWindowId = this.selfAssignedWindowId || `g42-${nanoid(10)}`; - return this.selfAssignedWindowId; - } - } - - const waitForInvocations = (invocations, callback) => { - let left = invocations; - return () => { - left--; - if (left === 0) { - callback(); - } - }; - }; - - class AsyncSequelizer { - minSequenceInterval; - queue = []; - isExecutingQueue = false; - constructor(minSequenceInterval = 0) { - this.minSequenceInterval = minSequenceInterval; - } - enqueue(action) { - return new Promise((resolve, reject) => { - this.queue.push({ action, resolve, reject }); - this.executeQueue(); - }); - } - async executeQueue() { - if (this.isExecutingQueue) { - return; - } - this.isExecutingQueue = true; - while (this.queue.length) { - const operation = this.queue.shift(); - if (!operation) { - this.isExecutingQueue = false; - return; - } - try { - const actionResult = await operation.action(); - operation.resolve(actionResult); - } - catch (error) { - operation.reject(error); - } - await this.intervalBreak(); - } - this.isExecutingQueue = false; - } - intervalBreak() { - return new Promise((res) => setTimeout(res, this.minSequenceInterval)); - } - } - - function domainSession (domain, connection, logger, successMessages, errorMessages) { - if (domain == null) { - domain = "global"; - } - successMessages = successMessages ?? ["success"]; - errorMessages = errorMessages ?? ["error"]; - let isJoined = domain === "global"; - let tryReconnecting = false; - let _latestOptions; - let _connectionOn = false; - const callbacks = CallbackRegistryFactory(); - connection.disconnected(handleConnectionDisconnected); - connection.loggedIn(handleConnectionLoggedIn); - connection.on("success", (msg) => handleSuccessMessage(msg)); - connection.on("error", (msg) => handleErrorMessage(msg)); - connection.on("result", (msg) => handleSuccessMessage(msg)); - if (successMessages) { - successMessages.forEach((sm) => { - connection.on(sm, (msg) => handleSuccessMessage(msg)); - }); - } - if (errorMessages) { - errorMessages.forEach((sm) => { - connection.on(sm, (msg) => handleErrorMessage(msg)); - }); - } - const requestsMap = {}; - function join(options) { - _latestOptions = options; - return new Promise((resolve, reject) => { - if (isJoined) { - resolve({}); - return; - } - let joinPromise; - if (domain === "global") { - joinPromise = _connectionOn ? Promise.resolve({}) : Promise.reject("not connected to gateway"); - } - else { - logger.debug(`joining domain ${domain}`); - const joinMsg = { - type: "join", - destination: domain, - domain: "global", - options, - }; - joinPromise = send(joinMsg); - } - joinPromise - .then(() => { - handleJoined(); - resolve({}); - }) - .catch((err) => { - logger.debug("error joining " + domain + " domain: " + JSON.stringify(err)); - reject(err); - }); - }); - } - function leave() { - if (domain === "global") { - return Promise.resolve(); - } - logger.debug("stopping session " + domain + "..."); - const leaveMsg = { - type: "leave", - destination: domain, - domain: "global", - }; - tryReconnecting = false; - return send(leaveMsg) - .then(() => { - isJoined = false; - callbacks.execute("onLeft"); - }) - .catch(() => { - isJoined = false; - callbacks.execute("onLeft"); - }); - } - function handleJoined() { - logger.debug("did join " + domain); - isJoined = true; - const wasReconnect = tryReconnecting; - tryReconnecting = false; - callbacks.execute("onJoined", wasReconnect); - } - function handleConnectionDisconnected() { - logger.debug("connection is down"); - _connectionOn = false; - isJoined = false; - tryReconnecting = true; - Object.keys(requestsMap).forEach(requestId => { - const request = requestsMap[requestId]; - if (request) { - logger.trace(`failing pending request ${requestId} due to connection lost`); - request.error({ - err: "Connection lost - gateway connection was disconnected" - }); - } - }); - callbacks.execute("onLeft", { disconnected: true }); - } - async function handleConnectionLoggedIn() { - _connectionOn = true; - if (tryReconnecting) { - logger.debug("connection is now up - trying to reconnect..."); - try { - await join(_latestOptions); - } - catch { - logger.trace(`failed to reconnect`); - } - } - } - function onJoined(callback) { - if (isJoined) { - callback(false); - } - return callbacks.add("onJoined", callback); - } - function onLeft(callback) { - if (!isJoined) { - callback(); - } - return callbacks.add("onLeft", callback); - } - function handleErrorMessage(msg) { - if (domain !== msg.domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.error(msg); - } - function handleSuccessMessage(msg) { - if (msg.domain !== domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.success(msg); - } - function getNextRequestId() { - return nanoid(10); - } - let queuedCalls = []; - function send(msg, tag, options) { - const ignore = ["hello", "join"]; - if (msg.type && ignore.indexOf(msg.type) === -1) { - if (!isJoined) { - console.warn(`trying to send a message (${msg.domain} ${msg.type}) but not connected, will queue`); - const pw = new PromiseWrapper(); - queuedCalls.push({ msg, tag, options, pw }); - if (queuedCalls.length === 1) { - const unsubscribe = onJoined(() => { - logger.info(`joined - will now send queued messages (${queuedCalls.length} -> [${queuedCalls.map((m) => m.msg.type)}])`); - queuedCalls.forEach((qm) => { - send(qm.msg, qm.tag, qm.options) - .then((t) => qm.pw.resolve(t)) - .catch((e) => qm.pw.reject(e)); - }); - queuedCalls = []; - unsubscribe(); - }); - } - return pw.promise; - } - } - options = options ?? {}; - msg.request_id = msg.request_id ?? getNextRequestId(); - msg.domain = msg.domain ?? domain; - if (!options.skipPeerId) { - msg.peer_id = connection.peerId; - } - const requestId = msg.request_id; - return new Promise((resolve, reject) => { - requestsMap[requestId] = { - success: (successMsg) => { - delete requestsMap[requestId]; - successMsg._tag = tag; - resolve(successMsg); - }, - error: (errorMsg) => { - console.warn(`Gateway error - ${JSON.stringify(errorMsg)}`); - delete requestsMap[requestId]; - errorMsg._tag = tag; - reject(errorMsg); - }, - }; - connection - .send(msg, options) - .catch((err) => { - requestsMap[requestId]?.error({ err }); - }); - }); - } - function sendFireAndForget(msg) { - msg.request_id = msg.request_id ? msg.request_id : getNextRequestId(); - msg.domain = msg.domain ?? domain; - msg.peer_id = connection.peerId; - return connection.send(msg); - } - return { - join, - leave, - onJoined, - onLeft, - send, - sendFireAndForget, - on: (type, callback) => { - connection.on(type, (msg) => { - if (msg.domain !== domain) { - return; - } - try { - callback(msg); - } - catch (e) { - logger.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(msg)}`, e); - } - }); - }, - loggedIn: (callback) => connection.loggedIn(callback), - connected: (callback) => connection.connected(callback), - disconnected: (callback) => connection.disconnected(callback), - get peerId() { - return connection.peerId; - }, - get domain() { - return domain; - }, - }; - } - - class Connection { - settings; - logger; - protocolVersion = 3; - peerId; - token; - info; - resolvedIdentity; - availableDomains; - gatewayToken; - replayer; - messageHandlers = {}; - ids = 1; - registry = CallbackRegistryFactory(); - _connected = false; - isTrace = false; - transport; - _defaultTransport; - _defaultAuth; - _targetTransport; - _targetAuth; - _swapTransport = false; - _switchInProgress = false; - _transportSubscriptions = []; - datePrefix = "#T42_DATE#"; - datePrefixLen = this.datePrefix.length; - dateMinLen = this.datePrefixLen + 1; - datePrefixFirstChar = this.datePrefix[0]; - _sequelizer = new AsyncSequelizer(); - _isLoggedIn = false; - shouldTryLogin = true; - pingTimer; - sessions = []; - globalDomain; - initialLogin = true; - initialLoginAttempts = 3; - loginConfig; - loginRetryInProgress = false; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - settings = settings || {}; - settings.reconnectAttempts = settings.reconnectAttempts ?? 10; - settings.reconnectInterval = settings.reconnectInterval ?? 1000; - if (settings.inproc) { - this.transport = new InProcTransport(settings.inproc, logger.subLogger("inMemory")); - } - else if (settings.sharedWorker) { - this.transport = new SharedWorkerTransport(settings.sharedWorker, logger.subLogger("shared-worker")); - } - else if (settings.webPlatform) { - this.transport = new WebPlatformTransport(settings.webPlatform, logger.subLogger("web-platform"), settings.identity); - } - else if (settings.ws !== undefined) { - this.transport = new WS(settings, logger.subLogger("ws")); - } - else { - throw new Error("No connection information specified"); - } - this.isTrace = logger.canPublish("trace"); - logger.debug(`starting with ${this.transport.name()} transport`); - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - this._defaultTransport = this.transport; - this.ping(); - } - async switchTransport(settings) { - return this._sequelizer.enqueue(async () => { - if (!settings || typeof settings !== "object") { - throw new Error("Cannot switch transports, because the settings are missing or invalid."); - } - if (typeof settings.type === "undefined") { - throw new Error("Cannot switch the transport, because the type is not defined"); - } - this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(settings)}`); - const switchTargetTransport = settings.type === "secondary" ? this.getNewSecondaryTransport(settings) : this._defaultTransport; - this._targetTransport = switchTargetTransport; - this._targetAuth = settings.type === "secondary" ? this.getNewSecondaryAuth(settings) : this._defaultAuth; - const verifyPromise = this.verifyConnection(); - this._swapTransport = true; - this._switchInProgress = true; - this.logger.trace("The new transport has been set, closing the current transport"); - await this.transport.close(); - try { - await verifyPromise; - const isSwitchSuccess = this.transport === switchTargetTransport; - this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${isSwitchSuccess}`); - this._switchInProgress = false; - return { success: isSwitchSuccess }; - } - catch (error) { - this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."); - this.switchTransport({ type: "default" }); - this._switchInProgress = false; - return { success: false }; - } - }); - } - onLibReAnnounced(callback) { - return this.registry.add("libReAnnounced", callback); - } - setLibReAnnounced(lib) { - this.registry.execute("libReAnnounced", lib); - } - send(message, options) { - if (this.transport.sendObject && - this.transport.isObjectBasedTransport) { - const msg = this.createObjectMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${JSON.stringify(msg)}`); - } - return this.transport.sendObject(msg, options); - } - else { - const strMessage = this.createStringMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${strMessage}`); - } - return this.transport.send(strMessage, options); - } - } - on(type, messageHandler) { - type = type.toLowerCase(); - if (this.messageHandlers[type] === undefined) { - this.messageHandlers[type] = {}; - } - const id = this.ids++; - this.messageHandlers[type][id] = messageHandler; - return { - type, - id, - }; - } - off(info) { - delete this.messageHandlers[info.type.toLowerCase()][info.id]; - } - get isConnected() { - return this._isLoggedIn; - } - connected(callback) { - return this.loggedIn(() => { - const currentServer = this.transport.name(); - callback(currentServer); - }); - } - disconnected(callback) { - return this.registry.add("disconnected", callback); - } - async login(authRequest, reconnect) { - this.logger.debug(`Login initiated - reconnect: ${reconnect}, transport: ${this.transport.name()}`); - if (!this._defaultAuth) { - this._defaultAuth = authRequest; - } - if (this._swapTransport) { - this.logger.trace("Detected a transport swap, swapping transports"); - const newAuth = this.transportSwap(); - authRequest = newAuth ?? authRequest; - } - try { - await this.transport.open(); - this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`); - timer("connection").mark("transport-opened"); - const identity = await this.loginCore(authRequest, reconnect); - this.logger.debug(`Logged in with identity: ${JSON.stringify(identity)}`); - timer("connection").mark("protocol-logged-in"); - return identity; - } - catch (error) { - if (this._switchInProgress) { - this.logger.debug("An error while logging in after a transport swap, preparing a default swap."); - this.prepareDefaultSwap(); - } - throw new Error(error); - } - } - async logout() { - await this.logoutCore(); - await this.transport.close(); - } - loggedIn(callback) { - if (this._isLoggedIn) { - callback(); - } - return this.registry.add("onLoggedIn", callback); - } - domain(domain, successMessages, errorMessages) { - let session = this.sessions.find((s) => s.domain === domain); - if (!session) { - session = domainSession(domain, this, this.logger.subLogger(`domain=${domain}`), successMessages, errorMessages); - this.sessions.push(session); - } - return session; - } - authToken() { - const createTokenReq = { - domain: "global", - type: "create-token" - }; - if (!this.globalDomain) { - return Promise.reject(new Error("no global domain session")); - } - return this.globalDomain.send(createTokenReq) - .then((res) => { - return res.token; - }); - } - reconnect() { - return this.transport.reconnect(); - } - setLoggedIn(value) { - this._isLoggedIn = value; - if (this._isLoggedIn) { - this.initialLogin = false; - this.registry.execute("onLoggedIn"); - } - } - distributeMessage(message, type) { - const handlers = this.messageHandlers[type.toLowerCase()]; - if (handlers !== undefined) { - Object.keys(handlers).forEach((handlerId) => { - const handler = handlers[handlerId]; - if (handler !== undefined) { - try { - handler(message); - } - catch (error) { - try { - this.logger.error(`Message handler failed with ${error.stack}`, error); - } - catch (loggerError) { - console.log("Message handler failed", error); - } - } - } - }); - } - } - handleConnectionChanged(connected) { - if (this._connected === connected) { - this.logger.trace("connection state unchanged, skipping"); - return; - } - this.logger.info(`connection state changed to ${connected ? "connected" : "disconnected"}`); - this._connected = connected; - if (connected) { - if (this.settings?.replaySpecs?.length) { - this.replayer = new MessageReplayerImpl(this.settings.replaySpecs); - this.replayer.init(this); - } - this.registry.execute("connected"); - } - else { - this.setLoggedIn(false); - if (this.shouldTryLogin) { - this.attemptLoginWithRetry(); - } - this.registry.execute("disconnected"); - } - } - async attemptLoginWithRetry() { - if (!this.loginConfig) { - throw new Error("no login info"); - } - if (this.loginRetryInProgress) { - this.logger.debug("login attempt already in progress, ignoring request..."); - return; - } - if (this._isLoggedIn) { - this.logger.debug("already logged in, ignoring request..."); - return; - } - if (this.initialLogin) { - this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`); - if (this.initialLoginAttempts <= 0) { - this.logger.info("maximum initial login attempts reached, will not try to login again"); - return; - } - this.initialLoginAttempts--; - } - try { - this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`); - this.loginRetryInProgress = true; - await this.login(this.loginConfig, true); - } - catch (e) { - this.logger.error(`error trying to login: ${e?.message}`, e); - setTimeout(this.attemptLoginWithRetry.bind(this), this.settings.reconnectInterval ?? 1000); - } - finally { - this.loginRetryInProgress = false; - } - } - handleTransportMessage(msg) { - let msgObj; - if (typeof msg === "string") { - msgObj = this.processStringMessage(msg); - } - else { - msgObj = this.processObjectMessage(msg); - } - if (this.isTrace) { - this.logger.trace(`<< ${JSON.stringify(msgObj)}`); - } - this.distributeMessage(msgObj.msg, msgObj.msgType); - } - verifyConnection() { - return PromisePlus((resolve) => { - let unsub; - const ready = waitForInvocations(2, () => { - if (unsub) { - unsub(); - } - resolve(); - }); - unsub = this.onLibReAnnounced((lib) => { - if (lib.name === "interop") { - return ready(); - } - if (lib.name === "contexts") { - return ready(); - } - }); - }, 10000, "Transport switch timed out waiting for all libraries to be re-announced"); - } - getNewSecondaryTransport(settings) { - if (!settings.transportConfig?.url) { - throw new Error("Missing secondary transport URL."); - } - return new WS(Object.assign({}, this.settings, { ws: settings.transportConfig.url, reconnectAttempts: 1 }), this.logger.subLogger("ws-secondary")); - } - getNewSecondaryAuth(settings) { - if (!settings.transportConfig?.auth) { - throw new Error("Missing secondary transport auth information."); - } - return settings.transportConfig.auth; - } - transportSwap() { - this._swapTransport = false; - if (!this._targetTransport || !this._targetAuth) { - this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`); - return; - } - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport = this._targetTransport; - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - return this._targetAuth; - } - prepareDefaultSwap() { - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport.close().catch((error) => this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(error)}`)); - this._targetTransport = this._defaultTransport; - this._targetAuth = this._defaultAuth; - this._swapTransport = true; - } - processStringMessage(message) { - const msg = JSON.parse(message, (key, value) => { - if (typeof value !== "string") { - return value; - } - if (value.length < this.dateMinLen) { - return value; - } - if (!value.startsWith(this.datePrefixFirstChar)) { - return value; - } - if (value.substring(0, this.datePrefixLen) !== this.datePrefix) { - return value; - } - try { - const milliseconds = parseInt(value.substring(this.datePrefixLen, value.length), 10); - if (isNaN(milliseconds)) { - return value; - } - return new Date(milliseconds); - } - catch (ex) { - return value; - } - }); - return { - msg, - msgType: msg.type, - }; - } - createStringMessage(message) { - const oldToJson = Date.prototype.toJSON; - try { - const datePrefix = this.datePrefix; - Date.prototype.toJSON = function () { - return datePrefix + this.getTime(); - }; - const result = JSON.stringify(message); - return result; - } - finally { - Date.prototype.toJSON = oldToJson; - } - } - processObjectMessage(message) { - if (!message.type) { - throw new Error("Object should have type property"); - } - return { - msg: message, - msgType: message.type, - }; - } - createObjectMessage(message) { - return message; - } - async loginCore(config, reconnect) { - this.loginConfig = config; - if (!this.loginConfig) { - this.loginConfig = { username: "", password: "" }; - } - this.shouldTryLogin = true; - const authentication = await this.setupAuthConfig(config, reconnect); - const helloMsg = { - type: "hello", - identity: this.settings.identity, - authentication - }; - if (config.sessionId) { - helloMsg.request_id = config.sessionId; - } - if (!this.globalDomain) { - this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [ - "welcome", - "token", - "authentication-request" - ]); - } - const sendOptions = { skipPeerId: true }; - if (this.initialLogin) { - sendOptions.retryInterval = this.settings.reconnectInterval; - sendOptions.maxRetries = this.settings.reconnectAttempts; - } - try { - const welcomeMsg = await this.tryAuthenticate(this.globalDomain, helloMsg, sendOptions, config); - this.logger.info("login successful with peerId " + welcomeMsg.peer_id); - this.peerId = welcomeMsg.peer_id; - this.resolvedIdentity = welcomeMsg.resolved_identity; - this.availableDomains = welcomeMsg.available_domains; - if (welcomeMsg.options) { - this.token = welcomeMsg.options.access_token; - this.info = welcomeMsg.options.info; - } - this.setLoggedIn(true); - return welcomeMsg.resolved_identity; - } - catch (err) { - this.logger.error("error sending hello message - " + (err.message || err.msg || err.reason || err), err); - throw err; - } - finally { - if (config?.flowCallback && config.sessionId) { - config.flowCallback(config.sessionId, null); - } - } - } - async tryAuthenticate(globalDomain, helloMsg, sendOptions, config) { - let welcomeMsg; - while (true) { - const msg = await globalDomain.send(helloMsg, undefined, sendOptions); - if (msg.type === "authentication-request") { - const token = Buffer.from(msg.authentication.token, "base64"); - if (config.flowCallback && config.sessionId) { - helloMsg.authentication.token = - (await config.flowCallback(config.sessionId, token)) - .data - .toString("base64"); - } - helloMsg.request_id = config.sessionId; - } - else if (msg.type === "welcome") { - welcomeMsg = msg; - break; - } - else if (msg.type === "error") { - throw new Error("Authentication failed: " + msg.reason); - } - else { - throw new Error("Unexpected message type during authentication: " + msg.type); - } - } - return welcomeMsg; - } - async setupAuthConfig(config, reconnect) { - const authentication = {}; - this.gatewayToken = config.gatewayToken; - if (config.gatewayToken) { - if (reconnect) { - try { - config.gatewayToken = await this.getNewGWToken(); - } - catch (e) { - this.logger.warn(`failed to get GW token when reconnecting ${e?.message || e}`); - } - } - authentication.method = "gateway-token"; - authentication.token = config.gatewayToken; - this.gatewayToken = config.gatewayToken; - } - else if (config.flowName === "sspi") { - authentication.provider = "win"; - authentication.method = "access-token"; - if (config.flowCallback && config.sessionId) { - authentication.token = - (await config.flowCallback(config.sessionId, null)) - .data - .toString("base64"); - } - else { - throw new Error("Invalid SSPI config"); - } - } - else if (config.token) { - authentication.method = "access-token"; - authentication.token = config.token; - } - else if (config.username) { - authentication.method = "secret"; - authentication.login = config.username; - authentication.secret = config.password; - } - else if (config.provider) { - authentication.provider = config.provider; - authentication.providerContext = config.providerContext; - } - else { - throw new Error("invalid auth message" + JSON.stringify(config)); - } - return authentication; - } - async logoutCore() { - this.logger.debug("core logging out..."); - this.shouldTryLogin = false; - if (this.pingTimer) { - clearTimeout(this.pingTimer); - } - const promises = this.sessions.map((session) => { - return session.leave(); - }); - await Promise.all(promises); - } - getNewGWToken() { - if (typeof window !== "undefined") { - const glue42gd = window.glue42gd; - if (glue42gd) { - return glue42gd.getGWToken(); - } - } - return Promise.reject(new Error("not running in GD")); - } - ping() { - if (!this.shouldTryLogin) { - return; - } - if (this._isLoggedIn) { - this.send({ type: "ping" }); - } - this.pingTimer = setTimeout(() => { - this.ping(); - }, 30 * 1000); - } - } - - const order = ["trace", "debug", "info", "warn", "error", "off"]; - class Logger { - name; - parent; - static Interop; - static InteropMethodName = "T42.AppLogger.Log"; - static Instance; - path; - subLoggers = []; - _consoleLevel; - _publishLevel; - loggerFullName; - includeTimeAndLevel; - logFn = console; - customLogFn = false; - constructor(name, parent, logFn) { - this.name = name; - this.parent = parent; - this.name = name; - if (parent) { - this.path = `${parent.path}.${name}`; - } - else { - this.path = name; - } - this.loggerFullName = `[${this.path}]`; - this.includeTimeAndLevel = !logFn; - if (logFn) { - this.logFn = logFn; - this.customLogFn = true; - } - } - subLogger(name) { - const existingSub = this.subLoggers.filter((subLogger) => { - return subLogger.name === name; - })[0]; - if (existingSub !== undefined) { - return existingSub; - } - Object.keys(this).forEach((key) => { - if (key === name) { - throw new Error("This sub logger name is not allowed."); - } - }); - const sub = new Logger(name, this, this.customLogFn ? this.logFn : undefined); - this.subLoggers.push(sub); - return sub; - } - publishLevel(level) { - if (level) { - this._publishLevel = level; - } - return this._publishLevel || this.parent?.publishLevel(); - } - consoleLevel(level) { - if (level) { - this._consoleLevel = level; - } - return this._consoleLevel || this.parent?.consoleLevel(); - } - log(message, level, error) { - this.publishMessage(level || "info", message, error); - } - trace(message) { - this.log(message, "trace"); - } - debug(message) { - this.log(message, "debug"); - } - info(message) { - this.log(message, "info"); - } - warn(message) { - this.log(message, "warn"); - } - error(message, err) { - this.log(message, "error", err); - } - canPublish(level, compareWith) { - const levelIdx = order.indexOf(level); - const restrictionIdx = order.indexOf(compareWith || this.consoleLevel() || "trace"); - return levelIdx >= restrictionIdx; - } - publishMessage(level, message, error) { - const loggerName = this.loggerFullName; - if (level === "error" && !error) { - const e = new Error(); - if (e.stack) { - message = - message + - "\n" + - e.stack - .split("\n") - .slice(4) - .join("\n"); - } - } - if (this.canPublish(level, this.publishLevel())) { - const interop = Logger.Interop; - if (interop) { - try { - if (interop.methods({ name: Logger.InteropMethodName }).length > 0) { - const args = { - msg: message, - logger: loggerName, - level - }; - if (error && error instanceof Error) { - args.error = { - message: error.message, - stack: error.stack ?? "" - }; - } - interop.invoke(Logger.InteropMethodName, args) - .catch((e) => { - this.logFn.error(`Unable to send log message to the platform: ${e.message}`, e); - }); - } - } - catch { - } - } - } - if (this.canPublish(level)) { - let prefix = ""; - if (this.includeTimeAndLevel) { - const date = new Date(); - const time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`; - prefix = `[${time}] [${level}] `; - } - const toPrint = `${prefix}${loggerName}: ${message}`; - switch (level) { - case "trace": - this.logFn.debug(toPrint); - break; - case "debug": - if (this.logFn.debug) { - this.logFn.debug(toPrint); - } - else { - this.logFn.log(toPrint); - } - break; - case "info": - this.logFn.info(toPrint); - break; - case "warn": - this.logFn.warn(toPrint); - break; - case "error": - if (error) { - this.logFn.error(toPrint, error); - } - else { - this.logFn.error(toPrint); - } - break; - } - } - } - } - - const GW_MESSAGE_CREATE_CONTEXT = "create-context"; - const GW_MESSAGE_ACTIVITY_CREATED = "created"; - const GW_MESSAGE_ACTIVITY_DESTROYED = "destroyed"; - const GW_MESSAGE_CONTEXT_CREATED = "context-created"; - const GW_MESSAGE_CONTEXT_ADDED = "context-added"; - const GW_MESSAGE_SUBSCRIBE_CONTEXT = "subscribe-context"; - const GW_MESSAGE_SUBSCRIBED_CONTEXT = "subscribed-context"; - const GW_MESSAGE_UNSUBSCRIBE_CONTEXT = "unsubscribe-context"; - const GW_MESSAGE_DESTROY_CONTEXT = "destroy-context"; - const GW_MESSAGE_CONTEXT_DESTROYED = "context-destroyed"; - const GW_MESSAGE_UPDATE_CONTEXT = "update-context"; - const GW_MESSAGE_CONTEXT_UPDATED = "context-updated"; - const GW_MESSAGE_JOINED_ACTIVITY = "joined"; - - const ContextMessageReplaySpec = { - get name() { - return "context"; - }, - get types() { - return [ - GW_MESSAGE_CREATE_CONTEXT, - GW_MESSAGE_ACTIVITY_CREATED, - GW_MESSAGE_ACTIVITY_DESTROYED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_SUBSCRIBE_CONTEXT, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - GW_MESSAGE_DESTROY_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_UPDATE_CONTEXT, - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_JOINED_ACTIVITY - ]; - } - }; - - var version = "6.8.1"; - - function prepareConfig (configuration, ext, glue42gd) { - let nodeStartingContext; - if (Utils.isNode()) { - const startingContextString = process.env._GD_STARTING_CONTEXT_; - if (startingContextString) { - try { - nodeStartingContext = JSON.parse(startingContextString); - } - catch { - } - } - } - function getConnection() { - const gwConfig = configuration.gateway; - const protocolVersion = gwConfig?.protocolVersion ?? 3; - const reconnectInterval = gwConfig?.reconnectInterval; - const reconnectAttempts = gwConfig?.reconnectAttempts; - const defaultWs = "ws://localhost:8385"; - let ws = gwConfig?.ws; - const sharedWorker = gwConfig?.sharedWorker; - const inproc = gwConfig?.inproc; - const webPlatform = gwConfig?.webPlatform ?? undefined; - if (glue42gd) { - ws = glue42gd.gwURL; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) { - ws = nodeStartingContext.gwURL; - } - if (!ws && !sharedWorker && !inproc) { - ws = defaultWs; - } - let instanceId; - let windowId; - let pid; - let environment; - let region; - const appName = getApplication(); - let uniqueAppName = appName; - if (typeof glue42gd !== "undefined") { - windowId = glue42gd.windowId; - pid = glue42gd.pid; - if (glue42gd.env) { - environment = glue42gd.env.env; - region = glue42gd.env.region; - } - uniqueAppName = glue42gd.application ?? "glue-app"; - instanceId = glue42gd.appInstanceId; - } - else if (Utils.isNode()) { - pid = process.pid; - if (nodeStartingContext) { - environment = nodeStartingContext.env; - region = nodeStartingContext.region; - instanceId = nodeStartingContext.instanceId; - } - } - else if (typeof window?.glue42electron !== "undefined") { - windowId = window?.glue42electron.instanceId; - pid = window?.glue42electron.pid; - environment = window?.glue42electron.env; - region = window?.glue42electron.region; - uniqueAppName = window?.glue42electron.application ?? "glue-app"; - instanceId = window?.glue42electron.instanceId; - } - else ; - const replaySpecs = configuration.gateway?.replaySpecs ?? []; - replaySpecs.push(ContextMessageReplaySpec); - let identity = { - application: uniqueAppName, - applicationName: appName, - windowId, - instance: instanceId, - process: pid, - region, - environment, - api: ext.version || version - }; - if (configuration.identity) { - identity = Object.assign(identity, configuration.identity); - } - return { - identity, - reconnectInterval, - ws, - sharedWorker, - webPlatform, - inproc, - protocolVersion, - reconnectAttempts, - replaySpecs, - }; - } - function getContexts() { - const defaultConfig = { - reAnnounceKnownContexts: true, - subscribeOnUpdate: true, - subscribeOnGet: true, - onlyReAnnounceSubscribedContexts: true - }; - if (typeof configuration.contexts === "undefined") { - return defaultConfig; - } - if (typeof configuration.contexts === "boolean" && configuration.contexts) { - return defaultConfig; - } - if (typeof configuration.contexts === "object") { - return { ...defaultConfig, ...configuration.contexts }; - } - return false; - } - function getApplication() { - if (configuration.application) { - return configuration.application; - } - if (glue42gd) { - return glue42gd.applicationName; - } - if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") { - return window.glue42electron.application; - } - const uid = nanoid(10); - if (Utils.isNode()) { - if (nodeStartingContext) { - return nodeStartingContext.applicationConfig.name; - } - return "NodeJS" + uid; - } - if (typeof window !== "undefined" && typeof document !== "undefined") { - return document.title + ` (${uid})`; - } - return uid; - } - function getAuth() { - if (typeof configuration.auth === "string") { - return { - token: configuration.auth - }; - } - if (configuration.auth) { - return configuration.auth; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) { - return { - gatewayToken: nodeStartingContext.gwToken - }; - } - if (configuration.gateway?.webPlatform) { - return { - username: "glue42", - password: "" - }; - } - } - function getLogger() { - let config = configuration.logger; - const defaultLevel = "warn"; - if (!config) { - config = defaultLevel; - } - let gdConsoleLevel; - if (glue42gd) { - gdConsoleLevel = glue42gd.consoleLogLevel; - } - if (typeof config === "string") { - return { console: gdConsoleLevel ?? config, publish: defaultLevel }; - } - return { - console: gdConsoleLevel ?? config.console ?? defaultLevel, - publish: config.publish ?? defaultLevel - }; - } - const connection = getConnection(); - let application = getApplication(); - if (typeof window !== "undefined") { - const windowAsAny = window; - const containerApplication = windowAsAny.htmlContainer ? - `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` : - windowAsAny?.glue42gd?.application; - if (containerApplication) { - application = containerApplication; - } - } - return { - bus: configuration.bus ?? false, - application, - auth: getAuth(), - logger: getLogger(), - connection, - metrics: configuration.metrics ?? true, - contexts: getContexts(), - version: ext.version || version, - libs: ext.libs ?? [], - customLogger: configuration.customLogger - }; - } - - class GW3ContextData { - name; - contextId; - context; - isAnnounced; - createdByUs; - joinedActivity; - updateCallbacks = {}; - activityId; - sentExplicitSubscription; - get hasReceivedSnapshot() { - return this.snapshotPromiseWrapper.resolved; - } - set hasReceivedSnapshot(has) { - if (has) { - this.snapshotPromiseWrapper.resolve(); - } - else { - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - } - get snapshotPromise() { - return this.snapshotPromiseWrapper.promise; - } - snapshotPromiseWrapper; - constructor(contextId, name, isAnnounced, activityId) { - this.contextId = contextId; - this.name = name; - this.isAnnounced = isAnnounced; - this.activityId = activityId; - this.context = {}; - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - hasCallbacks() { - return Object.keys(this.updateCallbacks).length > 0; - } - getState() { - if (this.isAnnounced && this.hasCallbacks()) { - return 3; - } - if (this.isAnnounced) { - return 2; - } - if (this.hasCallbacks()) { - return 1; - } - return 0; - } - } - - var lodash_clonedeep = {exports: {}}; - - /** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - lodash_clonedeep.exports; - - (function (module, exports) { - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** - * Adds the key-value `pair` to `map`. - * - * @private - * @param {Object} map The map to modify. - * @param {Array} pair The key-value pair to add. - * @returns {Object} Returns `map`. - */ - function addMapEntry(map, pair) { - // Don't return `map.set` because it's not chainable in IE 11. - map.set(pair[0], pair[1]); - return map; - } - - /** - * Adds `value` to `set`. - * - * @private - * @param {Object} set The set to modify. - * @param {*} value The value to add. - * @returns {Object} Returns `set`. - */ - function addSetEntry(set, value) { - // Don't return `set.add` because it's not chainable in IE 11. - set.add(value); - return set; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array ? array.length : 0; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array ? array.length : 0; - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ - function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var objectToString = objectProto.toString; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined, - Symbol = root.Symbol, - Uint8Array = root.Uint8Array, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeKeys = overArg(Object.keys, Object); - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'), - Map = getNative(root, 'Map'), - Promise = getNative(root, 'Promise'), - Set = getNative(root, 'Set'), - WeakMap = getNative(root, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - this.__data__ = new ListCache(entries); - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - return this.__data__['delete'](key); - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var cache = this.__data__; - if (cache instanceof ListCache) { - var pairs = cache.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - return this; - } - cache = this.__data__ = new MapCache(pairs); - } - cache.set(key, value); - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - - var length = result.length, - skipIndexes = !!length; - - for (var key in value) { - if ((hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {boolean} [isFull] Specify a clone including symbols. - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, isFull, customizer, key, object, stack) { - var result; - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - if (isHostObject(value)) { - return object ? value : {}; - } - result = initCloneObject(isFunc ? {} : value); - if (!isDeep) { - return copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, baseClone, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (!isArr) { - var props = isFull ? getAllKeys(value) : keys(value); - } - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(proto) { - return isObject(proto) ? objectCreate(proto) : {}; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - return objectToString.call(value); - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var result = new buffer.constructor(buffer.length); - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `map`. - * - * @private - * @param {Object} map The map to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned map. - */ - function cloneMap(map, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); - return arrayReduce(array, addMapEntry, new map.constructor); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of `set`. - * - * @private - * @param {Object} set The set to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned set. - */ - function cloneSet(set, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); - return arrayReduce(array, addSetEntry, new set.constructor); - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = undefined; - - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; - } - - /** - * Copies own symbol properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * Creates an array of the own enumerable symbol properties of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11, - // for data views in Edge < 14, and promises in Node.js. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = objectToString.call(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : undefined; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, cloneFunc, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return cloneMap(object, isDeep, cloneFunc); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return cloneSet(object, isDeep, cloneFunc); - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, true, true); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return !!value && typeof value == 'object'; - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - module.exports = cloneDeep; - } (lodash_clonedeep, lodash_clonedeep.exports)); - - var lodash_clonedeepExports = lodash_clonedeep.exports; - var cloneDeep = /*@__PURE__*/getDefaultExportFromCjs(lodash_clonedeepExports); - - function applyContextDelta(context, delta, logger) { - try { - if (logger?.canPublish("trace")) { - logger?.trace(`applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`); - } - if (!delta) { - return context; - } - if (delta.reset) { - context = { ...delta.reset }; - return context; - } - context = deepClone(context, undefined); - if (delta.commands) { - for (const command of delta.commands) { - if (command.type === "remove") { - deletePath(context, command.path); - } - else if (command.type === "set") { - setValueToPath(context, command.value, command.path); - } - } - return context; - } - const added = delta.added; - const updated = delta.updated; - const removed = delta.removed; - if (added) { - Object.keys(added).forEach((key) => { - context[key] = added[key]; - }); - } - if (updated) { - Object.keys(updated).forEach((key) => { - mergeObjectsProperties(key, context, updated); - }); - } - if (removed) { - removed.forEach((key) => { - delete context[key]; - }); - } - return context; - } - catch (e) { - logger?.error(`error applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`, e); - return context; - } - } - function deepClone(obj, hash) { - return cloneDeep(obj); - } - const mergeObjectsProperties = (key, what, withWhat) => { - const right = withWhat[key]; - if (right === undefined) { - return what; - } - const left = what[key]; - if (!left || !right) { - what[key] = right; - return what; - } - if (typeof left === "string" || - typeof left === "number" || - typeof left === "boolean" || - typeof right === "string" || - typeof right === "number" || - typeof right === "boolean" || - Array.isArray(left) || - Array.isArray(right)) { - what[key] = right; - return what; - } - what[key] = Object.assign({}, left, right); - return what; - }; - function deepEqual(x, y) { - if (x === y) { - return true; - } - if (!(x instanceof Object) || !(y instanceof Object)) { - return false; - } - if (x.constructor !== y.constructor) { - return false; - } - for (const p in x) { - if (!x.hasOwnProperty(p)) { - continue; - } - if (!y.hasOwnProperty(p)) { - return false; - } - if (x[p] === y[p]) { - continue; - } - if (typeof (x[p]) !== "object") { - return false; - } - if (!deepEqual(x[p], y[p])) { - return false; - } - } - for (const p in y) { - if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) { - return false; - } - } - return true; - } - function setValueToPath(obj, value, path) { - const pathArr = path.split("."); - const forbiddenKeys = ["__proto__", "constructor", "prototype"]; - let i; - for (i = 0; i < pathArr.length - 1; i++) { - const key = pathArr[i]; - if (forbiddenKeys.includes(key)) { - throw new Error(`The provided path ${path} is invalid. It cannot contain segment/key that is equal to one of the following values: ${forbiddenKeys}.`); - } - if (!obj[key]) { - obj[key] = {}; - } - if (typeof obj[key] !== "object") { - obj[key] = {}; - } - obj = obj[key]; - } - obj[pathArr[i]] = value; - } - function isSubset(superObj, subObj) { - return Object.keys(subObj).every((ele) => { - if (typeof subObj[ele] === "object") { - return isSubset(superObj?.[ele] || {}, subObj[ele] || {}); - } - return subObj[ele] === superObj?.[ele]; - }); - } - function deletePath(obj, path) { - const pathArr = path.split("."); - let i; - for (i = 0; i < pathArr.length - 1; i++) { - if (!obj[pathArr[i]]) { - return; - } - obj = obj[pathArr[i]]; - } - delete obj[pathArr[i]]; - } - - class GW3Bridge { - ERROR_URI_FAILURE = "global.errors.failure"; - ERROR_URI_INVALID_CONTEXT = "global.errors.invalid_context"; - _logger; - _connection; - _trackAllContexts; - _reAnnounceKnownContexts; - _subscribeOnUpdate; - _subscribeOnGet; - _onlyReAnnounceSubscribedContexts; - _gw3Session; - _contextNameToData = {}; - _gw3Subscriptions = []; - _nextCallbackSubscriptionNumber = 0; - _creationPromises = {}; - _contextNameToId = {}; - _contextIdToName = {}; - _protocolVersion = undefined; - _contextsTempCache = {}; - _contextsSubscriptionsCache = []; - _systemContextsSubKey; - get protocolVersion() { - if (!this._protocolVersion) { - const contextsDomainInfo = this._connection.availableDomains.find((d) => d.uri === "context"); - this._protocolVersion = contextsDomainInfo?.version ?? 1; - } - return this._protocolVersion; - } - get setPathSupported() { - return this.protocolVersion >= 2; - } - constructor(config) { - this._connection = config.connection; - this._logger = config.logger; - this._trackAllContexts = config.trackAllContexts; - this._reAnnounceKnownContexts = config.reAnnounceKnownContexts; - this._subscribeOnUpdate = config.subscribeOnUpdate ?? true; - this._subscribeOnGet = config.subscribeOnGet ?? true; - this._onlyReAnnounceSubscribedContexts = config.onlyReAnnounceSubscribedContexts ?? true; - this._gw3Session = this._connection.domain("global", [ - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_CONTEXT_UPDATED, - ]); - this._gw3Session.disconnected(this.resetState.bind(this)); - this._gw3Session.onJoined((wasReconnect) => { - if (!wasReconnect) { - return; - } - if (!this._reAnnounceKnownContexts) { - this._contextsTempCache = {}; - return this._connection.setLibReAnnounced({ name: "contexts" }); - } - this.reInitiateState() - .then(() => this._connection.setLibReAnnounced({ name: "contexts" })) - .catch((err) => { - this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(err)}`); - }); - }); - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - } - dispose() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - this._gw3Subscriptions.length = 0; - for (const contextName in this._contextNameToData) { - if (this._contextNameToId.hasOwnProperty(contextName)) { - delete this._contextNameToData[contextName]; - } - } - } - createContext(name, data) { - if (name in this._creationPromises) { - return this._creationPromises[name]; - } - this._creationPromises[name] = - this._gw3Session - .send({ - type: GW_MESSAGE_CREATE_CONTEXT, - domain: "global", - name, - data, - lifetime: "retained", - }) - .then((createContextMsg) => { - this._contextNameToId[name] = createContextMsg.context_id; - this._contextIdToName[createContextMsg.context_id] = name; - const contextData = this._contextNameToData[name] || new GW3ContextData(createContextMsg.context_id, name, true, undefined); - contextData.isAnnounced = true; - contextData.name = name; - contextData.contextId = createContextMsg.context_id; - contextData.context = createContextMsg.data || deepClone(data); - contextData.hasReceivedSnapshot = true; - this._contextNameToData[name] = contextData; - delete this._creationPromises[name]; - contextData.sentExplicitSubscription = true; - contextData.createdByUs = true; - this.subscribe(name, () => { }); - return createContextMsg.context_id; - }); - return this._creationPromises[name]; - } - all() { - return Object.keys(this._contextNameToData) - .filter((name) => this._contextNameToData[name].isAnnounced); - } - async update(name, delta) { - if (delta) { - delta = deepClone(delta); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - await this.createContext(name, delta); - return; - } - const currentContext = await this.get(contextData.name); - const calculatedDelta = this.setPathSupported ? - this.calculateContextDeltaV2(currentContext, delta) : - this.calculateContextDeltaV1(currentContext, delta); - if (!Object.keys(calculatedDelta.added).length - && !Object.keys(calculatedDelta.updated).length - && !calculatedDelta.removed.length - && !calculatedDelta.commands?.length) { - return Promise.resolve(); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: calculatedDelta, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, calculatedDelta, { - updaterId: gwResponse.peer_id - }); - } - } - async set(name, data) { - if (data) { - data = deepClone(data); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - return this.createContext(name, data); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { reset: data }, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - this.handleUpdated(contextData, { - reset: data, - added: {}, - removed: [], - updated: {} - }, { - updaterId: gwResponse.peer_id - }); - } - } - setPath(name, path, value) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later"); - } - return this.setPaths(name, [{ path, value }]); - } - async setPaths(name, pathValues) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later"); - } - if (pathValues) { - pathValues = deepClone(pathValues); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - const obj = {}; - for (const pathValue of pathValues) { - setValueToPath(obj, pathValue.value, pathValue.path); - } - return this.createContext(name, obj); - } - const commands = []; - for (const pathValue of pathValues) { - if (pathValue.value === null) { - commands.push({ type: "remove", path: pathValue.path }); - } - else { - commands.push({ type: "set", path: pathValue.path, value: pathValue.value }); - } - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { commands } - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, { - added: {}, - removed: [], - updated: {}, - commands - }, { - updaterId: gwResponse.peer_id - }); - } - } - async get(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - if (!contextData && this._subscribeOnGet) { - this.subscribe(name, () => { }); - } - return Promise.resolve({}); - } - if (contextData && !contextData.sentExplicitSubscription) { - return new Promise((resolve, reject) => { - this.subscribe(name, (data, _d, _r, un) => { - if (!this._subscribeOnGet) { - this.unsubscribe(un); - } - resolve(data); - }).catch((e) => { - if (this.isInvalidContextError(e)) { - resolve({}); - return; - } - reject(e); - }); - }); - } - await contextData.snapshotPromise; - const context = contextData?.context ?? {}; - return Promise.resolve(deepClone(context)); - } - isInvalidContextError(e) { - return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT - || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id")); - } - async subscribe(name, callback, subscriptionKey) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const thisCallbackSubscriptionNumber = typeof subscriptionKey === "undefined" ? this._nextCallbackSubscriptionNumber : subscriptionKey; - if (typeof subscriptionKey === "undefined") { - this._nextCallbackSubscriptionNumber += 1; - this._contextsSubscriptionsCache.push({ contextName: name, subKey: thisCallbackSubscriptionNumber, callback }); - } - let contextData = this._contextNameToData[name]; - if (!contextData || - !contextData.isAnnounced) { - contextData = contextData || new GW3ContextData(undefined, name, false, undefined); - this._contextNameToData[name] = contextData; - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - return Promise.resolve(thisCallbackSubscriptionNumber); - } - const hadCallbacks = contextData.hasCallbacks(); - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - if (!hadCallbacks) { - if (!contextData.joinedActivity && !contextData.createdByUs) { - if (contextData.context && contextData.sentExplicitSubscription) { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - return this.sendSubscribe(contextData) - .then(() => thisCallbackSubscriptionNumber, () => { - this.unsubscribe(thisCallbackSubscriptionNumber, true); - return thisCallbackSubscriptionNumber; - }); - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - unsubscribe(subscriptionKey, keepInSubscriptionsCache) { - if (!keepInSubscriptionsCache) { - this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter(x => x.subKey !== subscriptionKey); - } - for (const name of Object.keys(this._contextNameToData)) { - const contextData = this._contextNameToData[name]; - if (!contextData) { - continue; - } - const hadCallbacks = contextData.hasCallbacks(); - delete contextData.updateCallbacks[subscriptionKey]; - if (contextData.isAnnounced && - hadCallbacks && - !contextData.hasCallbacks() && - contextData.sentExplicitSubscription) { - contextData.hasReceivedSnapshot = false; - contextData.context = {}; - this.sendUnsubscribe(contextData).catch(() => { }); - } - if (!contextData.isAnnounced && - !contextData.hasCallbacks()) { - delete this._contextNameToData[name]; - delete this._contextNameToId[name]; - if (contextData.contextId) { - delete this._contextIdToName[contextData.contextId]; - } - } - } - } - async destroy(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - const contextId = contextData?.contextId; - if (!contextData || !contextId) { - return Promise.reject(`context with ${name} does not exist`); - } - return this._gw3Session - .send({ - type: GW_MESSAGE_DESTROY_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }).then(() => undefined); - } - handleUpdated(contextData, delta, extraData) { - const oldContext = contextData.context; - contextData.context = applyContextDelta(contextData.context, delta, this._logger); - if (this._contextNameToData[contextData.name] === contextData && - !deepEqual(oldContext, contextData.context)) { - this.invokeUpdateCallbacks(contextData, delta, extraData); - } - } - subscribeToContextCreatedMessages() { - const createdMessageTypes = [ - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_ACTIVITY_CREATED, - ]; - for (const createdMessageType of createdMessageTypes) { - const sub = this._connection.on(createdMessageType, this.handleContextCreatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextCreatedMessage(contextCreatedMsg) { - const createdMessageType = contextCreatedMsg.type; - if (createdMessageType === GW_MESSAGE_ACTIVITY_CREATED) { - this._contextNameToId[contextCreatedMsg.activity_id] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.activity_id; - } - else if (createdMessageType === GW_MESSAGE_CONTEXT_ADDED) { - this._contextNameToId[contextCreatedMsg.name] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.name; - } - else ; - const name = this._contextIdToName[contextCreatedMsg.context_id]; - if (!name) { - throw new Error("Received created event for context with unknown name: " + contextCreatedMsg.context_id); - } - if (!this._contextNameToId[name]) { - throw new Error("Received created event for context with unknown id: " + contextCreatedMsg.context_id); - } - let contextData = this._contextNameToData[name]; - if (contextData) { - if (contextData.isAnnounced) { - return; - } - else { - if (!contextData.hasCallbacks()) { - throw new Error("Assertion failure: contextData.hasCallbacks()"); - } - contextData.isAnnounced = true; - contextData.contextId = contextCreatedMsg.context_id; - contextData.activityId = contextCreatedMsg.activity_id; - if (!contextData.sentExplicitSubscription) { - this.sendSubscribe(contextData).catch(() => { }); - } - } - } - else { - this._contextNameToData[name] = contextData = - new GW3ContextData(contextCreatedMsg.context_id, name, true, contextCreatedMsg.activity_id); - if (this._trackAllContexts) { - this.subscribe(name, () => { }).then((subKey) => this._systemContextsSubKey = subKey); - } - } - } - subscribeToContextUpdatedMessages() { - const updatedMessageTypes = [ - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_JOINED_ACTIVITY, - ]; - for (const updatedMessageType of updatedMessageTypes) { - const sub = this._connection.on(updatedMessageType, this.handleContextUpdatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextUpdatedMessage(contextUpdatedMsg) { - const updatedMessageType = contextUpdatedMsg.type; - const contextId = contextUpdatedMsg.context_id; - let contextData = this._contextNameToData[this._contextIdToName[contextId]]; - const justSeen = !contextData || !contextData.isAnnounced; - if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - if (!contextData) { - contextData = - this._contextNameToData[contextUpdatedMsg.activity_id] || - new GW3ContextData(contextId, contextUpdatedMsg.activity_id, true, contextUpdatedMsg.activity_id); - } - this._contextNameToData[contextUpdatedMsg.activity_id] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.activity_id; - this._contextNameToId[contextUpdatedMsg.activity_id] = contextId; - contextData.contextId = contextId; - contextData.isAnnounced = true; - contextData.activityId = contextUpdatedMsg.activity_id; - contextData.joinedActivity = true; - } - else { - if (!contextData || !contextData.isAnnounced) { - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData = contextData || new GW3ContextData(contextId, contextUpdatedMsg.name, true, undefined); - contextData.sentExplicitSubscription = true; - this._contextNameToData[contextUpdatedMsg.name] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.name; - this._contextNameToId[contextUpdatedMsg.name] = contextId; - } - else { - this._logger.error(`Received 'update' for unknown context: ${contextId}`); - } - return; - } - } - const oldContext = contextData.context; - contextData.hasReceivedSnapshot = true; - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData.context = contextUpdatedMsg.data ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - contextData.context = contextUpdatedMsg.context_snapshot ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_CONTEXT_UPDATED) { - contextData.context = applyContextDelta(contextData.context, contextUpdatedMsg.delta, this._logger); - } - else { - throw new Error("Unrecognized context update message " + updatedMessageType); - } - if (justSeen || - !deepEqual(contextData.context, oldContext) || - updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta, { updaterId: contextUpdatedMsg.updater_id }); - } - } - invokeUpdateCallbacks(contextData, delta, extraData) { - delta = delta || { added: {}, updated: {}, reset: {}, removed: [] }; - if (delta.commands) { - delta.added = delta.updated = delta.reset = {}; - delta.removed = []; - for (const command of delta.commands) { - if (command.type === "remove") { - if (command.path.indexOf(".") === -1) { - delta.removed.push(command.path); - } - setValueToPath(delta.updated, null, command.path); - } - else if (command.type === "set") { - setValueToPath(delta.updated, command.value, command.path); - } - } - } - for (const updateCallbackIndex in contextData.updateCallbacks) { - if (contextData.updateCallbacks.hasOwnProperty(updateCallbackIndex)) { - try { - const updateCallback = contextData.updateCallbacks[updateCallbackIndex]; - updateCallback(deepClone(contextData.context), deepClone(Object.assign({}, delta.added || {}, delta.updated || {}, delta.reset || {})), delta.removed, parseInt(updateCallbackIndex, 10), extraData); - } - catch (err) { - this._logger.debug("callback error: " + JSON.stringify(err)); - } - } - } - } - subscribeToContextDestroyedMessages() { - const destroyedMessageTypes = [ - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_ACTIVITY_DESTROYED, - ]; - for (const destroyedMessageType of destroyedMessageTypes) { - const sub = this._connection.on(destroyedMessageType, this.handleContextDestroyedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextDestroyedMessage(destroyedMsg) { - const destroyedMessageType = destroyedMsg.type; - let contextId; - let name; - if (destroyedMessageType === GW_MESSAGE_ACTIVITY_DESTROYED) { - name = destroyedMsg.activity_id; - contextId = this._contextNameToId[name]; - if (!contextId) { - this._logger.error(`Received 'destroyed' for unknown activity: ${destroyedMsg.activity_id}`); - return; - } - } - else { - contextId = destroyedMsg.context_id; - name = this._contextIdToName[contextId]; - if (!name) { - this._logger.error(`Received 'destroyed' for unknown context: ${destroyedMsg.context_id}`); - return; - } - } - delete this._contextIdToName[contextId]; - delete this._contextNameToId[name]; - const contextData = this._contextNameToData[name]; - delete this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - this._logger.error(`Received 'destroyed' for unknown context: ${contextId}`); - return; - } - } - async sendSubscribe(contextData) { - contextData.sentExplicitSubscription = true; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_SUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = false; - throw error; - } - } - async sendUnsubscribe(contextData) { - const prev = contextData.sentExplicitSubscription; - contextData.sentExplicitSubscription = false; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = prev; - throw error; - } - } - calculateContextDeltaV1(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined }; - if (from) { - for (const x of Object.keys(from)) { - if (Object.keys(to).indexOf(x) !== -1 - && to[x] !== null - && !deepEqual(from[x], to[x])) { - delta.updated[x] = to[x]; - } - } - } - for (const x of Object.keys(to)) { - if (!from || (Object.keys(from).indexOf(x) === -1)) { - if (to[x] !== null) { - delta.added[x] = to[x]; - } - } - else if (to[x] === null) { - delta.removed.push(x); - } - } - return delta; - } - calculateContextDeltaV2(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined, commands: [] }; - for (const x of Object.keys(to)) { - if (to[x] !== null) { - const fromX = from ? from[x] : null; - if (!deepEqual(fromX, to[x])) { - delta.commands?.push({ type: "set", path: x, value: to[x] }); - } - } - else { - delta.commands?.push({ type: "remove", path: x }); - } - } - return delta; - } - resetState() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - if (this._systemContextsSubKey) { - this.unsubscribe(this._systemContextsSubKey, true); - delete this._systemContextsSubKey; - } - this._gw3Subscriptions = []; - this._contextNameToId = {}; - this._contextIdToName = {}; - delete this._protocolVersion; - this._contextsTempCache = Object.keys(this._contextNameToData).reduce((cacheSoFar, ctxName) => { - const contextData = this._contextNameToData[ctxName]; - const addToCache = !this._onlyReAnnounceSubscribedContexts || contextData.hasReceivedSnapshot; - if (addToCache) { - cacheSoFar[ctxName] = this._contextNameToData[ctxName].context; - } - return cacheSoFar; - }, {}); - this._contextNameToData = {}; - } - async reInitiateState() { - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - await Promise.all(this._contextsSubscriptionsCache.map((subscription) => this.subscribe(subscription.contextName, subscription.callback, subscription.subKey))); - await this.flushQueue(); - for (const ctxName in this._contextsTempCache) { - if (typeof this._contextsTempCache[ctxName] !== "object" || Object.keys(this._contextsTempCache[ctxName]).length === 0) { - continue; - } - const lastKnownData = this._contextsTempCache[ctxName]; - this._logger.info(`Re-announcing known context: ${ctxName}`); - await this.flushQueue(); - await this.update(ctxName, lastKnownData); - } - this._contextsTempCache = {}; - this._logger.info("Contexts are re-announced"); - } - flushQueue() { - return new Promise((resolve) => setTimeout(() => resolve(), 0)); - } - } - - class ContextsModule { - initTime; - initStartTime; - initEndTime; - _bridge; - constructor(config) { - this._bridge = new GW3Bridge(config); - } - all() { - return this._bridge.all(); - } - update(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.update(name, data); - } - set(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.set(name, data); - } - setPath(name, path, data) { - this.checkName(name); - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(data); - return this.set(name, data); - } - return this._bridge.setPath(name, path, data); - } - setPaths(name, paths) { - this.checkName(name); - if (!Array.isArray(paths)) { - throw new Error("Please provide the paths as an array of PathValues!"); - } - for (const { path, value } of paths) { - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(value); - } - } - return this._bridge.setPaths(name, paths); - } - subscribe(name, callback) { - this.checkName(name); - if (typeof callback !== "function") { - throw new Error("Please provide the callback as a function!"); - } - return this._bridge - .subscribe(name, (data, delta, removed, key, extraData) => callback(data, delta, removed, () => this._bridge.unsubscribe(key), extraData)) - .then((key) => () => { - this._bridge.unsubscribe(key); - }); - } - get(name) { - this.checkName(name); - return this._bridge.get(name); - } - ready() { - return Promise.resolve(this); - } - destroy(name) { - this.checkName(name); - return this._bridge.destroy(name); - } - get setPathSupported() { - return this._bridge.setPathSupported; - } - checkName(name) { - if (typeof name !== "string" || name === "") { - throw new Error("Please provide the name as a non-empty string!"); - } - } - checkPath(path) { - if (typeof path !== "string") { - throw new Error("Please provide the path as a dot delimited string!"); - } - } - checkData(data) { - if (typeof data !== "object") { - throw new Error("Please provide the data as an object!"); - } - } - } - - function promisify (promise, successCallback, errorCallback) { - if (typeof successCallback !== "function" && typeof errorCallback !== "function") { - return promise; - } - if (typeof successCallback !== "function") { - successCallback = () => { }; - } - else if (typeof errorCallback !== "function") { - errorCallback = () => { }; - } - return promise.then(successCallback, errorCallback); - } - - function rejectAfter(ms = 0, promise, error) { - let timeout; - const clearTimeoutIfThere = () => { - if (timeout) { - clearTimeout(timeout); - } - }; - promise - .then(() => { - clearTimeoutIfThere(); - }) - .catch(() => { - clearTimeoutIfThere(); - }); - return new Promise((resolve, reject) => { - timeout = setTimeout(() => reject(error), ms); - }); - } - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - Decoder.oneOf; - /** See `Decoder.union` */ - var union = Decoder.union; - /** See `Decoder.intersection` */ - Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - var fail$1 = Decoder.fail; - /** See `Decoder.lazy` */ - Decoder.lazy; - - const functionCheck = (input, propDescription) => { - const providedType = typeof input; - return providedType === "function" ? - anyJson() : - fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${typeof providedType}`); - }; - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number or 0"); - const methodDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - objectTypes: optional(array(nonEmptyStringDecoder)), - displayName: optional(nonEmptyStringDecoder), - accepts: optional(nonEmptyStringDecoder), - returns: optional(nonEmptyStringDecoder), - description: optional(nonEmptyStringDecoder), - version: optional(nonNegativeNumberDecoder), - supportsStreaming: optional(boolean()), - flags: optional(object()), - getServers: optional(anyJson().andThen((result) => functionCheck(result, "method definition getServers"))) - }); - const methodFilterDecoder = union(nonEmptyStringDecoder, methodDefinitionDecoder); - const instanceDecoder = object({ - application: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - pid: optional(nonNegativeNumberDecoder), - machine: optional(nonEmptyStringDecoder), - user: optional(nonEmptyStringDecoder), - environment: optional(nonEmptyStringDecoder), - region: optional(nonEmptyStringDecoder), - service: optional(nonEmptyStringDecoder), - instance: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - peerId: optional(nonEmptyStringDecoder), - isLocal: optional(boolean()), - api: optional(nonEmptyStringDecoder), - getMethods: optional(anyJson().andThen((result) => functionCheck(result, "instance getMethods"))), - getStreams: optional(anyJson().andThen((result) => functionCheck(result, "instance getStreams"))) - }); - const targetDecoder = union(constant("best"), constant("all"), constant("skipMine"), instanceDecoder, array(instanceDecoder)); - const invokeOptionsDecoder = object({ - waitTimeoutMs: optional(nonNegativeNumberDecoder), - methodResponseTimeoutMs: optional(nonNegativeNumberDecoder) - }); - - var InvokeStatus; - (function (InvokeStatus) { - InvokeStatus[InvokeStatus["Success"] = 0] = "Success"; - InvokeStatus[InvokeStatus["Error"] = 1] = "Error"; - })(InvokeStatus || (InvokeStatus = {})); - class Client { - protocol; - repo; - instance; - configuration; - constructor(protocol, repo, instance, configuration) { - this.protocol = protocol; - this.repo = repo; - this.instance = instance; - this.configuration = configuration; - } - subscribe(method, options, successCallback, errorCallback, existingSub) { - const callProtocolSubscribe = (targetServers, stream, successProxy, errorProxy) => { - options.methodResponseTimeout = options.methodResponseTimeout ?? options.waitTimeoutMs; - this.protocol.client.subscribe(stream, options, targetServers, successProxy, errorProxy, existingSub); - }; - const promise = new Promise((resolve, reject) => { - const successProxy = (sub) => { - resolve(sub); - }; - const errorProxy = (err) => { - reject(err); - }; - if (!method) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - let methodDef; - if (typeof method === "string") { - methodDef = { name: method }; - } - else { - methodDef = method; - } - if (!methodDef.name) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - if (options === undefined) { - options = {}; - } - let target = options.target; - if (target === undefined) { - target = "best"; - } - if (typeof target === "string" && target !== "all" && target !== "best") { - reject(new Error(`"${target}" is not a valid target. Valid targets are "all", "best", or an instance.`)); - return; - } - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = options.method_response_timeout; - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = this.configuration.methodResponseTimeout; - } - } - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = options.wait_for_method_timeout; - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - const delayStep = 500; - let delayTillNow = 0; - let currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - callProtocolSubscribe(currentServers, currentServers[0].methods[0], successProxy, errorProxy); - } - else { - const retry = () => { - if (!target || !(options.waitTimeoutMs)) { - return; - } - delayTillNow += delayStep; - currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - const streamInfo = currentServers[0].methods[0]; - callProtocolSubscribe(currentServers, streamInfo, successProxy, errorProxy); - } - else if (delayTillNow >= options.waitTimeoutMs) { - const def = typeof method === "string" ? { name: method } : method; - callProtocolSubscribe(currentServers, def, successProxy, errorProxy); - } - else { - setTimeout(retry, delayStep); - } - }; - setTimeout(retry, delayStep); - } - }); - return promisify(promise, successCallback, errorCallback); - } - servers(methodFilter) { - const filterCopy = methodFilter === undefined - ? undefined - : { ...methodFilter }; - return this.getServers(filterCopy).map((serverMethodMap) => { - return serverMethodMap.server.instance; - }); - } - methods(methodFilter) { - if (typeof methodFilter === "string") { - methodFilter = { name: methodFilter }; - } - else { - methodFilter = { ...methodFilter }; - } - return this.getMethods(methodFilter); - } - methodsForInstance(instance) { - return this.getMethodsForInstance(instance); - } - methodAdded(callback) { - return this.repo.onMethodAdded(callback); - } - methodRemoved(callback) { - return this.repo.onMethodRemoved(callback); - } - serverAdded(callback) { - return this.repo.onServerAdded(callback); - } - serverRemoved(callback) { - return this.repo.onServerRemoved((server, reason) => { - callback(server, reason); - }); - } - serverMethodAdded(callback) { - return this.repo.onServerMethodAdded((server, method) => { - callback({ server, method }); - }); - } - serverMethodRemoved(callback) { - return this.repo.onServerMethodRemoved((server, method) => { - callback({ server, method }); - }); - } - async invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - const getInvokePromise = async () => { - const methodDefinition = typeof methodFilter === "string" ? { name: methodFilter } : { ...methodFilter }; - if (!argumentObj) { - argumentObj = {}; - } - if (!target) { - target = "best"; - } - if (!additionalOptions) { - additionalOptions = {}; - } - const methodFilterDecoderResult = methodFilterDecoder.run(methodDefinition); - if (!methodFilterDecoderResult.ok) { - const message = `The provided 'method' argument is invalid. Error: ${JSON.stringify(methodFilterDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (typeof argumentObj !== "object") { - const message = "The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const targetDecoderResult = targetDecoder.run(target); - if (!targetDecoderResult.ok) { - const message = `The provided 'target' argument is invalid. Error: ${JSON.stringify(targetDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const invokeOptionsDecoderResult = invokeOptionsDecoder.run(additionalOptions); - if (!invokeOptionsDecoderResult.ok) { - const message = `The provided 'options' argument is invalid. Error: ${JSON.stringify(invokeOptionsDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (success && typeof success !== "function") { - const message = "The provided 'success' function is invalid. Error: The success should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (error && typeof error !== "function") { - const message = "The provided 'error' function is invalid. Error: The error should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = additionalOptions.method_response_timeout; - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = this.configuration.methodResponseTimeout; - } - } - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = additionalOptions.wait_for_method_timeout; - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - let serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length === 0) { - try { - serversMethodMap = await this.tryToAwaitForMethods(methodDefinition, target, additionalOptions); - } - catch (err) { - const message = `Can not find a method matching ${JSON.stringify(methodFilter)} with server filter ${JSON.stringify(target)}`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - } - const timeout = additionalOptions.methodResponseTimeoutMs; - const additionalOptionsCopy = additionalOptions; - const invokePromises = serversMethodMap.map((serversMethodPair) => { - const invId = nanoid(10); - const method = serversMethodPair.methods[0]; - const server = serversMethodPair.server; - const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy); - return Promise.race([ - invokePromise, - rejectAfter(timeout, invokePromise, { - invocationId: invId, - message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`, - status: InvokeStatus.Error, - }) - ]); - }); - const invocationMessages = await Promise.all(invokePromises); - const results = this.getInvocationResultObj(invocationMessages, methodDefinition, argumentObj); - const allRejected = invocationMessages.every((result) => result.status === InvokeStatus.Error); - if (allRejected) { - return Promise.reject(results); - } - return results; - }; - return promisify(getInvokePromise(), success, error); - } - generateInvalidInputInvocationResult(message, methodDefinition, argumentObj) { - const method = { - ...methodDefinition, - getServers: () => [], - supportsStreaming: false, - objectTypes: methodDefinition.objectTypes ?? [], - flags: methodDefinition.flags?.metadata ?? {} - }; - const invokeResultMessage = { - invocationId: nanoid(10), - status: InvokeStatus.Error, - message - }; - return this.getInvocationResultObj([invokeResultMessage], method, argumentObj); - } - getInvocationResultObj(invocationResults, method, calledWith) { - const all_return_values = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Success) - .reduce((allValues, currentValue) => { - allValues = [ - ...allValues, - { - executed_by: currentValue.instance, - returned: currentValue.result, - called_with: calledWith, - method, - message: currentValue.message, - status: currentValue.status, - } - ]; - return allValues; - }, []); - const all_errors = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Error) - .reduce((allErrors, currError) => { - allErrors = [ - ...allErrors, - { - executed_by: currError.instance, - called_with: calledWith, - name: method.name, - message: currError.message, - } - ]; - return allErrors; - }, []); - const invResult = invocationResults[0]; - const result = { - method, - called_with: calledWith, - returned: invResult.result, - executed_by: invResult.instance, - all_return_values, - all_errors, - message: invResult.message, - status: invResult.status - }; - return result; - } - tryToAwaitForMethods(methodDefinition, target, additionalOptions) { - return new Promise((resolve, reject) => { - if (additionalOptions.waitTimeoutMs === 0) { - reject(); - return; - } - const delayStep = 500; - let delayTillNow = 0; - const retry = () => { - delayTillNow += delayStep; - const serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length > 0) { - clearInterval(interval); - resolve(serversMethodMap); - } - else if (delayTillNow >= (additionalOptions.waitTimeoutMs || 10000)) { - clearInterval(interval); - reject(); - return; - } - }; - const interval = setInterval(retry, delayStep); - }); - } - filterByTarget(target, serverMethodMap) { - if (typeof target === "string") { - if (target === "all") { - return [...serverMethodMap]; - } - else if (target === "best") { - const localMachine = serverMethodMap - .find((s) => s.server.instance.isLocal); - if (localMachine) { - return [localMachine]; - } - if (serverMethodMap[0] !== undefined) { - return [serverMethodMap[0]]; - } - } - else if (target === "skipMine") { - return serverMethodMap.filter(({ server }) => server.instance.peerId !== this.instance.peerId); - } - } - else { - let targetArray; - if (!Array.isArray(target)) { - targetArray = [target]; - } - else { - targetArray = target; - } - const allServersMatching = targetArray.reduce((matches, filter) => { - const myMatches = serverMethodMap.filter((serverMethodPair) => { - return this.instanceMatch(filter, serverMethodPair.server.instance); - }); - return matches.concat(myMatches); - }, []); - return allServersMatching; - } - return []; - } - instanceMatch(instanceFilter, instanceDefinition) { - if (instanceFilter?.peerId && instanceFilter?.instance) { - instanceFilter = { ...instanceFilter }; - delete instanceFilter.peerId; - } - return this.containsProps(instanceFilter, instanceDefinition); - } - methodMatch(methodFilter, methodDefinition) { - return this.containsProps(methodFilter, methodDefinition); - } - containsProps(filter, repoMethod) { - const filterProps = Object.keys(filter) - .filter((prop) => { - return filter[prop] !== undefined - && filter[prop] !== null - && typeof filter[prop] !== "function" - && prop !== "object_types" - && prop !== "display_name" - && prop !== "id" - && prop !== "gatewayId" - && prop !== "identifier" - && prop[0] !== "_"; - }); - return filterProps.every((prop) => { - let isMatch; - const filterValue = filter[prop]; - const repoMethodValue = repoMethod[prop]; - switch (prop) { - case "objectTypes": - isMatch = (filterValue || []).every((filterValueEl) => { - return (repoMethodValue || []).includes(filterValueEl); - }); - break; - case "flags": - isMatch = isSubset(repoMethodValue || {}, filterValue || {}); - break; - default: - isMatch = String(filterValue).toLowerCase() === String(repoMethodValue).toLowerCase(); - } - return isMatch; - }); - } - getMethods(methodFilter) { - if (methodFilter === undefined) { - return this.repo.getMethods(); - } - const methods = this.repo.getMethods().filter((method) => { - return this.methodMatch(methodFilter, method); - }); - return methods; - } - getMethodsForInstance(instanceFilter) { - const allServers = this.repo.getServers(); - const matchingServers = allServers.filter((server) => { - return this.instanceMatch(instanceFilter, server.instance); - }); - if (matchingServers.length === 0) { - return []; - } - let resultMethodsObject = {}; - if (matchingServers.length === 1) { - resultMethodsObject = matchingServers[0].methods; - } - else { - matchingServers.forEach((server) => { - Object.keys(server.methods).forEach((methodKey) => { - const method = server.methods[methodKey]; - resultMethodsObject[method.identifier] = method; - }); - }); - } - return Object.keys(resultMethodsObject) - .map((key) => { - return resultMethodsObject[key]; - }); - } - getServers(methodFilter) { - const servers = this.repo.getServers(); - if (methodFilter === undefined) { - return servers.map((server) => { - return { server, methods: [] }; - }); - } - return servers.reduce((prev, current) => { - const methodsForServer = Object.values(current.methods); - const matchingMethods = methodsForServer.filter((method) => { - return this.methodMatch(methodFilter, method); - }); - if (matchingMethods.length > 0) { - prev.push({ server: current, methods: matchingMethods }); - } - return prev; - }, []); - } - getServerMethodsByFilterAndTarget(methodFilter, target) { - const serversMethodMap = this.getServers(methodFilter); - return this.filterByTarget(target, serversMethodMap); - } - } - - class ServerSubscription { - protocol; - repoMethod; - subscription; - constructor(protocol, repoMethod, subscription) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.subscription = subscription; - } - get stream() { - if (!this.repoMethod.stream) { - throw new Error("no stream"); - } - return this.repoMethod.stream; - } - get arguments() { return this.subscription.arguments || {}; } - get branchKey() { return this.subscription.branchKey; } - get instance() { - if (!this.subscription.instance) { - throw new Error("no instance"); - } - return this.subscription.instance; - } - close() { - this.protocol.server.closeSingleSubscription(this.repoMethod, this.subscription); - } - push(data) { - this.protocol.server.pushDataToSingle(this.repoMethod, this.subscription, data); - } - } - - class Request { - protocol; - repoMethod; - requestContext; - arguments; - instance; - constructor(protocol, repoMethod, requestContext) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.requestContext = requestContext; - this.arguments = requestContext.arguments; - this.instance = requestContext.instance; - } - accept() { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, ""); - } - acceptOnBranch(branch) { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, branch); - } - reject(reason) { - this.protocol.server.rejectRequest(this.requestContext, this.repoMethod, reason); - } - } - - let ServerStreaming$1 = class ServerStreaming { - protocol; - server; - constructor(protocol, server) { - this.protocol = protocol; - this.server = server; - protocol.server.onSubRequest((rc, rm) => this.handleSubRequest(rc, rm)); - protocol.server.onSubAdded((sub, rm) => this.handleSubAdded(sub, rm)); - protocol.server.onSubRemoved((sub, rm) => this.handleSubRemoved(sub, rm)); - } - handleSubRequest(requestContext, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRequestHandler === "function")) { - return; - } - const request = new Request(this.protocol, repoMethod, requestContext); - repoMethod.streamCallbacks.subscriptionRequestHandler(request); - } - handleSubAdded(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionAddedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionAddedHandler(sub); - } - handleSubRemoved(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRemovedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionRemovedHandler(sub); - } - }; - - class ServerBranch { - key; - protocol; - repoMethod; - constructor(key, protocol, repoMethod) { - this.key = key; - this.protocol = protocol; - this.repoMethod = repoMethod; - } - subscriptions() { - const subList = this.protocol.server.getSubscriptionList(this.repoMethod, this.key); - return subList.map((sub) => { - return new ServerSubscription(this.protocol, this.repoMethod, sub); - }); - } - close() { - this.protocol.server.closeAllSubscriptions(this.repoMethod, this.key); - } - push(data) { - this.protocol.server.pushData(this.repoMethod, data, [this.key]); - } - } - - class ServerStream { - _protocol; - _repoMethod; - _server; - name; - constructor(_protocol, _repoMethod, _server) { - this._protocol = _protocol; - this._repoMethod = _repoMethod; - this._server = _server; - this.name = this._repoMethod.definition.name; - } - branches(key) { - const bList = this._protocol.server.getBranchList(this._repoMethod); - if (key) { - if (bList.indexOf(key) > -1) { - return new ServerBranch(key, this._protocol, this._repoMethod); - } - return undefined; - } - else { - return bList.map((branchKey) => { - return new ServerBranch(branchKey, this._protocol, this._repoMethod); - }); - } - } - branch(key) { - return this.branches(key); - } - subscriptions() { - const subList = this._protocol.server.getSubscriptionList(this._repoMethod); - return subList.map((sub) => { - return new ServerSubscription(this._protocol, this._repoMethod, sub); - }); - } - get definition() { - const def2 = this._repoMethod.definition; - return { - accepts: def2.accepts, - description: def2.description, - displayName: def2.displayName, - name: def2.name, - objectTypes: def2.objectTypes, - returns: def2.returns, - supportsStreaming: def2.supportsStreaming, - flags: def2.flags?.metadata, - }; - } - close() { - this._protocol.server.closeAllSubscriptions(this._repoMethod); - this._server.unregister(this._repoMethod.definition, true); - } - push(data, branches) { - if (typeof branches !== "string" && !Array.isArray(branches) && branches !== undefined) { - throw new Error("invalid branches should be string or string array"); - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - this._protocol.server.pushData(this._repoMethod, data, branches); - } - updateRepoMethod(repoMethod) { - this._repoMethod = repoMethod; - } - } - - class Server { - protocol; - serverRepository; - streaming; - invocations = 0; - currentlyUnregistering = {}; - constructor(protocol, serverRepository) { - this.protocol = protocol; - this.serverRepository = serverRepository; - this.streaming = new ServerStreaming$1(protocol, this); - this.protocol.server.onInvoked(this.onMethodInvoked.bind(this)); - } - createStream(streamDef, callbacks, successCallback, errorCallback, existingStream) { - const promise = new Promise((resolve, reject) => { - if (!streamDef) { - reject("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream."); - return; - } - let streamMethodDefinition; - if (typeof streamDef === "string") { - streamMethodDefinition = { name: "" + streamDef }; - } - else { - streamMethodDefinition = { ...streamDef }; - } - if (!streamMethodDefinition.name) { - return reject(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(streamMethodDefinition)}`); - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === streamMethodDefinition.name); - if (nameAlreadyExists) { - return reject(`A stream with the name "${streamMethodDefinition.name}" already exists! Please, provide a unique name for the stream.`); - } - streamMethodDefinition.supportsStreaming = true; - if (!callbacks) { - callbacks = {}; - } - if (typeof callbacks.subscriptionRequestHandler !== "function") { - callbacks.subscriptionRequestHandler = (request) => { - request.accept(); - }; - } - const repoMethod = this.serverRepository.add({ - definition: streamMethodDefinition, - streamCallbacks: callbacks, - protocolState: {}, - }); - this.protocol.server.createStream(repoMethod) - .then(() => { - let streamUserObject; - if (existingStream) { - streamUserObject = existingStream; - existingStream.updateRepoMethod(repoMethod); - } - else { - streamUserObject = new ServerStream(this.protocol, repoMethod, this); - } - repoMethod.stream = streamUserObject; - resolve(streamUserObject); - }) - .catch((err) => { - if (repoMethod.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - reject(err); - }); - }); - return promisify(promise, successCallback, errorCallback); - } - register(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallbackFunction = async (context, resultCallback) => { - try { - const result = callback(context.args, context.instance); - if (result && typeof result.then === "function") { - const resultValue = await result; - resultCallback(undefined, resultValue); - } - else { - resultCallback(undefined, result); - } - } - catch (e) { - resultCallback(e ?? "", e ?? ""); - } - }; - wrappedCallbackFunction.userCallback = callback; - return this.registerCore(methodDefinition, wrappedCallbackFunction); - } - registerAsync(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallback = async (context, resultCallback) => { - try { - let resultCalled = false; - const success = (result) => { - if (!resultCalled) { - resultCallback(undefined, result); - } - resultCalled = true; - }; - const error = (e) => { - if (!resultCalled) { - if (!e) { - e = ""; - } - resultCallback(e, e); - } - resultCalled = true; - }; - const methodResult = callback(context.args, context.instance, success, error); - if (methodResult && typeof methodResult.then === "function") { - methodResult - .then(success) - .catch(error); - } - } - catch (e) { - resultCallback(e, undefined); - } - }; - wrappedCallback.userCallbackAsync = callback; - return this.registerCore(methodDefinition, wrappedCallback); - } - async unregister(methodFilter, forStream = false) { - if (methodFilter === undefined) { - return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property."); - } - if (typeof methodFilter === "function") { - await this.unregisterWithPredicate(methodFilter, forStream); - return; - } - let methodDefinition; - if (typeof methodFilter === "string") { - methodDefinition = { name: methodFilter }; - } - else { - methodDefinition = methodFilter; - } - if (methodDefinition.name === undefined) { - return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!"); - } - const methodToBeRemoved = this.serverRepository.getList().find((serverMethod) => { - return serverMethod.definition.name === methodDefinition.name - && (serverMethod.definition.supportsStreaming || false) === forStream; - }); - if (!methodToBeRemoved) { - return Promise.reject(`Method with a name "${methodDefinition.name}" does not exist or is not registered by your application!`); - } - await this.removeMethodsOrStreams([methodToBeRemoved]); - } - async unregisterWithPredicate(filterPredicate, forStream) { - const methodsOrStreamsToRemove = this.serverRepository.getList() - .filter((sm) => filterPredicate(sm.definition)) - .filter((serverMethod) => (serverMethod.definition.supportsStreaming || false) === forStream); - if (!methodsOrStreamsToRemove || methodsOrStreamsToRemove.length === 0) { - return Promise.reject(`Could not find a ${forStream ? "stream" : "method"} matching the specified condition!`); - } - await this.removeMethodsOrStreams(methodsOrStreamsToRemove); - } - removeMethodsOrStreams(methodsToRemove) { - const methodUnregPromises = []; - methodsToRemove.forEach((method) => { - const promise = this.protocol.server.unregister(method) - .then(() => { - if (method.repoId) { - this.serverRepository.remove(method.repoId); - } - }); - methodUnregPromises.push(promise); - this.addAsCurrentlyUnregistering(method.definition.name, promise); - }); - return Promise.all(methodUnregPromises); - } - async addAsCurrentlyUnregistering(methodName, promise) { - const timeout = new Promise((resolve) => setTimeout(resolve, 5000)); - this.currentlyUnregistering[methodName] = Promise.race([promise, timeout]).then(() => { - delete this.currentlyUnregistering[methodName]; - }); - } - async registerCore(method, theFunction) { - let methodDefinition; - if (typeof method === "string") { - methodDefinition = { name: "" + method }; - } - else { - methodDefinition = { ...method }; - } - if (!methodDefinition.name) { - return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(method)}`); - } - const unregisterInProgress = this.currentlyUnregistering[methodDefinition.name]; - if (typeof unregisterInProgress !== "undefined") { - await unregisterInProgress; - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === methodDefinition.name); - if (nameAlreadyExists) { - return Promise.reject(`A method with the name "${methodDefinition.name}" already exists! Please, provide a unique name for the method.`); - } - if (methodDefinition.supportsStreaming) { - return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${methodDefinition.name}” to be a stream, please use the “glue.interop.createStream()” method.`); - } - const repoMethod = this.serverRepository.add({ - definition: methodDefinition, - theFunction, - protocolState: {}, - }); - return this.protocol.server.register(repoMethod) - .catch((err) => { - if (repoMethod?.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - throw err; - }); - } - onMethodInvoked(methodToExecute, invocationId, invocationArgs) { - if (!methodToExecute || !methodToExecute.theFunction) { - return; - } - methodToExecute.theFunction(invocationArgs, (err, result) => { - if (err !== undefined && err !== null) { - if (err.message && typeof err.message === "string") { - err = err.message; - } - else if (typeof err !== "string") { - try { - err = JSON.stringify(err); - } - catch (unStrException) { - err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`; - } - } - } - if (!result) { - result = {}; - } - else if (typeof result !== "object" || Array.isArray(result)) { - result = { _value: result }; - } - this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result); - }); - } - } - - class InstanceWrapper { - wrapped = {}; - constructor(API, instance, connection) { - this.wrapped.getMethods = function () { - return API.methodsForInstance(this); - }; - this.wrapped.getStreams = function () { - return API.methodsForInstance(this).filter((m) => m.supportsStreaming); - }; - if (instance) { - this.refreshWrappedObject(instance); - } - if (connection) { - connection.loggedIn(() => { - this.refresh(connection); - }); - this.refresh(connection); - } - } - unwrap() { - return this.wrapped; - } - refresh(connection) { - if (!connection) { - return; - } - const resolvedIdentity = connection?.resolvedIdentity; - const instance = Object.assign({}, resolvedIdentity ?? {}, { peerId: connection?.peerId }); - this.refreshWrappedObject(instance); - } - refreshWrappedObject(resolvedIdentity) { - Object.keys(resolvedIdentity).forEach((key) => { - this.wrapped[key] = resolvedIdentity[key]; - }); - this.wrapped.user = resolvedIdentity.user; - this.wrapped.instance = resolvedIdentity.instance; - this.wrapped.application = resolvedIdentity.application ?? nanoid(10); - this.wrapped.applicationName = resolvedIdentity.applicationName; - this.wrapped.pid = resolvedIdentity.pid ?? resolvedIdentity.process ?? Math.floor(Math.random() * 10000000000); - this.wrapped.machine = resolvedIdentity.machine; - this.wrapped.environment = resolvedIdentity.environment; - this.wrapped.region = resolvedIdentity.region; - this.wrapped.windowId = resolvedIdentity.windowId; - this.wrapped.isLocal = resolvedIdentity.isLocal ?? true; - this.wrapped.api = resolvedIdentity.api; - this.wrapped.service = resolvedIdentity.service; - this.wrapped.peerId = resolvedIdentity.peerId; - } - } - - const hideMethodSystemFlags = (method) => { - return { - ...method, - flags: method.flags.metadata || {} - }; - }; - class ClientRepository { - logger; - API; - servers = {}; - myServer; - methodsCount = {}; - callbacks = CallbackRegistryFactory(); - constructor(logger, API) { - this.logger = logger; - this.API = API; - const peerId = this.API.instance.peerId; - this.myServer = { - id: peerId, - methods: {}, - instance: this.API.instance, - wrapper: this.API.unwrappedInstance, - }; - this.servers[peerId] = this.myServer; - } - addServer(info, serverId) { - this.logger.debug(`adding server ${serverId}`); - const current = this.servers[serverId]; - if (current) { - return current.id; - } - const wrapper = new InstanceWrapper(this.API, info); - const serverEntry = { - id: serverId, - methods: {}, - instance: wrapper.unwrap(), - wrapper, - }; - this.servers[serverId] = serverEntry; - this.callbacks.execute("onServerAdded", serverEntry.instance); - return serverId; - } - removeServerById(id, reason) { - const server = this.servers[id]; - if (!server) { - this.logger.warn(`not aware of server ${id}, my state ${JSON.stringify(Object.keys(this.servers))}`); - return; - } - else { - this.logger.debug(`removing server ${id}`); - } - Object.keys(server.methods).forEach((methodId) => { - this.removeServerMethod(id, methodId); - }); - delete this.servers[id]; - this.callbacks.execute("onServerRemoved", server.instance, reason); - } - addServerMethod(serverId, method) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - if (server.methods[method.id]) { - return; - } - const identifier = this.createMethodIdentifier(method); - const that = this; - const methodDefinition = { - identifier, - gatewayId: method.id, - name: method.name, - displayName: method.display_name, - description: method.description, - version: method.version, - objectTypes: method.object_types || [], - accepts: method.input_signature, - returns: method.result_signature, - supportsStreaming: typeof method.flags !== "undefined" ? method.flags.streaming : false, - flags: method.flags ?? {}, - getServers: () => { - return that.getServersByMethod(identifier); - } - }; - methodDefinition.object_types = methodDefinition.objectTypes; - methodDefinition.display_name = methodDefinition.displayName; - methodDefinition.version = methodDefinition.version; - server.methods[method.id] = methodDefinition; - const clientMethodDefinition = hideMethodSystemFlags(methodDefinition); - if (!this.methodsCount[identifier]) { - this.methodsCount[identifier] = 0; - this.callbacks.execute("onMethodAdded", clientMethodDefinition); - } - this.methodsCount[identifier] = this.methodsCount[identifier] + 1; - this.callbacks.execute("onServerMethodAdded", server.instance, clientMethodDefinition); - return methodDefinition; - } - removeServerMethod(serverId, methodId) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - const method = server.methods[methodId]; - delete server.methods[methodId]; - const clientMethodDefinition = hideMethodSystemFlags(method); - this.methodsCount[method.identifier] = this.methodsCount[method.identifier] - 1; - if (this.methodsCount[method.identifier] === 0) { - this.callbacks.execute("onMethodRemoved", clientMethodDefinition); - } - this.callbacks.execute("onServerMethodRemoved", server.instance, clientMethodDefinition); - } - getMethods() { - return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags); - } - getServers() { - return Object.values(this.servers).map(this.hideServerMethodSystemFlags); - } - onServerAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerAdded", callback); - const serversWithMethodsToReplay = this.getServers().map((s) => s.instance); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, serversWithMethodsToReplay, callback); - } - onMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodAdded", callback); - const methodsToReplay = this.getMethods(); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, methodsToReplay, callback); - } - onServerMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodAdded", callback); - let unsubCalled = false; - const servers = this.getServers(); - setTimeout(() => { - servers.forEach((server) => { - const methods = server.methods; - Object.keys(methods).forEach((methodId) => { - if (!unsubCalled) { - callback(server.instance, methods[methodId]); - } - }); - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - onMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodRemoved", callback); - return unsubscribeFunc; - } - onServerRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerRemoved", callback); - return unsubscribeFunc; - } - onServerMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodRemoved", callback); - return unsubscribeFunc; - } - getServerById(id) { - const server = this.servers[id]; - if (!server) { - return undefined; - } - return this.hideServerMethodSystemFlags(this.servers[id]); - } - reset() { - Object.keys(this.servers).forEach((key) => { - this.removeServerById(key, "reset"); - }); - this.servers = { - [this.myServer.id]: this.myServer - }; - this.methodsCount = {}; - } - createMethodIdentifier(methodInfo) { - const accepts = methodInfo.input_signature ?? ""; - const returns = methodInfo.result_signature ?? ""; - return (methodInfo.name + accepts + returns).toLowerCase(); - } - getServersByMethod(identifier) { - const allServers = []; - Object.values(this.servers).forEach((server) => { - Object.values(server.methods).forEach((method) => { - if (method.identifier === identifier) { - allServers.push(server.instance); - } - }); - }); - return allServers; - } - returnUnsubWithDelayedReplay(unsubscribeFunc, collectionToReplay, callback) { - let unsubCalled = false; - setTimeout(() => { - collectionToReplay.forEach((item) => { - if (!unsubCalled) { - callback(item); - } - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - hideServerMethodSystemFlags(server) { - const clientMethods = {}; - Object.entries(server.methods).forEach(([name, method]) => { - clientMethods[name] = hideMethodSystemFlags(method); - }); - return { - ...server, - methods: clientMethods - }; - } - extractMethodsFromServers(servers) { - const methods = Object.values(servers).reduce((clientMethods, server) => { - return [...clientMethods, ...Object.values(server.methods)]; - }, []); - return methods; - } - } - - class ServerRepository { - nextId = 0; - methods = []; - add(method) { - method.repoId = String(this.nextId); - this.nextId += 1; - this.methods.push(method); - return method; - } - remove(repoId) { - if (typeof repoId !== "string") { - return new TypeError("Expecting a string"); - } - this.methods = this.methods.filter((m) => { - return m.repoId !== repoId; - }); - } - getById(id) { - if (typeof id !== "string") { - return undefined; - } - return this.methods.find((m) => { - return m.repoId === id; - }); - } - getList() { - return this.methods.map((m) => m); - } - length() { - return this.methods.length; - } - reset() { - this.methods = []; - } - } - - const SUBSCRIPTION_REQUEST = "onSubscriptionRequest"; - const SUBSCRIPTION_ADDED = "onSubscriptionAdded"; - const SUBSCRIPTION_REMOVED = "onSubscriptionRemoved"; - class ServerStreaming { - session; - repository; - serverRepository; - logger; - ERR_URI_SUBSCRIPTION_FAILED = "com.tick42.agm.errors.subscription.failure"; - callbacks = CallbackRegistryFactory(); - nextStreamId = 0; - constructor(session, repository, serverRepository, logger) { - this.session = session; - this.repository = repository; - this.serverRepository = serverRepository; - this.logger = logger; - session.on("add-interest", (msg) => { - this.handleAddInterest(msg); - }); - session.on("remove-interest", (msg) => { - this.handleRemoveInterest(msg); - }); - } - acceptRequestOnBranch(requestContext, streamingMethod, branch) { - if (typeof branch !== "string") { - branch = ""; - } - if (typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - throw new TypeError("The streaming method is missing its subscriptions."); - } - if (!Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - throw new TypeError("The streaming method is missing its branches."); - } - const streamId = this.getStreamId(streamingMethod, branch); - const key = requestContext.msg.subscription_id; - const subscription = { - id: key, - arguments: requestContext.arguments, - instance: requestContext.instance, - branchKey: branch, - streamId, - subscribeMsg: requestContext.msg, - }; - streamingMethod.protocolState.subscriptionsMap[key] = subscription; - this.session.sendFireAndForget({ - type: "accepted", - subscription_id: key, - stream_id: streamId, - }).catch((err) => { - this.logger.warn(`Failed to send accepted message for subscription ${key}: ${JSON.stringify(err)}`); - }); - this.callbacks.execute(SUBSCRIPTION_ADDED, subscription, streamingMethod); - } - rejectRequest(requestContext, streamingMethod, reason) { - if (typeof reason !== "string") { - reason = ""; - } - this.sendSubscriptionFailed("Subscription rejected by user. " + reason, requestContext.msg.subscription_id); - } - pushData(streamingMethod, data, branches) { - if (typeof streamingMethod !== "object" || !Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - return; - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - if (typeof branches === "string") { - branches = [branches]; - } - else if (!Array.isArray(branches) || branches.length <= 0) { - branches = []; - } - const streamIdList = streamingMethod.protocolState.branchKeyToStreamIdMap - .filter((br) => { - if (!branches || branches.length === 0) { - return true; - } - return branches.indexOf(br.key) >= 0; - }).map((br) => { - return br.streamId; - }); - streamIdList.forEach((streamId) => { - const publishMessage = { - type: "publish", - stream_id: streamId, - data, - }; - this.session.sendFireAndForget(publishMessage) - .catch((err) => { - this.logger.warn(`Failed to send publish message for stream ${streamId}: ${JSON.stringify(err)}`); - }); - }); - } - pushDataToSingle(method, subscription, data) { - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - const postMessage = { - type: "post", - subscription_id: subscription.id, - data, - }; - this.session.sendFireAndForget(postMessage) - .catch((err) => { - this.logger.warn(`Failed to send post message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - } - closeSingleSubscription(streamingMethod, subscription) { - if (streamingMethod.protocolState.subscriptionsMap) { - delete streamingMethod.protocolState.subscriptionsMap[subscription.id]; - } - const dropSubscriptionMessage = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping a single subscription", - }; - this.session.sendFireAndForget(dropSubscriptionMessage) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - subscription.instance; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - closeMultipleSubscriptions(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object" || typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - let subscriptionsToClose = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey === "string") { - subscriptionsToClose = subscriptionsToClose.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - subscriptionsToClose.forEach((subscription) => { - delete subscriptionsMap[subscription.id]; - const drop = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping all subscriptions on stream_id: " + subscription.streamId, - }; - this.session.sendFireAndForget(drop) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - }); - } - getSubscriptionList(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object") { - return []; - } - let subscriptions = []; - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey !== "string") { - subscriptions = allSubscriptions; - } - else { - subscriptions = allSubscriptions.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - return subscriptions; - } - getBranchList(streamingMethod) { - if (typeof streamingMethod !== "object") { - return []; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - const result = []; - allSubscriptions.forEach((sub) => { - let branch = ""; - if (typeof sub === "object" && typeof sub.branchKey === "string") { - branch = sub.branchKey; - } - if (result.indexOf(branch) === -1) { - result.push(branch); - } - }); - return result; - } - onSubAdded(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED, callback); - } - onSubRequest(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST, callback); - } - onSubRemoved(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED, callback); - } - handleRemoveInterest(msg) { - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (typeof msg.subscription_id !== "string" || - typeof streamingMethod !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - if (typeof streamingMethod.protocolState.subscriptionsMap[msg.subscription_id] !== "object") { - return; - } - const subscription = streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - delete streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - onSubscriptionLifetimeEvent(eventName, handlerFunc) { - this.callbacks.add(eventName, handlerFunc); - } - getNextStreamId() { - return this.nextStreamId++ + ""; - } - handleAddInterest(msg) { - const caller = this.repository.getServerById(msg.caller_id); - const instance = caller?.instance ?? {}; - const requestContext = { - msg, - arguments: msg.arguments_kv || {}, - instance, - }; - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (streamingMethod === undefined) { - const errorMsg = "No method with id " + msg.method_id + " on this server."; - this.sendSubscriptionFailed(errorMsg, msg.subscription_id); - return; - } - if (streamingMethod.protocolState.subscriptionsMap && - streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]) { - this.sendSubscriptionFailed("A subscription with id " + msg.subscription_id + " already exists.", msg.subscription_id); - return; - } - this.callbacks.execute(SUBSCRIPTION_REQUEST, requestContext, streamingMethod); - } - sendSubscriptionFailed(reason, subscriptionId) { - const errorMessage = { - type: "error", - reason_uri: this.ERR_URI_SUBSCRIPTION_FAILED, - reason, - request_id: subscriptionId, - }; - this.session.sendFireAndForget(errorMessage) - .catch((err) => { - this.logger.warn(`Failed to send subscription failed message for subscription ${subscriptionId}: ${JSON.stringify(err)}`); - }); - } - getStreamId(streamingMethod, branchKey) { - if (typeof branchKey !== "string") { - branchKey = ""; - } - if (!streamingMethod.protocolState.branchKeyToStreamIdMap) { - throw new Error(`streaming ${streamingMethod.definition.name} method without protocol state`); - } - const needleBranch = streamingMethod.protocolState.branchKeyToStreamIdMap.filter((branch) => { - return branch.key === branchKey; - })[0]; - let streamId = (needleBranch ? needleBranch.streamId : undefined); - if (typeof streamId !== "string" || streamId === "") { - streamId = this.getNextStreamId(); - streamingMethod.protocolState.branchKeyToStreamIdMap.push({ key: branchKey, streamId }); - } - return streamId; - } - } - - class ServerProtocol { - session; - clientRepository; - serverRepository; - logger; - callbacks = CallbackRegistryFactory(); - streaming; - constructor(session, clientRepository, serverRepository, logger) { - this.session = session; - this.clientRepository = clientRepository; - this.serverRepository = serverRepository; - this.logger = logger; - this.streaming = new ServerStreaming(session, clientRepository, serverRepository, logger.subLogger("streaming")); - this.session.on("invoke", (msg) => this.handleInvokeMessage(msg)); - } - createStream(repoMethod) { - repoMethod.protocolState.subscriptionsMap = {}; - repoMethod.protocolState.branchKeyToStreamIdMap = []; - return this.register(repoMethod, true); - } - register(repoMethod, isStreaming) { - const methodDef = repoMethod.definition; - const flags = Object.assign({}, { metadata: methodDef.flags ?? {} }, { streaming: isStreaming || false }); - const registerMsg = { - type: "register", - methods: [{ - id: repoMethod.repoId, - name: methodDef.name, - display_name: methodDef.displayName, - description: methodDef.description, - version: methodDef.version, - flags, - object_types: methodDef.objectTypes || methodDef.object_types, - input_signature: methodDef.accepts, - result_signature: methodDef.returns, - restrictions: undefined, - }], - }; - return this.session.send(registerMsg, { methodId: repoMethod.repoId }) - .then(() => { - this.logger.debug("registered method " + repoMethod.definition.name + " with id " + repoMethod.repoId); - }) - .catch((msg) => { - this.logger.warn(`failed to register method ${repoMethod.definition.name} with id ${repoMethod.repoId} - ${JSON.stringify(msg)}`); - throw msg; - }); - } - onInvoked(callback) { - this.callbacks.add("onInvoked", callback); - } - methodInvocationResult(method, invocationId, err, result) { - let msg; - if (err || err === "") { - msg = { - type: "error", - request_id: invocationId, - reason_uri: "agm.errors.client_error", - reason: err, - context: result, - peer_id: undefined, - }; - } - else { - msg = { - type: "yield", - invocation_id: invocationId, - peer_id: this.session.peerId, - result, - request_id: undefined, - }; - } - this.session.sendFireAndForget(msg) - .catch((error => { - this.logger.warn(`Failed to send method invocation result for method ${method.definition.name} invocation ${invocationId} - ${JSON.stringify(error)}`); - })); - } - async unregister(method) { - const msg = { - type: "unregister", - methods: [method.repoId], - }; - await this.session.send(msg); - } - getBranchList(method) { - return this.streaming.getBranchList(method); - } - getSubscriptionList(method, branchKey) { - return this.streaming.getSubscriptionList(method, branchKey); - } - closeAllSubscriptions(method, branchKey) { - this.streaming.closeMultipleSubscriptions(method, branchKey); - } - pushData(method, data, branches) { - this.streaming.pushData(method, data, branches); - } - pushDataToSingle(method, subscription, data) { - this.streaming.pushDataToSingle(method, subscription, data); - } - closeSingleSubscription(method, subscription) { - this.streaming.closeSingleSubscription(method, subscription); - } - acceptRequestOnBranch(requestContext, method, branch) { - this.streaming.acceptRequestOnBranch(requestContext, method, branch); - } - rejectRequest(requestContext, method, reason) { - this.streaming.rejectRequest(requestContext, method, reason); - } - onSubRequest(callback) { - this.streaming.onSubRequest(callback); - } - onSubAdded(callback) { - this.streaming.onSubAdded(callback); - } - onSubRemoved(callback) { - this.streaming.onSubRemoved(callback); - } - handleInvokeMessage(msg) { - const invocationId = msg.invocation_id; - const callerId = msg.caller_id; - const methodId = msg.method_id; - const args = msg.arguments_kv; - const methodList = this.serverRepository.getList(); - const method = methodList.filter((m) => { - return m.repoId === methodId; - })[0]; - if (method === undefined) { - return; - } - const client = this.clientRepository.getServerById(callerId)?.instance; - const invocationArgs = { args, instance: client }; - this.callbacks.execute("onInvoked", method, invocationId, invocationArgs); - } - } - - class UserSubscription { - repository; - subscriptionData; - get requestArguments() { - return this.subscriptionData.params.arguments || {}; - } - get servers() { - return this.subscriptionData.trackedServers.reduce((servers, pair) => { - if (pair.subscriptionId) { - const server = this.repository.getServerById(pair.serverId)?.instance; - if (server) { - servers.push(server); - } - } - return servers; - }, []); - } - get serverInstance() { - return this.servers[0]; - } - get stream() { - return this.subscriptionData.method; - } - constructor(repository, subscriptionData) { - this.repository = repository; - this.subscriptionData = subscriptionData; - } - onData(dataCallback) { - if (typeof dataCallback !== "function") { - throw new TypeError("The data callback must be a function."); - } - this.subscriptionData.handlers.onData.push(dataCallback); - if (this.subscriptionData.handlers.onData.length === 1 && this.subscriptionData.queued.data.length > 0) { - this.subscriptionData.queued.data.forEach((dataItem) => { - dataCallback(dataItem); - }); - } - } - onClosed(closedCallback) { - if (typeof closedCallback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onClosed.push(closedCallback); - } - onFailed(callback) { - } - onConnected(callback) { - if (typeof callback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onConnected.push(callback); - } - close() { - this.subscriptionData.close(); - } - setNewSubscription(newSub) { - this.subscriptionData = newSub; - } - } - - class TimedCache { - config; - cache = []; - timeoutIds = []; - constructor(config) { - this.config = config; - } - add(element) { - const id = nanoid(10); - this.cache.push({ id, element }); - const timeoutId = setTimeout(() => { - const elementIdx = this.cache.findIndex((entry) => entry.id === id); - if (elementIdx < 0) { - return; - } - this.cache.splice(elementIdx, 1); - }, this.config.ELEMENT_TTL_MS); - this.timeoutIds.push(timeoutId); - } - flush() { - const elements = this.cache.map((entry) => entry.element); - this.timeoutIds.forEach((id) => clearInterval(id)); - this.cache = []; - this.timeoutIds = []; - return elements; - } - } - - const STATUS_AWAITING_ACCEPT = "awaitingAccept"; - const STATUS_SUBSCRIBED = "subscribed"; - const ERR_MSG_SUB_FAILED = "Subscription failed."; - const ERR_MSG_SUB_REJECTED = "Subscription rejected."; - const ON_CLOSE_MSG_SERVER_INIT = "ServerInitiated"; - const ON_CLOSE_MSG_CLIENT_INIT = "ClientInitiated"; - class ClientStreaming { - session; - repository; - logger; - subscriptionsList = {}; - timedCache = new TimedCache({ ELEMENT_TTL_MS: 10000 }); - subscriptionIdToLocalKeyMap = {}; - nextSubLocalKey = 0; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("subscribed", this.handleSubscribed); - session.on("event", this.handleEventData); - session.on("subscription-cancelled", this.handleSubscriptionCancelled); - } - subscribe(streamingMethod, params, targetServers, success, error, existingSub) { - if (targetServers.length === 0) { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " No available servers matched the target params.", - }); - return; - } - const subLocalKey = this.getNextSubscriptionLocalKey(); - const pendingSub = this.registerSubscription(subLocalKey, streamingMethod, params, success, error, params.methodResponseTimeout || 10000, existingSub); - if (typeof pendingSub !== "object") { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Unable to register the user callbacks.", - }); - return; - } - targetServers.forEach((target) => { - const serverId = target.server.id; - const method = target.methods.find((m) => m.name === streamingMethod.name); - if (!method) { - this.logger.error(`can not find method ${streamingMethod.name} for target ${target.server.id}`); - return; - } - pendingSub.trackedServers.push({ - serverId, - subscriptionId: undefined, - }); - const msg = { - type: "subscribe", - server_id: serverId, - method_id: method.gatewayId, - arguments_kv: params.arguments, - }; - this.session.send(msg, { serverId, subLocalKey }) - .then((m) => this.handleSubscribed(m)) - .catch((err) => this.handleErrorSubscribing(err)); - }); - } - drainSubscriptions() { - const existing = Object.values(this.subscriptionsList); - this.subscriptionsList = {}; - this.subscriptionIdToLocalKeyMap = {}; - return existing; - } - drainSubscriptionsCache() { - return this.timedCache.flush(); - } - getNextSubscriptionLocalKey() { - const current = this.nextSubLocalKey; - this.nextSubLocalKey += 1; - return current; - } - registerSubscription(subLocalKey, method, params, success, error, timeout, existingSub) { - const subsInfo = { - localKey: subLocalKey, - status: STATUS_AWAITING_ACCEPT, - method, - params, - success, - error, - trackedServers: [], - handlers: { - onData: existingSub?.handlers.onData || [], - onClosed: existingSub?.handlers.onClosed || [], - onConnected: existingSub?.handlers.onConnected || [], - }, - queued: { - data: [], - closers: [], - }, - timeoutId: undefined, - close: () => this.closeSubscription(subLocalKey), - subscription: existingSub?.subscription - }; - if (!existingSub) { - if (params.onData) { - subsInfo.handlers.onData.push(params.onData); - } - if (params.onClosed) { - subsInfo.handlers.onClosed.push(params.onClosed); - } - if (params.onConnected) { - subsInfo.handlers.onConnected.push(params.onConnected); - } - } - this.subscriptionsList[subLocalKey] = subsInfo; - subsInfo.timeoutId = setTimeout(() => { - if (this.subscriptionsList[subLocalKey] === undefined) { - return; - } - const pendingSub = this.subscriptionsList[subLocalKey]; - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - error({ - method, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Subscription attempt timed out after " + timeout + " ms.", - }); - delete this.subscriptionsList[subLocalKey]; - } - else if (pendingSub.status === STATUS_SUBSCRIBED && pendingSub.trackedServers.length > 0) { - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return (typeof server.subscriptionId !== "undefined"); - }); - delete pendingSub.timeoutId; - if (pendingSub.trackedServers.length <= 0) { - this.callOnClosedHandlers(pendingSub); - delete this.subscriptionsList[subLocalKey]; - } - } - }, timeout); - return subsInfo; - } - handleErrorSubscribing = (errorResponse) => { - const tag = errorResponse._tag; - const subLocalKey = tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return server.serverId !== tag.serverId; - }); - if (pendingSub.trackedServers.length <= 0) { - clearTimeout(pendingSub.timeoutId); - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - const reason = (typeof errorResponse.reason === "string" && errorResponse.reason !== "") ? - ' Publisher said "' + errorResponse.reason + '".' : - " No reason given."; - const callArgs = typeof pendingSub.params.arguments === "object" ? - JSON.stringify(pendingSub.params.arguments) : - "{}"; - pendingSub.error({ - message: ERR_MSG_SUB_REJECTED + reason + " Called with:" + callArgs, - called_with: pendingSub.params.arguments, - method: pendingSub.method, - }); - } - else if (pendingSub.status === STATUS_SUBSCRIBED) { - this.callOnClosedHandlers(pendingSub); - } - delete this.subscriptionsList[subLocalKey]; - } - }; - handleSubscribed = (msg) => { - const subLocalKey = msg._tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - const serverId = msg._tag.serverId; - const acceptingServer = pendingSub.trackedServers - .filter((server) => { - return server.serverId === serverId; - })[0]; - if (typeof acceptingServer !== "object") { - return; - } - acceptingServer.subscriptionId = msg.subscription_id; - this.subscriptionIdToLocalKeyMap[msg.subscription_id] = subLocalKey; - const isFirstResponse = (pendingSub.status === STATUS_AWAITING_ACCEPT); - pendingSub.status = STATUS_SUBSCRIBED; - if (isFirstResponse) { - let reconnect = false; - let sub = pendingSub.subscription; - if (sub) { - sub.setNewSubscription(pendingSub); - pendingSub.success(sub); - reconnect = true; - } - else { - sub = new UserSubscription(this.repository, pendingSub); - pendingSub.subscription = sub; - pendingSub.success(sub); - } - for (const handler of pendingSub.handlers.onConnected) { - try { - handler(sub.serverInstance, reconnect); - } - catch (e) { - } - } - } - }; - handleEventData = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const trackedServersFound = subscription.trackedServers.filter((s) => { - return s.subscriptionId === msg.subscription_id; - }); - if (trackedServersFound.length !== 1) { - return; - } - const isPrivateData = msg.oob; - const sendingServerId = trackedServersFound[0].serverId; - const server = this.repository.getServerById(sendingServerId); - const receivedStreamData = () => { - return { - data: msg.data, - server: server?.instance ?? {}, - requestArguments: subscription.params.arguments, - message: undefined, - private: isPrivateData, - }; - }; - const onDataHandlers = subscription.handlers.onData; - const queuedData = subscription.queued.data; - if (onDataHandlers.length > 0) { - onDataHandlers.forEach((callback) => { - if (typeof callback === "function") { - callback(receivedStreamData()); - } - }); - } - else { - queuedData.push(receivedStreamData()); - } - }; - handleSubscriptionCancelled = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const expectedNewLength = subscription.trackedServers.length - 1; - subscription.trackedServers = subscription.trackedServers.filter((server) => { - if (server.subscriptionId === msg.subscription_id) { - subscription.queued.closers.push(server.serverId); - return false; - } - else { - return true; - } - }); - if (subscription.trackedServers.length !== expectedNewLength) { - return; - } - if (subscription.trackedServers.length <= 0) { - this.timedCache.add(subscription); - clearTimeout(subscription.timeoutId); - this.callOnClosedHandlers(subscription); - delete this.subscriptionsList[subLocalKey]; - } - delete this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - }; - callOnClosedHandlers(subscription, reason) { - const closersCount = subscription.queued.closers.length; - const closingServerId = (closersCount > 0) ? subscription.queued.closers[closersCount - 1] : null; - let closingServer; - if (closingServerId !== undefined && typeof closingServerId === "string") { - closingServer = this.repository.getServerById(closingServerId)?.instance ?? {}; - } - subscription.handlers.onClosed.forEach((callback) => { - if (typeof callback !== "function") { - return; - } - callback({ - message: reason || ON_CLOSE_MSG_SERVER_INIT, - requestArguments: subscription.params.arguments || {}, - server: closingServer, - stream: subscription.method, - }); - }); - } - closeSubscription(subLocalKey) { - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - subscription.trackedServers.forEach((server) => { - if (typeof server.subscriptionId === "undefined") { - return; - } - subscription.queued.closers.push(server.serverId); - this.session.sendFireAndForget({ - type: "unsubscribe", - subscription_id: server.subscriptionId, - reason_uri: "", - reason: ON_CLOSE_MSG_CLIENT_INIT, - }).catch((err) => { - this.logger.warn(`Error sending unsubscribe for subscription id ${server.subscriptionId}: ${JSON.stringify(err)}`); - }); - delete this.subscriptionIdToLocalKeyMap[server.subscriptionId]; - }); - subscription.trackedServers = []; - this.callOnClosedHandlers(subscription, ON_CLOSE_MSG_CLIENT_INIT); - delete this.subscriptionsList[subLocalKey]; - } - } - - class ClientProtocol { - session; - repository; - logger; - streaming; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("peer-added", (msg) => this.handlePeerAdded(msg)); - session.on("peer-removed", (msg) => this.handlePeerRemoved(msg)); - session.on("methods-added", (msg) => this.handleMethodsAddedMessage(msg)); - session.on("methods-removed", (msg) => this.handleMethodsRemovedMessage(msg)); - this.streaming = new ClientStreaming(session, repository, logger); - } - subscribe(stream, options, targetServers, success, error, existingSub) { - this.streaming.subscribe(stream, options, targetServers, success, error, existingSub); - } - invoke(id, method, args, target) { - const serverId = target.id; - const methodId = method.gatewayId; - const msg = { - type: "call", - server_id: serverId, - method_id: methodId, - arguments_kv: args, - }; - return this.session.send(msg, { invocationId: id, serverId }) - .then((m) => this.handleResultMessage(m)) - .catch((err) => this.handleInvocationError(err)); - } - drainSubscriptions() { - return this.streaming.drainSubscriptions(); - } - drainSubscriptionsCache() { - return this.streaming.drainSubscriptionsCache(); - } - handlePeerAdded(msg) { - const newPeerId = msg.new_peer_id; - const remoteId = msg.identity; - const isLocal = msg.meta ? msg.meta.local : true; - const pid = Number(remoteId.process); - const serverInfo = { - machine: remoteId.machine, - pid: isNaN(pid) ? remoteId.process : pid, - instance: remoteId.instance, - application: remoteId.application, - applicationName: remoteId.applicationName, - environment: remoteId.environment, - region: remoteId.region, - user: remoteId.user, - windowId: remoteId.windowId, - peerId: newPeerId, - api: remoteId.api, - isLocal - }; - this.repository.addServer(serverInfo, newPeerId); - } - handlePeerRemoved(msg) { - const removedPeerId = msg.removed_id; - const reason = msg.reason; - this.repository.removeServerById(removedPeerId, reason); - } - handleMethodsAddedMessage(msg) { - const serverId = msg.server_id; - const methods = msg.methods; - methods.forEach((method) => { - this.repository.addServerMethod(serverId, method); - }); - } - handleMethodsRemovedMessage(msg) { - const serverId = msg.server_id; - const methodIdList = msg.methods; - const server = this.repository.getServerById(serverId); - if (server) { - const serverMethodKeys = Object.keys(server.methods); - serverMethodKeys.forEach((methodKey) => { - const method = server.methods[methodKey]; - if (methodIdList.indexOf(method.gatewayId) > -1) { - this.repository.removeServerMethod(serverId, methodKey); - } - }); - } - } - handleResultMessage(msg) { - const invocationId = msg._tag.invocationId; - const result = msg.result; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - return { - invocationId, - result, - instance: server?.instance, - status: InvokeStatus.Success, - message: "" - }; - } - handleInvocationError(msg) { - this.logger.debug(`handle invocation error ${JSON.stringify(msg)}`); - if ("_tag" in msg) { - const invocationId = msg._tag.invocationId; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - const message = msg.reason; - const context = msg.context; - return { - invocationId, - result: context, - instance: server?.instance, - status: InvokeStatus.Error, - message - }; - } - else { - return { - invocationId: "", - message: msg.message, - status: InvokeStatus.Error, - error: msg - }; - } - } - } - - function gW3ProtocolFactory (instance, connection, clientRepository, serverRepository, libConfig, interop) { - const logger = libConfig.logger.subLogger("gw3-protocol"); - let resolveReadyPromise; - const readyPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - const session = connection.domain("agm", ["subscribed"]); - const server = new ServerProtocol(session, clientRepository, serverRepository, logger.subLogger("server")); - const client = new ClientProtocol(session, clientRepository, logger.subLogger("client")); - async function handleReconnect() { - logger.info("reconnected - will replay registered methods and subscriptions"); - client.drainSubscriptionsCache().forEach((sub) => { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to soft-re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`soft-subscribing to method ${methodInfo.name} DONE`)).catch((error) => logger.warn(`subscribing to method ${methodInfo.name} failed: ${JSON.stringify(error)}}`)); - }); - const reconnectionPromises = []; - const existingSubscriptions = client.drainSubscriptions(); - for (const sub of existingSubscriptions) { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - reconnectionPromises.push(interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`subscribing to method ${methodInfo.name} DONE`))); - } - const registeredMethods = serverRepository.getList(); - serverRepository.reset(); - for (const method of registeredMethods) { - const def = method.definition; - if (method.stream) { - reconnectionPromises.push(interop.server.createStream(def, method.streamCallbacks, undefined, undefined, method.stream) - .then(() => logger.info(`subscribing to method ${def.name} DONE`)) - .catch(() => logger.warn(`subscribing to method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallback) { - reconnectionPromises.push(interop.register(def, method.theFunction.userCallback) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallbackAsync) { - reconnectionPromises.push(interop.registerAsync(def, method.theFunction.userCallbackAsync) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - } - await Promise.all(reconnectionPromises); - logger.info("Interop is re-announced"); - } - function handleInitialJoin() { - if (resolveReadyPromise) { - resolveReadyPromise({ - client, - server, - }); - resolveReadyPromise = undefined; - } - } - session.onJoined((reconnect) => { - clientRepository.addServer(instance, connection.peerId); - if (reconnect) { - handleReconnect().then(() => connection.setLibReAnnounced({ name: "interop" })).catch((error) => logger.warn(`Error while re-announcing interop: ${JSON.stringify(error)}`)); - } - else { - handleInitialJoin(); - } - }); - session.onLeft(() => { - clientRepository.reset(); - }); - session.join(); - return readyPromise; - } - - class Interop { - instance; - readyPromise; - client; - server; - unwrappedInstance; - protocol; - clientRepository; - serverRepository; - constructor(configuration) { - if (typeof configuration === "undefined") { - throw new Error("configuration is required"); - } - if (typeof configuration.connection === "undefined") { - throw new Error("configuration.connections is required"); - } - const connection = configuration.connection; - if (typeof configuration.methodResponseTimeout !== "number") { - configuration.methodResponseTimeout = 30 * 1000; - } - if (typeof configuration.waitTimeoutMs !== "number") { - configuration.waitTimeoutMs = 30 * 1000; - } - this.unwrappedInstance = new InstanceWrapper(this, undefined, connection); - this.instance = this.unwrappedInstance.unwrap(); - this.clientRepository = new ClientRepository(configuration.logger.subLogger("cRep"), this); - this.serverRepository = new ServerRepository(); - let protocolPromise; - if (connection.protocolVersion === 3) { - protocolPromise = gW3ProtocolFactory(this.instance, connection, this.clientRepository, this.serverRepository, configuration, this); - } - else { - throw new Error(`protocol ${connection.protocolVersion} not supported`); - } - this.readyPromise = protocolPromise.then((protocol) => { - this.protocol = protocol; - this.client = new Client(this.protocol, this.clientRepository, this.instance, configuration); - this.server = new Server(this.protocol, this.serverRepository); - return this; - }); - } - ready() { - return this.readyPromise; - } - serverRemoved(callback) { - return this.client.serverRemoved(callback); - } - serverAdded(callback) { - return this.client.serverAdded(callback); - } - serverMethodRemoved(callback) { - return this.client.serverMethodRemoved(callback); - } - serverMethodAdded(callback) { - return this.client.serverMethodAdded(callback); - } - methodRemoved(callback) { - return this.client.methodRemoved(callback); - } - methodAdded(callback) { - return this.client.methodAdded(callback); - } - methodsForInstance(instance) { - return this.client.methodsForInstance(instance); - } - methods(methodFilter) { - return this.client.methods(methodFilter); - } - servers(methodFilter) { - return this.client.servers(methodFilter); - } - subscribe(method, options, successCallback, errorCallback) { - return this.client.subscribe(method, options, successCallback, errorCallback); - } - createStream(streamDef, callbacks, successCallback, errorCallback) { - return this.server.createStream(streamDef, callbacks, successCallback, errorCallback); - } - unregister(methodFilter) { - return this.server.unregister(methodFilter); - } - registerAsync(methodDefinition, callback) { - return this.server.registerAsync(methodDefinition, callback); - } - register(methodDefinition, callback) { - return this.server.register(methodDefinition, callback); - } - invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - return this.client.invoke(methodFilter, argumentObj, target, additionalOptions, success, error); - } - waitForMethod(name) { - const pw = new PromiseWrapper(); - const unsubscribe = this.client.methodAdded((m) => { - if (m.name === name) { - unsubscribe(); - pw.resolve(m); - } - }); - return pw.promise; - } - } - - const successMessages = ["subscribed", "success"]; - class MessageBus { - connection; - logger; - peerId; - session; - subscriptions; - readyPromise; - constructor(connection, logger) { - this.connection = connection; - this.logger = logger; - this.peerId = connection.peerId; - this.subscriptions = []; - this.session = connection.domain("bus", successMessages); - this.readyPromise = this.session.join(); - this.readyPromise.then(() => { - this.watchOnEvent(); - }); - } - ready() { - return this.readyPromise; - } - publish = (topic, data, options) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "publish", - topic, - data, - peer_id: this.peerId, - routing_key: routingKey, - target_identity: target - }); - this.session.send(args) - .catch((err) => { - this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`); - }); - }; - subscribe = (topic, callback, options) => { - return new Promise((resolve, reject) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "subscribe", - topic, - peer_id: this.peerId, - routing_key: routingKey, - source: target - }); - this.session.send(args) - .then((response) => { - const { subscription_id } = response; - this.subscriptions.push({ subscription_id, topic, callback, source: target }); - resolve({ - unsubscribe: () => { - this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId }) - .then(() => { - this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id); - }).catch((err) => { - this.logger.warn(`Failed to send unsubscribe request for ${subscription_id}: ${JSON.stringify(err)}`); - }); - return Promise.resolve(); - } - }); - }) - .catch((error) => reject(error)); - }); - }; - watchOnEvent = () => { - this.session.on("event", (args) => { - const { data, subscription_id } = args; - const source = args["publisher-identity"]; - const subscription = this.subscriptions.find((s) => s.subscription_id === subscription_id); - if (subscription) { - if (!subscription.source) { - subscription.callback(data, subscription.topic, source); - } - else { - if (this.keysMatch(subscription.source, source)) { - subscription.callback(data, subscription.topic, source); - } - } - } - }); - }; - removeEmptyValues(obj) { - const cleaned = {}; - Object.keys(obj).forEach((key) => { - if (obj[key] !== undefined && obj[key] !== null) { - cleaned[key] = obj[key]; - } - }); - return cleaned; - } - keysMatch(obj1, obj2) { - const keysObj1 = Object.keys(obj1); - let allMatch = true; - keysObj1.forEach((key) => { - if (obj1[key] !== obj2[key]) { - allMatch = false; - } - }); - return allMatch; - } - } - - const IOConnectCoreFactory = (userConfig, ext) => { - const iodesktop = typeof window === "object" ? (window.iodesktop ?? window.glue42gd) : undefined; - const preloadPromise = typeof window === "object" ? (window.gdPreloadPromise ?? Promise.resolve()) : Promise.resolve(); - const glueInitTimer = timer("glue"); - userConfig = userConfig || {}; - ext = ext || {}; - const internalConfig = prepareConfig(userConfig, ext, iodesktop); - let _connection; - let _interop; - let _logger; - let _metrics; - let _contexts; - let _bus; - let _allowTrace; - const libs = {}; - function registerLib(name, inner, t) { - _allowTrace = _logger.canPublish("trace"); - if (_allowTrace) { - _logger.trace(`registering ${name} module`); - } - const done = (e) => { - inner.initTime = t.stop(); - inner.initEndTime = t.endTime; - inner.marks = t.marks; - if (!_allowTrace) { - return; - } - const traceMessage = e ? - `${name} failed - ${e.message}` : - `${name} is ready - ${t.endTime - t.startTime}`; - _logger.trace(traceMessage); - }; - inner.initStartTime = t.startTime; - if (inner.ready) { - inner.ready() - .then(() => { - done(); - }) - .catch((e) => { - const error = typeof e === "string" ? new Error(e) : e; - done(error); - }); - } - else { - done(); - } - if (!Array.isArray(name)) { - name = [name]; - } - name.forEach((n) => { - libs[n] = inner; - IOConnectCoreFactory[n] = inner; - }); - } - function setupConnection() { - const initTimer = timer("connection"); - _connection = new Connection(internalConfig.connection, _logger.subLogger("connection")); - let authPromise = Promise.resolve(internalConfig.auth); - if (internalConfig.connection && !internalConfig.auth) { - if (iodesktop) { - authPromise = iodesktop.getGWToken() - .then((token) => { - return { - gatewayToken: token - }; - }); - } - else if (typeof window !== "undefined" && window?.glue42electron) { - if (typeof window.glue42electron.gwToken === "string") { - authPromise = Promise.resolve({ - gatewayToken: window.glue42electron.gwToken - }); - } - } - else { - authPromise = Promise.reject("You need to provide auth information"); - } - } - return authPromise - .then((authConfig) => { - initTimer.mark("auth-promise-resolved"); - let authRequest; - if (Object.prototype.toString.call(authConfig) === "[object Object]") { - authRequest = authConfig; - } - else { - throw new Error("Invalid auth object - " + JSON.stringify(authConfig)); - } - return _connection.login(authRequest); - }) - .then(() => { - registerLib("connection", _connection, initTimer); - return internalConfig; - }) - .catch((e) => { - if (_connection) { - _connection.logout(); - } - throw e; - }); - } - function setupLogger() { - const initTimer = timer("logger"); - _logger = new Logger(`${internalConfig.connection.identity?.application}`, undefined, internalConfig.customLogger); - _logger.consoleLevel(internalConfig.logger.console); - _logger.publishLevel(internalConfig.logger.publish); - if (_logger.canPublish("debug")) { - _logger.debug("initializing glue..."); - } - registerLib("logger", _logger, initTimer); - return Promise.resolve(undefined); - } - function setupMetrics() { - const initTimer = timer("metrics"); - const config = internalConfig.metrics; - const metricsPublishingEnabledFunc = iodesktop?.getMetricsPublishingEnabled; - const identity = internalConfig.connection.identity; - const canUpdateMetric = metricsPublishingEnabledFunc ? metricsPublishingEnabledFunc : () => true; - const disableAutoAppSystem = (typeof config !== "boolean" && config.disableAutoAppSystem) ?? false; - _metrics = metrics({ - connection: config ? _connection : undefined, - logger: _logger.subLogger("metrics"), - canUpdateMetric, - system: "Glue42", - service: identity?.service ?? iodesktop?.applicationName ?? internalConfig.application, - instance: identity?.instance ?? identity?.windowId ?? nanoid(10), - disableAutoAppSystem, - pagePerformanceMetrics: typeof config !== "boolean" ? config?.pagePerformanceMetrics : undefined - }); - registerLib("metrics", _metrics, initTimer); - return Promise.resolve(); - } - function setupInterop() { - const initTimer = timer("interop"); - const agmConfig = { - connection: _connection, - logger: _logger.subLogger("interop"), - }; - _interop = new Interop(agmConfig); - Logger.Interop = _interop; - registerLib(["interop", "agm"], _interop, initTimer); - return Promise.resolve(); - } - function setupContexts() { - const hasActivities = (internalConfig.activities && _connection.protocolVersion === 3); - const needsContexts = internalConfig.contexts || hasActivities; - if (needsContexts) { - const initTimer = timer("contexts"); - _contexts = new ContextsModule({ - connection: _connection, - logger: _logger.subLogger("contexts"), - trackAllContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.trackAllContexts : false, - reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false, - subscribeOnGet: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnGet : true, - subscribeOnUpdate: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnUpdate : true, - onlyReAnnounceSubscribedContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.onlyReAnnounceSubscribedContexts : true - }); - registerLib("contexts", _contexts, initTimer); - } - else { - const replayer = _connection.replayer; - if (replayer) { - replayer.drain(ContextMessageReplaySpec.name); - } - } - return Promise.resolve(); - } - async function setupBus() { - if (!internalConfig.bus) { - return Promise.resolve(); - } - const initTimer = timer("bus"); - _bus = new MessageBus(_connection, _logger.subLogger("bus")); - registerLib("bus", _bus, initTimer); - return Promise.resolve(); - } - function setupExternalLibs(externalLibs) { - try { - externalLibs.forEach((lib) => { - setupExternalLib(lib.name, lib.create); - }); - return Promise.resolve(); - } - catch (e) { - return Promise.reject(e); - } - } - function setupExternalLib(name, createCallback) { - const initTimer = timer(name); - const lib = createCallback(libs); - if (lib) { - registerLib(name, lib, initTimer); - } - } - function waitForLibs() { - const libsReadyPromises = Object.keys(libs).map((key) => { - const lib = libs[key]; - return lib.ready ? - lib.ready() : Promise.resolve(); - }); - return Promise.all(libsReadyPromises); - } - function constructGlueObject() { - const feedbackFunc = (feedbackInfo) => { - if (!_interop) { - return; - } - _interop.invoke("T42.ACS.Feedback", feedbackInfo, "best"); - }; - const info = { - coreVersion: version, - version: internalConfig.version - }; - glueInitTimer.stop(); - const glue = { - feedback: feedbackFunc, - info, - logger: _logger, - interop: _interop, - agm: _interop, - connection: _connection, - metrics: _metrics, - contexts: _contexts, - bus: _bus, - version: internalConfig.version, - userConfig, - done: () => { - _logger?.info("done called by user..."); - return _connection.logout(); - } - }; - glue.performance = { - get glueVer() { - return internalConfig.version; - }, - get glueConfig() { - return JSON.stringify(userConfig); - }, - get browser() { - return window.performance.timing.toJSON(); - }, - get memory() { - return window.performance.memory; - }, - get initTimes() { - const all = getAllTimers(); - return Object.keys(all).map((key) => { - const t = all[key]; - return { - name: key, - duration: t.endTime - t.startTime, - marks: t.marks, - startTime: t.startTime, - endTime: t.endTime - }; - }); - } - }; - Object.keys(libs).forEach((key) => { - const lib = libs[key]; - glue[key] = lib; - }); - glue.config = {}; - Object.keys(internalConfig).forEach((k) => { - glue.config[k] = internalConfig[k]; - }); - if (ext && ext.extOptions) { - Object.keys(ext.extOptions).forEach((k) => { - glue.config[k] = ext?.extOptions[k]; - }); - } - if (ext?.enrichGlue) { - ext.enrichGlue(glue); - } - if (iodesktop && iodesktop.updatePerfData) { - iodesktop.updatePerfData(glue.performance); - } - if (glue.agm) { - const deprecatedDecorator = (fn, wrong, proper) => { - return function () { - glue.logger.warn(`glue.js - 'glue.agm.${wrong}' method is deprecated, use 'glue.interop.${proper}' instead.`); - return fn.apply(glue.agm, arguments); - }; - }; - const agmAny = glue.agm; - agmAny.method_added = deprecatedDecorator(glue.agm.methodAdded, "method_added", "methodAdded"); - agmAny.method_removed = deprecatedDecorator(glue.agm.methodRemoved, "method_removed", "methodRemoved"); - agmAny.server_added = deprecatedDecorator(glue.agm.serverAdded, "server_added", "serverAdded"); - agmAny.server_method_aded = deprecatedDecorator(glue.agm.serverMethodAdded, "server_method_aded", "serverMethodAdded"); - agmAny.server_method_removed = deprecatedDecorator(glue.agm.serverMethodRemoved, "server_method_removed", "serverMethodRemoved"); - } - return glue; - } - async function registerInstanceIfNeeded() { - const RegisterInstanceMethodName = "T42.ACS.RegisterInstance"; - if (Utils.isNode() && typeof process.env._GD_STARTING_CONTEXT_ === "undefined" && typeof userConfig?.application !== "undefined") { - const isMethodAvailable = _interop.methods({ name: RegisterInstanceMethodName }).length > 0; - if (isMethodAvailable) { - try { - await _interop.invoke(RegisterInstanceMethodName, { appName: userConfig?.application, pid: process.pid }); - } - catch (error) { - const typedError = error; - _logger.error(`Cannot register as an instance: ${JSON.stringify(typedError.message)}`); - } - } - } - } - return preloadPromise - .then(setupLogger) - .then(setupConnection) - .then(() => Promise.all([setupMetrics(), setupInterop(), setupContexts(), setupBus()])) - .then(() => _interop.readyPromise) - .then(() => registerInstanceIfNeeded()) - .then(() => { - return setupExternalLibs(internalConfig.libs || []); - }) - .then(waitForLibs) - .then(constructGlueObject) - .catch((err) => { - return Promise.reject({ - err, - libs - }); - }); - }; - if (typeof window !== "undefined") { - window.IOConnectCore = IOConnectCoreFactory; - } - IOConnectCoreFactory.version = version; - IOConnectCoreFactory.default = IOConnectCoreFactory; - - const iOConnectBrowserFactory = createFactoryFunction(IOConnectCoreFactory); - if (typeof window !== "undefined") { - const windowAny = window; - windowAny.IOBrowser = iOConnectBrowserFactory; - delete windowAny.GlueCore; - delete windowAny.IOConnectCore; - } - const legacyGlobal = window.glue42gd || window.glue42core; - const ioGlobal = window.iodesktop || window.iobrowser; - if (!legacyGlobal && !ioGlobal) { - window.iobrowser = { webStarted: false }; - } - if (!window.iodesktop && !window.iobrowser.system) { - window.iobrowser.system = setupGlobalSystem(); - } - iOConnectBrowserFactory.version = version$1; - - return iOConnectBrowserFactory; - -})); -//# sourceMappingURL=browser.umd.js.map diff --git a/javascript/solution/client-details/lib/workspaces.umd.js b/javascript/solution/client-details/lib/workspaces.umd.js deleted file mode 100644 index 8d833a0..0000000 --- a/javascript/solution/client-details/lib/workspaces.umd.js +++ /dev/null @@ -1,5618 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.workspaces = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder.oneOf; - /** See `Decoder.union` */ - Decoder.union; - /** See `Decoder.intersection` */ - var intersection = Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - Decoder.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder.lazy; - - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number"); - const positiveNumberDecoder = number().where((num) => num > 0, "Expected a positive number"); - const windowDragModeDecoder = oneOf(constant("keepInside"), constant("autoEject")); - const isWindowInSwimlaneResultDecoder = object({ - inWorkspace: boolean() - }); - const frameVisibilityResultDecoder = object({ - isVisible: boolean() - }); - const iconDecoder = object({ - base64Image: nonEmptyStringDecoder - }); - const setIconArgumentsDecoder = object({ - icon: iconDecoder, - frameId: nonEmptyStringDecoder - }); - const allParentDecoder = oneOf(constant("workspace"), constant("row"), constant("column"), constant("group")); - const subParentDecoder = oneOf(constant("row"), constant("column"), constant("group")); - const frameStateDecoder = oneOf(constant("maximized"), constant("minimized"), constant("normal")); - const loadingAnimationTypeDecoder = oneOf(constant("workspace")); - const checkThrowCallback = (callback, allowUndefined) => { - const argumentType = typeof callback; - if (allowUndefined && argumentType !== "function" && argumentType !== "undefined") { - throw new Error(`Provided argument must be either undefined or of type function, provided: ${argumentType}`); - } - if (!allowUndefined && argumentType !== "function") { - throw new Error(`Provided argument must be of type function, provided: ${argumentType}`); - } - }; - const workspaceBuilderCreateConfigDecoder = optional(object({ - saveLayout: optional(boolean()) - })); - const deleteLayoutConfigDecoder = object({ - name: nonEmptyStringDecoder - }); - const windowDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const groupDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropHeader: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()) - }); - const rowDefinitionConfigDecoder = object({ - minHeight: optional(number()), - maxHeight: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const columnDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const swimlaneWindowDefinitionDecoder = object({ - type: optional(constant("window")), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const strictSwimlaneWindowDefinitionDecoder = object({ - type: constant("window"), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const parentDefinitionDecoder = optional(object({ - type: optional(subParentDecoder), - children: optional(lazy(() => array(oneOf(swimlaneWindowDefinitionDecoder, parentDefinitionDecoder)))), - config: optional(anyJson()) - })); - const strictColumnDefinitionDecoder = object({ - type: constant("column"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(columnDefinitionConfigDecoder) - }); - const strictRowDefinitionDecoder = object({ - type: constant("row"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(rowDefinitionConfigDecoder) - }); - const strictGroupDefinitionDecoder = object({ - type: constant("group"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(groupDefinitionConfigDecoder) - }); - const strictParentDefinitionDecoder = oneOf(strictGroupDefinitionDecoder, strictColumnDefinitionDecoder, strictRowDefinitionDecoder); - oneOf(string().where((s) => s.toLowerCase() === "maximized", "Expected a case insensitive variation of 'maximized'"), string().where((s) => s.toLowerCase() === "normal", "Expected a case insensitive variation of 'normal'")); - const newFrameConfigDecoder = object({ - bounds: optional(object({ - left: optional(number()), - top: optional(number()), - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - })), - isVisible: optional(boolean()), - frameId: optional(nonEmptyStringDecoder) - }); - const loadingStrategyDecoder = oneOf(constant("direct"), constant("delayed"), constant("lazy")); - const restoreWorkspaceConfigDecoder = optional(object({ - app: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - loadingStrategy: optional(loadingStrategyDecoder), - title: optional(nonEmptyStringDecoder), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - frameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - lockdown: optional(boolean()), - activateFrame: optional(boolean()), - newFrame: optional(oneOf(newFrameConfigDecoder, boolean())), - noTabHeader: optional(boolean()), - inMemoryLayout: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - allowSystemHibernation: optional(boolean()) - })); - const openWorkspaceConfigDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const workspaceDefinitionDecoder = object({ - children: optional(array(oneOf(swimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder))), - context: optional(anyJson()), - config: optional(object({ - title: optional(nonEmptyStringDecoder), - position: optional(nonNegativeNumberDecoder), - isFocused: optional(boolean()), - noTabHeader: optional(boolean()), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - loadingStrategy: optional(loadingStrategyDecoder), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showCloseButton: optional(boolean()), - allowSplitters: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - windowDragMode: optional(windowDragModeDecoder) - })), - frame: optional(object({ - activate: optional(boolean()), - reuseFrameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - newFrame: optional(oneOf(boolean(), newFrameConfigDecoder)) - })) - }); - const workspaceSelectorDecoder = object({ - workspaceId: nonEmptyStringDecoder - }); - const restoreWorkspaceDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const emptyFrameDefinitionDecoder = optional(object({ - applicationName: optional(string()), - frameConfig: optional(newFrameConfigDecoder), - context: optional(object()), - layoutComponentId: optional(nonEmptyStringDecoder) - })); - const frameInitConfigDecoder = object({ - workspaces: array(oneOf(optional(workspaceDefinitionDecoder), optional(restoreWorkspaceDefinitionDecoder))) - }); - const frameInitProtocolConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaces: array(oneOf(workspaceDefinitionDecoder, restoreWorkspaceDefinitionDecoder)) - }); - const builderConfigDecoder = object({ - type: allParentDecoder, - definition: optional(oneOf(workspaceDefinitionDecoder, parentDefinitionDecoder)) - }); - const workspaceCreateConfigDecoder = intersection(workspaceDefinitionDecoder, object({ - saveConfig: optional(object({ - saveLayout: optional(boolean()) - })) - })); - const getFrameSummaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const frameInitializationContextDecoder = object({ - context: optional(object()) - }); - const frameSummaryDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - object({ - type: subParentDecoder, - id: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number() - }); - const eventTypeDecoder = oneOf(constant("frame"), constant("workspace"), constant("container"), constant("window")); - const streamRequestArgumentsDecoder = object({ - type: eventTypeDecoder, - branch: nonEmptyStringDecoder - }); - const workspaceEventActionDecoder = oneOf(constant("opened"), constant("closing"), constant("closed"), constant("focus"), constant("added"), constant("loaded"), constant("removed"), constant("childrenUpdate"), constant("containerChange"), constant("maximized"), constant("restored"), constant("minimized"), constant("normal"), constant("selected"), constant("lock-configuration-changed"), constant("hibernated"), constant("resumed")); - const workspaceConfigResultDecoder = object({ - frameId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder, - positionIndex: nonNegativeNumberDecoder, - name: nonEmptyStringDecoder, - layoutName: optional(nonEmptyStringDecoder), - isHibernated: optional(boolean()), - isSelected: optional(boolean()), - allowDrop: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - widthInPx: optional(number()), - heightInPx: optional(number()), - isPinned: optional(boolean()), - windowDragMode: optional(windowDragModeDecoder), - loadingStrategy: optional(loadingStrategyDecoder) - }); - const baseChildSnapshotConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number(), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()) - }); - const parentSnapshotConfigDecoder = anyJson(); - const swimlaneWindowSnapshotConfigDecoder = intersection(baseChildSnapshotConfigDecoder, object({ - windowId: optional(nonEmptyStringDecoder), - isMaximized: optional(boolean()), - isFocused: boolean(), - isSelected: optional(boolean()), - title: optional(string()), - appName: optional(nonEmptyStringDecoder), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - widthInPx: optional(number()), - heightInPx: optional(number()), - context: optional(anyJson()) - })); - const customWorkspaceSubParentSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: parentSnapshotConfigDecoder, - children: optional(lazy(() => array(customWorkspaceChildSnapshotDecoder))), - type: oneOf(constant("row"), constant("column"), constant("group")) - }); - const customWorkspaceWindowSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: swimlaneWindowSnapshotConfigDecoder, - type: constant("window") - }); - const customWorkspaceChildSnapshotDecoder = oneOf(customWorkspaceWindowSnapshotDecoder, customWorkspaceSubParentSnapshotDecoder); - const childSnapshotResultDecoder = customWorkspaceChildSnapshotDecoder; - const workspaceSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder, - children: array(childSnapshotResultDecoder), - frameSummary: frameSummaryDecoder, - context: optional(anyJson()) - }); - const windowLayoutItemDecoder = object({ - type: constant("window"), - config: object({ - appName: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - url: optional(nonEmptyStringDecoder), - title: optional(string()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - isMaximized: optional(boolean()) - }) - }); - const groupLayoutItemDecoder = object({ - type: constant("group"), - config: anyJson(), - children: array(oneOf(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object({ - type: constant("column"), - config: anyJson(), - children: array(oneOf(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object({ - type: constant("row"), - config: anyJson(), - children: array(oneOf(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutDecoder = object({ - name: nonEmptyStringDecoder, - type: constant("Workspace"), - metadata: optional(anyJson()), - components: array(object({ - type: constant("Workspace"), - application: optional(string()), - state: object({ - config: anyJson(), - context: anyJson(), - children: array(oneOf(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }) - })) - }); - const workspacesImportLayoutDecoder = object({ - layout: workspaceLayoutDecoder, - mode: oneOf(constant("replace"), constant("merge")) - }); - const workspacesImportLayoutsDecoder = object({ - layouts: array(workspaceLayoutDecoder), - mode: oneOf(constant("replace"), constant("merge")) - }); - const exportedLayoutsResultDecoder = object({ - layouts: array(workspaceLayoutDecoder) - }); - const frameSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - const frameSummariesResultDecoder = object({ - summaries: array(frameSummaryResultDecoder) - }); - const workspaceSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder - }); - const workspaceSummariesResultDecoder = object({ - summaries: array(workspaceSummaryResultDecoder) - }); - const frameSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: anyJson(), - workspaces: array(workspaceSnapshotResultDecoder) - }); - const layoutSummaryDecoder = object({ - name: nonEmptyStringDecoder, - applicationName: optional(string()) - }); - const layoutSummariesDecoder = object({ - summaries: array(layoutSummaryDecoder) - }); - const simpleWindowOperationSuccessResultDecoder = object({ - windowId: nonEmptyStringDecoder - }); - const voidResultDecoder = anyJson(); - const frameStateResultDecoder = object({ - state: frameStateDecoder - }); - const frameBoundsDecoder = object({ - top: number(), - left: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const frameBoundsResultDecoder = object({ - bounds: frameBoundsDecoder - }); - const getWorkspaceIconResultDecoder = object({ - icon: optional(nonEmptyStringDecoder) - }); - const getPlatformFrameIdResultDecoder = object({ - id: optional(nonEmptyStringDecoder) - }); - const operationCheckResultDecoder = object({ - isSupported: boolean() - }); - const resizeConfigDecoder = object({ - width: optional(positiveNumberDecoder), - height: optional(positiveNumberDecoder), - relative: optional(boolean()) - }); - const moveConfigDecoder = object({ - top: optional(number()), - left: optional(number()), - relative: optional(boolean()) - }); - const simpleItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const closeOptionsDecoder = object({ - allowPrevent: optional(boolean()), - showDialog: optional(boolean()), - }); - const closeItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - closeOptions: optional(closeOptionsDecoder) - }); - const frameSnapshotConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - excludeIds: optional(boolean()) - }); - const frameStateConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - requestedState: frameStateDecoder - }); - const setItemTitleConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder - }); - const moveWindowConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - containerId: nonEmptyStringDecoder - }); - const resizeItemConfigDecoder = intersection(simpleItemConfigDecoder, resizeConfigDecoder); - const setMaximizationBoundaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - enabled: boolean() - }); - const moveFrameConfigDecoder = intersection(simpleItemConfigDecoder, moveConfigDecoder); - object({ - id: nonEmptyStringDecoder, - type: subParentDecoder - }); - const addWindowConfigDecoder = object({ - definition: swimlaneWindowDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addContainerConfigDecoder = object({ - definition: strictParentDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addItemResultDecoder = object({ - itemId: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder) - }); - const pingResultDecoder = object({ - live: boolean() - }); - const bundleWorkspaceConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - workspaceId: nonEmptyStringDecoder - }); - const bundleItemConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - itemId: nonEmptyStringDecoder - }); - const containerSummaryResultDecoder = object({ - itemId: nonEmptyStringDecoder, - config: parentSnapshotConfigDecoder - }); - const frameStreamDataDecoder = object({ - frameSummary: frameSummaryDecoder, - frameBounds: optional(frameBoundsDecoder) - }); - const workspaceStreamDataDecoder = object({ - workspaceSummary: workspaceSummaryResultDecoder, - frameSummary: frameSummaryDecoder, - workspaceSnapshot: optional(workspaceSnapshotResultDecoder), - frameBounds: optional(frameBoundsDecoder) - }); - const containerStreamDataDecoder = object({ - containerSummary: containerSummaryResultDecoder - }); - const windowStreamDataDecoder = object({ - windowSummary: object({ - itemId: nonEmptyStringDecoder, - parentId: nonEmptyStringDecoder, - config: swimlaneWindowSnapshotConfigDecoder - }) - }); - const workspaceLayoutSaveConfigDecoder = object({ - name: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - saveContext: optional(boolean()), - allowMultiple: optional(boolean()), - metadata: optional(object()) - }); - const workspaceLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - }); - const lockWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - config: optional(workspaceLockConfigDecoder) - }); - const windowLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const elementResizeConfigDecoder = object({ - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - }); - const lockWindowDecoder = object({ - windowPlacementId: nonEmptyStringDecoder, - config: optional(windowLockConfigDecoder) - }); - const rowLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const columnLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const groupLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - allowDropHeader: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()), - }); - const lockRowDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("row"), - config: optional(rowLockConfigDecoder) - }); - const lockColumnDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("column"), - config: optional(columnLockConfigDecoder) - }); - const lockGroupDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("group"), - config: optional(groupLockConfigDecoder) - }); - const lockContainerDecoder = oneOf(lockRowDecoder, lockColumnDecoder, lockGroupDecoder); - const pinWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const setWorkspaceIconDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const workspacePinOptionsDecoder = optional(object({ - icon: optional(nonEmptyStringDecoder) - })); - const frameShowConfigDecoder = optional(object({ - activate: optional(boolean()) - })); - const shortcutConfigDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const shortcutClickedDataDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const frameClosingDataDecoder = object({ - frameId: nonEmptyStringDecoder, - }); - const setMaximizationBoundaryAPIConfigDecoder = object({ - enabled: boolean() - }); - const loadingAnimationConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - type: loadingAnimationTypeDecoder - }); - const operationCheckConfigDecoder = object({ - operation: nonEmptyStringDecoder - }); - const setWindowDragModeDecoder = object({ - itemId: nonEmptyStringDecoder, - dragMode: windowDragModeDecoder - }); - const setLoadingStrategyDecoder = object({ - itemId: nonEmptyStringDecoder, - strategy: loadingStrategyDecoder - }); - const frameClosingResultDecoder = object({ - prevent: boolean() - }); - const sizeDecoder = object({ - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const boundsDecoder = object({ - left: number(), - top: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const popupTargetLocationDecoder = oneOf(constant("none"), constant("left"), constant("right"), constant("top"), constant("bottom")); - const popupConfigDecoder = object({ - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const ShowPopupConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const changeFrameVisibilityConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - activate: optional(boolean()), - isVisible: boolean() - }); - const frameDialogOptionsDecoder = object({ - mode: optional(oneOf(constant("Global"), constant("WindowContainer"))), - type: string(), - size: optional(sizeDecoder), - message: nonEmptyStringDecoder, - messageTitle: optional(nonEmptyStringDecoder), - movable: optional(boolean()), - transparent: optional(boolean()), - title: nonEmptyStringDecoder, - context: optional(anyJson()), - affirmativeButtonName: optional(nonEmptyStringDecoder), - showAffirmativeButton: optional(boolean()), - cancelButtonName: optional(nonEmptyStringDecoder), - showCancelButton: optional(boolean()), - negativeButtonName: optional(nonEmptyStringDecoder), - showNegativeButton: optional(boolean()), - defaultAction: optional(oneOf(constant("affirmative"), constant("negative"), constant("cancel"))), - timerDuration: optional(positiveNumberDecoder), - showTimer: optional(boolean()), - inputMaxLength: optional(positiveNumberDecoder), - inputPattern: optional(nonEmptyStringDecoder), - inputPatternErrorMessage: optional(nonEmptyStringDecoder), - inputPlaceholder: optional(string()), - blur: optional(boolean()) - }); - const showFrameDialogConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - options: frameDialogOptionsDecoder - }); - - const webPlatformMethodName = "T42.Web.Platform.Control"; - const webPlatformWspStreamName = "T42.Web.Platform.WSP.Stream"; - const OUTGOING_METHODS = { - control: { name: "T42.Workspaces.Control", isStream: false }, - frameStream: { name: "T42.Workspaces.Stream.Frame", isStream: true }, - workspaceStream: { name: "T42.Workspaces.Stream.Workspace", isStream: true }, - containerStream: { name: "T42.Workspaces.Stream.Container", isStream: true }, - windowStream: { name: "T42.Workspaces.Stream.Window", isStream: true } - }; - const INCOMING_METHODS = { - control: { name: "T42.Workspaces.Client.Control", isStream: false }, - }; - const STREAMS = { - frame: { name: "T42.Workspaces.Stream.Frame", payloadDecoder: frameStreamDataDecoder }, - workspace: { name: "T42.Workspaces.Stream.Workspace", payloadDecoder: workspaceStreamDataDecoder }, - container: { name: "T42.Workspaces.Stream.Container", payloadDecoder: containerStreamDataDecoder }, - window: { name: "T42.Workspaces.Stream.Window", payloadDecoder: windowStreamDataDecoder } - }; - const CLIENT_OPERATIONS = { - shortcutClicked: { name: "shortcutClicked", argsDecoder: shortcutClickedDataDecoder, resultDecoder: voidResultDecoder }, - frameClosing: { name: "frameClosing", argsDecoder: frameClosingDataDecoder, resultDecoder: frameClosingResultDecoder }, - }; - const OPERATIONS = { - ping: { name: "ping", resultDecoder: pingResultDecoder }, - isWindowInWorkspace: { name: "isWindowInWorkspace", argsDecoder: simpleItemConfigDecoder, resultDecoder: isWindowInSwimlaneResultDecoder }, - createWorkspace: { name: "createWorkspace", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: workspaceCreateConfigDecoder }, - createFrame: { name: "createFrame", resultDecoder: frameSummaryResultDecoder, argsDecoder: emptyFrameDefinitionDecoder }, - initFrame: { name: "initFrame", resultDecoder: voidResultDecoder, argsDecoder: frameInitProtocolConfigDecoder }, - getAllFramesSummaries: { name: "getAllFramesSummaries", resultDecoder: frameSummariesResultDecoder }, - getFrameSummary: { name: "getFrameSummary", resultDecoder: frameSummaryDecoder, argsDecoder: getFrameSummaryConfigDecoder }, - getAllWorkspacesSummaries: { name: "getAllWorkspacesSummaries", resultDecoder: workspaceSummariesResultDecoder }, - getWorkspaceSnapshot: { name: "getWorkspaceSnapshot", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: simpleItemConfigDecoder }, - getAllLayoutsSummaries: { name: "getAllLayoutsSummaries", resultDecoder: layoutSummariesDecoder }, - openWorkspace: { name: "openWorkspace", argsDecoder: openWorkspaceConfigDecoder, resultDecoder: workspaceSnapshotResultDecoder }, - deleteLayout: { name: "deleteLayout", resultDecoder: voidResultDecoder, argsDecoder: deleteLayoutConfigDecoder }, - saveLayout: { name: "saveLayout", resultDecoder: workspaceLayoutDecoder, argsDecoder: workspaceLayoutSaveConfigDecoder }, - importLayout: { name: "importLayout", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutDecoder }, - importLayouts: { name: "importLayouts", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutsDecoder }, - exportAllLayouts: { name: "exportAllLayouts", resultDecoder: exportedLayoutsResultDecoder }, - restoreItem: { name: "restoreItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - maximizeItem: { name: "maximizeItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - focusItem: { name: "focusItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeItem: { name: "closeItem", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeWorkspace: { name: "closeWorkspace", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - resizeItem: { name: "resizeItem", argsDecoder: resizeItemConfigDecoder, resultDecoder: voidResultDecoder }, - setMaximizationBoundary: { name: "setMaximizationBoundary", argsDecoder: setMaximizationBoundaryConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameState: { name: "changeFrameState", argsDecoder: frameStateConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameState: { name: "getFrameState", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameStateResultDecoder }, - getFrameBounds: { name: "getFrameBounds", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameBoundsResultDecoder }, - moveFrame: { name: "moveFrame", argsDecoder: moveFrameConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameSnapshot: { name: "getFrameSnapshot", argsDecoder: frameSnapshotConfigDecoder, resultDecoder: frameSnapshotResultDecoder }, - forceLoadWindow: { name: "forceLoadWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - ejectWindow: { name: "ejectWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - setItemTitle: { name: "setItemTitle", argsDecoder: setItemTitleConfigDecoder, resultDecoder: voidResultDecoder }, - moveWindowTo: { name: "moveWindowTo", argsDecoder: moveWindowConfigDecoder, resultDecoder: voidResultDecoder }, - addWindow: { name: "addWindow", argsDecoder: addWindowConfigDecoder, resultDecoder: addItemResultDecoder }, - addContainer: { name: "addContainer", argsDecoder: addContainerConfigDecoder, resultDecoder: addItemResultDecoder }, - bundleWorkspace: { name: "bundleWorkspace", argsDecoder: bundleWorkspaceConfigDecoder, resultDecoder: voidResultDecoder }, - bundleItem: { name: "bundleItem", argsDecoder: bundleItemConfigDecoder, resultDecoder: voidResultDecoder }, - hibernateWorkspace: { name: "hibernateWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - resumeWorkspace: { name: "resumeWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - lockWorkspace: { name: "lockWorkspace", argsDecoder: lockWorkspaceDecoder, resultDecoder: voidResultDecoder }, - lockWindow: { name: "lockWindow", argsDecoder: lockWindowDecoder, resultDecoder: voidResultDecoder }, - lockContainer: { name: "lockContainer", argsDecoder: lockContainerDecoder, resultDecoder: voidResultDecoder }, - pinWorkspace: { name: "pinWorkspace", argsDecoder: pinWorkspaceDecoder, resultDecoder: voidResultDecoder }, - unpinWorkspace: { name: "unpinWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - getWorkspaceIcon: { name: "getWorkspaceIcon", argsDecoder: workspaceSelectorDecoder, resultDecoder: getWorkspaceIconResultDecoder }, - setWorkspaceIcon: { name: "setWorkspaceIcon", argsDecoder: setWorkspaceIconDecoder, resultDecoder: voidResultDecoder }, - registerShortcut: { name: "registerShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - unregisterShortcut: { name: "unregisterShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - showLoadingAnimation: { name: "showLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - hideLoadingAnimation: { name: "hideLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - getPlatformFrameId: { name: "getPlatformFrameId", resultDecoder: getPlatformFrameIdResultDecoder }, - operationCheck: { name: "operationCheck", argsDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - setWindowDragMode: { name: "setWindowDragMode", argsDecoder: setWindowDragModeDecoder, resultDecoder: voidResultDecoder }, - setLoadingStrategy: { name: "setLoadingStrategy", argsDecoder: setLoadingStrategyDecoder, resultDecoder: voidResultDecoder }, - getTaskbarIcon: { name: "getTaskbarIcon", resultDecoder: iconDecoder }, - setTaskbarIcon: { name: "setTaskbarIcon", argsDecoder: setIconArgumentsDecoder, resultDecoder: voidResultDecoder }, - subscribeToFrameClosing: { name: "subscribeToFrameClosing", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - showPopup: { name: "showPopup", argsDecoder: ShowPopupConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameVisibility: { name: "changeFrameVisibility", argsDecoder: changeFrameVisibilityConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameVisibility: { name: "getFrameVisibility", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameVisibilityResultDecoder }, - showFrameDialog: { name: "showFrameDialog", argsDecoder: showFrameDialogConfigDecoder, resultDecoder: anyJson() } - }; - - class PromiseWrapper { - resolve; - reject; - promise; - constructor() { - this.promise = new Promise((res, rej) => { - this.resolve = res; - this.reject = rej; - }); - } - } - - class Bridge { - transport; - registry; - activeSubscriptions = []; - pendingSubScriptions = []; - constructor(transport, registry) { - this.transport = transport; - this.registry = registry; - } - async createCoreEventSubscription() { - await this.transport.coreSubscriptionReady(this.handleCoreEvent.bind(this)); - } - handleCoreSubscription(config) { - const registryKey = `${config.eventType}-${config.action}`; - const scope = config.scope; - const scopeId = config.scopeId; - return this.registry.add(registryKey, (args) => { - const scopeConfig = { - type: scope, - id: scopeId - }; - const receivedIds = { - frame: args.frameSummary?.id || args.windowSummary?.config.frameId, - workspace: args.workspaceSummary?.id || args.windowSummary?.config.workspaceId, - container: args.containerSummary?.itemId, - window: args.windowSummary?.itemId - }; - const shouldInvokeCallback = this.checkScopeMatch(scopeConfig, receivedIds); - if (!shouldInvokeCallback) { - return; - } - config.callback(args); - }); - } - async send(operationName, operationArgs, invocationOptions) { - const operationDefinition = Object.values(OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - try { - const operationResult = await this.transport.transmitControl(operationDefinition.name, operationArgs, invocationOptions); - operationDefinition.resultDecoder.runWithException(operationResult); - return operationResult; - } - catch (error) { - if (error.kind) { - throw new Error(`Unexpected internal incoming validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - throw new Error(error.message); - } - } - async subscribe(config) { - const pendingSub = this.getPendingSubscription(config); - if (pendingSub) { - await pendingSub.promise; - } - let activeSub = this.getActiveSubscription(config); - const registryKey = this.getRegistryKey(config); - if (!activeSub) { - const pendingPromise = new PromiseWrapper(); - const pendingSubscription = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - promise: pendingPromise.promise - }; - this.pendingSubScriptions.push(pendingSubscription); - try { - const stream = STREAMS[config.eventType]; - const gdSub = await this.transport.subscribe(stream.name, this.getBranchKey(config), config.eventType); - gdSub.onData((streamData) => { - const data = streamData.data; - const requestedArgumentsResult = streamRequestArgumentsDecoder.run(streamData.requestArguments); - const actionResult = workspaceEventActionDecoder.run(data.action); - if (!requestedArgumentsResult.ok || !actionResult.ok) { - return; - } - const streamType = requestedArgumentsResult.result.type; - const branch = requestedArgumentsResult.result.branch; - const keyToExecute = `${streamType}-${branch}-${actionResult.result}`; - const validatedPayload = STREAMS[streamType].payloadDecoder.run(data.payload); - if (!validatedPayload.ok) { - return; - } - this.registry.execute(keyToExecute, validatedPayload.result); - }); - activeSub = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - callbacksCount: 0, - gdSub - }; - this.activeSubscriptions.push(activeSub); - pendingPromise.resolve(); - } - catch (error) { - pendingPromise.reject(error); - throw error; - } - finally { - this.removePendingSubscription(pendingSubscription); - } - } - const unsubscribe = this.registry.add(registryKey, config.callback); - ++activeSub.callbacksCount; - return () => { - unsubscribe(); - --activeSub.callbacksCount; - if (activeSub.callbacksCount === 0) { - activeSub.gdSub.close(); - this.activeSubscriptions.splice(this.activeSubscriptions.indexOf(activeSub), 1); - } - }; - } - onOperation(callback) { - const wrappedCallback = (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - callback(payload, caller); - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - onOperationWithResponse(callback) { - const wrappedCallback = async (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - const result = await callback(payload, caller); - if (operationDefinition.resultDecoder) { - try { - operationDefinition.resultDecoder.runWithException(result); - } - catch (error) { - throw new Error(`Unexpected internal outgoing result validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - return result; - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - checkScopeMatch(scope, receivedIds) { - if (scope.type === "global") { - return true; - } - if (scope.type === "frame" && scope.id === receivedIds.frame) { - return true; - } - if (scope.type === "workspace" && scope.id === receivedIds.workspace) { - return true; - } - if (scope.type === "container" && scope.id === receivedIds.container) { - return true; - } - if (scope.type === "window" && scope.id === receivedIds.window) { - return true; - } - return false; - } - handleCoreEvent(args) { - const data = args.data; - try { - const verifiedAction = workspaceEventActionDecoder.runWithException(data.action); - const verifiedType = eventTypeDecoder.runWithException(data.type); - const verifiedPayload = STREAMS[verifiedType].payloadDecoder.runWithException(data.payload); - const registryKey = `${verifiedType}-${verifiedAction}`; - this.registry.execute(registryKey, verifiedPayload); - } - catch (error) { - console.warn(`Cannot handle event with data ${JSON.stringify(data)}, because of validation error: ${error.message}`); - } - } - getBranchKey(config) { - return config.scope === "global" ? config.scope : `${config.scope}_${config.scopeId}`; - } - getRegistryKey(config) { - return `${config.eventType}-${this.getBranchKey(config)}-${config.action}`; - } - getActiveSubscription(config) { - return this.activeSubscriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - getPendingSubscription(config) { - return this.pendingSubScriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - removePendingSubscription(pendingSubscription) { - const index = this.pendingSubScriptions.indexOf(pendingSubscription); - if (index >= 0) { - this.pendingSubScriptions.splice(index, 1); - } - } - } - - const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage; - reject(message); - }, timeoutMilliseconds); - promise() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - - const isDesktop = () => { - return typeof window === "undefined" ? - true : - window.glue42gd || window.iodesktop; - }; - const browserGlobal = () => { - return typeof window === "undefined" ? null : - window.glue42core || window.iobrowser; - }; - - class InteropTransport { - agm; - registry; - defaultTransportTimeout = 120000; - coreEventMethodInitiated = false; - corePlatformSubPromise; - constructor(agm, registry) { - this.agm = agm; - this.registry = registry; - } - async initiate(actualWindowId) { - if (isDesktop()) { - await Promise.all(Object.values(OUTGOING_METHODS).map((method) => { - return this.verifyMethodLive(method.name); - })); - await Promise.all(Object.keys(INCOMING_METHODS).map((method) => { - return this.registerMethod(method); - })); - return; - } - const systemId = browserGlobal().communicationId; - await Promise.all([ - this.verifyMethodLive(webPlatformMethodName, systemId), - this.verifyMethodLive(webPlatformWspStreamName, systemId) - ]); - await this.transmitControl("frameHello", { windowId: actualWindowId }); - } - coreSubscriptionReady(eventCallback) { - if (!this.coreEventMethodInitiated) { - this.subscribePlatform(eventCallback); - } - return this.corePlatformSubPromise; - } - subscribePlatform(eventCallback) { - this.coreEventMethodInitiated = true; - const systemId = browserGlobal().communicationId; - this.corePlatformSubPromise = this.agm.subscribe(webPlatformWspStreamName, systemId ? { target: { instance: systemId } } : undefined); - this.corePlatformSubPromise - .then((sub) => { - sub.onData((data) => eventCallback(data.data)); - }); - } - async subscribe(streamName, streamBranch, streamType) { - const subscriptionArgs = { - branch: streamBranch, - type: streamType - }; - let subscription; - try { - subscription = await this.agm.subscribe(streamName, { arguments: subscriptionArgs }); - } - catch (error) { - const message = `Internal subscription error! Error details: stream - ${streamName}, branch: ${streamBranch}. Internal message: ${error.message}`; - throw new Error(message); - } - return subscription; - } - async transmitControl(operation, operationArguments, invocationOptions) { - const invocationArguments = isDesktop() ? { operation, operationArguments } : { operation, domain: "workspaces", data: operationArguments }; - const methodName = isDesktop() ? OUTGOING_METHODS.control.name : webPlatformMethodName; - const platformTarget = isDesktop() ? undefined : browserGlobal().communicationId; - let invocationResult; - const baseErrorMessage = `Internal Workspaces Communication Error. Attempted operation: ${JSON.stringify(invocationArguments)}. `; - try { - invocationResult = await this.agm.invoke(methodName, invocationArguments, platformTarget ? { instance: platformTarget } : "best", { methodResponseTimeoutMs: invocationOptions?.timeout ?? this.defaultTransportTimeout }); - if (!invocationResult) { - throw new Error("Received unsupported result from GD - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from GD - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - onInternalMethodInvoked(key, callback) { - return this.registry.add(key, callback); - } - verifyMethodLive(name, systemId) { - return promisePlus(() => { - return new Promise((resolve) => { - const hasMethod = this.agm.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = systemId ? - method.getServers().some((server) => server.instance === systemId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - resolve(); - return; - } - const unSub = this.agm.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = systemId ? - server.instance === systemId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }); - }, 15000, "Timeout waiting for the Workspaces communication channels"); - } - registerMethod(key) { - const method = INCOMING_METHODS[key]; - return this.agm.register(method.name, (args, caller) => { - return Promise.all(this.registry.execute(key, args, caller)); - }); - } - } - - const privateData$4 = new WeakMap(); - class ParentBuilder { - constructor(definition, base) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$4.set(this, { base, children, definition }); - } - get type() { - return privateData$4.get(this).definition.type; - } - addColumn(definition) { - const base = privateData$4.get(this).base; - return base.add("column", privateData$4.get(this).children, definition); - } - addRow(definition) { - const base = privateData$4.get(this).base; - return base.add("row", privateData$4.get(this).children, definition); - } - addGroup(definition) { - const base = privateData$4.get(this).base; - return base.add("group", privateData$4.get(this).children, definition); - } - addWindow(definition) { - const base = privateData$4.get(this).base; - base.addWindow(privateData$4.get(this).children, definition); - return this; - } - serialize() { - const definition = privateData$4.get(this).definition; - definition.children = privateData$4.get(this).base.serializeChildren(privateData$4.get(this).children); - return definition; - } - } - - class BaseBuilder { - getBuilder; - constructor(getBuilder) { - this.getBuilder = getBuilder; - } - wrapChildren(children) { - return children.map((child) => { - if (child.type === "window") { - return child; - } - return this.getBuilder({ type: child.type, definition: child }); - }); - } - add(type, children, definition) { - const validatedDefinition = parentDefinitionDecoder.runWithException(definition); - const childBuilder = this.getBuilder({ type, definition: validatedDefinition }); - children.push(childBuilder); - return childBuilder; - } - addWindow(children, definition) { - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - validatedDefinition.type = "window"; - children.push(validatedDefinition); - } - serializeChildren(children) { - return children.map((child) => { - if (child instanceof ParentBuilder) { - return child.serialize(); - } - else { - return child; - } - }); - } - } - - const privateData$3 = new WeakMap(); - class WorkspaceBuilder { - constructor(definition, base, controller) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$3.set(this, { base, children, definition, controller }); - } - addColumn(definition) { - const children = privateData$3.get(this).children; - const areAllColumns = children.every((child) => child instanceof ParentBuilder && child.type === "column"); - if (!areAllColumns) { - throw new Error("Cannot add a column to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("column", children, definition); - } - addRow(definition) { - const children = privateData$3.get(this).children; - const areAllRows = children.every((child) => child instanceof ParentBuilder && child.type === "row"); - if (!areAllRows) { - throw new Error("Cannot add a row to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("row", children, definition); - } - addGroup(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a group to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - return base.add("group", children, definition); - } - addWindow(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a window to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - base.addWindow(children, definition); - return this; - } - getChildAt(index) { - nonNegativeNumberDecoder.runWithException(index); - const data = privateData$3.get(this).children; - return data[index]; - } - async create(config) { - const saveConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - const definition = privateData$3.get(this).definition; - definition.children = privateData$3.get(this).base.serializeChildren(privateData$3.get(this).children); - const controller = privateData$3.get(this).controller; - return controller.createWorkspace(definition, saveConfig); - } - } - - const privateData$2 = new WeakMap(); - const getBase$2 = (model) => { - return privateData$2.get(model).base; - }; - class Row { - constructor(base) { - privateData$2.set(this, { base }); - } - get type() { - return "row"; - } - get id() { - return getBase$2(this).getId(this); - } - get frameId() { - return getBase$2(this).getFrameId(this); - } - get workspaceId() { - return getBase$2(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$2(this).getPositionIndex(this); - } - get children() { - return getBase$2(this).getAllChildren(this); - } - get parent() { - return getBase$2(this).getMyParent(this); - } - get frame() { - return getBase$2(this).getMyFrame(this); - } - get workspace() { - return getBase$2(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$2(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$2(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$2(this).getMinWidth(this); - } - get minHeight() { - return getBase$2(this).getMinHeight(this); - } - get maxWidth() { - return getBase$2(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$2(this).getMaxHeight(this); - } - get width() { - return getBase$2(this).getWidthInPx(this); - } - get height() { - return getBase$2(this).getHeightInPx(this); - } - get isPinned() { - return getBase$2(this).getIsPinned(this); - } - get isMaximized() { - return getBase$2(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$2(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$2(this).addWindow(this, definition, "row"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "group", "row", definition); - } - async addColumn(definition) { - if (definition?.type && definition.type !== "column") { - throw new Error(`Expected a column definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "column", "row", definition); - } - async addRow() { - throw new Error("Adding rows as row children is not supported"); - } - removeChild(predicate) { - return getBase$2(this).removeChild(this, predicate); - } - maximize() { - return getBase$2(this).maximize(this); - } - restore() { - return getBase$2(this).restore(this); - } - close() { - return getBase$2(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : rowLockConfigDecoder.runWithException(lockConfigResult); - return getBase$2(this).lockContainer(this, verifiedConfig); - } - async setHeight(height) { - nonNegativeNumberDecoder.runWithException(height); - return getBase$2(this).setHeight(this, height); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$2(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$2(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData$1 = new WeakMap(); - const getBase$1 = (model) => { - return privateData$1.get(model).base; - }; - class Column { - constructor(base) { - privateData$1.set(this, { base }); - } - get type() { - return "column"; - } - get id() { - return getBase$1(this).getId(this); - } - get frameId() { - return getBase$1(this).getFrameId(this); - } - get workspaceId() { - return getBase$1(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$1(this).getPositionIndex(this); - } - get children() { - return getBase$1(this).getAllChildren(this); - } - get parent() { - return getBase$1(this).getMyParent(this); - } - get frame() { - return getBase$1(this).getMyFrame(this); - } - get workspace() { - return getBase$1(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$1(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$1(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$1(this).getMinWidth(this); - } - get minHeight() { - return getBase$1(this).getMinHeight(this); - } - get maxWidth() { - return getBase$1(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$1(this).getMaxHeight(this); - } - get width() { - return getBase$1(this).getWidthInPx(this); - } - get height() { - return getBase$1(this).getHeightInPx(this); - } - get isPinned() { - return getBase$1(this).getIsPinned(this); - } - get isMaximized() { - return getBase$1(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$1(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$1(this).addWindow(this, definition, "column"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "group", "column", definition); - } - async addColumn() { - throw new Error("Adding columns as column children is not supported"); - } - async addRow(definition) { - if (definition?.type && definition.type !== "row") { - throw new Error(`Expected a row definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "row", "column", definition); - } - removeChild(predicate) { - return getBase$1(this).removeChild(this, predicate); - } - maximize() { - return getBase$1(this).maximize(this); - } - restore() { - return getBase$1(this).restore(this); - } - close() { - return getBase$1(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : columnLockConfigDecoder.runWithException(lockConfigResult); - return getBase$1(this).lockContainer(this, verifiedConfig); - } - async setWidth(width) { - nonNegativeNumberDecoder.runWithException(width); - return getBase$1(this).setWidth(this, width); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$1(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$1(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData = new WeakMap(); - const getBase = (model) => { - return privateData.get(model).base; - }; - class Group { - constructor(base) { - privateData.set(this, { base }); - } - get type() { - return "group"; - } - get id() { - return getBase(this).getId(this); - } - get frameId() { - return getBase(this).getFrameId(this); - } - get workspaceId() { - return getBase(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase(this).getPositionIndex(this); - } - get children() { - return getBase(this).getAllChildren(this); - } - get parent() { - return getBase(this).getMyParent(this); - } - get frame() { - return getBase(this).getMyFrame(this); - } - get workspace() { - return getBase(this).getMyWorkspace(this); - } - get allowExtract() { - return getBase(this).getAllowExtract(this); - } - get allowReorder() { - return getBase(this).getAllowReorder(this); - } - get allowDropLeft() { - return getBase(this).getAllowDropLeft(this); - } - get allowDropRight() { - return getBase(this).getAllowDropRight(this); - } - get allowDropTop() { - return getBase(this).getAllowDropTop(this); - } - get allowDropBottom() { - return getBase(this).getAllowDropBottom(this); - } - get allowDropHeader() { - return getBase(this).getAllowDropHeader(this); - } - get allowDrop() { - return getBase(this).getAllowDrop(this); - } - get showMaximizeButton() { - return getBase(this).getShowMaximizeButton(this); - } - get showEjectButton() { - return getBase(this).getShowEjectButton(this); - } - get showAddWindowButton() { - return getBase(this).getShowAddWindowButton(this); - } - get minWidth() { - return getBase(this).getMinWidth(this); - } - get minHeight() { - return getBase(this).getMinHeight(this); - } - get maxWidth() { - return getBase(this).getMaxWidth(this); - } - get maxHeight() { - return getBase(this).getMaxHeight(this); - } - get width() { - return getBase(this).getWidthInPx(this); - } - get height() { - return getBase(this).getHeightInPx(this); - } - get isMaximized() { - return getBase(this).getIsMaximized(this); - } - addWindow(definition) { - return getBase(this).addWindow(this, definition, "group"); - } - async addGroup() { - throw new Error("Adding groups as group child is not supported"); - } - async addColumn() { - throw new Error("Adding columns as group child is not supported"); - } - async addRow() { - throw new Error("Adding rows as group child is not supported"); - } - removeChild(predicate) { - return getBase(this).removeChild(this, predicate); - } - maximize() { - return getBase(this).maximize(this); - } - restore() { - return getBase(this).restore(this); - } - close() { - return getBase(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropRight: this.allowDropRight, - allowDropTop: this.allowDropTop, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : groupLockConfigDecoder.runWithException(lockConfigResult); - return getBase(this).lockContainer(this, verifiedConfig); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - return getBase(this).setSize(this, config.width, config.height); - } - async bundleToRow() { - await getBase(this).bundleTo(this, "row"); - await this.workspace.refreshReference(); - } - async bundleToColumn() { - await getBase(this).bundleTo(this, "column"); - await this.workspace.refreshReference(); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase(this).processLocalSubscription(this, config); - return unsubscribe; - } - } - - const DEFAULT_WINDOW_DRAG_MODE = "keepInside"; - const ONE_DAY_MS = 86_400_000; - - const data$3 = new WeakMap(); - const getData$3 = (model) => { - return data$3.get(model).manager.getWorkspaceData(model); - }; - const getDataManager = (model) => { - return data$3.get(model).manager; - }; - class Workspace { - constructor(dataManager) { - data$3.set(this, { manager: dataManager }); - } - get id() { - return getData$3(this).id; - } - get frameId() { - return getData$3(this).config.frameId; - } - get positionIndex() { - return getData$3(this).config.positionIndex; - } - get title() { - return getData$3(this).config.title; - } - get layoutName() { - return getData$3(this).config.layoutName; - } - get isHibernated() { - return getData$3(this).config.isHibernated; - } - get isSelected() { - return getData$3(this).config.isSelected; - } - get children() { - return getData$3(this).children; - } - get frame() { - return getData$3(this).frame; - } - get allowSplitters() { - return getData$3(this).config.allowSplitters; - } - get allowSystemHibernation() { - return getData$3(this).config.allowSystemHibernation; - } - get allowDrop() { - return getData$3(this).config.allowDrop; - } - get allowDropLeft() { - return getData$3(this).config.allowDropLeft; - } - get allowDropTop() { - return getData$3(this).config.allowDropTop; - } - get allowDropRight() { - return getData$3(this).config.allowDropRight; - } - get allowDropBottom() { - return getData$3(this).config.allowDropBottom; - } - get allowExtract() { - return getData$3(this).config.allowExtract; - } - get allowWindowReorder() { - return getData$3(this).config.allowWindowReorder; - } - get showCloseButton() { - return getData$3(this).config.showCloseButton; - } - get showSaveButton() { - return getData$3(this).config.showSaveButton; - } - get allowWorkspaceTabReorder() { - return getData$3(this).config.allowWorkspaceTabReorder; - } - get allowWorkspaceTabExtract() { - return getData$3(this).config.allowWorkspaceTabExtract; - } - get minWidth() { - return getData$3(this).config.minWidth; - } - get minHeight() { - return getData$3(this).config.minHeight; - } - get maxWidth() { - return getData$3(this).config.maxWidth; - } - get maxHeight() { - return getData$3(this).config.maxHeight; - } - get width() { - return getData$3(this).config.widthInPx; - } - get height() { - return getData$3(this).config.heightInPx; - } - get showWindowCloseButtons() { - return getData$3(this).config.showWindowCloseButtons; - } - get showEjectButtons() { - return getData$3(this).config.showEjectButtons; - } - get showAddWindowButtons() { - return getData$3(this).config.showAddWindowButtons; - } - get isPinned() { - return getData$3(this).config.isPinned; - } - get windowDragMode() { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - return DEFAULT_WINDOW_DRAG_MODE; - } - return getData$3(this).config.windowDragMode; - } - get loadingStrategy() { - if (!isDesktop()) { - console.warn("The workspace.loadingStrategy property is not supported in IO Connect Browser"); - } - return getData$3(this).config.loadingStrategy; - } - async setLoadingStrategy(strategy) { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - const controller = getData$3(this).controller; - await controller.setLoadingStrategy(this.id, strategy); - await this.refreshReference(); - } - async removeChild(predicate) { - checkThrowCallback(predicate); - const child = this.children.find(predicate); - if (!child) { - return; - } - await child.close(); - await this.refreshReference(); - } - async remove(predicate) { - checkThrowCallback(predicate); - const controller = getData$3(this).controller; - const child = controller.iterateFindChild(this.children, predicate); - await child.close(); - await this.refreshReference(); - } - async focus() { - await getData$3(this).controller.focusItem(this.id); - await this.refreshReference(); - } - async close() { - const controller = getData$3(this).controller; - await controller.closeWorkspace(this.id, this.frameId); - } - snapshot() { - return getData$3(this).controller.getSnapshot(this.id, "workspace"); - } - async saveLayout(name, config) { - nonEmptyStringDecoder.runWithException(name); - await getData$3(this).controller.saveLayout({ name, workspaceId: this.id, saveContext: config?.saveContext, metadata: config?.metadata, allowMultiple: config?.allowMultiple }); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const controller = getData$3(this).controller; - await controller.setItemTitle(this.id, title); - await this.refreshReference(); - } - getContext() { - const controller = getData$3(this).controller; - return controller.getWorkspaceContext(this.id); - } - setContext(data) { - const controller = getData$3(this).controller; - return controller.setWorkspaceContext(this.id, data); - } - updateContext(data) { - const controller = getData$3(this).controller; - return controller.updateWorkspaceContext(this.id, data); - } - onContextUpdated(callback) { - const controller = getData$3(this).controller; - return controller.subscribeWorkspaceContextUpdated(this.id, callback); - } - async refreshReference() { - const newSnapshot = (await getData$3(this).controller.getSnapshot(this.id, "workspace")); - const currentChildrenFlat = getData$3(this).controller.flatChildren(getData$3(this).children); - const newChildren = getData$3(this).controller.refreshChildren({ - existingChildren: currentChildrenFlat, - workspace: this, - parent: this, - children: newSnapshot.children - }); - const currentFrame = this.frame; - let actualFrame; - if (currentFrame.id === newSnapshot.config.frameId) { - getDataManager(this).remapFrame(currentFrame, newSnapshot.frameSummary); - actualFrame = currentFrame; - } - else { - const frameCreateConfig = { - summary: newSnapshot.frameSummary - }; - const newFrame = getData$3(this).ioc.getModel("frame", frameCreateConfig); - actualFrame = newFrame; - } - getDataManager(this).remapWorkspace(this, { - config: newSnapshot.config, - children: newChildren, - frame: actualFrame - }); - } - async getIcon() { - const controller = getData$3(this).controller; - return controller.getWorkspaceIcon(this.id); - } - async setIcon(icon) { - const controller = getData$3(this).controller; - return controller.setWorkspaceIcon(this.id, icon); - } - getBox(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type !== "window" && predicate(child)); - } - getAllBoxes(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allParents = controller.iterateFilterChildren(children, (child) => child.type !== "window"); - if (!predicate) { - return allParents; - } - return allParents.filter(predicate); - } - getRow(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "row" && predicate(parent)); - } - getAllRows(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "row" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "row"); - } - getColumn(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "column" && predicate(parent)); - } - getAllColumns(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "column" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "column"); - } - getGroup(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "group" && predicate(parent)); - } - getAllGroups(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "group" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "group"); - } - getWindow(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type === "window" && predicate(child)); - } - getAllWindows(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allWindows = controller.iterateFilterChildren(children, (child) => child.type === "window"); - if (!predicate) { - return allWindows; - } - return allWindows.filter(predicate); - } - addRow(definition) { - return getData$3(this).base.addParent(this, "row", "workspace", definition); - } - addColumn(definition) { - return getData$3(this).base.addParent(this, "column", "workspace", definition); - } - addGroup(definition) { - return getData$3(this).base.addParent(this, "group", "workspace", definition); - } - addWindow(definition) { - return getData$3(this).base.addWindow(this, definition, "workspace"); - } - async bundleToRow() { - await getData$3(this).controller.bundleWorkspaceTo("row", this.id); - await this.refreshReference(); - } - async bundleToColumn() { - await getData$3(this).controller.bundleWorkspaceTo("column", this.id); - await this.refreshReference(); - } - async hibernate() { - await getData$3(this).controller.hibernateWorkspace(this.id); - await this.refreshReference(); - } - async resume() { - await getData$3(this).controller.resumeWorkspace(this.id); - await this.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowWindowReorder: this.allowWindowReorder, - allowSplitters: this.allowSplitters, - showCloseButton: this.showCloseButton, - showSaveButton: this.showSaveButton, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - showAddWindowButtons: this.showAddWindowButtons, - showEjectButtons: this.showEjectButtons, - showWindowCloseButtons: this.showWindowCloseButtons - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : workspaceLockConfigDecoder.runWithException(lockConfigResult); - await getData$3(this).controller.lockWorkspace(this.id, verifiedConfig); - await this.refreshReference(); - } - async pin(options) { - workspacePinOptionsDecoder.runWithException(options); - await getData$3(this).controller.pinWorkspace(this.id, options?.icon); - await this.refreshReference(); - } - async unpin() { - await getData$3(this).controller.unpinWorkspace(this.id); - await this.refreshReference(); - } - async showLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.showWorkspaceLoadingAnimation(this.id); - } - async hideLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.hideWorkspaceLoadingAnimation(this.id); - } - async setWindowDragMode(mode) { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - throw new Error("Not supported in IO Connect Browser"); - } - windowDragModeDecoder.runWithException(mode); - await getData$3(this).controller.setWindowDragMode(this.id, mode); - await this.refreshReference(); - } - async onClosed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - action: "closed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onHibernated(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "hibernated", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onResumed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "resumed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "added", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - action: "removed", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const foundWindow = this.getWindow((win) => { - return win.id && win.id === payload.windowSummary.config.windowId; - }); - callback(foundWindow); - }; - const config = { - action: "loaded", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowMaximized(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "maximized", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRestored(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "restored", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowSelected(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "selected", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowSplitters: this.allowSplitters, - allowWindowReorder: this.allowWindowReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - showAddWindowButtons: this.showAddWindowButtons, - showCloseButton: this.showCloseButton, - showEjectButtons: this.showEjectButtons, - showSaveButton: this.showSaveButton, - showWindowCloseButtons: this.showWindowCloseButtons - }); - }; - const config = { - action: "lock-configuration-changed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$2 = new WeakMap(); - const getData$2 = (model) => { - return data$2.get(model).manager.getWindowData(model); - }; - class Window { - constructor(dataManager) { - data$2.set(this, { manager: dataManager }); - } - get id() { - return getData$2(this).config.windowId; - } - get elementId() { - return getData$2(this).id; - } - get type() { - return "window"; - } - get frameId() { - return getData$2(this).frame.id; - } - get workspaceId() { - return getData$2(this).workspace.id; - } - get positionIndex() { - return getData$2(this).config.positionIndex; - } - get isMaximized() { - return getData$2(this).config.isMaximized; - } - get isLoaded() { - return getData$2(this).controller.checkIsWindowLoaded(this.id); - } - get isSelected() { - return getData$2(this).config.isSelected; - } - get focused() { - return this.getGdWindow().isFocused; - } - get title() { - return getData$2(this).config.title; - } - get allowExtract() { - return getData$2(this).config.allowExtract; - } - get allowReorder() { - return getData$2(this).config.allowReorder; - } - get showCloseButton() { - return getData$2(this).config.showCloseButton; - } - get width() { - return getData$2(this).config.widthInPx; - } - get height() { - return getData$2(this).config.heightInPx; - } - get minWidth() { - return getData$2(this).config.minWidth; - } - get minHeight() { - return getData$2(this).config.minHeight; - } - get maxWidth() { - return getData$2(this).config.maxWidth; - } - get maxHeight() { - return getData$2(this).config.maxHeight; - } - get workspace() { - return getData$2(this).workspace; - } - get frame() { - return getData$2(this).frame; - } - get parent() { - return getData$2(this).parent; - } - get appName() { - return getData$2(this).config.appName; - } - async forceLoad() { - if (this.isLoaded) { - return; - } - const controller = getData$2(this).controller; - const itemId = getData$2(this).id; - const windowId = await controller.forceLoadWindow(itemId); - getData$2(this).config.windowId = windowId; - await this.workspace.refreshReference(); - } - async focus() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.focusItem(id); - await this.workspace.refreshReference(); - } - async close() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.closeItem(id); - await getData$2(this) - .parent - .removeChild((child) => child.id === id); - await this.workspace.refreshReference(); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const itemId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.setItemTitle(itemId, title); - await this.workspace.refreshReference(); - } - async maximize() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.maximizeItem(id); - await this.workspace.refreshReference(); - } - async restore() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.restoreItem(id); - await this.workspace.refreshReference(); - } - async eject() { - if (!this.isLoaded) { - throw new Error("Cannot eject this window, because it is not loaded yet"); - } - const itemId = getData$2(this).id; - const windowId = getData$2(this).config.windowId; - const newWindowId = await getData$2(this).controller.ejectWindow(itemId, windowId); - getData$2(this).config.windowId = newWindowId; - await this.workspace.refreshReference(); - return this.getGdWindow(); - } - getGdWindow() { - if (!this.isLoaded) { - throw new Error("Cannot fetch this GD window, because the window is not yet loaded"); - } - const myId = getData$2(this).config.windowId; - const controller = getData$2(this).controller; - return controller.getGDWindow(myId); - } - async moveTo(parent) { - if (!(parent instanceof Row || parent instanceof Column || parent instanceof Group)) { - throw new Error("Cannot add to the provided parent, because the provided parent is not an instance of Row, Column or Group"); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - const foundParent = await controller.getParent((p) => p.id === parent.id); - if (!foundParent) { - throw new Error("Cannot move the window to the selected parent, because this parent does not exist."); - } - await controller.moveWindowTo(myId, parent.id); - await this.workspace.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : windowLockConfigDecoder.runWithException(lockConfigResult); - const windowPlacementId = getData$2(this).id; - await getData$2(this).controller.lockWindow(windowPlacementId, verifiedConfig); - await this.workspace.refreshReference(); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.resizeItem(myId, { - height: verifiedConfig.height, - width: verifiedConfig.width, - relative: false - }); - await this.workspace.refreshReference(); - } - async onRemoved(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback(); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$1 = new WeakMap(); - const getData$1 = (model) => { - return data$1.get(model).manager.getFrameData(model); - }; - class Frame { - constructor(dataManager) { - data$1.set(this, { manager: dataManager }); - } - async registerShortcut(shortcut, callback) { - nonEmptyStringDecoder.runWithException(shortcut); - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const unsubscribe = await getData$1(this).controller.registerShortcut(shortcut, myId, callback); - return unsubscribe; - } - get id() { - return getData$1(this).summary.id; - } - get isInitialized() { - return getData$1(this).summary.isInitialized; - } - getBounds() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameBounds(myId); - } - async resize(config) { - const validatedConfig = resizeConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.resizeItem(myId, validatedConfig); - } - async move(config) { - const validatedConfig = moveConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.moveFrame(myId, validatedConfig); - } - focus() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.focusItem(myId); - } - async state() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameState(myId); - } - setIcon(icon) { - if (!isDesktop()) { - throw new Error("frame.setIcon() is not supported in IO Connect Browser"); - } - iconDecoder.runWithException(icon); - const frameId = this.id; - return getData$1(this).controller.setTaskbarIcon(icon, frameId); - } - getIcon() { - if (!isDesktop()) { - throw new Error("frame.getIcon() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getTaskbarIcon(frameId); - } - isVisible() { - if (!isDesktop()) { - throw new Error("frame.isVisible() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getFrameVisibility(frameId); - } - async minimize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "minimized"); - } - async maximize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "maximized"); - } - async restore() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "normal"); - } - close(options) { - const validatedOptions = optional(closeOptionsDecoder).runWithException(options); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.closeFrame(myId, validatedOptions); - } - snapshot() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getSnapshot(myId, "frame"); - } - async workspaces() { - const controller = getData$1(this).controller; - return controller.getWorkspacesByFrameId(this.id); - } - async getConstraints() { - const controller = getData$1(this).controller; - const myId = getData$1(this).summary.id; - return controller.getFrameConstraints(myId); - } - async restoreWorkspace(name, options) { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return getData$1(this).controller.restoreWorkspace(name, validatedOptions); - } - createWorkspace(definition, config) { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - return getData$1(this).controller.createWorkspace(validatedDefinition, validatedConfig); - } - async init(config) { - frameInitConfigDecoder.runWithException(config); - if (getData$1(this).summary.isInitialized) { - throw new Error("The frame has already been initialized"); - } - return getData$1(this).controller.initFrame(this.id, config); - } - async showPopup(config) { - if (!isDesktop()) { - throw new Error("Popup operations are not supported in IO Connect Browser"); - } - const validatedConfig = popupConfigDecoder.runWithException(config); - const controller = getData$1(this).controller; - await controller.showPopup(validatedConfig, this.id); - return controller.getGDWindow(validatedConfig.windowId); - } - async show(config) { - if (!isDesktop()) { - throw new Error("The show operation is not supported in IO Connect Browser"); - } - const validatedConfig = frameShowConfigDecoder.runWithException(config); - return getData$1(this).controller.showFrame(this.id, validatedConfig); - } - async hide() { - if (!isDesktop()) { - throw new Error("The hide operation is not supported in IO Connect Browser"); - } - return getData$1(this).controller.hideFrame(this.id); - } - async showDialog(options) { - if (!isDesktop()) { - throw new Error("The showModal operation is not supported in IO Connect Browser"); - } - frameDialogOptionsDecoder.runWithException(options); - return getData$1(this).controller.showFrameDialog(this.id, options); - } - async onClosing(callback) { - if (!isDesktop()) { - throw new Error("Frame closing operations are not supported in io.Connect Browser"); - } - checkThrowCallback(callback); - const wrappedCallback = async () => { - let shouldPrevent = false; - const preventClose = () => shouldPrevent = true; - await callback({ prevent: preventClose }); - return { prevent: shouldPrevent }; - }; - const unsubscribe = await getData$1(this).controller.registerFrameOnClosing(this.id, wrappedCallback); - return unsubscribe; - } - async onClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMaximized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "maximized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMinimized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "minimized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onNormal(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "normal", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceOpened(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "opened", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceSelected(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.getWorkspaceById(payload.workspaceSummary.id); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "selected", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "added", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => { - return parent.id === payload.windowSummary.parentId; - }); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "loaded", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onInitializationRequested(callback) { - checkThrowCallback(callback); - if (!this.isInitialized) { - callback(getData$1(this).summary.initializationContext); - } - return () => { }; - } - async onFocusChanged(callback) { - checkThrowCallback(callback); - const myData = getData$1(this); - const { id } = myData.summary; - const wrappedCallback = (args) => { - callback({ isFocused: args.frameSummary.isFocused }); - }; - const config = { - callback: wrappedCallback, - action: "focus", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await myData.controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - class PrivateDataManager { - parentsData = new WeakMap(); - workspacesData = new WeakMap(); - windowsData = new WeakMap(); - framesData = new WeakMap(); - deleteData(model) { - if (model instanceof Window) { - this.windowsData.delete(model); - } - if (model instanceof Workspace) { - this.workspacesData.delete(model); - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - this.parentsData.delete(model); - } - if (model instanceof Frame) { - this.framesData.delete(model); - } - } - setWindowData(model, data) { - this.windowsData.set(model, data); - } - setWorkspaceData(model, data) { - this.workspacesData.set(model, data); - } - setParentData(model, data) { - this.parentsData.set(model, data); - } - setFrameData(model, data) { - this.framesData.set(model, data); - } - getWindowData(model) { - return this.windowsData.get(model); - } - getWorkspaceData(model) { - return this.workspacesData.get(model); - } - getParentData(model) { - return this.parentsData.get(model); - } - getFrameData(model) { - return this.framesData.get(model); - } - remapChild(model, newData) { - if (model instanceof Window) { - const data = this.windowsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - const data = this.parentsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - remapFrame(model, newData) { - const data = this.framesData.get(model); - data.summary = newData; - } - remapWorkspace(model, newData) { - const data = this.workspacesData.get(model); - data.frame = newData.frame || data.frame; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - - const data = new WeakMap(); - const getData = (base, model) => { - const manager = data.get(base).manager; - if (model instanceof Workspace) { - return manager.getWorkspaceData(model); - } - return data.get(base).manager.getParentData(model); - }; - class Base { - frameId; - workspaceId; - positionIndex; - constructor(dataManager) { - data.set(this, { manager: dataManager }); - } - getId(model) { - return getData(this, model).id; - } - getPositionIndex(model) { - return getData(this, model).config.positionIndex; - } - getWorkspaceId(model) { - const privateData = getData(this, model); - return privateData.config.workspaceId || privateData.workspace.id; - } - getFrameId(model) { - return getData(this, model).frame.id; - } - getAllChildren(model, predicate) { - checkThrowCallback(predicate, true); - const children = getData(this, model).children; - if (typeof predicate === "undefined") { - return children; - } - return children.filter(predicate); - } - getMyParent(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).parent; - } - getMyFrame(model) { - return getData(this, model).frame; - } - getMyWorkspace(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).workspace; - } - async addWindow(model, definition, parentType) { - if (!definition.appName && !definition.windowId) { - throw new Error("The window definition should contain either an appName or a windowId"); - } - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - const controller = getData(this, model).controller; - const operationResult = await controller.add("window", getData(this, model).id, parentType, validatedDefinition); - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getWindow(w => w.elementId === operationResult.itemId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getWindow(w => w.elementId === operationResult.itemId); - } - async addParent(model, typeToAdd, parentType, definition) { - const parentDefinition = this.transformDefinition(typeToAdd, definition); - const controller = getData(this, model).controller; - const newParentId = (await controller.add("container", getData(this, model).id, parentType, parentDefinition)).itemId; - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getBox((parent) => parent.id === newParentId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getBox((parent) => parent.id === newParentId); - } - async removeChild(model, predicate) { - checkThrowCallback(predicate); - const child = this.getAllChildren(model).find(predicate); - if (!child) { - return; - } - await child.close(); - if (model instanceof Workspace) { - await model.refreshReference(); - return; - } - await this.getMyWorkspace(model).refreshReference(); - } - async maximize(model) { - const { controller, id } = getData(this, model); - await controller.maximizeItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async restore(model) { - const { controller, id } = getData(this, model); - await controller.restoreItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async close(model) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.closeItem(modelData.id); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async lockContainer(model, config) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.lockContainer(modelData.id, model.type, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - getAllowDrop(model) { - return getData(this, model).config.allowDrop; - } - getAllowDropLeft(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropLeft is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropLeft; - } - getAllowDropRight(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropRight is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropRight; - } - getAllowDropTop(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropTop is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropTop; - } - getAllowDropBottom(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropBottom is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropBottom; - } - getAllowDropHeader(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropHeader is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropHeader; - } - getAllowSplitters(model) { - const privateData = getData(this, model); - if (privateData.type === "group") { - throw new Error(`Cannot get allow splitters from private data ${privateData.type}`); - } - return privateData.config.allowSplitters; - } - getAllowExtract(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowExtract; - } - getAllowReorder(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowReorder; - } - getShowMaximizeButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show maximize button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showMaximizeButton; - } - getShowEjectButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show eject button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showEjectButton; - } - getShowAddWindowButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get add window button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showAddWindowButton; - } - getMinWidth(model) { - const privateData = getData(this, model); - return privateData.config.minWidth; - } - getMaxWidth(model) { - const privateData = getData(this, model); - return privateData.config.maxWidth; - } - getMinHeight(model) { - const privateData = getData(this, model); - return privateData.config.minHeight; - } - getMaxHeight(model) { - const privateData = getData(this, model); - return privateData.config.maxHeight; - } - getWidthInPx(model) { - const privateData = getData(this, model); - return privateData.config.widthInPx; - } - getHeightInPx(model) { - const privateData = getData(this, model); - return privateData.config.heightInPx; - } - getIsPinned(model) { - const privateData = getData(this, model); - return privateData.config.isPinned; - } - getIsMaximized(model) { - const privateData = getData(this, model); - return privateData.config.isMaximized; - } - getMaximizationBoundary(model) { - const privateData = getData(this, model); - return privateData.config.maximizationBoundary; - } - async setHeight(model, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setWidth(model, width) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setSize(model, width, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width, - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setMaximizationBoundary(model, config) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.setMaximizationBoundary(id, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async bundleTo(model, type) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.bundleItemTo(type, id); - } - async processLocalSubscription(model, subscriptionConfig) { - return getData(this, model).controller.processLocalSubscription(subscriptionConfig, this.getId(model)); - } - transformDefinition(type, definition) { - let parentDefinition; - if (typeof definition === "undefined") { - parentDefinition = { type, children: [] }; - } - else if (definition instanceof ParentBuilder) { - parentDefinition = definition.serialize(); - } - else { - if (typeof definition.type === "undefined") { - definition.type = type; - } - parentDefinition = strictParentDefinitionDecoder.runWithException(definition); - parentDefinition.children = parentDefinition.children || []; - } - return parentDefinition; - } - } - - class BaseController { - ioc; - windows; - contexts; - layouts; - constructor(ioc, windows, contexts, layouts) { - this.ioc = ioc; - this.windows = windows; - this.contexts = contexts; - this.layouts = layouts; - } - get bridge() { - return this.ioc.bridge; - } - get privateDataManager() { - return this.ioc.privateDataManager; - } - checkIsWindowLoaded(windowId) { - return (!!windowId) && this.windows.list().some((win) => win.id === windowId); - } - async createWorkspace(createConfig) { - const snapshot = await this.bridge.send(OPERATIONS.createWorkspace.name, createConfig); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async createEmptyFrame(definition) { - const frameSummary = await this.bridge.send(OPERATIONS.createFrame.name, definition); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - async initFrame(frameId, config) { - await this.bridge.send(OPERATIONS.initFrame.name, { frameId, ...config }); - } - async restoreWorkspace(name, options) { - const snapshot = await this.bridge.send(OPERATIONS.openWorkspace.name, { name, restoreOptions: options }); - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: snapshot.config.frameId }); - const frameConfig = { - summary: frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async add(type, parentId, parentType, definition) { - let operationName; - const operationArgs = { definition, parentId, parentType }; - if (type === "window") { - operationName = OPERATIONS.addWindow.name; - } - else if (type === "container") { - operationName = OPERATIONS.addContainer.name; - } - else { - throw new Error(`Unrecognized add type: ${type}`); - } - return await this.bridge.send(operationName, operationArgs); - } - async getFrame(windowId) { - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: windowId }); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - getFrames(allFrameSummaries, predicate) { - return allFrameSummaries.reduce((frames, frameSummary) => { - const frameConfig = { - summary: frameSummary - }; - const frameToCheck = this.ioc.getModel("frame", frameConfig); - if (!predicate || predicate(frameToCheck)) { - frames.push(frameToCheck); - } - return frames; - }, []); - } - getAllWorkspaceSummaries(...bridgeResults) { - const allSummaries = bridgeResults.reduce((summaries, summaryResult) => { - summaries.push(...summaryResult.summaries); - return summaries; - }, []); - return allSummaries.map((summary) => { - return Object.assign({}, { id: summary.id, width: summary.config.widthInPx, height: summary.config.heightInPx }, summary.config); - }); - } - handleOnSaved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - const addedUnSub = this.layouts.onAdded(wrappedCallback); - const changedUnSub = this.layouts.onChanged(wrappedCallback); - return () => { - addedUnSub(); - changedUnSub(); - }; - } - handleOnRemoved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - return this.layouts.onRemoved(wrappedCallback); - } - async importLayouts(layouts, mode) { - await this.layouts.import(layouts, mode); - } - async transformStreamPayloadToWorkspace(payload) { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const snapshot = payload.workspaceSnapshot || (await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId: payload.workspaceSummary.id })); - const workspaceConfig = { frame, snapshot }; - const workspace = this.ioc.getModel("workspace", workspaceConfig); - return workspace; - } - async fetchWorkspace(itemId) { - const snapshot = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async bundleWorkspaceTo(type, workspaceId) { - await this.bridge.send(OPERATIONS.bundleWorkspace.name, { type, workspaceId }); - } - async bundleItemTo(type, itemId) { - const isSupported = await this.isOperationSupported(OPERATIONS.bundleItem.name); - if (!isSupported) { - throw new Error(`Operation ${OPERATIONS.bundleItem.name} is not supported. Ensure that you are running the latest version of all packages`); - } - await this.bridge.send(OPERATIONS.bundleItem.name, { type, itemId }); - } - async getTaskbarIcon(frameId) { - return await this.bridge.send(OPERATIONS.getTaskbarIcon.name, { frameId }); - } - async setTaskbarIcon(icon, frameId) { - await this.bridge.send(OPERATIONS.setTaskbarIcon.name, { icon, frameId }); - } - getWorkspaceContext(workspaceId) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.get(contextName); - } - setWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.set(contextName, data); - } - updateWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.update(contextName, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.subscribe(contextName, callback); - } - async restoreItem(itemId) { - await this.bridge.send(OPERATIONS.restoreItem.name, { itemId }); - } - async maximizeItem(itemId) { - await this.bridge.send(OPERATIONS.maximizeItem.name, { itemId }); - } - async focusItem(itemId) { - await this.bridge.send(OPERATIONS.focusItem.name, { itemId }); - } - async closeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.closeWorkspace.name, { itemId: workspaceId }); - } - async closeItem(itemId) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId }); - } - async closeFrame(itemId, closeOptions) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId, closeOptions }); - } - async resizeItem(itemId, config) { - await this.bridge.send(OPERATIONS.resizeItem.name, Object.assign({}, { itemId }, config)); - } - async setMaximizationBoundary(itemId, config) { - await this.bridge.send(OPERATIONS.setMaximizationBoundary.name, Object.assign({}, { itemId }, config)); - } - async showWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.showLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.hideLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async setWindowDragMode(workspaceId, dragMode) { - await this.bridge.send(OPERATIONS.setWindowDragMode.name, { itemId: workspaceId, dragMode }); - } - async moveFrame(itemId, config) { - await this.bridge.send(OPERATIONS.moveFrame.name, Object.assign({}, { itemId }, config)); - } - getGDWindow(itemId) { - return this.windows.list().find((gdWindow) => gdWindow.id === itemId); - } - async forceLoadWindow(itemId) { - const controlResult = await this.bridge.send(OPERATIONS.forceLoadWindow.name, { itemId }); - return controlResult.windowId; - } - async ejectWindow(itemId, windowId) { - return await this.bridge.send(OPERATIONS.ejectWindow.name, { itemId, windowId }); - } - async moveWindowTo(itemId, newParentId) { - await this.bridge.send(OPERATIONS.moveWindowTo.name, { itemId, containerId: newParentId }); - } - async getSnapshot(itemId, type) { - let result; - if (type === "workspace") { - result = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - } - else if (type === "frame") { - result = await this.bridge.send(OPERATIONS.getFrameSnapshot.name, { itemId }); - } - return result; - } - async setItemTitle(itemId, title) { - await this.bridge.send(OPERATIONS.setItemTitle.name, { itemId, title }); - } - refreshChildren(config) { - const { parent, children, existingChildren, workspace } = config; - if (parent instanceof Window || parent.type === "window") { - return; - } - const newChildren = children.map((newChildSnapshot) => { - let childToAdd = existingChildren.find((child) => { - return child.type === "window" ? child.elementId === newChildSnapshot.id : child.id === newChildSnapshot.id; - }); - if (childToAdd) { - this.privateDataManager.remapChild(childToAdd, { - parent: parent, - children: [], - config: newChildSnapshot.config - }); - } - else { - let createConfig; - if (newChildSnapshot.type === "window") { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - }; - } - else { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - children: [] - }; - } - childToAdd = this.ioc.getModel(newChildSnapshot.type, createConfig); - } - if (newChildSnapshot.type !== "window") { - this.refreshChildren({ - workspace, existingChildren, - children: newChildSnapshot.children, - parent: childToAdd - }); - } - return childToAdd; - }); - if (parent instanceof Workspace) { - return newChildren; - } - else { - this.privateDataManager.remapChild(parent, { children: newChildren }); - return newChildren; - } - } - iterateFindChild(children, predicate) { - let foundChild = children.find((child) => predicate(child)); - if (foundChild) { - return foundChild; - } - children.some((child) => { - if (child instanceof Window) { - return false; - } - foundChild = this.iterateFindChild(child.children, predicate); - if (foundChild) { - return true; - } - }); - return foundChild; - } - iterateFilterChildren(children, predicate) { - const foundChildren = children.filter((child) => predicate(child)); - const grandChildren = children.reduce((innerFound, child) => { - if (child instanceof Window) { - return innerFound; - } - innerFound.push(...this.iterateFilterChildren(child.children, predicate)); - return innerFound; - }, []); - foundChildren.push(...grandChildren); - return foundChildren; - } - notifyWindowAdded(windowId) { - return new Promise((resolve) => { - const alreadyPresent = this.windows.list().some((win) => win.id === windowId); - if (alreadyPresent) { - return resolve(); - } - const unsubscribe = this.windows.onWindowAdded((win) => { - if (win.id !== windowId) { - return; - } - if (unsubscribe) { - unsubscribe(); - } - resolve(); - }); - }); - } - async hibernateWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.hibernateWorkspace.name, { workspaceId }); - } - async resumeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.resumeWorkspace.name, { workspaceId }); - } - async lockWorkspace(workspaceId, config) { - await this.bridge.send(OPERATIONS.lockWorkspace.name, { workspaceId, config }); - } - async lockWindow(windowPlacementId, config) { - await this.bridge.send(OPERATIONS.lockWindow.name, { windowPlacementId, config }); - } - async lockContainer(itemId, type, config) { - await this.bridge.send(OPERATIONS.lockContainer.name, { itemId, type, config }); - } - async pinWorkspace(workspaceId, icon) { - await this.bridge.send(OPERATIONS.pinWorkspace.name, { workspaceId, icon }); - } - async unpinWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.unpinWorkspace.name, { workspaceId }); - } - async getWorkspaceIcon(workspaceId) { - const result = await this.bridge.send(OPERATIONS.getWorkspaceIcon.name, { workspaceId }); - return result.icon; - } - setWorkspaceIcon(workspaceId, icon) { - return this.bridge.send(OPERATIONS.setWorkspaceIcon.name, { workspaceId, icon }); - } - async getPlatformFrameId() { - try { - const result = await this.bridge.send(OPERATIONS.getPlatformFrameId.name, {}); - return result; - } - catch (error) { - return {}; - } - } - async setLoadingStrategy(workspaceId, strategy) { - await this.isOperationSupported(OPERATIONS.setLoadingStrategy.name); - return this.bridge.send(OPERATIONS.setLoadingStrategy.name, { itemId: workspaceId, strategy }); - } - async showFrame(frameId, config) { - const payload = { frameId, isVisible: true, ...config }; - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, payload); - } - async hideFrame(frameId) { - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, { frameId, isVisible: false }); - } - async getFrameVisibility(frameId) { - const result = await this.bridge.send(OPERATIONS.getFrameVisibility.name, { itemId: frameId }); - return result.isVisible; - } - async showFrameDialog(frameId, options) { - const result = await this.bridge.send(OPERATIONS.showFrameDialog.name, { frameId, options }, { timeout: ONE_DAY_MS }); - return result; - } - async isOperationSupported(operation) { - if (isDesktop()) { - return { isSupported: true }; - } - return await this.bridge.send(OPERATIONS.operationCheck.name, { operation }); - } - async showPopup(config, frameId) { - return this.bridge.send(OPERATIONS.showPopup.name, { ...config, frameId }); - } - } - - class MainController { - bridge; - base; - shortcutsController; - closingController; - constructor(bridge, base, shortcutsController, closingController) { - this.bridge = bridge; - this.base = base; - this.shortcutsController = shortcutsController; - this.closingController = closingController; - } - setTaskbarIcon(icon, frameId) { - return this.base.setTaskbarIcon(icon, frameId); - } - getTaskbarIcon(frameId) { - return this.base.getTaskbarIcon(frameId); - } - checkIsWindowLoaded(windowId) { - return this.base.checkIsWindowLoaded(windowId); - } - async checkIsInSwimlane(windowId) { - const controlResult = await this.bridge.send(OPERATIONS.isWindowInWorkspace.name, { itemId: windowId }); - return controlResult.inWorkspace; - } - async createWorkspace(definition, saveConfig) { - const createConfig = Object.assign({}, definition, { saveConfig }); - return await this.base.createWorkspace(createConfig); - } - async createEmptyFrame(definition) { - return await this.base.createEmptyFrame(definition); - } - async initFrame(frameId, config) { - return this.base.initFrame(frameId, config); - } - async restoreWorkspace(name, options) { - const allLayouts = await this.getLayoutSummaries(); - const layoutExists = allLayouts.some((summary) => summary.name === name); - if (!layoutExists) { - throw new Error(`This layout: ${name} cannot be restored, because it doesn't exist.`); - } - if (options?.frameId) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - const foundMatchingFrame = allFrameSummaries.summaries.some((summary) => summary.id === options.frameId); - if (!foundMatchingFrame) { - throw new Error(`Cannot reuse the frame with id: ${options.frameId}, because there is no frame with that ID found`); - } - } - return await this.base.restoreWorkspace(name, options); - } - async add(type, parentId, parentType, definition) { - return await this.base.add(type, parentId, parentType, definition); - } - processLocalSubscription(config, levelId) { - return isDesktop() ? - this.handleEnterpriseLocalSubscription(config, levelId) : - this.handleCoreLocalSubscription(config, levelId); - } - processGlobalSubscription(callback, eventType, action) { - return isDesktop() ? - this.handleEnterpriseGlobalSubscription(callback, eventType, action) : - this.handleCoreGlobalSubscription(callback, eventType, action); - } - async getFrame(selector) { - if (selector.windowId) { - return await this.base.getFrame(selector.windowId); - } - if (selector.predicate) { - return (await this.getFrames(selector.predicate))[0]; - } - throw new Error(`The provided selector is not valid: ${JSON.stringify(selector)}`); - } - async getFrames(predicate) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - return this.base.getFrames(allFrameSummaries.summaries, predicate); - } - getWorkspaceById(workspaceId) { - return this.base.fetchWorkspace(workspaceId); - } - async getWorkspaceByWindowId(itemId) { - if (!isDesktop()) { - return (await this.getWorkspaces((wsp) => !!wsp.getWindow((w) => w.id === itemId)))[0]; - } - return this.base.fetchWorkspace(itemId); - } - transformStreamPayloadToWorkspace(payload) { - return this.base.transformStreamPayloadToWorkspace(payload); - } - async getWorkspace(predicate) { - let foundWorkspace; - await this.iterateWorkspaces((wsp, end) => { - if (predicate(wsp)) { - foundWorkspace = wsp; - end(); - } - }); - return foundWorkspace; - } - async getWorkspaces(predicate) { - const matchingWorkspaces = []; - await this.iterateWorkspaces((wsp) => { - if (!predicate || predicate(wsp)) { - matchingWorkspaces.push(wsp); - } - }); - return matchingWorkspaces; - } - async getWorkspacesByFrameId(frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - const workspacesForFrame = await Promise.all(summariesForFrame.map((summary) => { - return this.base.fetchWorkspace(summary.id); - })); - return workspacesForFrame; - } - async isLastWorkspaceInFrame(workspaceId, frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - return summariesForFrame.length === 1 && summariesForFrame[0].id === workspaceId; - } - async getAllWorkspaceSummaries() { - const allSummariesResult = await this.bridge.send(OPERATIONS.getAllWorkspacesSummaries.name, {}); - return this.base.getAllWorkspaceSummaries(allSummariesResult); - } - async getWindow(predicate) { - let resultWindow; - await this.iterateWorkspaces((wsp, end) => { - const foundWindow = wsp.getWindow(predicate); - if (foundWindow) { - resultWindow = foundWindow; - end(); - } - }); - return resultWindow; - } - async getParent(predicate) { - let resultParent; - await this.iterateWorkspaces((wsp, end) => { - const foundParent = wsp.getBox(predicate); - if (foundParent) { - resultParent = foundParent; - end(); - } - }); - return resultParent; - } - async getLayoutSummaries() { - const allLayouts = await this.bridge.send(OPERATIONS.getAllLayoutsSummaries.name); - return allLayouts.summaries; - } - async deleteLayout(name) { - await this.bridge.send(OPERATIONS.deleteLayout.name, { name }); - } - async exportLayout(predicate) { - const allLayoutsResult = await this.bridge.send(OPERATIONS.exportAllLayouts.name); - return allLayoutsResult.layouts.reduce((matchingLayouts, layout) => { - if (!predicate || predicate(layout)) { - matchingLayouts.push(layout); - } - return matchingLayouts; - }, []); - } - async saveLayout(config) { - return await this.bridge.send(OPERATIONS.saveLayout.name, config); - } - async importLayouts(layouts, mode) { - if (isDesktop()) { - try { - await this.bridge.send(OPERATIONS.importLayouts.name, { layouts, mode }); - } - catch (error) { - await Promise.all(layouts.map((layout) => this.bridge.send(OPERATIONS.importLayout.name, { layout, mode }))); - } - return; - } - await this.base.importLayouts(layouts, mode); - } - handleOnSaved(callback) { - return this.base.handleOnSaved(callback); - } - handleOnRemoved(callback) { - return this.base.handleOnRemoved(callback); - } - async bundleWorkspaceTo(type, workspaceId) { - return await this.base.bundleWorkspaceTo(type, workspaceId); - } - async bundleItemTo(type, id) { - return await this.base.bundleItemTo(type, id); - } - getWorkspaceContext(workspaceId) { - return this.base.getWorkspaceContext(workspaceId); - } - setWorkspaceContext(workspaceId, data) { - return this.base.setWorkspaceContext(workspaceId, data); - } - updateWorkspaceContext(workspaceId, data) { - return this.base.updateWorkspaceContext(workspaceId, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - return this.base.subscribeWorkspaceContextUpdated(workspaceId, callback); - } - async restoreItem(itemId) { - return await this.base.restoreItem(itemId); - } - async maximizeItem(itemId) { - return await this.base.maximizeItem(itemId); - } - async focusItem(itemId) { - return await this.base.focusItem(itemId); - } - async changeFrameState(frameId, state) { - await this.bridge.send(OPERATIONS.changeFrameState.name, { frameId, requestedState: state }); - } - async getFrameBounds(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameBounds.name, { itemId: frameId }); - return frameResult.bounds; - } - async getFrameState(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameState.name, { itemId: frameId }); - return frameResult.state; - } - async closeWorkspace(workspaceId, frameId) { - if (isDesktop()) { - return await this.closeItem(workspaceId); - } - let closeWorkspaceCommandExists = false; - try { - const { isSupported } = await this.base.isOperationSupported(OPERATIONS.closeWorkspace.name); - closeWorkspaceCommandExists = isSupported; - } - catch (error) { - closeWorkspaceCommandExists = false; - } - if (closeWorkspaceCommandExists) { - return await this.base.closeWorkspace(workspaceId); - } - return await this.legacyCloseWorkspace(workspaceId, frameId); - } - async closeItem(itemId) { - return await this.base.closeItem(itemId); - } - async closeFrame(itemId, closeOptions) { - return await this.base.closeFrame(itemId, closeOptions); - } - async resizeItem(itemId, config) { - return await this.base.resizeItem(itemId, config); - } - async setMaximizationBoundary(itemId, config) { - return await this.base.setMaximizationBoundary(itemId, config); - } - async showWorkspaceLoadingAnimation(workspaceId) { - return await this.base.showWorkspaceLoadingAnimation(workspaceId); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - return await this.base.hideWorkspaceLoadingAnimation(workspaceId); - } - async setWindowDragMode(workspaceId, dragMode) { - return await this.base.setWindowDragMode(workspaceId, dragMode); - } - async moveFrame(itemId, config) { - return await this.base.moveFrame(itemId, config); - } - getGDWindow(itemId) { - return this.base.getGDWindow(itemId); - } - async forceLoadWindow(itemId) { - const windowId = await this.base.forceLoadWindow(itemId); - await this.base.notifyWindowAdded(windowId); - return windowId; - } - async ejectWindow(itemId, windowId) { - const id = (await this.base.ejectWindow(itemId, windowId)).windowId; - await this.base.notifyWindowAdded(id); - return id; - } - async moveWindowTo(itemId, newParentId) { - return await this.base.moveWindowTo(itemId, newParentId); - } - async getSnapshot(itemId, type) { - return await this.base.getSnapshot(itemId, type); - } - async setItemTitle(itemId, title) { - return await this.base.setItemTitle(itemId, title); - } - flatChildren(children) { - return children.reduce((soFar, child) => { - soFar.push(child); - if (child.type !== "window") { - soFar.push(...this.flatChildren(child.children)); - } - return soFar; - }, []); - } - refreshChildren(config) { - return this.base.refreshChildren(config); - } - iterateFindChild(children, predicate) { - return this.base.iterateFindChild(children, predicate); - } - iterateFilterChildren(children, predicate) { - return this.base.iterateFilterChildren(children, predicate); - } - hibernateWorkspace(workspaceId) { - return this.base.hibernateWorkspace(workspaceId); - } - resumeWorkspace(workspaceId) { - return this.base.resumeWorkspace(workspaceId); - } - lockWorkspace(workspaceId, config) { - return this.base.lockWorkspace(workspaceId, config); - } - lockWindow(windowPlacementId, config) { - return this.base.lockWindow(windowPlacementId, config); - } - lockContainer(itemId, type, config) { - return this.base.lockContainer(itemId, type, config); - } - pinWorkspace(workspaceId, icon) { - return this.base.pinWorkspace(workspaceId, icon); - } - unpinWorkspace(workspaceId) { - return this.base.unpinWorkspace(workspaceId); - } - getWorkspaceIcon(workspaceId) { - return this.base.getWorkspaceIcon(workspaceId); - } - setWorkspaceIcon(workspaceId, icon) { - return this.base.setWorkspaceIcon(workspaceId, icon); - } - async getFrameConstraints(frameId) { - const frameSnapshot = await this.getSnapshot(frameId, "frame"); - return { - minWidth: frameSnapshot.config.minWidth, - maxWidth: frameSnapshot.config.maxWidth, - minHeight: frameSnapshot.config.minHeight, - maxHeight: frameSnapshot.config.maxHeight, - }; - } - registerShortcut(shortcut, frameId, callback) { - return this.shortcutsController.registerShortcut(shortcut, frameId, callback); - } - getPlatformFrameId() { - return this.base.getPlatformFrameId(); - } - setLoadingStrategy(workspaceId, strategy) { - return this.base.setLoadingStrategy(workspaceId, strategy); - } - registerFrameOnClosing(frameId, callback) { - return this.closingController.registerFrameOnClosing(frameId, callback); - } - showPopup(config, frameId) { - return this.base.showPopup(config, frameId); - } - async showFrame(frameId, config) { - return this.base.showFrame(frameId, config); - } - async hideFrame(frameId) { - return this.base.hideFrame(frameId); - } - async getFrameVisibility(frameId) { - return this.base.getFrameVisibility(frameId); - } - async showFrameDialog(frameId, options) { - return this.base.showFrameDialog(frameId, options); - } - async handleCoreLocalSubscription(config, levelId) { - await this.bridge.createCoreEventSubscription(); - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseLocalSubscription(config, levelId) { - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async handleCoreGlobalSubscription(callback, eventType, action) { - await this.bridge.createCoreEventSubscription(); - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseGlobalSubscription(callback, eventType, action) { - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async iterateWorkspaces(callback) { - let ended = false; - const end = () => { ended = true; }; - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - for (const summary of workspaceSummaries) { - if (ended) { - return; - } - const wsp = await this.base.fetchWorkspace(summary.id); - callback(wsp, end); - } - } - async legacyCloseWorkspace(workspaceId, frameId) { - const isLastWorkspaceInFrame = await this.isLastWorkspaceInFrame(workspaceId, frameId); - const platformFrameId = (await this.getPlatformFrameId()).id; - const shouldCloseFrame = isLastWorkspaceInFrame && - platformFrameId !== frameId; - if (shouldCloseFrame) { - return await this.closeFrame(frameId, {}); - } - await this.closeItem(workspaceId); - } - } - - class ShortcutsController { - bridge; - _shortcuts = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.bridge.onOperation((payload) => { - if (payload.operation === CLIENT_OPERATIONS.shortcutClicked.name) { - const data = payload.data; - this._shortcuts.execute(`${data.frameId}-${data.shortcut}`); - } - }); - } - async registerShortcut(shortcut, frameId, callback) { - await this.bridge.send(OPERATIONS.registerShortcut.name, { shortcut, frameId }); - const un = this._shortcuts.add(`${frameId}-${shortcut}`, callback); - return () => { - un(); - this.bridge.send(OPERATIONS.unregisterShortcut.name, { shortcut, frameId }); - }; - } - } - - class ClosingController { - bridge; - registry = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.subscribeToFrameClosing(); - } - async registerFrameOnClosing(frameId, callback) { - await this.bridge.send(OPERATIONS.subscribeToFrameClosing.name, { itemId: frameId }); - return this.registry.add(frameId, callback); - } - subscribeToFrameClosing() { - this.bridge.onOperationWithResponse(async (payload) => { - if (payload.operation !== CLIENT_OPERATIONS.frameClosing.name) { - return; - } - const data = payload.data; - const frameClosingResult = await Promise.all(this.registry.execute(data.frameId)); - return this.aggregateFrameClosingResult(frameClosingResult); - }); - } - aggregateFrameClosingResult(results) { - return { - prevent: results.some((result) => result?.prevent) - }; - } - } - - class IoC { - agm; - windows; - layouts; - contexts; - _controllerInstance; - _bridgeInstance; - _transportInstance; - _privateDataManagerInstance; - _parentBaseInstance; - _baseController; - _shortcutsController; - _closingController; - constructor(agm, windows, layouts, contexts) { - this.agm = agm; - this.windows = windows; - this.layouts = layouts; - this.contexts = contexts; - } - get baseController() { - if (!this._baseController) { - this._baseController = new BaseController(this, this.windows, this.contexts, this.layouts); - } - return this._baseController; - } - get controller() { - if (!this._controllerInstance) { - this._controllerInstance = new MainController(this.bridge, this.baseController, this.shortcutsController, this.closingController); - } - return this._controllerInstance; - } - get shortcutsController() { - if (!this._shortcutsController) { - this._shortcutsController = new ShortcutsController(this.bridge); - } - return this._shortcutsController; - } - get closingController() { - if (!this._closingController) { - this._closingController = new ClosingController(this.bridge); - } - return this._closingController; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new Bridge(this.transport, CallbackFactory()); - } - return this._bridgeInstance; - } - get transport() { - if (!this._transportInstance) { - this._transportInstance = new InteropTransport(this.agm, CallbackFactory()); - } - return this._transportInstance; - } - get privateDataManager() { - if (!this._privateDataManagerInstance) { - this._privateDataManagerInstance = new PrivateDataManager(); - } - return this._privateDataManagerInstance; - } - get parentBase() { - if (!this._parentBaseInstance) { - this._parentBaseInstance = new Base(this.privateDataManager); - } - return this._parentBaseInstance; - } - async initiate(actualWindowId) { - await this.transport.initiate(actualWindowId); - } - getModel(type, createConfig) { - switch (type) { - case "frame": { - const newFrame = new Frame(this.privateDataManager); - const { summary } = createConfig; - const frameData = { summary, controller: this.controller }; - this.privateDataManager.setFrameData(newFrame, frameData); - return newFrame; - } - case "window": { - const { id, parent, frame, workspace, config } = createConfig; - const windowPrivateData = { - type: "window", - controller: this.controller, - config, id, parent, frame, workspace - }; - const newWindow = new Window(this.privateDataManager); - this.privateDataManager.setWindowData(newWindow, windowPrivateData); - return newWindow; - } - case "row": - case "column": - case "group": { - const { id, children, parent, frame, workspace, config } = createConfig; - const newParent = type === "column" ? new Column(this.parentBase) : - type === "row" ? new Row(this.parentBase) : new Group(this.parentBase); - const builtChildren = this.buildChildren(children, frame, workspace, newParent); - const parentPrivateData = { - id, parent, frame, workspace, - config, - type, - controller: this.controller, - children: builtChildren, - }; - this.privateDataManager.setParentData(newParent, parentPrivateData); - return newParent; - } - case "workspace": { - const { snapshot, frame } = createConfig; - const newWorkspace = new Workspace(this.privateDataManager); - const children = this.buildChildren(snapshot.children, frame, newWorkspace, newWorkspace); - const workspacePrivateData = { - id: snapshot.id, - type: "workspace", - config: snapshot.config, - base: this.parentBase, - controller: this.controller, - children, frame, ioc: this - }; - this.privateDataManager.setWorkspaceData(newWorkspace, workspacePrivateData); - return newWorkspace; - } - default: throw new Error(`Unrecognized type: ${type}`); - } - } - getBuilder(config) { - config.definition = config.definition || {}; - if (!Array.isArray(config.definition.children)) { - config.definition.children = []; - } - const baseBuilder = new BaseBuilder(this.getBuilder.bind(this)); - switch (config.type) { - case "workspace": { - return new WorkspaceBuilder(config.definition, baseBuilder, this.controller); - } - case "row": - case "column": - case "group": { - config.definition.type = config.type; - return new ParentBuilder(config.definition, baseBuilder); - } - default: throw new Error(`Unexpected Builder creation error, provided config: ${JSON.stringify(config)}`); - } - } - buildChildren(children, frame, workspace, parent) { - return children.map((child) => { - switch (child.type) { - case "window": return this.getModel("window", { - id: child.id, - config: child.config, - frame, workspace, parent - }); - case "column": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "row": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "group": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - default: throw new Error(`Unsupported child type: ${child.type}`); - } - }); - } - } - - var version = "4.2.3"; - - const composeAPI = (glue, ioc) => { - const controller = ioc.controller; - const inWorkspace = () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - return controller.checkIsInSwimlane(myId); - }; - const getBuilder = (config) => { - const validatedConfig = builderConfigDecoder.runWithException(config); - return ioc.getBuilder(validatedConfig); - }; - const getMyFrame = async () => { - const windowId = glue.windows.my().id; - if (!windowId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(windowId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your frame, because this window is not in a workspace"); - } - return controller.getFrame({ windowId }); - }; - const getFrame = async (predicate) => { - checkThrowCallback(predicate); - return controller.getFrame({ predicate }); - }; - const getAllFrames = async (predicate) => { - checkThrowCallback(predicate, true); - return controller.getFrames(predicate); - }; - const getAllWorkspacesSummaries = () => { - return controller.getAllWorkspaceSummaries(); - }; - const getMyWorkspace = async () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my workspace, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(myId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your workspace, because this window is not in a workspace"); - } - return await controller.getWorkspaceByWindowId(myId); - }; - const getWorkspace = async (predicate) => { - checkThrowCallback(predicate); - return (await controller.getWorkspaces(predicate))[0]; - }; - const getWorkspaceById = async (workspaceId) => { - nonEmptyStringDecoder.runWithException(workspaceId); - return controller.getWorkspaceById(workspaceId); - }; - const getAllWorkspaces = (predicate) => { - checkThrowCallback(predicate, true); - return controller.getWorkspaces(predicate); - }; - const getWindow = async (predicate) => { - checkThrowCallback(predicate); - return controller.getWindow(predicate); - }; - const getParent = async (predicate) => { - checkThrowCallback(predicate); - return controller.getParent(predicate); - }; - const restoreWorkspace = async (name, options) => { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return controller.restoreWorkspace(name, validatedOptions); - }; - const createWorkspace = async (definition, saveConfig) => { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(saveConfig); - return controller.createWorkspace(validatedDefinition, validatedConfig); - }; - const createEmptyFrame = async (definition) => { - const validatedDefinition = emptyFrameDefinitionDecoder.runWithException(definition); - return controller.createEmptyFrame(validatedDefinition ?? {}); - }; - const layouts = { - getSummaries: () => { - return controller.getLayoutSummaries(); - }, - delete: async (name) => { - nonEmptyStringDecoder.runWithException(name); - return controller.deleteLayout(name); - }, - export: async (predicate) => { - checkThrowCallback(predicate, true); - return controller.exportLayout(predicate); - }, - import: async (layouts, mode = "replace") => { - if (!Array.isArray(layouts)) { - throw new Error(`The provided layouts argument is not an array: ${JSON.stringify(layouts)}`); - } - layouts.forEach((layout) => workspaceLayoutDecoder.runWithException(layout)); - return controller.importLayouts(layouts, mode); - }, - save: async (config) => { - const verifiedConfig = workspaceLayoutSaveConfigDecoder.runWithException(config); - return controller.saveLayout(verifiedConfig); - }, - onSaved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnSaved(callback); - }, - onRemoved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnRemoved(callback); - } - }; - const onFrameOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - callback(frame); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "opened"); - return unsubscribe; - }; - const onFrameClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "closed"); - return unsubscribe; - }; - const onWorkspaceOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "opened"); - return unsubscribe; - }; - const onWorkspaceClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "closed"); - return unsubscribe; - }; - const onWorkspaceHibernated = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "hibernated"); - return unsubscribe; - }; - const onWorkspaceResumed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "resumed"); - return unsubscribe; - }; - const onWindowAdded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "added"); - return unsubscribe; - }; - const onWindowLoaded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const foundWindow = workspace.getWindow((win) => win.id && win.id === payload.windowSummary.config.windowId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "loaded"); - return unsubscribe; - }; - const onWindowRemoved = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "removed"); - return unsubscribe; - }; - const onWindowMaximized = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "maximized"); - return unsubscribe; - }; - const onWindowRestored = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "restored"); - return unsubscribe; - }; - const onWindowSelected = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "selected"); - return unsubscribe; - }; - const waitForFrame = async (id) => { - nonEmptyStringDecoder.runWithException(id); - return new Promise((res, rej) => { - let unsub = () => { - }; - onFrameOpened((f) => { - if (f.id === id) { - res(f); - unsub(); - } - }).then((u) => { - unsub = u; - return getAllFrames(); - }).then((frames) => { - const myFrame = frames.find((f) => f.id === id); - if (myFrame) { - res(myFrame); - unsub(); - } - }).catch(rej); - }); - }; - return { - inWorkspace, - getBuilder, - getMyFrame, - getFrame, - getAllFrames, - getAllWorkspacesSummaries, - getMyWorkspace, - getWorkspace, - getWorkspaceById, - getAllWorkspaces, - getWindow, - getBox: getParent, - restoreWorkspace, - createWorkspace, - createEmptyFrame, - waitForFrame, - layouts, - onFrameOpened, - onFrameClosed, - onWorkspaceOpened, - onWorkspaceClosed, - onWorkspaceHibernated, - onWorkspaceResumed, - onWindowAdded, - onWindowLoaded, - onWindowRemoved, - onWindowMaximized, - onWindowRestored, - onWindowSelected, - version - }; - }; - - const factoryFunction = async (io) => { - const ioc = new IoC(io.agm, io.windows, io.layouts, io.contexts); - const actualWindowId = io.interop.instance.windowId; - await ioc.initiate(actualWindowId); - io.workspaces = composeAPI(io, ioc); - }; - if (typeof window !== "undefined") { - window.IOWorkspaces = factoryFunction; - } - - return factoryFunction; - -})); -//# sourceMappingURL=workspaces.umd.js.map diff --git a/javascript/solution/client-details/package-lock.json b/javascript/solution/client-details/package-lock.json new file mode 100644 index 0000000..8a3a524 --- /dev/null +++ b/javascript/solution/client-details/package-lock.json @@ -0,0 +1,1280 @@ +{ + "name": "client-details", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "client-details", + "version": "1.0.0", + "dependencies": { + "@interopio/browser": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@interopio/browser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser/-/browser-4.2.4.tgz", + "integrity": "sha512-BPgkwH6N8HyGf7st99ZJwQ7arijz9j1bGu7pUAXBrtbv6cu4zH5GR7JKPGANZmFl0uefNPQyAQ4hc7C/i1i++A==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0", + "@interopio/search-api": "^3.2.1", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.2" + } + }, + "node_modules/@interopio/core": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@interopio/core/-/core-6.8.1.tgz", + "integrity": "sha512-WFWIV8JilNuAcxXaB+81IjL9j82sU73ABMUUEOWpvWoyqxhPlneOS+rSYViFX5gdk5pLH3fM6T/MmRGn3UFLwQ==", + "license": "MIT", + "dependencies": { + "callback-registry": "^2.7.2", + "ws": "^8.18.0" + } + }, + "node_modules/@interopio/desktop": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/@interopio/desktop/-/desktop-6.18.0.tgz", + "integrity": "sha512-YqRHRiCymbY2fOCT2HHJnLY4780JSRI1fUtaWEoIa5Z3djZk/3xRgVxIjOVw9Y/TAFGCwyIeW142a7HYnSGD5Q==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/schemas": "^10.1.0", + "@interopio/utils": "^1.4.2", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.1" + } + }, + "node_modules/@interopio/schemas": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@interopio/schemas/-/schemas-10.1.0.tgz", + "integrity": "sha512-8uDEoOAZenTr4a3O8vLq6JyS/LutkT/gh9EjuOrS9fOmHEUfJaS2u+qPo5em9/8MtjKgblZEJStSsW1gr34CtQ==", + "license": "ISC", + "dependencies": { + "ajv": "^6.12.6", + "ajv-keywords": "^3.4.1" + }, + "peerDependencies": { + "log4js": "^6.4.2" + }, + "peerDependenciesMeta": { + "log4js": { + "optional": true + } + } + }, + "node_modules/@interopio/search-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@interopio/search-api/-/search-api-3.2.1.tgz", + "integrity": "sha512-raUZzqBQoidm/6Mvgao2wFWlTDu9D4jghiX1dqor1LdsIfUpelJkkuFGeDl0z/3DWneaxDF8Vc/uoBtLz7qJLw==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1" + } + }, + "node_modules/@interopio/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@interopio/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-14Bb2WI9Cwf9zjhTurP4qP9AVY4cxR1AOrwrOtHrTGAeeHp88mALFWfMEv1QnRhlQ06To2vQcRgebNrPlHDZ8Q==", + "license": "ISC", + "dependencies": { + "decoder-validate": "^0.0.2" + } + }, + "node_modules/@interopio/workspaces-api": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@interopio/workspaces-api/-/workspaces-api-4.2.3.tgz", + "integrity": "sha512-5wrR1yhETKuX4txVrmS5q3G+8KI6GW4yOxsrVdf5qErO2HxN938XUdiAHIesarwlQoncrgnVx7uTn6IeOWUoXg==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/callback-registry": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/callback-registry/-/callback-registry-2.7.2.tgz", + "integrity": "sha512-VVrtF21DaH0VHeNMkLDd4VGuxsYM3V3l3lwYneKVMU/6X3TRtcQszUwlAcqj2HrLcbP1NyS12LsanUwCykaz/Q==", + "license": "ISC" + }, + "node_modules/decoder-validate": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/decoder-validate/-/decoder-validate-0.0.2.tgz", + "integrity": "sha512-9BsqAH9Zq6CvlxKHkSrZrH2iYlhuhHcrh6uTnDvcsa9P5YEweEzt1ci+X/9STgSCE7b9BA7/QIiwhfUDDWmjxw==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/javascript/solution/client-details/package.json b/javascript/solution/client-details/package.json new file mode 100644 index 0000000..dd18425 --- /dev/null +++ b/javascript/solution/client-details/package.json @@ -0,0 +1,14 @@ +{ + "name": "client-details", + "version": "1.0.0", + "scripts": { + "start": "vite --port 9200" + }, + "dependencies": { + "@interopio/browser": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } +} diff --git a/javascript/solution/clients/index.html b/javascript/solution/clients/index.html index 28bfbcf..953a22a 100644 --- a/javascript/solution/clients/index.html +++ b/javascript/solution/clients/index.html @@ -12,12 +12,8 @@ - - - - - + diff --git a/javascript/solution/clients/index.js b/javascript/solution/clients/index.js index b388938..5ceab46 100644 --- a/javascript/solution/clients/index.js +++ b/javascript/solution/clients/index.js @@ -1,3 +1,8 @@ +import IOBrowserPlatform from '@interopio/browser-platform'; +import IOWorkspaces from '@interopio/workspaces-api'; +import { setupApplications } from './plugins/applicationsPlugin.js'; +import { setupLayouts } from './plugins/layoutsPlugin.js'; + const setupClients = (clients) => { const table = document.getElementById("clientsTable").getElementsByTagName("tbody")[0]; diff --git a/javascript/solution/clients/lib/browser.platform.umd.js b/javascript/solution/clients/lib/browser.platform.umd.js deleted file mode 100644 index afae729..0000000 --- a/javascript/solution/clients/lib/browser.platform.umd.js +++ /dev/null @@ -1,34 +0,0 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).IoConnectBrowserPlatform=t()}(this,function(){"use strict";const global=window;function getDefaultExportFromCjs$1$1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var isMergeableObject$1=function(e){return isNonNullObject$1(e)&&!isSpecial$1(e)};function isNonNullObject$1(e){return!!e&&"object"==typeof e}function isSpecial$1(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||isReactElement$1(e)}var canUseSymbol$1="function"==typeof Symbol&&Symbol.for,REACT_ELEMENT_TYPE$1=canUseSymbol$1?Symbol.for("react.element"):60103;function isReactElement$1(e){return e.$$typeof===REACT_ELEMENT_TYPE$1}function emptyTarget$1(e){return Array.isArray(e)?[]:{}}function cloneUnlessOtherwiseSpecified$1(e,t){return!1!==t.clone&&t.isMergeableObject(e)?deepmerge$1(emptyTarget$1(e),e,t):e}function defaultArrayMerge$1(e,t,r){return e.concat(t).map(function(e){return cloneUnlessOtherwiseSpecified$1(e,r)})}function getMergeFunction$1(e,t){if(!t.customMerge)return deepmerge$1;var r=t.customMerge(e);return"function"==typeof r?r:deepmerge$1}function getEnumerableOwnPropertySymbols$1(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}function getKeys$1(e){return Object.keys(e).concat(getEnumerableOwnPropertySymbols$1(e))}function propertyIsOnObject$1(e,t){try{return t in e}catch(e){return!1}}function propertyIsUnsafe$1(e,t){return propertyIsOnObject$1(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}function mergeObject$1(e,t,r){var n={};return r.isMergeableObject(e)&&getKeys$1(e).forEach(function(t){n[t]=cloneUnlessOtherwiseSpecified$1(e[t],r)}),getKeys$1(t).forEach(function(i){propertyIsUnsafe$1(e,i)||(propertyIsOnObject$1(e,i)&&r.isMergeableObject(t[i])?n[i]=getMergeFunction$1(i,r)(e[i],t[i],r):n[i]=cloneUnlessOtherwiseSpecified$1(t[i],r))}),n}function deepmerge$1(e,t,r){(r=r||{}).arrayMerge=r.arrayMerge||defaultArrayMerge$1,r.isMergeableObject=r.isMergeableObject||isMergeableObject$1,r.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified$1;var n=Array.isArray(t);return n===Array.isArray(e)?n?r.arrayMerge(e,t,r):mergeObject$1(e,t,r):cloneUnlessOtherwiseSpecified$1(t,r)}deepmerge$1.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,r){return deepmerge$1(e,r,t)},{})};var deepmerge_1$1=deepmerge$1,cjs$1=deepmerge_1$1,deepmerge$1$1=getDefaultExportFromCjs$1$1(cjs$1),ok$2$1=function(e){return{ok:!0,result:e}},err$2$1=function(e){return{ok:!1,error:e}},asPromise$2$1=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$2$1=function(e,t){return!0===t.ok?t.result:e},withException$2$1=function(e){if(!0===e.ok)return e.result;throw e.error},map$2$1=function(e,t){return!0===t.ok?ok$2$1(e(t.result)):t},map2$2$1=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$2$1(e(t.result,r.result))},mapError$2$1=function(e,t){return!0===t.ok?t:err$2$1(e(t.error))},andThen$2$1=function(e,t){return!0===t.ok?e(t.result):t},__assign$2$1=function(){return __assign$2$1=Object.assign||function(e){for(var t,r=1,n=arguments.length;r"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),runDecoderWithIOError$1=(e,t)=>{try{return e.runWithException(t)}catch(e){return ioError$1.raiseError(e,!0)}},getSupportedOperationsNames=e=>Object.keys(e).filter(t=>e[t].execute),handleOperationCheck=(e,t)=>({isSupported:e.some(e=>e.toLowerCase()===t.toLowerCase())}),getSafeTimeoutDelay$1=e=>Math.min(e,MAX_SET_TIMEOUT_DELAY$1),wrapPromise=()=>{let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}};let IOError$1=class{raiseError(e,t){const r=extractErrorMsg$2(e);if(errorChannel$1.port1.postMessage(r),t)throw e;throw new Error(r)}};const ioError$1=new IOError$1,connectBrowserAppProps$1=["name","title","version","customProperties","icon","caption","type"],fdc3v2AppProps$1=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var ok$1$1=function(e){return{ok:!0,result:e}},err$1$1=function(e){return{ok:!1,error:e}},asPromise$1$1=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$1$1=function(e,t){return!0===t.ok?t.result:e},withException$1$1=function(e){if(!0===e.ok)return e.result;throw e.error},map$1$1=function(e,t){return!0===t.ok?ok$1$1(e(t.result)):t},map2$1$1=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$1$1(e(t.result,r.result))},mapError$1$1=function(e,t){return!0===t.ok?t:err$1$1(e(t.error))},andThen$1$1=function(e,t){return!0===t.ok?e(t.result):t},__assign$1$1=function(){return __assign$1$1=Object.assign||function(e){for(var t,r=1,n=arguments.length;re.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$3$1=number$1$1().where(e=>e>=0,"Expected a non-negative number"),regexDecoder$2=anyJson$1$1().andThen(e=>e instanceof RegExp?anyJson$1$1():fail("expected a regex, got a "+typeof e)),intentDefinitionDecoder$1$1=object$1$1({name:nonEmptyStringDecoder$3$1,displayName:optional$1$1(string$1$1()),contexts:optional$1$1(array$1$1(string$1$1())),customConfig:optional$1$1(object$1$1())}),v2TypeDecoder$1=oneOf$3(constant$1$1("web"),constant$1$1("native"),constant$1$1("citrix"),constant$1$1("onlineNative"),constant$1$1("other")),v2DetailsDecoder$1=object$1$1({url:nonEmptyStringDecoder$3$1}),v2IconDecoder$1=object$1$1({src:nonEmptyStringDecoder$3$1,size:optional$1$1(nonEmptyStringDecoder$3$1),type:optional$1$1(nonEmptyStringDecoder$3$1)}),v2ScreenshotDecoder$1=object$1$1({src:nonEmptyStringDecoder$3$1,size:optional$1$1(nonEmptyStringDecoder$3$1),type:optional$1$1(nonEmptyStringDecoder$3$1),label:optional$1$1(nonEmptyStringDecoder$3$1)}),v2ListensForIntentDecoder$1=object$1$1({contexts:array$1$1(nonEmptyStringDecoder$3$1),displayName:optional$1$1(nonEmptyStringDecoder$3$1),resultType:optional$1$1(nonEmptyStringDecoder$3$1),customConfig:optional$1$1(anyJson$1$1())}),v2IntentsDecoder$1=object$1$1({listensFor:optional$1$1(dict$1(v2ListensForIntentDecoder$1)),raises:optional$1$1(dict$1(array$1$1(nonEmptyStringDecoder$3$1)))}),v2UserChannelDecoder$1=object$1$1({broadcasts:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1)),listensFor:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1))}),v2AppChannelDecoder$1=object$1$1({name:nonEmptyStringDecoder$3$1,description:optional$1$1(nonEmptyStringDecoder$3$1),broadcasts:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1)),listensFor:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1))}),v2InteropDecoder$1=object$1$1({intents:optional$1$1(v2IntentsDecoder$1),userChannels:optional$1$1(v2UserChannelDecoder$1),appChannels:optional$1$1(array$1$1(v2AppChannelDecoder$1))}),glue42ApplicationDetailsDecoder$1=object$1$1({url:optional$1$1(nonEmptyStringDecoder$3$1),top:optional$1$1(number$1$1()),left:optional$1$1(number$1$1()),width:optional$1$1(nonNegativeNumberDecoder$3$1),height:optional$1$1(nonNegativeNumberDecoder$3$1)}),glue42HostManifestsBrowserDecoder$1=object$1$1({name:optional$1$1(nonEmptyStringDecoder$3$1),type:optional$1$1(nonEmptyStringDecoder$3$1.where(e=>"window"===e,"Expected a value of window")),title:optional$1$1(nonEmptyStringDecoder$3$1),version:optional$1$1(nonEmptyStringDecoder$3$1),customProperties:optional$1$1(anyJson$1$1()),icon:optional$1$1(string$1$1()),caption:optional$1$1(string$1$1()),details:optional$1$1(glue42ApplicationDetailsDecoder$1),intents:optional$1$1(array$1$1(intentDefinitionDecoder$1$1)),hidden:optional$1$1(boolean$1$1())}),v1DefinitionDecoder$1=object$1$1({name:nonEmptyStringDecoder$3$1,appId:nonEmptyStringDecoder$3$1,title:optional$1$1(nonEmptyStringDecoder$3$1),version:optional$1$1(nonEmptyStringDecoder$3$1),manifest:nonEmptyStringDecoder$3$1,manifestType:nonEmptyStringDecoder$3$1,tooltip:optional$1$1(nonEmptyStringDecoder$3$1),description:optional$1$1(nonEmptyStringDecoder$3$1),contactEmail:optional$1$1(nonEmptyStringDecoder$3$1),supportEmail:optional$1$1(nonEmptyStringDecoder$3$1),publisher:optional$1$1(nonEmptyStringDecoder$3$1),images:optional$1$1(array$1$1(object$1$1({url:optional$1$1(nonEmptyStringDecoder$3$1)}))),icons:optional$1$1(array$1$1(object$1$1({icon:optional$1$1(nonEmptyStringDecoder$3$1)}))),customConfig:anyJson$1$1(),intents:optional$1$1(array$1$1(intentDefinitionDecoder$1$1))}),v2LocalizedDefinitionDecoder$1=object$1$1({appId:optional$1$1(nonEmptyStringDecoder$3$1),name:optional$1$1(nonEmptyStringDecoder$3$1),details:optional$1$1(v2DetailsDecoder$1),version:optional$1$1(nonEmptyStringDecoder$3$1),title:optional$1$1(nonEmptyStringDecoder$3$1),tooltip:optional$1$1(nonEmptyStringDecoder$3$1),lang:optional$1$1(nonEmptyStringDecoder$3$1),description:optional$1$1(nonEmptyStringDecoder$3$1),categories:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1)),icons:optional$1$1(array$1$1(v2IconDecoder$1)),screenshots:optional$1$1(array$1$1(v2ScreenshotDecoder$1)),contactEmail:optional$1$1(nonEmptyStringDecoder$3$1),supportEmail:optional$1$1(nonEmptyStringDecoder$3$1),moreInfo:optional$1$1(nonEmptyStringDecoder$3$1),publisher:optional$1$1(nonEmptyStringDecoder$3$1),customConfig:optional$1$1(array$1$1(anyJson$1$1())),hostManifests:optional$1$1(anyJson$1$1()),interop:optional$1$1(v2InteropDecoder$1)}),v2DefinitionDecoder$1=object$1$1({appId:nonEmptyStringDecoder$3$1,name:optional$1$1(nonEmptyStringDecoder$3$1),type:v2TypeDecoder$1,details:v2DetailsDecoder$1,version:optional$1$1(nonEmptyStringDecoder$3$1),title:optional$1$1(nonEmptyStringDecoder$3$1),tooltip:optional$1$1(nonEmptyStringDecoder$3$1),lang:optional$1$1(nonEmptyStringDecoder$3$1),description:optional$1$1(nonEmptyStringDecoder$3$1),categories:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1)),icons:optional$1$1(array$1$1(v2IconDecoder$1)),screenshots:optional$1$1(array$1$1(v2ScreenshotDecoder$1)),contactEmail:optional$1$1(nonEmptyStringDecoder$3$1),supportEmail:optional$1$1(nonEmptyStringDecoder$3$1),moreInfo:optional$1$1(nonEmptyStringDecoder$3$1),publisher:optional$1$1(nonEmptyStringDecoder$3$1),customConfig:optional$1$1(array$1$1(anyJson$1$1())),hostManifests:optional$1$1(anyJson$1$1()),interop:optional$1$1(v2InteropDecoder$1),localizedVersions:optional$1$1(dict$1(v2LocalizedDefinitionDecoder$1))}),allDefinitionsDecoder$1=oneOf$3(v1DefinitionDecoder$1,v2DefinitionDecoder$1),parseDecoderErrorToStringMessage$1=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;let FDC3Service$1=class{fdc3ToDesktopDefinitionType={web:"window",native:"exe",citrix:"citrix",onlineNative:"clickonce",other:"window"};toApi(){return{isFdc3Definition:this.isFdc3Definition.bind(this),parseToBrowserBaseAppData:this.parseToBrowserBaseAppData.bind(this),parseToDesktopAppConfig:this.parseToDesktopAppConfig.bind(this)}}isFdc3Definition(e){const t=allDefinitionsDecoder$1.run(e);return t.ok?e.appId&&e.details?{isFdc3:!0,version:"2.0"}:e.manifest?{isFdc3:!0,version:"1.2"}:{isFdc3:!1,reason:"The passed definition is not FDC3"}:{isFdc3:!1,reason:parseDecoderErrorToStringMessage$1(t.error)}}parseToBrowserBaseAppData(e){const{isFdc3:t,version:r}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const n=allDefinitionsDecoder$1.run(e);if(!n.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage$1(n.error)}`);const i=this.getUserPropertiesFromDefinition(e,r),o={url:this.getUrl(e,r)},s={name:e.appId,type:"window",createOptions:o,userProperties:{...i,intents:"1.2"===r?i.intents:this.getIntentsFromV2AppDefinition(e),details:o},title:e.title,version:e.version,icon:this.getIconFromDefinition(e,r),caption:e.description,fdc3:"2.0"===r?{...e,definitionVersion:"2.0"}:void 0},a=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!a)return s;const c=glue42HostManifestsBrowserDecoder$1.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage$1(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(s,c.result):s}parseToDesktopAppConfig(e){const{isFdc3:t,version:r}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const n=allDefinitionsDecoder$1.run(e);if(!n.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage$1(n.error)}`);if("1.2"===r){const t=e;return{name:t.appId,type:"window",details:{url:this.getUrl(e,r)},version:t.version,title:t.title,tooltip:t.tooltip,caption:t.description,icon:t.icons?.[0].icon,intents:t.intents,customProperties:{manifestType:t.manifestType,images:t.images,contactEmail:t.contactEmail,supportEmail:t.supportEmail,publisher:t.publisher,icons:t.icons,customConfig:t.customConfig}}}const i=e,o={name:i.appId,type:this.fdc3ToDesktopDefinitionType[i.type],details:i.details,version:i.version,title:i.title,tooltip:i.tooltip,caption:i.description,icon:this.getIconFromDefinition(i,"2.0"),intents:this.getIntentsFromV2AppDefinition(i),fdc3:{...i,definitionVersion:"2.0"}},s=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!s)return o;if("object"!=typeof s||Array.isArray(s))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(o,s)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!connectBrowserAppProps$1.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!connectBrowserAppProps$1.includes(e)&&!fdc3v2AppProps$1.includes(e)))}getUrl(e,t){let r;if("1.2"===t){const t=JSON.parse(e.manifest);r=t.details?.url||t.url}else r=e.details?.url;if(!r||"string"!=typeof r)throw new Error(`Invalid FDC3 ${t} definition. Provide valid 'url' under '${"1.2"===t?"manifest":"details"}' key`);return r}getIntentsFromV2AppDefinition(e){const t=e.interop?.intents?.listensFor;if(!t)return;return Object.entries(t).map(e=>{const[t,r]=e;return{name:t,...r}})}getIconFromDefinition(e,t){return"1.2"===t?e.icons?.find(e=>e.icon)?.icon||void 0:e.icons?.find(e=>e.src)?.src||void 0}mergeBaseAppDataWithGlueManifest(e,t){let r=e;if(t.customProperties&&(r.userProperties={...e.userProperties,...t.customProperties}),t.details){const n={...e.createOptions,...t.details};r.createOptions=n,r.userProperties.details=n}return Array.isArray(t.intents)&&(r.userProperties.intents=(r.userProperties.intents||[]).concat(t.intents)),r={...r,...t},delete r.details,delete r.intents,r}mergeDesktopConfigWithGlueManifest(e,t){const r=Object.assign({},e,t,{details:{...e.details,...t.details}});return Array.isArray(t.intents)&&(r.intents=(e.intents||[]).concat(t.intents)),r}};const decoders$1$1={common:{nonEmptyStringDecoder:nonEmptyStringDecoder$3$1,nonNegativeNumberDecoder:nonNegativeNumberDecoder$3$1,regexDecoder:regexDecoder$2},fdc3:{allDefinitionsDecoder:allDefinitionsDecoder$1,v1DefinitionDecoder:v1DefinitionDecoder$1,v2DefinitionDecoder:v2DefinitionDecoder$1}};var INTENTS_ERRORS$1;!function(e){e.USER_CANCELLED="User Closed Intents Resolver UI without choosing a handler",e.CALLER_NOT_DEFINED="Caller Id is not defined",e.TIMEOUT_HIT="Timeout hit",e.INTENT_NOT_FOUND="Cannot find Intent",e.HANDLER_NOT_FOUND="Cannot find Intent Handler",e.TARGET_INSTANCE_UNAVAILABLE="Cannot start Target Instance",e.INTENT_DELIVERY_FAILED="Target Instance did not add a listener",e.RESOLVER_UNAVAILABLE="Intents Resolver UI unavailable",e.RESOLVER_TIMEOUT="User did not choose a handler",e.INVALID_RESOLVER_RESPONSE="Intents Resolver UI returned invalid response",e.INTENT_HANDLER_REJECTION="Intent Handler function processing the raised intent threw an error or rejected the promise it returned"}(INTENTS_ERRORS$1||(INTENTS_ERRORS$1={}));let IoC$1$1=class{_fdc3;_decoders=decoders$1$1;_errors={intents:INTENTS_ERRORS$1};get fdc3(){return this._fdc3||(this._fdc3=(new FDC3Service$1).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};const ioc$1=new IoC$1$1;ioc$1.fdc3;const decoders$2=ioc$1.decoders;ioc$1.errors;const nonEmptyStringDecoder$2$1=string$2$1().where(e=>e.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$2$1=number$2$1().where(e=>e>=0,"Expected a non-negative number"),optionalNonEmptyStringDecoder=optional$2$1(nonEmptyStringDecoder$2$1),libDomainDecoder$1=oneOf$1$1(constant$2$1("system"),constant$2$1("windows"),constant$2$1("appManager"),constant$2$1("layouts"),constant$2$1("intents"),constant$2$1("notifications"),constant$2$1("channels"),constant$2$1("extension"),constant$2$1("themes"),constant$2$1("prefs"),constant$2$1("ui")),windowOperationTypesDecoder=oneOf$1$1(constant$2$1("openWindow"),constant$2$1("windowHello"),constant$2$1("windowAdded"),constant$2$1("windowRemoved"),constant$2$1("getBounds"),constant$2$1("getFrameBounds"),constant$2$1("getUrl"),constant$2$1("moveResize"),constant$2$1("focus"),constant$2$1("close"),constant$2$1("getTitle"),constant$2$1("setTitle"),constant$2$1("focusChange"),constant$2$1("getChannel"),constant$2$1("notifyChannelsChanged"),constant$2$1("setZoomFactor"),constant$2$1("zoomFactorChange"),constant$2$1("refresh"),constant$2$1("operationCheck")),appManagerOperationTypesDecoder$1=oneOf$1$1(constant$2$1("appHello"),constant$2$1("appDirectoryStateChange"),constant$2$1("instanceStarted"),constant$2$1("instanceStopped"),constant$2$1("applicationStart"),constant$2$1("instanceStop"),constant$2$1("clear"),constant$2$1("operationCheck")),layoutsOperationTypesDecoder$1=oneOf$1$1(constant$2$1("layoutAdded"),constant$2$1("layoutChanged"),constant$2$1("layoutRemoved"),constant$2$1("layoutRenamed"),constant$2$1("get"),constant$2$1("getAll"),constant$2$1("export"),constant$2$1("import"),constant$2$1("remove"),constant$2$1("rename"),constant$2$1("clientSaveRequest"),constant$2$1("getGlobalPermissionState"),constant$2$1("checkGlobalActivated"),constant$2$1("requestGlobalPermission"),constant$2$1("getDefaultGlobal"),constant$2$1("setDefaultGlobal"),constant$2$1("clearDefaultGlobal"),constant$2$1("updateMetadata"),constant$2$1("operationCheck"),constant$2$1("getCurrent"),constant$2$1("defaultLayoutChanged"),constant$2$1("layoutRestored")),notificationsOperationTypesDecoder=oneOf$1$1(constant$2$1("raiseNotification"),constant$2$1("requestPermission"),constant$2$1("notificationShow"),constant$2$1("notificationClick"),constant$2$1("getPermission"),constant$2$1("list"),constant$2$1("notificationRaised"),constant$2$1("notificationClosed"),constant$2$1("click"),constant$2$1("clear"),constant$2$1("clearAll"),constant$2$1("configure"),constant$2$1("getConfiguration"),constant$2$1("configurationChanged"),constant$2$1("setState"),constant$2$1("clearOld"),constant$2$1("activeCountChange"),constant$2$1("stateChange"),constant$2$1("operationCheck"),constant$2$1("getActiveCount")),systemOperationTypesDecoder$1=oneOf$1$1(constant$2$1("getEnvironment"),constant$2$1("getBase"),constant$2$1("platformShutdown"),constant$2$1("isFdc3DataWrappingSupported"),constant$2$1("clientError"),constant$2$1("systemHello"),constant$2$1("operationCheck")),windowRelativeDirectionDecoder$1=oneOf$1$1(constant$2$1("top"),constant$2$1("left"),constant$2$1("right"),constant$2$1("bottom")),windowBoundsDecoder$1=object$2$1({top:number$2$1(),left:number$2$1(),width:nonNegativeNumberDecoder$2$1,height:nonNegativeNumberDecoder$2$1}),windowOpenSettingsDecoder$1=optional$2$1(object$2$1({top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),context:optional$2$1(anyJson$2$1()),relativeTo:optional$2$1(nonEmptyStringDecoder$2$1),relativeDirection:optional$2$1(windowRelativeDirectionDecoder$1),windowId:optional$2$1(nonEmptyStringDecoder$2$1),layoutComponentId:optional$2$1(nonEmptyStringDecoder$2$1)})),openWindowConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,url:nonEmptyStringDecoder$2$1,options:windowOpenSettingsDecoder$1}),windowHelloDecoder=object$2$1({windowId:optional$2$1(nonEmptyStringDecoder$2$1)}),coreWindowDataDecoder=object$2$1({windowId:nonEmptyStringDecoder$2$1,name:nonEmptyStringDecoder$2$1}),simpleWindowDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1}),helloSuccessDecoder=object$2$1({windows:array$2$1(coreWindowDataDecoder),isWorkspaceFrame:boolean$2$1()}),windowTitleConfigDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,title:string$2$1()}),focusEventDataDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,hasFocus:boolean$2$1()}),windowMoveResizeConfigDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),relative:optional$2$1(boolean$2$1())}),windowBoundsResultDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,bounds:object$2$1({top:number$2$1(),left:number$2$1(),width:nonNegativeNumberDecoder$2$1,height:nonNegativeNumberDecoder$2$1})}),frameWindowBoundsResultDecoder$1=object$2$1({bounds:object$2$1({top:number$2$1(),left:number$2$1(),width:nonNegativeNumberDecoder$2$1,height:nonNegativeNumberDecoder$2$1})}),windowUrlResultDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,url:nonEmptyStringDecoder$2$1}),windowZoomFactorConfigDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,factorIndex:nonNegativeNumberDecoder$2$1}),anyDecoder$1=anyJson$2$1(),boundsDecoder=object$2$1({top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1)}),instanceDataDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1,applicationName:nonEmptyStringDecoder$2$1}),iframePermissionsPolicyConfigDecoder$1=object$2$1({flags:string$2$1()}),workspacesSandboxDecoder$1=object$2$1({flags:string$2$1()}),requestChannelSelectorConfigDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,channelsNames:array$2$1(nonEmptyStringDecoder$2$1)}),channelSelectorDecoder$1=object$2$1({enabled:boolean$2$1()}),applicationDetailsDecoder$1=object$2$1({url:nonEmptyStringDecoder$2$1,top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),workspacesSandbox:optional$2$1(workspacesSandboxDecoder$1),channelSelector:optional$2$1(channelSelectorDecoder$1),iframePermissionsPolicy:optional$2$1(iframePermissionsPolicyConfigDecoder$1)}),intentDefinitionDecoder$2=object$2$1({name:nonEmptyStringDecoder$2$1,displayName:optional$2$1(string$2$1()),contexts:optional$2$1(array$2$1(string$2$1())),customConfig:optional$2$1(object$2$1()),resultType:optional$2$1(string$2$1())}),applicationDefinitionDecoder=object$2$1({name:nonEmptyStringDecoder$2$1,type:nonEmptyStringDecoder$2$1.where(e=>"window"===e,"Expected a value of window"),title:optional$2$1(nonEmptyStringDecoder$2$1),version:optional$2$1(nonEmptyStringDecoder$2$1),customProperties:optional$2$1(anyJson$2$1()),icon:optional$2$1(string$2$1()),caption:optional$2$1(string$2$1()),details:applicationDetailsDecoder$1,intents:optional$2$1(array$2$1(intentDefinitionDecoder$2)),hidden:optional$2$1(boolean$2$1()),fdc3:optional$2$1(decoders$2.fdc3.v2DefinitionDecoder)}),appRemoveConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1}),appsExportOperationDecoder$1=object$2$1({definitions:array$2$1(applicationDefinitionDecoder)}),applicationDataDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,type:nonEmptyStringDecoder$2$1.where(e=>"window"===e,"Expected a value of window"),instances:array$2$1(instanceDataDecoder$1),userProperties:optional$2$1(anyJson$2$1()),title:optional$2$1(nonEmptyStringDecoder$2$1),version:optional$2$1(nonEmptyStringDecoder$2$1),icon:optional$2$1(string$2$1()),caption:optional$2$1(nonEmptyStringDecoder$2$1)}),baseApplicationDataDecoder=object$2$1({name:nonEmptyStringDecoder$2$1,type:nonEmptyStringDecoder$2$1.where(e=>"window"===e,"Expected a value of window"),userProperties:anyJson$2$1(),title:optional$2$1(nonEmptyStringDecoder$2$1),version:optional$2$1(nonEmptyStringDecoder$2$1),icon:optional$2$1(string$2$1()),caption:optional$2$1(nonEmptyStringDecoder$2$1)}),appDirectoryStateChangeDecoder=object$2$1({appsAdded:array$2$1(baseApplicationDataDecoder),appsChanged:array$2$1(baseApplicationDataDecoder),appsRemoved:array$2$1(baseApplicationDataDecoder)}),appHelloSuccessDecoder$2=object$2$1({apps:array$2$1(applicationDataDecoder$1),initialChannelId:optional$2$1(nonEmptyStringDecoder$2$1)}),basicInstanceDataDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1}),layoutTypeDecoder$1=oneOf$1$1(constant$2$1("Global"),constant$2$1("Activity"),constant$2$1("ApplicationDefault"),constant$2$1("Swimlane"),constant$2$1("Workspace")),componentTypeDecoder$1=oneOf$1$1(constant$2$1("application"),constant$2$1("activity")),windowComponentStateDecoder$1=object$2$1({context:optional$2$1(anyJson$2$1()),bounds:windowBoundsDecoder$1,createArgs:object$2$1({name:optional$2$1(nonEmptyStringDecoder$2$1),url:optional$2$1(nonEmptyStringDecoder$2$1),context:optional$2$1(anyJson$2$1())}),windowState:optional$2$1(nonEmptyStringDecoder$2$1),restoreState:optional$2$1(nonEmptyStringDecoder$2$1),instanceId:nonEmptyStringDecoder$2$1,isCollapsed:optional$2$1(boolean$2$1()),isSticky:optional$2$1(boolean$2$1()),restoreSettings:object$2$1({groupId:optional$2$1(nonEmptyStringDecoder$2$1),groupZOrder:optional$2$1(number$2$1())}),channelId:optional$2$1(nonEmptyStringDecoder$2$1)}),windowLayoutComponentDecoder$1=object$2$1({type:constant$2$1("window"),componentType:optional$2$1(componentTypeDecoder$1),application:nonEmptyStringDecoder$2$1,state:windowComponentStateDecoder$1}),windowLayoutItemDecoder$1=object$2$1({type:constant$2$1("window"),config:object$2$1({appName:nonEmptyStringDecoder$2$1,url:optional$2$1(nonEmptyStringDecoder$2$1),title:optional$2$1(string$2$1()),allowExtract:optional$2$1(boolean$2$1()),allowReorder:optional$2$1(boolean$2$1()),showCloseButton:optional$2$1(boolean$2$1()),isMaximized:optional$2$1(boolean$2$1())})}),groupLayoutItemDecoder$2=object$2$1({type:constant$2$1("group"),config:anyJson$2$1(),children:array$2$1(oneOf$1$1(windowLayoutItemDecoder$1))}),columnLayoutItemDecoder$2=object$2$1({type:constant$2$1("column"),config:anyJson$2$1(),children:array$2$1(oneOf$1$1(groupLayoutItemDecoder$2,windowLayoutItemDecoder$1,lazy$2(()=>columnLayoutItemDecoder$2),lazy$2(()=>rowLayoutItemDecoder$2)))}),rowLayoutItemDecoder$2=object$2$1({type:constant$2$1("row"),config:anyJson$2$1(),children:array$2$1(oneOf$1$1(columnLayoutItemDecoder$2,groupLayoutItemDecoder$2,windowLayoutItemDecoder$1,lazy$2(()=>rowLayoutItemDecoder$2)))}),workspaceLayoutComponentStateDecoder$1=object$2$1({config:anyJson$2$1(),context:anyJson$2$1(),children:array$2$1(oneOf$1$1(rowLayoutItemDecoder$2,columnLayoutItemDecoder$2,groupLayoutItemDecoder$2,windowLayoutItemDecoder$1))}),workspaceLayoutComponentDecoder$1=object$2$1({type:constant$2$1("Workspace"),application:optional$2$1(nonEmptyStringDecoder$2$1),state:workspaceLayoutComponentStateDecoder$1}),workspaceFrameComponentStateDecoder$1=object$2$1({bounds:windowBoundsDecoder$1,instanceId:nonEmptyStringDecoder$2$1,selectedWorkspace:nonNegativeNumberDecoder$2$1,workspaces:array$2$1(workspaceLayoutComponentStateDecoder$1),windowState:optional$2$1(nonEmptyStringDecoder$2$1),restoreState:optional$2$1(nonEmptyStringDecoder$2$1),context:optional$2$1(anyJson$2$1())}),workspaceFrameComponentDecoder$1=object$2$1({type:constant$2$1("workspaceFrame"),application:nonEmptyStringDecoder$2$1,componentType:optional$2$1(componentTypeDecoder$1),state:workspaceFrameComponentStateDecoder$1}),glueLayoutDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,type:layoutTypeDecoder$1,token:optional$2$1(nonEmptyStringDecoder$2$1),components:array$2$1(oneOf$1$1(windowLayoutComponentDecoder$1,workspaceLayoutComponentDecoder$1,workspaceFrameComponentDecoder$1)),context:optional$2$1(anyJson$2$1()),metadata:optional$2$1(anyJson$2$1()),version:optional$2$1(number$2$1())}),renamedLayoutNotificationDecoder=object$2$1({name:nonEmptyStringDecoder$2$1,type:layoutTypeDecoder$1,token:optional$2$1(nonEmptyStringDecoder$2$1),components:array$2$1(oneOf$1$1(windowLayoutComponentDecoder$1,workspaceLayoutComponentDecoder$1,workspaceFrameComponentDecoder$1)),context:optional$2$1(anyJson$2$1()),metadata:optional$2$1(anyJson$2$1()),version:optional$2$1(number$2$1()),prevName:nonEmptyStringDecoder$2$1}),newLayoutOptionsDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,context:optional$2$1(anyJson$2$1()),metadata:optional$2$1(anyJson$2$1()),instances:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),ignoreInstances:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),setAsCurrent:optional$2$1(boolean$2$1()),ignoreContexts:optional$2$1(boolean$2$1())}),restoreOptionsDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,context:optional$2$1(anyJson$2$1()),closeRunningInstance:optional$2$1(boolean$2$1()),closeMe:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$2$1)}),layoutSummaryDecoder$2=object$2$1({name:nonEmptyStringDecoder$2$1,type:layoutTypeDecoder$1,context:optional$2$1(anyJson$2$1()),metadata:optional$2$1(anyJson$2$1())}),simpleLayoutConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,type:layoutTypeDecoder$1}),saveLayoutConfigDecoder$1=object$2$1({layout:newLayoutOptionsDecoder$1}),renameLayoutConfigDecoder$1=object$2$1({layout:glueLayoutDecoder$1,newName:nonEmptyStringDecoder$2$1}),layoutResultDecoder$1=object$2$1({status:nonEmptyStringDecoder$2$1}),updateLayoutMetadataConfigDecoder$1=object$2$1({layout:glueLayoutDecoder$1}),restoreLayoutConfigDecoder$1=object$2$1({layout:restoreOptionsDecoder$1}),getAllLayoutsConfigDecoder$1=object$2$1({type:layoutTypeDecoder$1}),allLayoutsFullConfigDecoder$1=object$2$1({layouts:array$2$1(glueLayoutDecoder$1)}),defaultGlobalChangedDecoder=optional$2$1(object$2$1({name:nonEmptyStringDecoder$2$1})),importModeDecoder$1=oneOf$1$1(constant$2$1("replace"),constant$2$1("merge")),layoutsImportConfigDecoder$1=object$2$1({layouts:array$2$1(glueLayoutDecoder$1),mode:importModeDecoder$1,skipManagerRequest:optional$2$1(boolean$2$1())}),allLayoutsSummariesResultDecoder$1=object$2$1({summaries:array$2$1(layoutSummaryDecoder$2)}),simpleLayoutResultDecoder=object$2$1({layout:glueLayoutDecoder$1}),optionalSimpleLayoutResult$1=object$2$1({layout:optional$2$1(glueLayoutDecoder$1)}),setDefaultGlobalConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1}),intentsOperationTypesDecoder$1=oneOf$1$1(constant$2$1("findIntent"),constant$2$1("getIntents"),constant$2$1("getIntentsByHandler"),constant$2$1("raise"),constant$2$1("filterHandlers")),intentHandlerDecoder$1=object$2$1({applicationName:nonEmptyStringDecoder$2$1,applicationTitle:optional$2$1(string$2$1()),applicationDescription:optional$2$1(string$2$1()),applicationIcon:optional$2$1(string$2$1()),type:oneOf$1$1(constant$2$1("app"),constant$2$1("instance")),displayName:optional$2$1(string$2$1()),contextTypes:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),instanceId:optional$2$1(string$2$1()),instanceTitle:optional$2$1(string$2$1()),resultType:optional$2$1(string$2$1()),customConfig:optional$2$1(object$2$1())});object$2$1({applicationName:string$2$1(),applicationIcon:optional$2$1(string$2$1()),instanceId:optional$2$1(string$2$1())}),object$2$1({intent:nonEmptyStringDecoder$2$1,handler:intentHandlerDecoder$1});const intentDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,handlers:array$2$1(intentHandlerDecoder$1)}),intentTargetDecoder$1=oneOf$1$1(constant$2$1("startNew"),constant$2$1("reuse"),object$2$1({app:optional$2$1(nonEmptyStringDecoder$2$1),instance:optional$2$1(nonEmptyStringDecoder$2$1)})),intentContextDecoder$1=object$2$1({type:optional$2$1(nonEmptyStringDecoder$2$1),data:optional$2$1(anyJson$2$1())}),intentsDecoder$1=array$2$1(intentDecoder$1),wrappedIntentsDecoder$1=object$2$1({intents:intentsDecoder$1}),intentFilterDecoder=object$2$1({name:optional$2$1(nonEmptyStringDecoder$2$1),contextType:optional$2$1(nonEmptyStringDecoder$2$1),resultType:optional$2$1(nonEmptyStringDecoder$2$1)}),findFilterDecoder=oneOf$1$1(nonEmptyStringDecoder$2$1,intentFilterDecoder),wrappedIntentFilterDecoder$1=object$2$1({filter:optional$2$1(intentFilterDecoder)}),applicationStartOptionsDecoder$1=object$2$1({top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),relativeTo:optional$2$1(nonEmptyStringDecoder$2$1),relativeDirection:optional$2$1(windowRelativeDirectionDecoder$1),waitForAGMReady:optional$2$1(boolean$2$1()),channelId:optional$2$1(nonEmptyStringDecoder$2$1)}),intentRequestDecoder$1=object$2$1({intent:nonEmptyStringDecoder$2$1,target:optional$2$1(intentTargetDecoder$1),context:optional$2$1(intentContextDecoder$1),options:optional$2$1(applicationStartOptionsDecoder$1),handlers:optional$2$1(array$2$1(intentHandlerDecoder$1)),timeout:optional$2$1(nonNegativeNumberDecoder$2$1),waitUserResponseIndefinitely:optional$2$1(boolean$2$1()),clearSavedHandler:optional$2$1(boolean$2$1())}),originAppDecoder$1=object$2$1({interopInstance:nonEmptyStringDecoder$2$1,name:optional$2$1(nonEmptyStringDecoder$2$1)}),startReasonDecoder$1=object$2$1({originApp:originAppDecoder$1,intentRequest:optional$2$1(intentRequestDecoder$1)}),applicationStartConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,waitForAGMReady:boolean$2$1(),id:optional$2$1(nonEmptyStringDecoder$2$1),context:optional$2$1(anyJson$2$1()),top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),relativeTo:optional$2$1(nonEmptyStringDecoder$2$1),relativeDirection:optional$2$1(windowRelativeDirectionDecoder$1),forceChromeTab:optional$2$1(boolean$2$1()),layoutComponentId:optional$2$1(nonEmptyStringDecoder$2$1),channelId:optional$2$1(nonEmptyStringDecoder$2$1),startReason:startReasonDecoder$1}),raiseRequestDecoder=oneOf$1$1(nonEmptyStringDecoder$2$1,intentRequestDecoder$1),resolverConfigDecoder$1=object$2$1({enabled:boolean$2$1(),appName:nonEmptyStringDecoder$2$1,waitResponseTimeout:number$2$1()}),handlerExclusionCriteriaApplicationNameDecoder$1=object$2$1({applicationName:nonEmptyStringDecoder$2$1}),handlerExclusionCriteriaInstanceIdDecoder$1=object$2$1({instanceId:nonEmptyStringDecoder$2$1}),handlerExclusionCriteriaDecoder$1=oneOf$1$1(handlerExclusionCriteriaApplicationNameDecoder$1,handlerExclusionCriteriaInstanceIdDecoder$1),handlerFilterDecoder$1=object$2$1({title:optional$2$1(nonEmptyStringDecoder$2$1),openResolver:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$2$1),intent:optional$2$1(nonEmptyStringDecoder$2$1),contextTypes:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),resultType:optional$2$1(nonEmptyStringDecoder$2$1),applicationNames:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),excludeList:optional$2$1(array$2$1(handlerExclusionCriteriaDecoder$1))}),embeddedResolverConfigDecoder$1=object$2$1({enabled:boolean$2$1(),initialCaller:object$2$1({instanceId:nonEmptyStringDecoder$2$1})}),raiseIntentRequestDecoder$1=object$2$1({intentRequest:intentRequestDecoder$1,resolverConfig:resolverConfigDecoder$1,embeddedResolverConfig:optional$2$1(embeddedResolverConfigDecoder$1)}),intentResultDecoder$1=object$2$1({request:intentRequestDecoder$1,handler:intentHandlerDecoder$1,result:anyJson$2$1()}),filterHandlersResultDecoder$1=object$2$1({handlers:array$2$1(intentHandlerDecoder$1)}),filterHandlersWithResolverConfigDecoder$1=object$2$1({filterHandlersRequest:handlerFilterDecoder$1,resolverConfig:resolverConfigDecoder$1,embeddedResolverConfig:optional$2$1(embeddedResolverConfigDecoder$1)}),AddIntentListenerRequestDecoder=object$2$1({intent:nonEmptyStringDecoder$2$1,contextTypes:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),displayName:optional$2$1(string$2$1()),icon:optional$2$1(string$2$1()),description:optional$2$1(string$2$1()),resultType:optional$2$1(string$2$1()),customConfig:optional$2$1(object$2$1())}),AddIntentListenerDecoder=oneOf$1$1(nonEmptyStringDecoder$2$1,AddIntentListenerRequestDecoder),intentInfoDecoder$1=object$2$1({intent:nonEmptyStringDecoder$2$1,contextTypes:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),description:optional$2$1(nonEmptyStringDecoder$2$1),displayName:optional$2$1(nonEmptyStringDecoder$2$1),icon:optional$2$1(nonEmptyStringDecoder$2$1),resultType:optional$2$1(nonEmptyStringDecoder$2$1)}),getIntentsResultDecoder$1=object$2$1({intents:array$2$1(intentInfoDecoder$1)}),channelNameDecoder=e=>nonEmptyStringDecoder$2$1.where(t=>e.includes(t),"Expected a valid channel name"),fdc3OptionsDecoder=object$2$1({contextType:optional$2$1(nonEmptyStringDecoder$2$1)}),publishOptionsDecoder=optional$2$1(oneOf$1$1(nonEmptyStringDecoder$2$1,object$2$1({name:optional$2$1(nonEmptyStringDecoder$2$1),fdc3:optional$2$1(boolean$2$1())}))),leaveChannelsConfig=object$2$1({windowId:optionalNonEmptyStringDecoder,channel:optionalNonEmptyStringDecoder}),fdc3ContextDecoder=anyJson$2$1().where(e=>"string"==typeof e.type,"Expected a valid FDC3 Context with compulsory 'type' field"),interopActionSettingsDecoder$1=object$2$1({method:nonEmptyStringDecoder$2$1,arguments:optional$2$1(anyJson$2$1()),target:optional$2$1(oneOf$1$1(constant$2$1("all"),constant$2$1("best")))}),glue42NotificationActionDecoder$1=object$2$1({action:string$2$1(),title:nonEmptyStringDecoder$2$1,icon:optional$2$1(string$2$1()),interop:optional$2$1(interopActionSettingsDecoder$1)}),notificationStateDecoder$1=oneOf$1$1(constant$2$1("Active"),constant$2$1("Acknowledged"),constant$2$1("Seen"),constant$2$1("Closed"),constant$2$1("Stale"),constant$2$1("Snoozed"),constant$2$1("Processing")),activeNotificationsCountChangeDecoder=object$2$1({count:number$2$1()}),notificationDefinitionDecoder=object$2$1({badge:optional$2$1(string$2$1()),body:optional$2$1(string$2$1()),data:optional$2$1(anyJson$2$1()),dir:optional$2$1(oneOf$1$1(constant$2$1("auto"),constant$2$1("ltr"),constant$2$1("rtl"))),icon:optional$2$1(string$2$1()),image:optional$2$1(string$2$1()),lang:optional$2$1(string$2$1()),renotify:optional$2$1(boolean$2$1()),requireInteraction:optional$2$1(boolean$2$1()),silent:optional$2$1(boolean$2$1()),tag:optional$2$1(string$2$1()),timestamp:optional$2$1(nonNegativeNumberDecoder$2$1),vibrate:optional$2$1(array$2$1(number$2$1()))}),glue42NotificationOptionsDecoder$1=object$2$1({title:nonEmptyStringDecoder$2$1,clickInterop:optional$2$1(interopActionSettingsDecoder$1),actions:optional$2$1(array$2$1(glue42NotificationActionDecoder$1)),focusPlatformOnDefaultClick:optional$2$1(boolean$2$1()),badge:optional$2$1(string$2$1()),body:optional$2$1(string$2$1()),data:optional$2$1(anyJson$2$1()),dir:optional$2$1(oneOf$1$1(constant$2$1("auto"),constant$2$1("ltr"),constant$2$1("rtl"))),icon:optional$2$1(string$2$1()),image:optional$2$1(string$2$1()),lang:optional$2$1(string$2$1()),renotify:optional$2$1(boolean$2$1()),requireInteraction:optional$2$1(boolean$2$1()),silent:optional$2$1(boolean$2$1()),tag:optional$2$1(string$2$1()),timestamp:optional$2$1(nonNegativeNumberDecoder$2$1),vibrate:optional$2$1(array$2$1(number$2$1())),severity:optional$2$1(oneOf$1$1(constant$2$1("Low"),constant$2$1("None"),constant$2$1("Medium"),constant$2$1("High"),constant$2$1("Critical"))),showToast:optional$2$1(boolean$2$1()),showInPanel:optional$2$1(boolean$2$1()),state:optional$2$1(notificationStateDecoder$1)}),notificationSetStateRequestDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1,state:notificationStateDecoder$1});object$2$1().where(e=>!e.fdc3||"string"==typeof e.fdc3.type,"Expected a valid FDC3 Context with compulsory 'type' field");const channelFDC3DisplayMetadataDecoder$1=object$2$1({color:optional$2$1(nonEmptyStringDecoder$2$1),icon:optional$2$1(nonEmptyStringDecoder$2$1),name:optional$2$1(nonEmptyStringDecoder$2$1),glyph:optional$2$1(nonEmptyStringDecoder$2$1)}),channelFdc3MetaDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1,displayMetadata:optional$2$1(channelFDC3DisplayMetadataDecoder$1)}),channelMetaDecoder$2=object$2$1({color:nonEmptyStringDecoder$2$1,fdc3:optional$2$1(channelFdc3MetaDecoder$1)}),channelDefinitionDecoder$2=object$2$1({name:nonEmptyStringDecoder$2$1,meta:channelMetaDecoder$2,data:optional$2$1(object$2$1())}),pathValueDecoder=object$2$1({path:nonEmptyStringDecoder$2$1,value:anyJson$2$1()}),pathsValueDecoder=array$2$1(pathValueDecoder),removeChannelDataDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1}),channelRestrictionsDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,read:boolean$2$1(),write:boolean$2$1(),windowId:optional$2$1(nonEmptyStringDecoder$2$1)}),channelRestrictionConfigWithWindowIdDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,read:boolean$2$1(),write:boolean$2$1(),windowId:nonEmptyStringDecoder$2$1}),restrictionConfigDataDecoder$1=object$2$1({config:channelRestrictionConfigWithWindowIdDecoder$1}),restrictionsDecoder$1=object$2$1({channels:array$2$1(channelRestrictionsDecoder$1)}),getRestrictionsDataDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1}),restrictionsConfigDecoder$1=object$2$1({read:boolean$2$1(),write:boolean$2$1(),windowId:optional$2$1(nonEmptyStringDecoder$2$1)}),restrictAllDataDecoder$1=object$2$1({restrictions:restrictionsConfigDecoder$1}),raiseNotificationDecoder$1=object$2$1({settings:glue42NotificationOptionsDecoder$1,id:nonEmptyStringDecoder$2$1}),raiseNotificationResultDecoder$1=object$2$1({settings:glue42NotificationOptionsDecoder$1}),permissionRequestResultDecoder$1=object$2$1({permissionGranted:boolean$2$1()}),permissionQueryResultDecoder$1=object$2$1({permission:oneOf$1$1(constant$2$1("default"),constant$2$1("granted"),constant$2$1("denied"))}),notificationEventPayloadDecoder=object$2$1({definition:notificationDefinitionDecoder,action:optional$2$1(string$2$1()),id:optional$2$1(nonEmptyStringDecoder$2$1)}),notificationFilterDecoder$1=object$2$1({allowed:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),blocked:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1))}),notificationsConfigurationDecoder$1=object$2$1({enable:optional$2$1(boolean$2$1()),enableToasts:optional$2$1(boolean$2$1()),sourceFilter:optional$2$1(notificationFilterDecoder$1),showNotificationBadge:optional$2$1(boolean$2$1())}),notificationsConfigurationProtocolDecoder$1=object$2$1({configuration:notificationsConfigurationDecoder$1}),strictNotificationsConfigurationProtocolDecoder=object$2$1({configuration:object$2$1({enable:boolean$2$1(),enableToasts:boolean$2$1(),sourceFilter:object$2$1({allowed:array$2$1(nonEmptyStringDecoder$2$1),blocked:array$2$1(nonEmptyStringDecoder$2$1)})})}),platformSaveRequestConfigDecoder=object$2$1({layoutType:oneOf$1$1(constant$2$1("Global"),constant$2$1("Workspace")),layoutName:nonEmptyStringDecoder$2$1,context:optional$2$1(anyJson$2$1())}),saveRequestClientResponseDecoder=object$2$1({windowContext:optional$2$1(anyJson$2$1())}),permissionStateResultDecoder$1=object$2$1({state:oneOf$1$1(constant$2$1("prompt"),constant$2$1("denied"),constant$2$1("granted"))}),simpleAvailabilityResultDecoder$1=object$2$1({isAvailable:boolean$2$1()}),simpleItemIdDecoder=object$2$1({itemId:nonEmptyStringDecoder$2$1}),operationCheckResultDecoder$1=object$2$1({isSupported:boolean$2$1()}),operationCheckConfigDecoder$1=object$2$1({operation:nonEmptyStringDecoder$2$1}),workspaceFrameBoundsResultDecoder=object$2$1({bounds:windowBoundsDecoder$1}),themeDecoder$1=object$2$1({displayName:nonEmptyStringDecoder$2$1,name:nonEmptyStringDecoder$2$1}),simpleThemeResponseDecoder$1=object$2$1({theme:themeDecoder$1}),allThemesResponseDecoder$1=object$2$1({themes:array$2$1(themeDecoder$1)}),selectThemeConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1}),notificationsDataDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1,title:nonEmptyStringDecoder$2$1,clickInterop:optional$2$1(interopActionSettingsDecoder$1),actions:optional$2$1(array$2$1(glue42NotificationActionDecoder$1)),focusPlatformOnDefaultClick:optional$2$1(boolean$2$1()),badge:optional$2$1(string$2$1()),body:optional$2$1(string$2$1()),data:optional$2$1(anyJson$2$1()),dir:optional$2$1(oneOf$1$1(constant$2$1("auto"),constant$2$1("ltr"),constant$2$1("rtl"))),icon:optional$2$1(string$2$1()),image:optional$2$1(string$2$1()),lang:optional$2$1(string$2$1()),renotify:optional$2$1(boolean$2$1()),requireInteraction:optional$2$1(boolean$2$1()),silent:optional$2$1(boolean$2$1()),tag:optional$2$1(string$2$1()),timestamp:optional$2$1(nonNegativeNumberDecoder$2$1),vibrate:optional$2$1(array$2$1(number$2$1())),severity:optional$2$1(oneOf$1$1(constant$2$1("Low"),constant$2$1("None"),constant$2$1("Medium"),constant$2$1("High"),constant$2$1("Critical"))),showToast:optional$2$1(boolean$2$1()),showInPanel:optional$2$1(boolean$2$1()),state:optional$2$1(notificationStateDecoder$1)}),simpleNotificationDataDecoder=object$2$1({notification:notificationsDataDecoder$1}),allNotificationsDataDecoder$1=object$2$1({notifications:array$2$1(notificationsDataDecoder$1)}),simpleNotificationSelectDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1}),getWindowIdsOnChannelDataDecoder$1=object$2$1({channel:nonEmptyStringDecoder$2$1}),getWindowIdsOnChannelResultDecoder$1=object$2$1({windowIds:array$2$1(nonEmptyStringDecoder$2$1)}),channelsOperationTypesDecoder=oneOf$1$1(constant$2$1("appHello"),constant$2$1("addChannel"),constant$2$1("getMyChannel"),constant$2$1("getWindowIdsOnChannel"),constant$2$1("getWindowIdsWithChannels"),constant$2$1("joinChannel"),constant$2$1("restrict"),constant$2$1("getRestrictions"),constant$2$1("restrictAll"),constant$2$1("notifyChannelsChanged"),constant$2$1("leaveChannel"),constant$2$1("getMode"),constant$2$1("operationCheck")),modeDecoder$1=oneOf$1$1(constant$2$1("single"),constant$2$1("multi")),getChannelsModeDecoder$1=object$2$1({mode:modeDecoder$1}),channelsAppHelloDataDecoder=object$2$1({windowId:nonEmptyStringDecoder$2$1}),channelsAppHelloSuccessDecoder=object$2$1({mode:modeDecoder$1,channels:array$2$1(nonEmptyStringDecoder$2$1),restrictions:array$2$1(channelRestrictionsDecoder$1)}),getMyChanelResultDecoder$1=object$2$1({channel:optional$2$1(nonEmptyStringDecoder$2$1)}),windowWithChannelFilterDecoder$1=object$2$1({application:optional$2$1(nonEmptyStringDecoder$2$1),channels:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),windowIds:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1))}),wrappedWindowWithChannelFilterDecoder$1=object$2$1({filter:optional$2$1(windowWithChannelFilterDecoder$1)}),getWindowIdsWithChannelsResultDecoder$1=object$2$1({windowIdsWithChannels:array$2$1(object$2$1({application:nonEmptyStringDecoder$2$1,channel:optional$2$1(nonEmptyStringDecoder$2$1),windowId:nonEmptyStringDecoder$2$1}))}),startApplicationContextDecoder=optional$2$1(anyJson$2$1()),startApplicationOptionsDecoder=optional$2$1(object$2$1({top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),relativeTo:optional$2$1(nonEmptyStringDecoder$2$1),relativeDirection:optional$2$1(windowRelativeDirectionDecoder$1),waitForAGMReady:optional$2$1(boolean$2$1()),channelId:optional$2$1(nonEmptyStringDecoder$2$1),reuseId:optional$2$1(nonEmptyStringDecoder$2$1),originIntentRequest:optional$2$1(intentRequestDecoder$1)})),joinChannelDataDecoder$1=object$2$1({channel:nonEmptyStringDecoder$2$1,windowId:nonEmptyStringDecoder$2$1}),leaveChannelDataDecoder=object$2$1({windowId:nonEmptyStringDecoder$2$1,channelName:optional$2$1(nonEmptyStringDecoder$2$1)}),channelsChangedDataDecoder=object$2$1({windowId:nonEmptyStringDecoder$2$1,channelNames:array$2$1(nonEmptyStringDecoder$2$1)}),windowChannelResultDecoder$1=object$2$1({channel:optional$2$1(nonEmptyStringDecoder$2$1)}),prefsOperationTypesDecoder$1=oneOf$1$1(constant$2$1("clear"),constant$2$1("clearAll"),constant$2$1("get"),constant$2$1("getAll"),constant$2$1("set"),constant$2$1("update"),constant$2$1("prefsChanged"),constant$2$1("prefsHello"),constant$2$1("operationCheck"),constant$2$1("registerSubscriber")),appPreferencesDecoder$1=object$2$1({app:nonEmptyStringDecoder$2$1,data:object$2$1(),lastUpdate:optional$2$1(nonEmptyStringDecoder$2$1)}),basePrefsConfigDecoder$1=object$2$1({app:nonEmptyStringDecoder$2$1}),getPrefsResultDecoder$1=object$2$1({prefs:appPreferencesDecoder$1}),getAllPrefsResultDecoder$1=object$2$1({all:array$2$1(appPreferencesDecoder$1)}),subscriberRegisterConfigDecoder$1=object$2$1({interopId:nonEmptyStringDecoder$2$1,appName:optional$2$1(nonEmptyStringDecoder$2$1)}),changePrefsDataDecoder$1=object$2$1({app:nonEmptyStringDecoder$2$1,data:object$2$1()}),prefsHelloSuccessDecoder$1=object$2$1({platform:object$2$1({app:nonEmptyStringDecoder$2$1}),validNonExistentApps:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1))}),clientErrorDataDecoder$1=object$2$1({message:nonEmptyStringDecoder$2$1}),systemHelloSuccessDecoder$1=object$2$1({isClientErrorOperationSupported:boolean$2$1()}),nonEmptyStringDecoder$1$1=decoders$2.common.nonEmptyStringDecoder,nonNegativeNumberDecoder$1$1=decoders$2.common.nonNegativeNumberDecoder,widgetSourcesDecoder=object$2$1({bundle:nonEmptyStringDecoder$1$1,styles:array$2$1(nonEmptyStringDecoder$1$1),fonts:optional$2$1(array$2$1(nonEmptyStringDecoder$1$1))}),modalsSourcesDecoder=object$2$1({bundle:nonEmptyStringDecoder$1$1,styles:array$2$1(nonEmptyStringDecoder$1$1),fonts:optional$2$1(array$2$1(nonEmptyStringDecoder$1$1))}),intentResolverSourcesDecoder=object$2$1({bundle:nonEmptyStringDecoder$1$1,styles:array$2$1(nonEmptyStringDecoder$1$1),fonts:optional$2$1(array$2$1(nonEmptyStringDecoder$1$1))}),channelSelectorTypeDecoder$1=oneOf$1$1(constant$2$1("directional"),constant$2$1("default")),channelSelectorDecoder$2=object$2$1({type:optional$2$1(channelSelectorTypeDecoder$1),enable:optional$2$1(boolean$2$1())}),positionDecoder$1=oneOf$1$1(constant$2$1("top-left"),constant$2$1("top-center"),constant$2$1("top-right"),constant$2$1("center-left"),constant$2$1("center-right"),constant$2$1("bottom-left"),constant$2$1("bottom-center"),constant$2$1("bottom-right")),displayModeDecoder$1=oneOf$1$1(constant$2$1("all"),constant$2$1("fdc3")),widgetChannelsDecoder$1=object$2$1({selector:optional$2$1(channelSelectorDecoder$2),displayMode:optional$2$1(displayModeDecoder$1)}),platformWidgetDefaultConfigDecoder=object$2$1({channels:optional$2$1(widgetChannelsDecoder$1),position:optional$2$1(positionDecoder$1),displayInWorkspace:optional$2$1(boolean$2$1()),restoreLastKnownPosition:optional$2$1(boolean$2$1())}),widgetConfigDecoder$1=object$2$1({enable:boolean$2$1(),awaitFactory:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$1$1),channels:optional$2$1(widgetChannelsDecoder$1),position:optional$2$1(positionDecoder$1),displayInWorkspace:optional$2$1(boolean$2$1()),restoreLastKnownPosition:optional$2$1(boolean$2$1())}),modalsConfigDecoder$1=object$2$1({alerts:optional$2$1(object$2$1({enabled:boolean$2$1()})),dialogs:optional$2$1(object$2$1({enabled:boolean$2$1()})),awaitFactory:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$1$1)}),uiOperationTypesDecoder$1=oneOf$1$1(constant$2$1("getResources"),constant$2$1("operationCheck"),constant$2$1("showAlert"),constant$2$1("showDialog"),constant$2$1("alertInteropAction"),constant$2$1("showResolver")),getResourcesDataDecoder$1=object$2$1({origin:nonEmptyStringDecoder$1$1}),blockedResourcesDecoder$1=object$2$1({blockedOrigin:constant$2$1(!0)}),availableWidgetResourcesDecoder$1=object$2$1({blockedOrigin:constant$2$1(!1),config:platformWidgetDefaultConfigDecoder,sources:widgetSourcesDecoder}),widgetResourcesDecoder$1=union$1$1(blockedResourcesDecoder$1,availableWidgetResourcesDecoder$1),availableModalsResourcesDecoder$1=object$2$1({blockedOrigin:constant$2$1(!1),sources:modalsSourcesDecoder}),modalsResourcesDecoder$1=union$1$1(blockedResourcesDecoder$1,availableModalsResourcesDecoder$1),availableIntentResolverResourcesDecoder=object$2$1({blockedOrigin:constant$2$1(!1),sources:intentResolverSourcesDecoder}),intentResolverResourcesDecoder=union$1$1(blockedResourcesDecoder$1,availableIntentResolverResourcesDecoder),resourcesDecoder$1=object$2$1({widget:optional$2$1(widgetResourcesDecoder$1),modals:optional$2$1(modalsResourcesDecoder$1),intentResolver:optional$2$1(intentResolverResourcesDecoder)}),getResourcesResultDecoder$1=object$2$1({resources:resourcesDecoder$1}),alertsInteropSettingsDecoder$1=object$2$1({method:nonEmptyStringDecoder$1$1,arguments:optional$2$1(anyJson$2$1()),target:optional$2$1(oneOf$1$1(constant$2$1("best"),constant$2$1("all"),nonEmptyStringDecoder$1$1))}),modalRequestTargetDecoder$1=oneOf$1$1(constant$2$1("Global"),constant$2$1("WindowContainer"),nonEmptyStringDecoder$1$1),modalRequestMessageTargetDecoder$1=object$2$1({instance:nonEmptyStringDecoder$1$1,container:optional$2$1(oneOf$1$1(constant$2$1("Global"),constant$2$1("WindowContainer")))}),alertRequestConfigDecoder$1=object$2$1({variant:oneOf$1$1(constant$2$1("default"),constant$2$1("success"),constant$2$1("critical"),constant$2$1("info"),constant$2$1("warning")),text:nonEmptyStringDecoder$1$1,showCloseButton:optional$2$1(boolean$2$1()),clickInterop:optional$2$1(alertsInteropSettingsDecoder$1),onCloseInterop:optional$2$1(alertsInteropSettingsDecoder$1),actions:optional$2$1(array$2$1(object$2$1({id:nonEmptyStringDecoder$1$1,title:nonEmptyStringDecoder$1$1,clickInterop:alertsInteropSettingsDecoder$1}))),data:optional$2$1(anyJson$2$1()),ttl:optional$2$1(nonNegativeNumberDecoder$1$1),target:optional$2$1(modalRequestTargetDecoder$1)}),uiAlertRequestMessageDecoder$1=object$2$1({config:alertRequestConfigDecoder$1,target:modalRequestMessageTargetDecoder$1}),dialogRequestConfigDecoder$1=object$2$1({templateName:nonEmptyStringDecoder$1$1,variables:anyJson$2$1(),target:optional$2$1(modalRequestTargetDecoder$1),timer:optional$2$1(object$2$1({duration:nonNegativeNumberDecoder$1$1})),size:optional$2$1(object$2$1({width:nonNegativeNumberDecoder$1$1,height:nonNegativeNumberDecoder$1$1})),movable:optional$2$1(boolean$2$1()),transparent:optional$2$1(boolean$2$1())}),dialogResponseDecoder$1=object$2$1({isExpired:optional$2$1(boolean$2$1()),isClosed:optional$2$1(boolean$2$1()),isEnterPressed:optional$2$1(boolean$2$1()),responseButtonClicked:optional$2$1(object$2$1({id:nonEmptyStringDecoder$1$1,text:nonEmptyStringDecoder$1$1})),inputs:optional$2$1(array$2$1(object$2$1({type:oneOf$1$1(constant$2$1("checkbox"),constant$2$1("email"),constant$2$1("number"),constant$2$1("password"),constant$2$1("text")),id:nonEmptyStringDecoder$1$1,checked:optional$2$1(boolean$2$1()),value:optional$2$1(string$2$1())})))});object$2$1({result:dialogResponseDecoder$1});const uiDialogRequestMessageDecoder$1=object$2$1({config:dialogRequestConfigDecoder$1,target:modalRequestMessageTargetDecoder$1}),openAlertResultDecoder=object$2$1({id:nonEmptyStringDecoder$1$1}),openDialogResultDecoder=object$2$1({id:nonEmptyStringDecoder$1$1,responsePromise:anyJson$2$1()}),dialogOnCompletionConfigDecoder=object$2$1({response:dialogResponseDecoder$1}),alertInteropActionDecoder$1=object$2$1({name:nonEmptyStringDecoder$1$1,settings:alertsInteropSettingsDecoder$1}),alertOnClickConfigDecoder=object$2$1({interopAction:alertInteropActionDecoder$1}),alertInteropActionDataDecoder$1=object$2$1({interopAction:alertInteropActionDecoder$1}),intentResolverConfigDecoder$1=object$2$1({enable:boolean$2$1(),awaitFactory:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$1$1)}),openResolverResultDecoder=object$2$1({id:nonEmptyStringDecoder$1$1}),userSettingsDecoder=object$2$1({preserveChoice:boolean$2$1()}),userChoiceResponseDecoder=object$2$1({intent:nonEmptyStringDecoder$1$1,handler:intentHandlerDecoder$1,userSettings:userSettingsDecoder}),intentResolverResponseDecoder=object$2$1({isExpired:optional$2$1(boolean$2$1()),isClosed:optional$2$1(boolean$2$1()),userChoice:optional$2$1(userChoiceResponseDecoder)}),onUserResponseResponseDecoder=object$2$1({response:intentResolverResponseDecoder}),openConfigWithIntentRequestDecoder=object$2$1({intentRequest:intentRequestDecoder$1}),openConfigWithHandlerFilterDecoder=object$2$1({handlerFilter:handlerFilterDecoder$1}),intentResolverOpenConfigDecoder=union$1$1(openConfigWithIntentRequestDecoder,openConfigWithHandlerFilterDecoder),uiResolverRequestMessageConfigDecoder=intersection$2(intentResolverOpenConfigDecoder,object$2$1({timeout:nonNegativeNumberDecoder$1$1})),uiResolverRequestMessageDecoder=object$2$1({config:uiResolverRequestMessageConfigDecoder}),uiResolverResponseMessageDecoder=object$2$1({result:intentResolverResponseDecoder}),parseConfig=(e={})=>{const t=!!e?.gateway?.webPlatform?.port,r=optional$2$1(widgetConfigDecoder$1).run(e.widget);if(!r.ok)throw ioError$1.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(r.error)}`);const n=optional$2$1(modalsConfigDecoder$1).run(e.modals);if(!n.ok)throw ioError$1.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(n.error)}`);const i=optional$2$1(intentResolverConfigDecoder$1).run(e.intentResolver);if(!i.ok)throw ioError$1.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(i.error)}`);return{...defaultConfig,...e,isPlatformInternal:t,logger:e.systemLogger?.level??"info",customLogger:e.systemLogger?.customLogger,widget:deepmerge$1$1(defaultWidgetConfig$1,r.result??{}),modals:deepmerge$1$1(defaultModalsConfig,n.result??{}),intentResolver:deepmerge$1$1(defaultIntentResolverConfig,i.result??{})}},checkSingleton$1=()=>{const e=window.glue42core||window.iobrowser;if(e&&e.webStarted)return ioError$1.raiseError("IoConnect Browser has already been started for this application.");e?e.webStarted=!0:window.iobrowser={webStarted:!0}},enterprise=e=>{const t={windows:!0,layouts:"full",appManager:"full",channels:!0,libraries:e?.libraries??[],logger:e?.systemLogger?.level??"warn"};return(window.IODesktop||window.Glue)(t)},operations$a={openWindow:{name:"openWindow",dataDecoder:openWindowConfigDecoder$1,resultDecoder:coreWindowDataDecoder},windowHello:{name:"windowHello",dataDecoder:windowHelloDecoder,resultDecoder:helloSuccessDecoder},windowAdded:{name:"windowAdded",dataDecoder:coreWindowDataDecoder},windowRemoved:{name:"windowRemoved",dataDecoder:simpleWindowDecoder$1},getBounds:{name:"getBounds",dataDecoder:simpleWindowDecoder$1,resultDecoder:windowBoundsResultDecoder$1},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleWindowDecoder$1,resultDecoder:frameWindowBoundsResultDecoder$1},getUrl:{name:"getUrl",dataDecoder:simpleWindowDecoder$1,resultDecoder:windowUrlResultDecoder$1},moveResize:{name:"moveResize",dataDecoder:windowMoveResizeConfigDecoder$1},focus:{name:"focus",dataDecoder:simpleWindowDecoder$1},close:{name:"close",dataDecoder:simpleWindowDecoder$1},getTitle:{name:"getTitle",dataDecoder:simpleWindowDecoder$1,resultDecoder:windowTitleConfigDecoder$1},setTitle:{name:"setTitle",dataDecoder:windowTitleConfigDecoder$1},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder$1},getChannel:{name:"getChannel",dataDecoder:simpleWindowDecoder$1,resultDecoder:windowChannelResultDecoder$1},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:channelsChangedDataDecoder},setZoomFactor:{name:"setZoomFactor",dataDecoder:windowZoomFactorConfigDecoder$1},zoomFactorChange:{name:"zoomFactorChange",dataDecoder:windowZoomFactorConfigDecoder$1},refresh:{name:"refresh",dataDecoder:simpleWindowDecoder$1},operationCheck:{name:"operationCheck"}};function createRegistry$1$1(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;ithis.registry.execute("context-updated",e)),this.me={id:this.id,name:this.name,isFocused:!1,zoomFactor:this.zoomFactor,getURL:this.getURL.bind(this),moveResize:this.moveResize.bind(this),resizeTo:this.resizeTo.bind(this),moveTo:this.moveTo.bind(this),focus:this.focus.bind(this),close:this.close.bind(this),getTitle:this.getTitle.bind(this),setTitle:this.setTitle.bind(this),getBounds:this.getBounds.bind(this),getContext:this.getContext.bind(this),updateContext:this.updateContext.bind(this),setContext:this.setContext.bind(this),refresh:this.refresh.bind(this),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this),getChannel:this.getChannel.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),zoomIn:this.zoomIn.bind(this),zoomOut:this.zoomOut.bind(this),setZoomFactor:this.setZoomFactor.bind(this),onZoomFactorChanged:this.onZoomFactorChanged.bind(this)},Object.defineProperties(this.me,{id:READONLY_PROPERTY_DESCRIPTOR,name:READONLY_PROPERTY_DESCRIPTOR,zoomFactor:{get:()=>this.zoomFactor,enumerable:!0}}),this.me}async getURL(){return(await this._bridge.send("windows",operations$a.getUrl,{windowId:this.id})).url}onFocusChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"):this.registry.add("focus-change",e)}async moveResize(e){const t=runDecoderWithIOError$1(boundsDecoder,e),r=Object.assign({},t,{windowId:this.id,relative:!1});return await this._bridge.send("windows",operations$a.moveResize,r),this.me}async resizeTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&runDecoderWithIOError$1(nonNegativeNumberDecoder$2$1,e),void 0!==t&&runDecoderWithIOError$1(nonNegativeNumberDecoder$2$1,t);const r=Object.assign({},{width:e,height:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",operations$a.moveResize,r),this.me}async moveTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&runDecoderWithIOError$1(number$2$1(),e),void 0!==t&&runDecoderWithIOError$1(number$2$1(),t);const r=Object.assign({},{top:e,left:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",operations$a.moveResize,r),this.me}async focus(){return"Platform"===this.name?window.open(void 0,this.id):await this._bridge.send("windows",operations$a.focus,{windowId:this.id}),this.me}async close(){return await this._bridge.send("windows",operations$a.close,{windowId:this.id}),this.me}async getTitle(){return(await this._bridge.send("windows",operations$a.getTitle,{windowId:this.id})).title}async setTitle(e){const t=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e);return await this._bridge.send("windows",operations$a.setTitle,{windowId:this.id,title:t}),this.me}async getBounds(){return(await this._bridge.send("windows",operations$a.getBounds,{windowId:this.id})).bounds}async getContext(){const e=await this._bridge.contextLib.get(this.myCtxKey),{___io___:t,...r}=e;return r}async updateContext(e){const t=runDecoderWithIOError$1(anyDecoder$1,e);return await this._bridge.contextLib.update(this.myCtxKey,t),this.me}async setContext(e){const t=runDecoderWithIOError$1(anyDecoder$1,e),r=await this._bridge.contextLib.get(this.myCtxKey),n=r.___io___?{...t,___io___:r.___io___}:t;return await this._bridge.contextLib.set(this.myCtxKey,n),this.me}onContextUpdated(e){if("function"!=typeof e)return ioError$1.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("context-updated",t=>{const{___io___:r,...n}=t;e(n,this.me)})}async getChannel(){return(await this._bridge.send("windows",operations$a.getChannel,{windowId:this.id},void 0,{includeOperationCheck:!0})).channel}onChannelsChanged(e){return this.registry.add("channels-changed",e)}getClosestZoomFactorIndex(e){const t=Object.entries(ZOOM_FACTORS$1).reduce((t,[r,n])=>Math.abs(n-e)<=Math.abs(ZOOM_FACTORS$1[t]-e)?parseInt(r):t,0),r=ZOOM_FACTORS$1[t];return r!==e&&this._logger.warn(`Zoom factor ${e} is not available, using closest value ${r} instead.`),t}async zoom(e){e!==this.zoomFactorIndex&&e in ZOOM_FACTORS$1&&(await this._bridge.send("windows",operations$a.setZoomFactor,{windowId:this.id,factorIndex:e},void 0,{includeOperationCheck:!0}),this.zoomFactorIndex=e)}async zoomIn(){return await this.zoom(this.zoomFactorIndex+1),this.me}async zoomOut(){return await this.zoom(this.zoomFactorIndex-1),this.me}async setZoomFactor(e){const t=runDecoderWithIOError$1(number$2$1(),e),r=this.getClosestZoomFactorIndex(t);return await this.zoom(r),this.me}onZoomFactorChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"):this.registry.add("zoom-factor-changed",e)}async refresh(){return await this._bridge.send("windows",operations$a.refresh,{windowId:this.id},void 0,{includeOperationCheck:!0}),this.me}}const commonOperations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder$1,resultDecoder:operationCheckResultDecoder$1},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:workspaceFrameBoundsResultDecoder,dataDecoder:simpleItemIdDecoder}},PromiseWrap$1=(e,t,r)=>new Promise((n,i)=>{let o=!0;const s=setTimeout(()=>{if(!o)return;o=!1;i(r||`Promise timeout hit: ${t}`)},t);e().then(e=>{o&&(o=!1,clearTimeout(s),n(e))}).catch(e=>{o&&(o=!1,clearTimeout(s),i(e))})}),PromisePlus$1$1=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});let WindowsController$1=class{supportedOperationsNames=[];focusEventHandler;registry=CallbackRegistryFactory$1$1();platformRegistration;ioc;bridge;publicWindowId;allWindowProjections=[];me;logger;isWorkspaceFrame;instanceId;channelsController;async start(e,t){this.logger=e.logger.subLogger("windows.controller.web"),this.logger.trace("starting the web windows controller"),this.publicWindowId=t.publicWindowId,this.addWindowOperationExecutors(),this.ioc=t,this.bridge=t.bridge,this.instanceId=e.interop.instance.instance,this.channelsController=t.channelsController,this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`),this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,await this.initializeFocusTracking(),this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning");const r=this.toApi();e.windows=r}handlePlatformShutdown(){this.registry.clear(),this.allWindowProjections=[],this.focusEventHandler&&(document.removeEventListener("visibilityChange",this.focusEventHandler),window.removeEventListener("focus",this.focusEventHandler),window.removeEventListener("blur",this.focusEventHandler))}async handleBridgeMessage(e){await this.platformRegistration;const t=runDecoderWithIOError$1(windowOperationTypesDecoder,e.operation),r=operations$a[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async open(e,t,r){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,t);const n=runDecoderWithIOError$1(windowOpenSettingsDecoder$1,r),i=await this.bridge.send("windows",operations$a.openWindow,{name:e,url:t,options:n});return this.waitForWindowAdded(i.windowId)}list(){return this.allWindowProjections.map(e=>e.api)}findById(e){return runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),this.allWindowProjections.find(t=>t.id===e)?.api}toApi(){return{open:this.open.bind(this),my:this.my.bind(this),list:this.list.bind(this),findById:this.findById.bind(this),onWindowAdded:this.onWindowAdded.bind(this),onWindowRemoved:this.onWindowRemoved.bind(this),onWindowGotFocus:this.onWindowGotFocus.bind(this),onWindowLostFocus:this.onWindowLostFocus.bind(this)}}addWindowOperationExecutors(){operations$a.focusChange.execute=this.handleFocusChangeEvent.bind(this),operations$a.windowAdded.execute=this.handleWindowAdded.bind(this),operations$a.windowRemoved.execute=this.handleWindowRemoved.bind(this),operations$a.getBounds.execute=this.handleGetBounds.bind(this),operations$a.getFrameBounds.execute=this.handleGetBounds.bind(this),operations$a.getTitle.execute=this.handleGetTitle.bind(this),operations$a.getUrl.execute=this.handleGetUrl.bind(this),operations$a.moveResize.execute=this.handleMoveResize.bind(this),operations$a.setTitle.execute=this.handleSetTitle.bind(this),operations$a.getChannel.execute=this.handleGetChannel.bind(this),operations$a.notifyChannelsChanged.execute=this.handleChannelsChanged.bind(this),operations$a.setZoomFactor.execute=this.handleSetZoomFactor.bind(this),operations$a.zoomFactorChange.execute=this.handleZoomFactorChanged.bind(this),operations$a.refresh.execute=this.handleRefresh.bind(this),operations$a.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$a)}my(){return Object.assign({},this.me)}onWindowAdded(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"):this.registry.add("window-added",e)}onWindowRemoved(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"):this.registry.add("window-removed",e)}onWindowGotFocus(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"):this.registry.add("window-got-focus",e)}onWindowLostFocus(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"):this.registry.add("window-lost-focus",e)}async sayHello(){return await this.bridge.send("windows",operations$a.windowHello,{windowId:this.publicWindowId})}async registerWithPlatform(){const{windows:e,isWorkspaceFrame:t}=await this.sayHello();if(this.isWorkspaceFrame=t,this.logger.trace("the platform responded to the hello message"),!this.isWorkspaceFrame&&this.publicWindowId){this.logger.trace("i am not treated as a workspace frame, setting my window");const t=e.find(e=>e.windowId===this.publicWindowId);if(!t){const t=e.map(e=>`${e.windowId}:${e.name}`).join(", ");return ioError$1.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${t}`)}const r=await this.ioc.buildWebWindow(this.publicWindowId,t.name,this.logger);this.me=r.api,this.allWindowProjections.push(r)}const r=await Promise.all(e.filter(e=>e.windowId!==this.publicWindowId).map(e=>this.ioc.buildWebWindow(e.windowId,e.name,this.logger)));this.logger.trace("all windows projections are completed, building the list collection"),this.allWindowProjections.push(...r)}async handleFocusChangeEvent(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);if(!t)return;t.model.processSelfFocusEvent(e.hasFocus);const r=e.hasFocus?"window-got-focus":"window-lost-focus";this.registry.execute(r,t.api)}async handleWindowAdded(e){if(this.allWindowProjections.some(t=>t.id===e.windowId))return;const t=await this.ioc.buildWebWindow(e.windowId,e.name,this.logger);this.allWindowProjections.push(t),this.registry.execute("window-added",t.api)}async handleWindowRemoved(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&(this.allWindowProjections=this.allWindowProjections.filter(t=>t.id!==e.windowId),t.model.clean(),this.registry.execute("window-removed",t.api))}async handleGetBounds(){return this.me||this.isWorkspaceFrame?{windowId:this.isWorkspaceFrame?"noop":this.me.id,bounds:{top:window.screenTop,left:window.screenLeft,width:window.innerWidth,height:window.innerHeight}}:ioError$1.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe")}async handleGetTitle(){return this.me?{windowId:this.me.id,title:document.title}:ioError$1.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe")}async handleGetUrl(){return this.me?{windowId:this.me.id,url:window.location.href}:ioError$1.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe")}async handleMoveResize(e){const t="number"==typeof e.top?e.top:e.relative?0:window.screenTop,r="number"==typeof e.left?e.left:e.relative?0:window.screenLeft,n="number"==typeof e.height?e.height:e.relative?0:window.innerHeight,i="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,o=e.relative?window.moveBy:window.moveTo,s=e.relative?window.resizeBy:window.resizeTo;o(r,t),s(i,n)}async handleSetTitle(e){document.title=e.title}async initializeFocusTracking(){if(this.isWorkspaceFrame)return void this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame");try{await this.bridge.send("windows",commonOperations.operationCheck,{operation:"focusChange"})}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client.")}const e=document.hasFocus();await this.transmitFocusChange(!0),e||await this.transmitFocusChange(!1),this.defineEventListeners()}processFocusEvent(){const e=document.hasFocus();this.transmitFocusChange(e)}waitForWindowAdded(e){const t=this.allWindowProjections.find(t=>t.id===e);return t?Promise.resolve(t.api):PromisePlus$1$1(t=>{const r=this.onWindowAdded(n=>{n.id===e&&(r(),t(n))})},3e4,`Timed out waiting for ${e} to be announced`)}async transmitFocusChange(e){const t={windowId:this.me?.id||`iframe-${this.instanceId}`,hasFocus:e};this.me&&(this.me.isFocused=e),await this.bridge.send("windows",operations$a.focusChange,t)}defineEventListeners(){this.focusEventHandler=this.processFocusEvent.bind(this),document.addEventListener("visibilityChange",this.focusEventHandler),window.addEventListener("focus",this.focusEventHandler),window.addEventListener("blur",this.focusEventHandler)}async handleGetChannel(){if(!this.me)return ioError$1.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe");const e=this.channelsController.my();return{...e?{channel:e}:{}}}async handleRefresh(){if(!this.me)return ioError$1.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe");setTimeout(()=>{window.location.reload()},0)}async handleChannelsChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t?.model.processChannelsChangedEvent(e.channelNames)}async handleSetZoomFactor(e){if(!this.me)return ioError$1.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe");document.body.style.zoom=`${ZOOM_FACTORS$1[e.factorIndex]}%`}async handleZoomFactorChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&t.model.processSelfZoomFactorChangedEvent(e.factorIndex)}};const GlueWebPlatformControlName$1="T42.Web.Platform.Control",GlueWebPlatformStreamName$1="T42.Web.Platform.Stream",GlueClientControlName$1="T42.Web.Client.Control",GlueCorePlusThemesStream$1="T42.Core.Plus.Themes.Stream";class GlueBridge{coreGlue;communicationId;platformMethodTimeoutMs=1e4;controllers;sub;running;constructor(e,t){this.coreGlue=e,this.communicationId=t}get contextLib(){return this.coreGlue.contexts}get interopInstance(){return this.coreGlue.interop.instance.instance}async stop(){this.running=!1,this.sub.close(),await this.coreGlue.interop.unregister(GlueClientControlName$1)}async start(e){this.running=!0,this.controllers=e,await Promise.all([this.checkWaitMethod(GlueWebPlatformControlName$1),this.checkWaitMethod(GlueWebPlatformStreamName$1)]);const t=this.communicationId,[r]=await Promise.all([this.coreGlue.interop.subscribe(GlueWebPlatformStreamName$1,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(GlueClientControlName$1,(e,t,r,n)=>this.passMessageController(e,r,n))]);this.sub=r,this.sub.onData(e=>this.passMessageController(e.data))}getInteropInstance(e){const t=this.coreGlue.interop.servers().find(t=>t.windowId&&t.windowId===e);return{application:t?.application,applicationName:t?.applicationName,peerId:t?.peerId,instance:t?.instance,windowId:t?.windowId}}async send(e,t,r,n,i){if(t.dataDecoder)try{t.dataDecoder.runWithException(r)}catch(e){return ioError$1.raiseError(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`)}if(!(!i?.includeOperationCheck||(await this.checkOperationSupported(e,t)).isSupported))return ioError$1.raiseError(`Cannot complete operation: ${t.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const i=await this.transmitMessage(e,t,r,n);return t.resultDecoder&&t.resultDecoder.runWithException(i),i}catch(e){return e?.kind?ioError$1.raiseError(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`):ioError$1.raiseError(e)}}async createNotificationsSteam(){return this.coreGlue.interop.methods().some(e=>e.name===GlueCorePlusThemesStream$1)?this.coreGlue.interop.subscribe(GlueCorePlusThemesStream$1,this.communicationId?{target:{instance:this.communicationId}}:void 0):ioError$1.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus.")}async checkOperationSupported(e,t){try{return await this.send(e,commonOperations.operationCheck,{operation:t.name})}catch(e){return{isSupported:!1}}}checkWaitMethod(e){return PromisePlus$1$1(t=>{if(this.coreGlue.interop.methods().some(t=>{const r=t.name===e,n=!this.communicationId||t.getServers().some(e=>e.instance===this.communicationId);return r&&n}))return t();const r=this.coreGlue.interop.serverMethodAdded(n=>{const i=n.method,o=n.server,s=!this.communicationId||o.instance===this.communicationId;i.name===e&&s&&(r(),t())})},this.platformMethodTimeoutMs,`Cannot initiate Glue Web, because a system method's discovery timed out: ${e}`)}passMessageController(e,t,r){const n=libDomainDecoder$1.run(e.domain);if(!n.ok)return void(r&&r(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(n.error)}`));const i=n.result;this.controllers[i].handleBridgeMessage(e).then(e=>{t&&t(e)}).catch(e=>{r&&r(e),console.warn(e)})}async transmitMessage(e,t,r,n){const i={domain:e,data:r,operation:t.name};let o;const s=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(t.name)} with data: ${JSON.stringify(r)}. `,a=this.communicationId;try{if(!this.running)throw new Error("Cannot send a control message, because the platform shut down");if(o=await this.coreGlue.interop.invoke(GlueWebPlatformControlName$1,i,a?{instance:this.communicationId}:void 0,n),!o)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(o.all_return_values)||0===o.all_return_values.length)throw new Error("Received unsupported result from the platform - empty values collection")}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;throw new Error(`${s} -> Inner message: ${t}`)}throw new Error(`${s} -> Inner message: ${e.message}`)}return o.all_return_values[0].returned}}const operations$9={appHello:{name:"appHello",dataDecoder:windowHelloDecoder,resultDecoder:appHelloSuccessDecoder$2},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:appDirectoryStateChangeDecoder},instanceStarted:{name:"instanceStarted",dataDecoder:instanceDataDecoder$1},instanceStopped:{name:"instanceStopped",dataDecoder:instanceDataDecoder$1},applicationStart:{name:"applicationStart",dataDecoder:applicationStartConfigDecoder$1,resultDecoder:instanceDataDecoder$1},instanceStop:{name:"instanceStop",dataDecoder:basicInstanceDataDecoder$1},import:{name:"import"},remove:{name:"remove",dataDecoder:appRemoveConfigDecoder$1},export:{name:"export",resultDecoder:appsExportOperationDecoder$1},clear:{name:"clear"},operationCheck:{name:"operationCheck"}};class AppManagerController{me;supportedOperationsNames=[];baseApplicationsTimeoutMS=6e4;appImportTimeoutMS=20;registry=CallbackRegistryFactory$1$1();ioc;bridge;publicWindowId;applications=[];instances=[];platformRegistration;logger;channelsController;interop;initialChannelId;handlePlatformShutdown(){this.registry.clear(),this.applications=[],this.instances=[],delete this.me}async start(e,t){this.logger=e.logger.subLogger("appManger.controller.web"),this.logger.trace("starting the web appManager controller"),this.publicWindowId=t.publicWindowId,this.addOperationsExecutors(),this.ioc=t,this.bridge=t.bridge,this.channelsController=t.channelsController,this.interop=e.interop,this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning");const r=this.toApi();e.appManager=r}async postStart(){this.initialChannelId&&await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId)}async handleBridgeMessage(e){await this.platformRegistration;const t=runDecoderWithIOError$1(appManagerOperationTypesDecoder$1,e.operation),r=operations$9[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}onInstanceStarted(e){return"function"!=typeof e?ioError$1.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){return"function"!=typeof e?ioError$1.raiseError("onInstanceStopped requires a single argument of type function"):this.registry.add("instance-stopped",e)}async startApplication(e,t,r){const n=await this.channelsController.all();if(r?.channelId&&!n.includes(r.channelId))return ioError$1.raiseError(`The channel with name "${r.channelId}" doesn't exist!`);const i={name:e,waitForAGMReady:r?.waitForAGMReady??!0,context:t,top:r?.top,left:r?.left,width:r?.width,height:r?.height,relativeTo:r?.relativeTo,relativeDirection:r?.relativeDirection,id:r?.reuseId,forceChromeTab:r?.forceTab,layoutComponentId:r?.layoutComponentId,channelId:r?.channelId,startReason:{originApp:{name:this.me?.application.name,interopInstance:this.interop.instance.instance}}};r?.originIntentRequest&&(i.startReason.intentRequest=r.originIntentRequest);const o=await this.bridge.send("appManager",operations$9.applicationStart,i),s=this.applications.find(e=>e.name===o.applicationName);return this.ioc.buildInstance(o,s)}getApplication(e){const t=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e);return this.applications.find(e=>e.name===t)}getInstances(){return this.instances.slice()}onAppAdded(e){return"function"!=typeof e?ioError$1.raiseError("onAppAdded requires a single argument of type function"):this.registry.add("application-added",e,this.applications)}onAppRemoved(e){return"function"!=typeof e?ioError$1.raiseError("onAppRemoved requires a single argument of type function"):this.registry.add("application-removed",e)}toApi(){return{myInstance:this.me,inMemory:{import:this.importApps.bind(this),remove:this.remove.bind(this),export:this.exportApps.bind(this),clear:this.clear.bind(this)},application:this.getApplication.bind(this),applications:this.getApplications.bind(this),instances:this.getInstances.bind(this),onAppAdded:this.onAppAdded.bind(this),onAppChanged:this.onAppChanged.bind(this),onAppRemoved:this.onAppRemoved.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)}}addOperationsExecutors(){operations$9.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),operations$9.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),operations$9.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this),operations$9.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$9)}async handleAppDirectoryStateChange(e){e.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)),e.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)),e.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this))}onAppChanged(e){return"function"!=typeof e?ioError$1.raiseError("onAppChanged requires a single argument of type function"):this.registry.add("application-changed",e)}async handleApplicationAddedMessage(e){if(this.applications.some(t=>t.name===e.name))return;const t=await this.ioc.buildApplication(e,[]),r=this.instances.filter(e=>e.application.name===t.name);t.instances.push(...r),this.applications.push(t),this.registry.execute("application-added",t)}async handleApplicationRemovedMessage(e){const t=this.applications.findIndex(t=>t.name===e.name);if(t<0)return;const r=this.applications[t];this.applications.splice(t,1),this.registry.execute("application-removed",r)}async handleApplicationChangedMessage(e){const t=this.applications.find(t=>t.name===e.name);if(!t)return this.handleApplicationAddedMessage(e);t.title=e.title,t.version=e.version,t.icon=e.icon,t.caption=e.caption,t.userProperties=e.userProperties,this.registry.execute("application-changed",t)}async handleInstanceStartedMessage(e){if(this.instances.some(t=>t.id===e.id))return;const t=this.applications.find(t=>t.name===e.applicationName);if(!t)return ioError$1.raiseError(`Cannot add instance: ${e.id}, because there is no application definition associated with it`);const r=this.ioc.buildInstance(e,t);this.instances.push(r),t.instances.push(r),this.registry.execute("instance-started",r)}async handleInstanceStoppedMessage(e){const t=this.instances.find(t=>t.id===e.id);if(t){const t=this.instances.findIndex(t=>t.id===e.id);this.instances.splice(t,1)}const r=this.applications.find(t=>t.instances.some(t=>t.id===e.id));if(r){const t=r.instances.findIndex(t=>t.id===e.id);r.instances.splice(t,1)}t&&this.registry.execute("instance-stopped",t)}async importApps(e,t="replace"){if(runDecoderWithIOError$1(importModeDecoder$1,t),!Array.isArray(e))return ioError$1.raiseError("Import must be called with an array of definitions");if(e.length>1e4)return ioError$1.raiseError("Cannot import more than 10000 app definitions in Glue42 Core.");const r=e.reduce((e,t)=>{const{isValid:r,error:n}=this.isValidDefinition(t);return r?e.valid.push(t):e.invalid.push({app:t?.name,error:n??`Provided definition is invalid ${JSON.stringify(t)}`}),e},{valid:[],invalid:[]}),n=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*r.valid.length;return await this.bridge.send("appManager",operations$9.import,{definitions:r.valid,mode:t},{methodResponseTimeoutMs:n}),{imported:r.valid.map(e=>e.name),errors:r.invalid}}isValidDefinition(e){if(e?.appId&&e?.details){const t=decoders$2.fdc3.v2DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v2 definition. Error: ${JSON.stringify(t.error)}`}}if(e?.appId&&e?.manifest){const t=decoders$2.fdc3.v1DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v1 definition. Error: ${JSON.stringify(t.error)}`}}const t=applicationDefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid definition. Error: ${JSON.stringify(t.error)}`}}async remove(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),await this.bridge.send("appManager",operations$9.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async clear(){await this.bridge.send("appManager",operations$9.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async exportApps(){return(await this.bridge.send("appManager",operations$9.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}getApplications(){return this.applications.slice()}async registerWithPlatform(){const e=await this.bridge.send("appManager",operations$9.appHello,{windowId:this.publicWindowId},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS});this.logger.trace("the platform responded to the hello message with a full list of apps"),this.applications=await Promise.all(e.apps.map(e=>this.ioc.buildApplication(e,e.instances))),this.instances=this.applications.reduce((e,t)=>(e.push(...t.instances),e),[]),this.me=this.findMyInstance(),this.logger.trace(`all applications were parsed and saved. I am ${this.me?"NOT a":"a"} valid instance`),this.initialChannelId=e.initialChannelId}findMyInstance(){for(const e of this.applications){const t=e.instances.find(e=>e.id===this.publicWindowId);if(t)return t}}}class InstanceModel{data;bridge;application;me;myCtxKey;constructor(e,t,r){this.data=e,this.bridge=t,this.application=r,this.myCtxKey=`___instance___${this.data.id}`}toApi(){const e=this.bridge.getInteropInstance(this.data.id),t={id:this.data.id,agm:e,application:this.application,stop:this.stop.bind(this),getContext:this.getContext.bind(this)};return this.me=Object.freeze(t),this.me}async getContext(){return this.bridge.contextLib.get(this.myCtxKey)}async stop(){await this.bridge.send("appManager",operations$9.instanceStop,{id:this.data.id})}}class ApplicationModel{data;instances;controller;me;constructor(e,t,r){this.data=e,this.instances=t,this.controller=r}toApi(){const e={name:this.data.name,title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,userProperties:this.data.userProperties,instances:this.instances,start:this.start.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){return"function"!=typeof e?ioError$1.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStarted(t=>{t.application.name===this.data.name&&e(t)})}onInstanceStopped(e){return"function"!=typeof e?ioError$1.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStopped(t=>{t.application.name===this.data.name&&e(t)})}async start(e,t){const r=runDecoderWithIOError$1(startApplicationContextDecoder,e),n=runDecoderWithIOError$1(startApplicationOptionsDecoder,t);return this.controller.startApplication(this.data.name,r,n)}}const operations$8={layoutAdded:{name:"layoutAdded",dataDecoder:glueLayoutDecoder$1},layoutChanged:{name:"layoutChanged",dataDecoder:glueLayoutDecoder$1},layoutRemoved:{name:"layoutRemoved",dataDecoder:glueLayoutDecoder$1},layoutRestored:{name:"layoutRestored",dataDecoder:glueLayoutDecoder$1},defaultLayoutChanged:{name:"defaultLayoutChanged",dataDecoder:defaultGlobalChangedDecoder},layoutRenamed:{name:"layoutRenamed",dataDecoder:renamedLayoutNotificationDecoder},get:{name:"get",dataDecoder:simpleLayoutConfigDecoder$1,resultDecoder:optionalSimpleLayoutResult$1},getAll:{name:"getAll",dataDecoder:getAllLayoutsConfigDecoder$1,resultDecoder:allLayoutsSummariesResultDecoder$1},export:{name:"export",dataDecoder:getAllLayoutsConfigDecoder$1,resultDecoder:allLayoutsFullConfigDecoder$1},import:{name:"import",dataDecoder:layoutsImportConfigDecoder$1},remove:{name:"remove",dataDecoder:simpleLayoutConfigDecoder$1},rename:{name:"rename",dataDecoder:renameLayoutConfigDecoder$1,resultDecoder:layoutResultDecoder$1},save:{name:"save",dataDecoder:saveLayoutConfigDecoder$1,resultDecoder:simpleLayoutResultDecoder},restore:{name:"restore",dataDecoder:restoreLayoutConfigDecoder$1},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:platformSaveRequestConfigDecoder,resultDecoder:saveRequestClientResponseDecoder},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:permissionStateResultDecoder$1},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:simpleAvailabilityResultDecoder$1},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:simpleAvailabilityResultDecoder$1},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:optionalSimpleLayoutResult$1},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:setDefaultGlobalConfigDecoder$1},clearDefaultGlobal:{name:"clearDefaultGlobal"},getCurrent:{name:"getCurrent",resultDecoder:optionalSimpleLayoutResult$1},updateMetadata:{name:"updateMetadata",dataDecoder:updateLayoutMetadataConfigDecoder$1},operationCheck:{name:"operationCheck"}};let LayoutsController$1=class{supportedOperationsNames=[];defaultLayoutRestoreTimeoutMS=12e4;registry=CallbackRegistryFactory$1$1();bridge;logger;windowsController;saveRequestSubscription;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("layouts.controller.web"),this.logger.trace("starting the web layouts controller"),this.bridge=t.bridge,this.windowsController=t.windowsController,this.addOperationsExecutors();const r=this.toApi();this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"),e.layouts=r}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(layoutsOperationTypesDecoder$1,e.operation),r=operations$8[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),getCurrentLayout:this.getCurrentLayout.bind(this),export:this.exportLayouts.bind(this),import:this.importLayouts.bind(this),save:this.save.bind(this),restore:this.restore.bind(this),remove:this.remove.bind(this),onAdded:this.onAdded.bind(this),onChanged:this.onChanged.bind(this),onRemoved:this.onRemoved.bind(this),onDefaultGlobalChanged:this.onDefaultGlobalChanged.bind(this),onSaveRequested:this.subscribeOnSaveRequested.bind(this),getMultiScreenPermissionState:this.getGlobalPermissionState.bind(this),requestMultiScreenPermission:this.requestGlobalPermission.bind(this),getGlobalTypeState:this.checkGlobalActivated.bind(this),getDefaultGlobal:this.getDefaultGlobal.bind(this),setDefaultGlobal:this.setDefaultGlobal.bind(this),clearDefaultGlobal:this.clearDefaultGlobal.bind(this),rename:this.rename.bind(this),onRenamed:this.onRenamed.bind(this),onRestored:this.onRestored.bind(this),updateMetadata:this.updateMetadata.bind(this)};return Object.freeze(e)}addOperationsExecutors(){operations$8.layoutAdded.execute=this.handleOnAdded.bind(this),operations$8.layoutChanged.execute=this.handleOnChanged.bind(this),operations$8.layoutRemoved.execute=this.handleOnRemoved.bind(this),operations$8.layoutRenamed.execute=this.handleOnRenamed.bind(this),operations$8.layoutRestored.execute=this.handleOnRestored.bind(this),operations$8.defaultLayoutChanged.execute=this.handleOnDefaultChanged.bind(this),operations$8.clientSaveRequest.execute=this.handleSaveRequest.bind(this),operations$8.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$8)}async get(e,t){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),runDecoderWithIOError$1(layoutTypeDecoder$1,t);return(await this.bridge.send("layouts",operations$8.get,{name:e,type:t})).layout}async getCurrentLayout(){return(await this.bridge.send("layouts",operations$8.getCurrent,void 0)).layout}async getAll(e){runDecoderWithIOError$1(layoutTypeDecoder$1,e);return(await this.bridge.send("layouts",operations$8.getAll,{type:e})).summaries}async exportLayouts(e){runDecoderWithIOError$1(layoutTypeDecoder$1,e);return(await this.bridge.send("layouts",operations$8.export,{type:e})).layouts}async importLayouts(e,t="replace"){if(runDecoderWithIOError$1(importModeDecoder$1,t),!Array.isArray(e))return ioError$1.raiseError("Import must be called with an array of layouts");if(e.length>1e3)return ioError$1.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core.");const r=e.reduce((e,t)=>{const r=glueLayoutDecoder$1.run(t);return r.ok?e.valid.push(t):this.logger.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]}),n=e.filter(e=>r.valid.some(t=>t.name===e.name));await this.bridge.send("layouts",operations$8.import,{layouts:n,mode:t})}async save(e){runDecoderWithIOError$1(newLayoutOptionsDecoder$1,e);return(await this.bridge.send("layouts",operations$8.save,{layout:e})).layout}async restore(e){runDecoderWithIOError$1(restoreOptionsDecoder$1,e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;await this.bridge.send("layouts",operations$8.restore,{layout:e},{methodResponseTimeoutMs:t})}async remove(e,t){runDecoderWithIOError$1(layoutTypeDecoder$1,e),runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,t),await this.bridge.send("layouts",operations$8.remove,{type:e,name:t})}async handleSaveRequest(e){const t={};if(this.saveRequestSubscription)try{const r=this.saveRequestSubscription(e);t.windowContext=r?.windowContext}catch(e){this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(e)}`)}return t}async getGlobalPermissionState(){return await this.bridge.send("layouts",operations$8.getGlobalPermissionState,void 0)}async requestGlobalPermission(){const e=(await this.getGlobalPermissionState()).state;if("denied"===e)return{permissionGranted:!1};if("granted"===e)return{permissionGranted:!0};const t=this.windowsController.my(),r=(window.glue42core||window.iobrowser).isPlatformFrame;if("Platform"!==t.name&&!r)return ioError$1.raiseError("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(await this.bridge.send("layouts",operations$8.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}async checkGlobalActivated(){return{activated:(await this.bridge.send("layouts",operations$8.checkGlobalActivated,void 0)).isAvailable}}async getDefaultGlobal(){return(await this.bridge.send("layouts",operations$8.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}async setDefaultGlobal(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),await this.bridge.send("layouts",operations$8.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}async clearDefaultGlobal(){await this.bridge.send("layouts",operations$8.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}async rename(e,t){runDecoderWithIOError$1(glueLayoutDecoder$1,e),runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,t);return await this.bridge.send("layouts",operations$8.rename,{layout:e,newName:t},void 0,{includeOperationCheck:!0})}async updateMetadata(e){runDecoderWithIOError$1(glueLayoutDecoder$1,e),await this.bridge.send("layouts",operations$8.updateMetadata,{layout:e},void 0,{includeOperationCheck:!0})}onAdded(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"):(this.exportLayouts("Global").then(t=>t.forEach(t=>e(t))).catch(()=>{}),this.exportLayouts("Workspace").then(t=>t.forEach(t=>e(t))).catch(()=>{}),this.registry.add(operations$8.layoutAdded.name,e))}onChanged(e){return this.registry.add(operations$8.layoutChanged.name,e)}onDefaultGlobalChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"):(this.getDefaultGlobal().then(t=>e(t?{name:t.name}:void 0)).catch(()=>{}),this.registry.add(operations$8.defaultLayoutChanged.name,e))}onRemoved(e){return this.registry.add(operations$8.layoutRemoved.name,e)}onRenamed(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"):this.registry.add(operations$8.layoutRenamed.name,e)}onRestored(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"):this.registry.add(operations$8.layoutRestored.name,e)}subscribeOnSaveRequested(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."):this.saveRequestSubscription?ioError$1.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."):(this.saveRequestSubscription=e,()=>{delete this.saveRequestSubscription})}async handleOnAdded(e){this.registry.execute(operations$8.layoutAdded.name,e)}async handleOnChanged(e){this.registry.execute(operations$8.layoutChanged.name,e)}async handleOnDefaultChanged(e){this.registry.execute(operations$8.defaultLayoutChanged.name,e)}async handleOnRemoved(e){this.registry.execute(operations$8.layoutRemoved.name,e)}async handleOnRestored(e){this.registry.execute(operations$8.layoutRestored.name,e)}async handleOnRenamed(e){const{prevName:t,...r}=e;this.registry.execute(operations$8.layoutRenamed.name,r,{name:t})}};const operations$7={raiseNotification:{name:"raiseNotification",dataDecoder:raiseNotificationDecoder$1,resultDecoder:raiseNotificationResultDecoder$1},requestPermission:{name:"requestPermission",resultDecoder:permissionRequestResultDecoder$1},notificationShow:{name:"notificationShow",dataDecoder:notificationEventPayloadDecoder},notificationClick:{name:"notificationClick",dataDecoder:notificationEventPayloadDecoder},getPermission:{name:"getPermission",resultDecoder:permissionQueryResultDecoder$1},list:{name:"list",resultDecoder:allNotificationsDataDecoder$1},notificationRaised:{name:"notificationRaised",dataDecoder:simpleNotificationDataDecoder},notificationClosed:{name:"notificationClosed",dataDecoder:simpleNotificationSelectDecoder$1},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"},clearOld:{name:"clearOld"},configure:{name:"configure",dataDecoder:notificationsConfigurationProtocolDecoder$1},getConfiguration:{name:"getConfiguration",resultDecoder:strictNotificationsConfigurationProtocolDecoder},getActiveCount:{name:"getActiveCount",resultDecoder:activeNotificationsCountChangeDecoder},configurationChanged:{name:"configurationChanged",resultDecoder:strictNotificationsConfigurationProtocolDecoder},setState:{name:"setState",dataDecoder:notificationSetStateRequestDecoder$1},activeCountChange:{name:"activeCountChange",resultDecoder:activeNotificationsCountChangeDecoder},stateChange:{name:"stateChange",resultDecoder:notificationSetStateRequestDecoder$1},operationCheck:{name:"operationCheck"}};let urlAlphabet$1$1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$1$1=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$1$1[64*Math.random()|0];return t},NotificationsController$1=class{supportedOperationsNames=[];registry=CallbackRegistryFactory$1$1();logger;bridge;notificationsSettings;notifications={};coreGlue;buildNotificationFunc;notificationsConfiguration;notificationsActiveCount=0;handlePlatformShutdown(){this.notifications={},this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("notifications.controller.web"),this.logger.trace("starting the web notifications controller"),this.bridge=t.bridge,this.coreGlue=e,this.notificationsSettings=t.config.notifications,this.buildNotificationFunc=t.buildNotification,this.notificationsConfiguration=await this.getConfiguration(),this.notificationsActiveCount=await this.getActiveCount();const r=this.toApi();this.addOperationExecutors(),e.notifications=r,this.logger.trace("notifications are ready")}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(notificationsOperationTypesDecoder,e.operation),r=operations$7[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}toApi(){const e={raise:this.raise.bind(this),requestPermission:this.requestPermission.bind(this),getPermission:this.getPermission.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onClosed:this.onClosed.bind(this),click:this.click.bind(this),clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),getFilter:this.getFilter.bind(this),setFilter:this.setFilter.bind(this),setState:this.setState.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onActiveCountChanged:this.onActiveCountChanged.bind(this),onCounterChanged:this.onActiveCountChanged.bind(this),onStateChanged:this.onStateChanged.bind(this)};return Object.freeze(e)}async getPermission(){return(await this.bridge.send("notifications",operations$7.getPermission,void 0)).permission}async requestPermission(){return(await this.bridge.send("notifications",operations$7.requestPermission,void 0)).permissionGranted}async raise(e){const t=runDecoderWithIOError$1(glue42NotificationOptionsDecoder$1,e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!await this.requestPermission())return ioError$1.raiseError("Cannot raise the notification, because the user has declined the permission request");const r=nanoid$1$1(10),n=await this.bridge.send("notifications",operations$7.raiseNotification,{settings:t,id:r}),i=this.buildNotificationFunc(n.settings,r);return this.notifications[r]=i,i}async list(){return(await this.bridge.send("notifications",operations$7.list,void 0,void 0,{includeOperationCheck:!0})).notifications}onRaised(e){return"function"!=typeof e?ioError$1.raiseError("onRaised expects a callback of type function"):this.registry.add("notification-raised",e)}onClosed(e){return"function"!=typeof e?ioError$1.raiseError("onClosed expects a callback of type function"):this.registry.add("notification-closed",e)}async click(e,t){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),t&&runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,t),await this.bridge.send("notifications",operations$7.click,{id:e,action:t},void 0,{includeOperationCheck:!0})}async clear(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),await this.bridge.send("notifications",operations$7.clear,{id:e},void 0,{includeOperationCheck:!0})}async clearAll(){await this.bridge.send("notifications",operations$7.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearOld(){await this.bridge.send("notifications",operations$7.clearOld,void 0,void 0,{includeOperationCheck:!0})}async configure(e){const t=runDecoderWithIOError$1(notificationsConfigurationDecoder$1,e);await this.bridge.send("notifications",operations$7.configure,{configuration:t},void 0,{includeOperationCheck:!0})}async getConfiguration(){return(await this.bridge.send("notifications",operations$7.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration}async getActiveCount(){try{return(await this.bridge.send("notifications",operations$7.getActiveCount,void 0,void 0,{includeOperationCheck:!0})).count}catch(e){return console.warn("Failed to get accurate active notifications count",e),0}}async getFilter(){return(await this.bridge.send("notifications",operations$7.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration.sourceFilter}async setFilter(e){const t=runDecoderWithIOError$1(notificationFilterDecoder$1,e);return await this.bridge.send("notifications",operations$7.configure,{configuration:{sourceFilter:t}},void 0,{includeOperationCheck:!0}),t}async setState(e,t){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),runDecoderWithIOError$1(notificationStateDecoder$1,t),await this.bridge.send("notifications",operations$7.setState,{id:e,state:t},void 0,{includeOperationCheck:!0})}onConfigurationChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"):(setTimeout(()=>e(this.notificationsConfiguration),0),this.registry.add("notifications-config-changed",e))}onActiveCountChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"):(setTimeout(()=>e({count:this.notificationsActiveCount}),0),this.registry.add("notifications-active-count-changed",e))}onStateChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"):this.registry.add("notification-state-changed",e)}addOperationExecutors(){operations$7.notificationShow.execute=this.handleNotificationShow.bind(this),operations$7.notificationClick.execute=this.handleNotificationClick.bind(this),operations$7.notificationRaised.execute=this.handleNotificationRaised.bind(this),operations$7.notificationClosed.execute=this.handleNotificationClosed.bind(this),operations$7.configurationChanged.execute=this.handleConfigurationChanged.bind(this),operations$7.activeCountChange.execute=this.handleActiveCountChanged.bind(this),operations$7.stateChange.execute=this.handleNotificationStateChanged.bind(this),operations$7.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$7)}async handleConfigurationChanged(e){this.notificationsConfiguration=e.configuration,this.registry.execute("notifications-config-changed",e.configuration)}async handleActiveCountChanged(e){this.notificationsActiveCount=e.count,this.registry.execute("notifications-active-count-changed",e)}async handleNotificationStateChanged(e){this.registry.execute("notification-state-changed",{id:e.id},e.state)}async handleNotificationShow(e){if(!e.id)return;const t=this.notifications[e.id];t&&t.onshow&&t.onshow()}async handleNotificationClick(e){if(!e.action&&this.notificationsSettings?.defaultClick&&this.notificationsSettings.defaultClick(this.coreGlue,e.definition),e.action&&this.notificationsSettings?.actionClicks?.some(t=>t.action===e.action)){const t=this.notificationsSettings?.actionClicks?.find(t=>t.action===e.action);t.handler(this.coreGlue,e.definition)}if(!e.id)return;const t=this.notifications[e.id];t&&t.onclick&&(t.onclick(),delete this.notifications[e.id])}async handleNotificationRaised(e){this.registry.execute("notification-raised",e.notification)}async handleNotificationClosed(e){this.registry.execute("notification-closed",e)}};const operations$6={getIntents:{name:"getIntents",resultDecoder:wrappedIntentsDecoder$1},findIntent:{name:"findIntent",dataDecoder:wrappedIntentFilterDecoder$1,resultDecoder:wrappedIntentsDecoder$1},raise:{name:"raise",dataDecoder:raiseIntentRequestDecoder$1,resultDecoder:intentResultDecoder$1},filterHandlers:{name:"filterHandlers",dataDecoder:filterHandlersWithResolverConfigDecoder$1,resultDecoder:filterHandlersResultDecoder$1},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:intentHandlerDecoder$1,resultDecoder:getIntentsResultDecoder$1}},GLUE42_FDC3_INTENTS_METHOD_PREFIX="Tick42.FDC3.Intents.",INTENTS_RESOLVER_APP_NAME="intentsResolver",DEFAULT_RESOLVER_RESPONSE_TIMEOUT=6e4,ADDITIONAL_BRIDGE_OPERATION_TIMEOUT=3e4,DEFAULT_PICK_HANDLER_BY_TIMEOUT=9e4;let IntentsController$1=class{bridge;logger;interop;appManagerController;windowsController;myIntents=new Set;prefsController;uiController;useIntentsResolverUI=!0;intentsResolverAppName;intentResolverResponseTimeout=DEFAULT_RESOLVER_RESPONSE_TIMEOUT;unregisterIntentPromises=[];async start(e,t){this.logger=e.logger.subLogger("intents.controller.web"),this.logger.trace("starting the web intents controller"),this.bridge=t.bridge,this.interop=e.interop,this.appManagerController=t.appManagerController,this.windowsController=t.windowsController,this.prefsController=t.prefsController,this.uiController=t.uiController,this.checkIfIntentsResolverIsEnabled(t.config);const r=this.toApi();this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"),e.intents=r}handlePlatformShutdown(){this.myIntents=new Set,this.unregisterIntentPromises=[]}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(intentsOperationTypesDecoder$1,e.operation),r=operations$6[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}toApi(){return{raise:this.raise.bind(this),all:this.all.bind(this),addIntentListener:this.addIntentListener.bind(this),register:this.register.bind(this),find:this.find.bind(this),filterHandlers:this.filterHandlers.bind(this),getIntents:this.getIntentsByHandler.bind(this),clearSavedHandlers:this.clearSavedHandlers.bind(this),onHandlerAdded:this.onHandlerAdded.bind(this),onHandlerRemoved:this.onHandlerRemoved.bind(this)}}async raise(e){const t=runDecoderWithIOError$1(raiseRequestDecoder,e),r="string"==typeof t?{intent:t}:t;await Promise.all(this.unregisterIntentPromises),r.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${r.intent}`),await this.removeRememberedHandler(r.intent));const n=await this.checkHandleRaiseWithRememberedHandler(r);if(n)return n;const i={intentRequest:r,resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:r}),embeddedResolverConfig:this.getEmbeddedResolverConfig()},o=r.waitUserResponseIndefinitely?MAX_SET_TIMEOUT_DELAY$1:(r.timeout||this.intentResolverResponseTimeout)+ADDITIONAL_BRIDGE_OPERATION_TIMEOUT;this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${o}ms`);const s=await this.bridge.send("intents",operations$6.raise,i,{methodResponseTimeoutMs:o,waitTimeoutMs:o});return this.logger.trace(`Raise operation completed with response: ${JSON.stringify(s)}`),s}getLegacyResolverConfigByRequest(e){if(e.handlerFilter)return{enabled:"boolean"==typeof e.handlerFilter?.openResolver?e.handlerFilter?.openResolver:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.handlerFilter?.timeout||DEFAULT_PICK_HANDLER_BY_TIMEOUT};const t=e.intentRequest?.waitUserResponseIndefinitely?MAX_SET_TIMEOUT_DELAY$1:this.intentResolverResponseTimeout;return{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:t}}getEmbeddedResolverConfig(){return{enabled:this.uiController.isIntentResolverEnabled(),initialCaller:{instanceId:this.interop.instance.instance}}}async all(){await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",operations$6.getIntents,void 0)).intents}addIntentListener(e,t){if(runDecoderWithIOError$1(AddIntentListenerDecoder,e),"function"!=typeof t)return ioError$1.raiseError("Cannot add intent listener, because the provided handler is not a function!");let r;const n="string"==typeof e?e:e.intent,i=this.buildInteropMethodName(n);if(this.myIntents.has(n))return ioError$1.raiseError(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);const o={unsubscribe:()=>{this.myIntents.delete(n),r.then(()=>this.interop.unregister(i)).catch(e=>this.logger.trace(`Unregistration of a method with name ${i} failed with reason: ${e}`))}};let s={};if("object"==typeof e){const{intent:t,...r}=e;s=r}return r=this.interop.register({name:i,flags:{intent:s}},e=>{if(this.myIntents.has(n)){const{_initialCallerId:r,...n}=e;return t(n)}}),r.catch(e=>{this.myIntents.delete(n),this.logger.warn(`Registration of a method with name ${i} failed with reason: ${e}`)}),o}async register(e,t){if(runDecoderWithIOError$1(AddIntentListenerDecoder,e),"function"!=typeof t)return ioError$1.raiseError("Cannot add intent listener, because the provided handler is not a function!");await Promise.all(this.unregisterIntentPromises);const r="string"==typeof e?e:e.intent,n=this.buildInteropMethodName(r);if(this.myIntents.has(r))return ioError$1.raiseError(`Intent listener for intent ${r} already registered!`);this.myIntents.add(r);let i={};if("object"==typeof e){const{intent:t,...r}=e;i=r}try{await this.interop.register({name:n,flags:{intent:i}},e=>{if(this.myIntents.has(r)){const{_initialCallerId:r,...n}=e,i=this.interop.servers().find(e=>e.instance===r);return t(n,i)}})}catch(e){return this.myIntents.delete(r),ioError$1.raiseError(`Registration of a method with name ${n} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(r)}}async find(e){let t;if(void 0!==e){const r=runDecoderWithIOError$1(findFilterDecoder,e);"string"==typeof r?t={filter:{name:r}}:"object"==typeof r&&(t={filter:r})}await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",operations$6.findIntent,t)).intents}onHandlerAdded(e){if("function"!=typeof e)return ioError$1.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppAdded",e),r=this.subscribeForServerMethodEvent("serverMethodAdded",e);return()=>{t(),r()}}onHandlerRemoved(e){if("function"!=typeof e)return ioError$1.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppRemoved",e),r=this.subscribeForServerMethodEvent("serverMethodRemoved",e);return()=>{t(),r()}}subscribeForAppEvent(e,t){return this.appManagerController[e](e=>{const r=e.userProperties.intents;r?.length&&r.forEach(r=>{const n=this.buildIntentHandlerFromApp(e,r);t(n,r.name)})})}subscribeForServerMethodEvent(e,t){return this.interop[e](async({server:r,method:n})=>{if(!n.name.startsWith(GLUE42_FDC3_INTENTS_METHOD_PREFIX))return;const i=n.name.replace(GLUE42_FDC3_INTENTS_METHOD_PREFIX,""),o=await this.buildIntentHandlerFromServerMethod(e,r,n,i);t(o,i)})}buildIntentHandlerFromApp(e,t){return{applicationName:e.name,type:"app",applicationDescription:e.caption,applicationIcon:e.icon,applicationTitle:e.title,contextTypes:t.contexts,displayName:t.displayName,resultType:t.resultType,customConfig:t.customConfig}}async buildIntentHandlerFromServerMethod(e,t,r,n){const i=r.flags.intent,o=this.appManagerController.getApplication(t.application||t.applicationName);let s;"serverMethodAdded"===e&&t.windowId&&(s=await(this.windowsController.findById(t.windowId)?.getTitle()));const a=o?.userProperties?.intents?.find(e=>e.name===n);return{applicationName:t.application||t.applicationName||"",instanceId:t.windowId||t.instance,type:"instance",applicationIcon:i?.icon||o?.icon,applicationTitle:o?.title,applicationDescription:i?.description||o?.caption,contextTypes:i?.contextTypes||a?.contexts,instanceTitle:s,displayName:i?.displayName||a?.displayName,resultType:i?.resultType||a?.resultType,customConfig:i?.customConfig}}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:void 0})}checkIfIntentsResolverIsEnabled(e){this.useIntentsResolverUI="boolean"!=typeof e.intents?.enableIntentsResolverUI||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=e.intents?.intentsResolverAppName??INTENTS_RESOLVER_APP_NAME,this.intentResolverResponseTimeout=e.intents?.methodResponseTimeoutMs??DEFAULT_RESOLVER_RESPONSE_TIMEOUT}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter(t=>t!==e)}buildInteropMethodName(e){return`${GLUE42_FDC3_INTENTS_METHOD_PREFIX}${e}`}unsubscribeIntent(e){this.myIntents.delete(e);const t=this.buildInteropMethodName(e),r=this.interop.unregister(t);this.unregisterIntentPromises.push(r),r.then(()=>{this.clearUnregistrationPromise(r)}).catch(e=>{this.logger.error(`Unregistration of a method with name ${t} failed with reason: ${e}`),this.clearUnregistrationPromise(r)})}async filterHandlers(e){runDecoderWithIOError$1(handlerFilterDecoder$1,e),this.checkIfAtLeastOneFilterIsPresent(e);const t=this.getEmbeddedResolverConfig();if(e.openResolver&&!this.useIntentsResolverUI&&!t.enabled)return ioError$1.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");const r=(e.timeout||DEFAULT_PICK_HANDLER_BY_TIMEOUT)+ADDITIONAL_BRIDGE_OPERATION_TIMEOUT,n={filterHandlersRequest:e,resolverConfig:this.getLegacyResolverConfigByRequest({handlerFilter:e}),embeddedResolverConfig:t};return await this.bridge.send("intents",operations$6.filterHandlers,n,{methodResponseTimeoutMs:r,waitTimeoutMs:r},{includeOperationCheck:!0})}checkIfAtLeastOneFilterIsPresent(e){const t="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)return ioError$1.raiseError(t);const{intent:r,resultType:n,contextTypes:i,applicationNames:o}=e,s=i?.length,a=o?.length;return r||n||s||a?void 0:ioError$1.raiseError(t)}async getIntentsByHandler(e){runDecoderWithIOError$1(intentHandlerDecoder$1,e);return await this.bridge.send("intents",operations$6.getIntentsByHandler,e,void 0,{includeOperationCheck:!0})}async removeRememberedHandler(e){let t;this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const r=t.data?.intents;if(!r)return void this.logger.trace("No app prefs found for current app");delete r[e];const n={...t.data,intents:r};try{await this.prefsController.update(n)}catch(e){return void this.logger.warn(`prefs.update() threw the following error: ${e}`)}this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){let t;try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const r=t.data?.intents?.[e.intent];return r?.handler}async checkHandleRaiseWithRememberedHandler(e){if(e.target)return;const t=await this.checkForRememberedHandler(e);if(!t)return;const r={intentRequest:{...e,target:{app:t.applicationName,instance:t.instanceId}},resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:e}),embeddedResolverConfig:this.getEmbeddedResolverConfig()};try{return await this.bridge.send("intents",operations$6.raise,r)}catch(t){this.logger.trace(`Could not raise intent to remembered handler. Reason: ${t}. Removing it from Prefs store`),await this.removeRememberedHandler(e.intent)}}};const operations$5={appHello:{name:"appHello",dataDecoder:channelsAppHelloDataDecoder,resultDecoder:channelsAppHelloSuccessDecoder},addChannel:{name:"addChannel",dataDecoder:channelDefinitionDecoder$2},removeChannel:{name:"removeChannel",dataDecoder:removeChannelDataDecoder$1},getMyChannel:{name:"getMyChannel",resultDecoder:getMyChanelResultDecoder$1},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",dataDecoder:getWindowIdsOnChannelDataDecoder$1,resultDecoder:getWindowIdsOnChannelResultDecoder$1},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",dataDecoder:wrappedWindowWithChannelFilterDecoder$1,resultDecoder:getWindowIdsWithChannelsResultDecoder$1},joinChannel:{name:"joinChannel",dataDecoder:joinChannelDataDecoder$1},restrict:{name:"restrict",dataDecoder:restrictionConfigDataDecoder$1},getRestrictions:{name:"getRestrictions",dataDecoder:getRestrictionsDataDecoder$1,resultDecoder:restrictionsDecoder$1},restrictAll:{name:"restrictAll",dataDecoder:restrictAllDataDecoder$1},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:channelsChangedDataDecoder},leaveChannel:{name:"leaveChannel",dataDecoder:leaveChannelDataDecoder},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:requestChannelSelectorConfigDecoder$1},getMode:{name:"getMode",resultDecoder:getChannelsModeDecoder$1},operationCheck:{name:"operationCheck"}},DEFAULT_MODE="single",CHANNELS_PREFIX="___channel___",SUBS_KEY="subs",CHANGED_KEY="changed",CHANNELS_CHANGED="channels_changed",STORAGE_NAMESPACE="io_connect_channels",DEFAULT_STORAGE_MODE="inMemory";let ChannelsController$1=class{supportedOperationsNames=[];registry=CallbackRegistryFactory$1$1();logger;contexts;interop;bridge;windowsController;_mode;myWindowId;storage;handlePlatformShutdown(){this.registry.clear(),this.storage.clear()}addOperationsExecutors(){operations$5.getMyChannel.execute=this.handleGetMyChannel.bind(this),operations$5.joinChannel.execute=this.handleJoinChannel.bind(this),operations$5.leaveChannel.execute=this.handleLeaveChannel.bind(this),operations$5.restrict.execute=this.handleRestrict.bind(this),operations$5.getRestrictions.execute=({windowId:e})=>this.getRestrictions(e),operations$5.restrictAll.execute=this.handleRestrictAll.bind(this),operations$5.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$5)}async start(e,t){this.logger=e.logger.subLogger("channels.controller.web"),this.logger.trace("starting the web channels controller"),this.contexts=e.contexts,this.interop=e.interop,this.addOperationsExecutors(),this.bridge=t.bridge,this.windowsController=t.windowsController,this.storage=t.channelsStorage,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"),this.myWindowId=this.windowsController.my().id??this.interop.instance.instance,await this.initialize();const r=this.toApi();e.channels=r}async postStart(e,t){try{await this.requestChannelSelector(e.appManager.myInstance)}catch(e){this.logger.warn(`Failed to display channel selector: ${extractErrorMsg$2(e)}`)}}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(channelsOperationTypesDecoder,e.operation),r=operations$5[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async list(){const e=this.getAllChannelNames();return await Promise.all(e.map(e=>this.get(e)))}my(){return this.current()}async handleGetMyChannel(){const e=this.my();return e?{channel:e}:{}}async join(e,t){const r=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(r),e),runDecoderWithIOError$1(optionalNonEmptyStringDecoder,t);const n={channel:e,windowId:t??this.myWindowId};await this.bridge.send("channels",operations$5.joinChannel,n,void 0,{includeOperationCheck:!0})}handleJoinChannel({channel:e}){return"single"===this._mode?this.switchToChannel(e):this.joinAdditionalChannel(e)}onChanged(e){return this.changed(e)}async leave(e={}){if(runDecoderWithIOError$1(leaveChannelsConfig,e),e.channel){const t=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(t),e.channel)}const t={channelName:e.channel,windowId:e.windowId??this.myWindowId};await this.bridge.send("channels",operations$5.leaveChannel,t,void 0,{includeOperationCheck:!0})}async handleAppManagerInitialChannelId(e){if("inMemory"!==this.storage.mode&&!this.storage.getSessionStorageData())return this.handleJoinChannel({channel:e,windowId:this.myWindowId})}async handleLeaveChannel({channelName:e}){const t=e?[e]:this.storage.channels;t.forEach(e=>this.storage.invokeUnsubscribes(e)),this.storage.channels=this.storage.channels.filter(e=>!t.includes(e)),this.executeChangedEvents(),await this.notifyChannelsChanged()}toApi(){const e={mode:this._mode,subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),publish:this.publish.bind(this),all:this.all.bind(this),list:this.list.bind(this),get:this.get.bind(this),getMyChannels:this.getMyChannels.bind(this),myChannels:this.myChannels.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),join:this.join.bind(this),leave:this.leave.bind(this),current:this.current.bind(this),my:this.my.bind(this),changed:this.changed.bind(this),onChanged:this.onChanged.bind(this),add:this.add.bind(this),remove:this.remove.bind(this),getMy:this.getMy.bind(this),getWindowsOnChannel:this.getWindowsOnChannel.bind(this),getWindowsWithChannels:this.getWindowsWithChannels.bind(this),restrict:this.restrict.bind(this),getRestrictions:this.getRestrictions.bind(this),restrictAll:this.restrictAll.bind(this),clearChannelData:this.clearChannelData.bind(this),setPath:this.setPath.bind(this),setPaths:this.setPaths.bind(this)};return Object.freeze(e)}createContextName(e){return`${CHANNELS_PREFIX}${e}`}getAllChannelNames(){return this.contexts.all().filter(e=>e.startsWith(CHANNELS_PREFIX)).map(e=>e.replace(CHANNELS_PREFIX,""))}async joinAdditionalChannel(e){if(this.storage.channels.includes(e))return;this.storage.channels=[...this.storage.channels,e];const t=this.createContextName(e),r=await this.contexts.subscribe(t,(e,t,r,n,i)=>{this.registry.execute(SUBS_KEY,e.data,e,t,i?.updaterId)});this.storage.addUnsubscribe(e,r),this.executeChangedEvents(e),await this.notifyChannelsChanged()}async switchToChannel(e){const t=this.storage.channels[0];if(e===t)return;this.storage.invokeUnsubscribes(t),this.storage.channels=[e];const r=this.createContextName(e),n=await this.contexts.subscribe(r,(e,t,r,n,i)=>{this.registry.execute(SUBS_KEY,e.data,e,t,i?.updaterId)});this.storage.addUnsubscribe(e,n),this.executeChangedEvents(e),await this.notifyChannelsChanged()}executeChangedEvents(e){this.registry.execute(CHANGED_KEY,e),this.registry.execute(CHANNELS_CHANGED,this.storage.channels)}async notifyChannelsChanged(){const e=this.windowsController.my().id;if(e)try{await this.bridge.send("channels",operations$5.notifyChannelsChanged,{channelNames:this.storage.channels,windowId:e},void 0,{includeOperationCheck:!0})}catch(e){this.logger.warn(`Failed to notify channel changed: ${extractErrorMsg$2(e)}`)}}async updateData(e,t){const r=this.createContextName(e),n=this.getFDC3Type(t);if(this.contexts.setPathSupported){const e=Object.keys(t).map(e=>({path:`data.${e}`,value:t[e]}));n&&e.push({path:latestFDC3Type,value:n}),await this.contexts.setPaths(r,e)}else n&&(t[latestFDC3Type]=n),await this.contexts.update(r,{data:t})}getFDC3Type(e){const t=Object.keys(e).filter(e=>0===e.indexOf("fdc3_"));if(0!==t.length)return t.length>1?ioError$1.raiseError("FDC3 does not support updating of multiple context keys"):t[0].split("_").slice(1).join("_")}subscribe(e,t){if("function"!=typeof e)return ioError$1.raiseError("Cannot subscribe to channels, because the provided callback is not a function!");t&&runDecoderWithIOError$1(fdc3OptionsDecoder,t);const r=this.current(),n=t?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(e,t.contextType):this.getWrappedSubscribeCallback(e);return r&&this.replaySubscribe(n,r),this.registry.add(SUBS_KEY,n)}async subscribeFor(e,t,r){const n=this.getAllChannelNames();if(runDecoderWithIOError$1(channelNameDecoder(n),e),"function"!=typeof t)return ioError$1.raiseError(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);r&&runDecoderWithIOError$1(fdc3OptionsDecoder,r);const i=this.createContextName(e),o=r?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(t,r.contextType):this.getWrappedSubscribeCallback(t);return this.contexts.subscribe(i,(e,t,r,n,i)=>{o(e.data,e,t,i?.updaterId)})}async publish(e,t){if("object"!=typeof e)return ioError$1.raiseError("Cannot publish to channel, because the provided data is not an object!");if(runDecoderWithIOError$1(publishOptionsDecoder,t),"object"==typeof t)return this.publishWithOptions(e,t);if("string"==typeof t){const e=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(e),t)}if(!t&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e);const r="string"==typeof t?t:this.storage.channels[0];if(!r)return ioError$1.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(r,"write")?this.updateData(r,e):ioError$1.raiseError(`Cannot publish on channel ${r} due to restrictions`)}async all(){return this.getAllChannelNames()}async get(e,t){const r=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(r),e),t&&runDecoderWithIOError$1(fdc3OptionsDecoder,t);const n=this.createContextName(e),i=await this.contexts.get(n);return t?.contextType?this.getContextForFdc3Type(i,t.contextType):i.latest_fdc3_type?this.getContextWithFdc3Data(i):i}async getMyChannels(){return Promise.all(this.storage.channels.map(e=>{const t=this.createContextName(e);return this.contexts.get(t)}))}myChannels(){return this.storage.channels}getContextForFdc3Type(e,t){const r=`fdc3_${t.split(".").join("&")}`;if(!e.data[r])return{name:e.name,meta:e.meta,data:{}};const n={type:t,...e.data[r]};return{name:e.name,meta:e.meta,data:{fdc3:n}}}getContextWithFdc3Data(e){const{latest_fdc3_type:t,...r}=e,n={type:t.split("&").join("."),...r.data[`fdc3_${t}`]};delete r.data[`fdc3_${t}`];return{name:e.name,meta:e.meta,data:{...r.data,fdc3:n}}}current(){return this.storage.channels[0]}changed(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"):this.registry.add(CHANGED_KEY,e)}async add(e){const t=runDecoderWithIOError$1(channelDefinitionDecoder$2,e);return this.getAllChannelNames().includes(t.name)?ioError$1.raiseError("There's an already existing channel with such name"):(await this.bridge.send("channels",operations$5.addChannel,t),{name:t.name,meta:t.meta,data:t.data||{}})}async remove(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e);if(!this.getAllChannelNames().includes(e))return ioError$1.raiseError("There's no channel with such name");await this.bridge.send("channels",operations$5.removeChannel,{name:e},void 0,{includeOperationCheck:!0})}replaySubscribe=(e,t)=>{this.get(t).then(t=>{if(!t)return;const r=this.createContextName(t.name);return this.contexts.subscribe(r,(t,r,n,i,o)=>{e(t.data,t,r,o?.updaterId)})}).then(e=>e?.()).catch(e=>this.logger.trace(e))};async getMy(e){if(this.storage.channels.length)return e&&runDecoderWithIOError$1(fdc3OptionsDecoder,e),this.get(this.storage.channels[this.storage.channels.length-1],e)}async getWindowsOnChannel(e){const t=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(t),e);const{windowIds:r}=await this.bridge.send("channels",operations$5.getWindowIdsOnChannel,{channel:e},void 0,{includeOperationCheck:!0});return r.reduce((e,t)=>{const r=this.windowsController.findById(t);return r?[...e,r]:e},[])}async getWindowsWithChannels(e){const t=void 0!==e?{filter:runDecoderWithIOError$1(windowWithChannelFilterDecoder$1,e)}:{},{windowIdsWithChannels:r}=await this.bridge.send("channels",operations$5.getWindowIdsWithChannels,t,void 0,{includeOperationCheck:!0}),n=r.reduce((e,{application:t,channel:r,windowId:n})=>{const i=this.windowsController.findById(n);return i?[...e,{application:t,channel:r,window:i}]:e},[]);return n}async clearChannelData(e){await this.handleSetPaths("clearChannelData",[{path:"data",value:{}},{path:"latest_fdc3_type",value:null}],e)}async restrict(e){runDecoderWithIOError$1(channelRestrictionsDecoder$1,e);const t=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(t),e.name);const r={config:{...e,windowId:e.windowId??this.myWindowId}};await this.bridge.send("channels",operations$5.restrict,r,void 0,{includeOperationCheck:!0})}async handleRestrict({config:e}){const t=await this.getMy();if(!t)return this.updateRestriction(e);const r=this.isAllowedByRestrictions(t.name,"read");this.updateRestriction(e);e.name===t.name&&!r&&e.read&&this.replaySubscribeCallback(e.name)}updateRestriction(e){const t=this.storage.restrictions.some(t=>t.name===e.name);this.storage.restrictions=t?this.storage.restrictions.map(t=>t.name===e.name?e:t):this.storage.restrictions.concat(e)}updateAllRestrictions(e){const t=this.getAllChannelNames();this.storage.restrictions=t.map(t=>({name:t,...e}))}async getRestrictions(e){runDecoderWithIOError$1(optionalNonEmptyStringDecoder,e);const t=e&&e!==this.interop.instance.instance;return e&&t?this.bridge.send("channels",operations$5.getRestrictions,{windowId:e},void 0,{includeOperationCheck:!0}):{channels:this.storage.restrictions}}async restrictAll(e){runDecoderWithIOError$1(restrictionsConfigDecoder$1,e);const t={restrictions:{...e,windowId:e.windowId??this.myWindowId}};return this.bridge.send("channels",operations$5.restrictAll,t,void 0,{includeOperationCheck:!0})}async handleRestrictAll({restrictions:e}){const t=await this.getMy();if(!t)return this.updateAllRestrictions(e);const r=this.isAllowedByRestrictions(t.name,"read");this.updateAllRestrictions(e),!r&&e.read&&this.replaySubscribeCallback(t.name)}async setPath(e,t){const r=runDecoderWithIOError$1(pathValueDecoder,e),n=[{path:`data.${r.path}`,value:r.value}];await this.handleSetPaths("setPath",n,t)}async setPaths(e,t){const r=runDecoderWithIOError$1(pathsValueDecoder,e).map(({path:e,value:t})=>({path:`data.${e}`,value:t}));await this.handleSetPaths("setPaths",r,t)}async handleSetPaths(e,t,r){const n=r?[r]:this.storage.channels;if(!n.length)return ioError$1.raiseError(`Cannot complete ${e} operation, because channel is not specified. Either join one or pass a channel name as second argument!`);this.validateChannelNames(n);const{allowed:i,forbidden:o}=this.groupChannelsByPermission("write",n);if(n.length===o.length)return ioError$1.raiseError(`Cannot complete ${e} operation due to write restrictions to the following channels: ${n.join(", ")}`);o.length&&this.logger.warn(`Cannot set paths on channel${o.length>1?"s":""}: ${o.join(", ")} due to write restrictions`),await Promise.all(i.map(e=>{const r=this.createContextName(e);return this.contexts.setPaths(r,t)}))}validateChannelNames(e){const t=this.getAllChannelNames();e.forEach(e=>runDecoderWithIOError$1(channelNameDecoder(t),e))}groupChannelsByPermission(e,t){return t.reduce((t,r)=>(this.isAllowedByRestrictions(r,e)?t.allowed.push(r):t.forbidden.push(r),t),{allowed:[],forbidden:[]})}isAllowedByRestrictions(e,t){const r=this.storage.restrictions.find(t=>t.name===e);return!r||r[t]}replaySubscribeCallback(e){const t=this.createContextName(e);this.contexts.subscribe(t,(e,t,r,n,i)=>{this.registry.execute(SUBS_KEY,e.data,e,t,i?.updaterId)}).then(e=>{e&&"function"==typeof e&&e()}).catch(e=>this.logger.error(e))}async publishWithOptions(e,t){if(t.name){const e=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(e),t.name)}if(!t.name&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e,t.fdc3);const r=t.name||this.storage.channels[0];if(!r)return ioError$1.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(r,"write")?t.fdc3?this.publishFdc3Data(r,e):this.updateData(r,e):ioError$1.raiseError(`Cannot publish on channel ${r} due to restrictions`)}async publishOnMultipleChannels(e,t){const{allowed:r,forbidden:n}=this.groupChannelsByPermission("write",this.storage.channels);if(this.storage.channels.length===n.length)return ioError$1.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`);n.length&&this.logger.warn(`Data on channel${n.length>1?"s":""}: ${n.join(", ")} won't be published due to write restrictions`);const i=t?this.publishFdc3Data.bind(this):this.updateData.bind(this);await Promise.all(r.map(t=>i(t,e)))}async publishFdc3Data(e,t){runDecoderWithIOError$1(fdc3ContextDecoder,t);const{type:r,...n}=t,i=r.split(".").join("&"),o={[`fdc3_${i}`]:n};return this.updateData(e,o)}getWrappedSubscribeCallback(e){return(t,r,n,i)=>{if(!this.isAllowedByRestrictions(r.name,"read"))return;const{data:o,latest_fdc3_type:s}=r,a=`fdc3_${s}`;if(!s||n.data&&!n.data[a])return void e(t,r,i);const c={type:s.split("&").join("."),...o[a]},{[a]:l,...u}=t;e({...u,fdc3:c},r,i)}}getWrappedSubscribeCallbackWithFdc3Type(e,t){const r={replayed:!1};return(n,i,o,s)=>{if(!this.isAllowedByRestrictions(i.name,"read"))return;const{data:a,latest_fdc3_type:c}=i,l=`fdc3_${t.split(".").join("&")}`;if(!a[l]||o.data&&!o.data[l])return;if(r.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:c,searchedType:t,callback:e,context:i,updaterId:s});const u={type:t,...a[l]};e({fdc3:u},i,s),r.replayed=!0}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:r,callback:n,context:i,updaterId:o}=e;if(t.split("&").join(".")!==r)return;n({fdc3:{type:r,...i.data[`fdc3_${t}`]}},i,o)}async requestChannelSelector(e){if(!e)return;const t=e.application,r=t.userProperties?.details;if(!r)return;if(!r?.channelSelector?.enabled)return;const n={windowId:e.id,channelsNames:this.storage.channels};await this.bridge.send("channels",operations$5.requestChannelSelector,n,void 0,{includeOperationCheck:!0})}async getPlatformChannelsMode(){try{return(await this.bridge.send("channels",operations$5.getMode,{},void 0,{includeOperationCheck:!0})).mode}catch(e){return this.logger.warn(e?.message||JSON.stringify(e)),DEFAULT_MODE}}onChannelsChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"):this.registry.add(CHANNELS_CHANGED,e)}async initialize(){if(!await this.checkIfAppHelloSupported())return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions");const{success:e,error:t}=await this.sendAppHello();if(t)return this.handleAppHelloFailure(t);this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(e)}`);const{mode:r,channels:n,restrictions:i}=e;this.storage.mode="inMemory",this._mode=r,this.storage.channels=n,this.storage.restrictions=i}async handleAppHelloFailure(e){this.logger.trace(e),this.storage.mode="sessionStorage",this._mode=await this.getPlatformChannelsMode()}async sendAppHello(){try{return{success:await this.bridge.send("channels",operations$5.appHello,{windowId:this.myWindowId},void 0,{includeOperationCheck:!0}),error:void 0}}catch(e){return{error:`Failed to get initial state from platform. Error: ${extractErrorMsg$2(e)}`,success:void 0}}}async checkIfAppHelloSupported(){try{const{isSupported:e}=await this.bridge.send("channels",operations$5.operationCheck,{operation:operations$5.appHello.name},void 0,{includeOperationCheck:!0});return e}catch(e){return this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${extractErrorMsg$2(e)}`),!1}}};const operations$4={getEnvironment:{name:"getEnvironment",resultDecoder:anyDecoder$1},getBase:{name:"getBase",resultDecoder:anyDecoder$1},platformShutdown:{name:"platformShutdown"},isFdc3DataWrappingSupported:{name:"isFdc3DataWrappingSupported"},clientError:{name:"clientError",dataDecoder:clientErrorDataDecoder$1},systemHello:{name:"systemHello",resultDecoder:systemHelloSuccessDecoder$1},operationCheck:{name:"operationCheck"}};let SystemController$1=class{supportedOperationsNames=[];bridge;ioc;logger;errorPort=errorChannel$1.port2;async start(e,t){this.logger=e.logger.subLogger("system.controller.web"),this.logger.trace("starting the web system controller"),this.bridge=t.bridge,this.ioc=t,this.addOperationsExecutors();let r=!1;try{const e=await this.bridge.send("system",operations$4.systemHello,void 0,void 0,{includeOperationCheck:!0});r=e.isClientErrorOperationSupported}catch(e){this.logger.warn("The platform of this client is outdated and does not support some system operations.")}this.errorPort.onmessage=async e=>{r&&await this.bridge.send("system",operations$4.clientError,{message:e.data},void 0,{includeOperationCheck:!0})},await this.setEnvironment()}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(systemOperationTypesDecoder$1,e.operation),r=operations$4[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async processPlatformShutdown(){Object.values(this.ioc.controllers).forEach(e=>e.handlePlatformShutdown?e.handlePlatformShutdown():null),this.ioc.preferredConnectionController.stop(),this.ioc.eventsDispatcher.stop(),await this.bridge.stop()}async setEnvironment(){const e=await this.bridge.send("system",operations$4.getEnvironment,void 0),t=await this.bridge.send("system",operations$4.getBase,void 0),r=window.glue42core||window.iobrowser,n=window.glue42core?"glue42core":"iobrowser",i=Object.assign({},r,t,{environment:e});window[n]=i}addOperationsExecutors(){operations$4.platformShutdown.execute=this.processPlatformShutdown.bind(this),operations$4.isFdc3DataWrappingSupported.execute=this.handleIsFdc3DataWrappingSupported.bind(this),operations$4.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$4)}async handleIsFdc3DataWrappingSupported(){return{isSupported:!0}}},Notification$1=class{onclick=()=>{};onshow=()=>{};id;title;badge;body;data;dir;icon;image;lang;renotify;requireInteraction;silent;tag;timestamp;vibrate;clickInterop;actions;focusPlatformOnDefaultClick;severity;showToast;showInPanel;state;constructor(e,t){this.id=t,this.badge=e.badge,this.body=e.body,this.data=e.data,this.dir=e.dir,this.icon=e.icon,this.image=e.image,this.lang=e.lang,this.renotify=e.renotify,this.requireInteraction=e.requireInteraction,this.silent=e.silent,this.tag=e.tag,this.timestamp=e.timestamp,this.vibrate=e.vibrate,this.title=e.title,this.clickInterop=e.clickInterop,this.actions=e.actions,this.focusPlatformOnDefaultClick=e.focusPlatformOnDefaultClick,this.severity=e.severity,this.showToast=e.showToast,this.showInPanel=e.showInPanel,this.state=e.state}};oneOf$1$1(constant$2$1("clientHello"));const extensionConfigDecoder=object$2$1({widget:object$2$1({inject:boolean$2$1()})}),operations$3={clientHello:{name:"clientHello",resultDecoder:extensionConfigDecoder}};class ExtController{windowId;logger;bridge;eventsDispatcher;channelsController;config;channels=[];unsubFuncs=[];contentCommands={widgetVisualizationPermission:{name:"widgetVisualizationPermission",handle:this.handleWidgetVisualizationPermission.bind(this)},changeChannel:{name:"changeChannel",handle:this.handleChangeChannel.bind(this)}};handlePlatformShutdown(){this.unsubFuncs.forEach(e=>e()),this.channels=[],this.unsubFuncs=[]}async start(e,t){this.logger=e.logger.subLogger("extension.controller.web"),this.windowId=t.publicWindowId,this.logger.trace("starting the extension web controller"),this.bridge=t.bridge,this.channelsController=t.channelsController,this.eventsDispatcher=t.eventsDispatcher;try{await this.registerWithPlatform()}catch(e){return}this.channels=await this.channelsController.list();const r=this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)),n=this.channelsController.onChanged(e=>{this.eventsDispatcher.sendContentMessage({command:"channelChange",newChannel:e})});this.unsubFuncs.push(r),this.unsubFuncs.push(n)}async handleBridgeMessage(e){}handleContentMessage(e){if(!e||"string"!=typeof e.command)return;const t=this.contentCommands[e.command];t&&t.handle(e)}async registerWithPlatform(){this.logger.trace("registering with the platform"),this.config=await this.bridge.send("extension",operations$3.clientHello,{windowId:this.windowId}),this.logger.trace("the platform responded to the hello message with a valid extension config")}async handleWidgetVisualizationPermission(){if(!this.config?.widget.inject)return this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!1});const e=this.channels.find(e=>e.name===this.channelsController.my());this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!0,channels:this.channels,currentChannel:e})}async handleChangeChannel(e){"no-channel"!==e.name?await this.channelsController.join(e.name):await this.channelsController.leave()}}class EventsDispatcher{config;glue;registry=CallbackRegistryFactory$1$1();glue42EventName="Glue42";_handleMessage;_resolveWidgetReadyPromise;_resolveModalsUIFactoryReadyPromise;_resolveIntentResolverUIFactoryReadyPromise;constructor(e){this.config=e}events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},contentInc:{name:"contentInc",handle:this.handleContentInc.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)},widgetFactoryReady:{name:"widgetFactoryReady",handle:this.handleWidgetReady.bind(this)},modalsUIFactoryReady:{name:"modalsUIFactoryReady",handle:this.handleModalsUIFactoryReady.bind(this)},intentResolverUIFactoryReady:{name:"intentResolverUIFactoryReady",handle:this.handleIntentResolverUIFactoryReady.bind(this)}};stop(){window.removeEventListener(this.glue42EventName,this._handleMessage)}start(e){this.glue=e,this.wireCustomEventListener(),this.announceStarted()}sendContentMessage(e){this.send("contentOut","glue42core",e)}onContentMessage(e){return this.registry.add("content-inc",e)}async widgetReady(){const e=new Promise(e=>{this._resolveWidgetReadyPromise=e});return this.requestWidgetReady(),e}async modalsUIFactoryReady(){const e=new Promise(e=>{this._resolveModalsUIFactoryReadyPromise=e});return this.requestModalsUIFactoryReady(),e}async intentResolverUIFactoryReady(){const e=new Promise(e=>{this._resolveIntentResolverUIFactoryReadyPromise=e});return this.requestIntentResolverUIFactoryReady(),e}wireCustomEventListener(){this._handleMessage=this.handleMessage.bind(this),window.addEventListener(this.glue42EventName,this._handleMessage)}handleMessage(e){const t=e.detail,r=t?.glue42??t?.glue42core;if(!r)return;const n=r.event,i=this.events[n];i&&i.handle(r.message)}announceStarted(){this.send("start","glue42")}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse","glue42",{glue:this.glue}):this.send("requestGlueResponse","glue42",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}handleContentInc(e){this.registry.execute("content-inc",e)}requestWidgetReady(){this.send(REQUEST_WIDGET_READY,"glue42")}handleWidgetReady(){this._resolveWidgetReadyPromise?.()}requestModalsUIFactoryReady(){this.send(REQUEST_MODALS_UI_FACTORY_READY,"glue42")}handleModalsUIFactoryReady(){this._resolveModalsUIFactoryReadyPromise?.()}requestIntentResolverUIFactoryReady(){this.send(REQUEST_INTENT_RESOLVER_UI_FACTORY_READY,"glue42")}handleIntentResolverUIFactoryReady(){this._resolveIntentResolverUIFactoryReadyPromise?.()}send(e,t,r){const n={};n[t]={event:e,message:r};const i=new CustomEvent(this.glue42EventName,{detail:n});window.dispatchEvent(i)}}let PreferredConnectionController$1=class{coreGlue;transactionTimeout=15e3;transactionLocks={};webPlatformTransport;webPlatformMessagesUnsubscribe;reconnectCounter=0;logger;constructor(e){this.coreGlue=e,this.logger=this.coreGlue.logger.subLogger("web.preferred.connection.controller")}stop(){this.webPlatformMessagesUnsubscribe&&this.webPlatformMessagesUnsubscribe()}async start(e){if(e.isPlatformInternal)return void this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic.");if(!(this.coreGlue.connection.transport.name()===webPlatformTransportName$1))return ioError$1.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport.");if(!this.coreGlue.connection.transport.isPreferredActivated)return void this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization.");this.webPlatformTransport=this.coreGlue.connection.transport,this.webPlatformMessagesUnsubscribe=this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this));const t=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(t)}handleWebPlatformMessage(e){if("string"==typeof e)return;const t=this.coreGlue.connection.transport.name()===webPlatformTransportName$1,r=e.type,n=e.args,i=e.transactionId;return r===Glue42CoreMessageTypes$1.transportSwitchRequest.name?this.handleTransportSwitchRequest(n,i):r!==Glue42CoreMessageTypes$1.platformUnload.name||t?r===Glue42CoreMessageTypes$1.getCurrentTransportResponse.name?this.handleGetCurrentTransportResponse(n,i):r===Glue42CoreMessageTypes$1.checkPreferredLogic.name?this.handleCheckPreferredLogic(i):r===Glue42CoreMessageTypes$1.checkPreferredConnection.name?this.handleCheckPreferredConnection(n,i):void 0:this.handlePlatformUnload()}async reEstablishPlatformPort(){try{await this.webPlatformTransport.connect()}catch(e){if(this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(e)}`),--this.reconnectCounter,this.reconnectCounter>0)return this.reEstablishPlatformPort();this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform.")}this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."),this.reconnectCounter=0,this.webPlatformTransport.close();const e=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(e)}async checkSwitchTransport(e){const t=this.coreGlue.connection.transport.name();if(t===e.transportName)return void this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary");this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${t}, but it should reconnect to ${JSON.stringify(e)}`);const r=await this.coreGlue.connection.switchTransport(e);this.setConnected(),this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(r)}`)}async getCurrentPlatformTransportState(){this.logger.trace("Requesting the current transport state of the platform.");const e=this.setTransaction(Glue42CoreMessageTypes$1.getCurrentTransport.name);this.sendPlatformMessage(Glue42CoreMessageTypes$1.getCurrentTransport.name,e.id);const t=await e.lock;return this.logger.trace(`The platform responded with transport state: ${JSON.stringify(t)}`),t}setTransaction(e){const t={},r=nanoid$1$1(10),n=new Promise((n,i)=>{let o=!0;t.lift=e=>{o=!1,delete this.transactionLocks[r],n(e)},t.fail=e=>{o=!1,delete this.transactionLocks[r],i(e)},setTimeout(()=>{o&&(o=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[r],i(`Transaction for operation: ${e} timed out.`))},this.transactionTimeout)});return t.lock=n,t.id=r,this.transactionLocks[r]=t,t}sendPlatformMessage(e,t,r){this.logger.trace(`Sending a platform message of type: ${e}, id: ${t} and args: ${JSON.stringify(r)}`),this.webPlatformTransport.sendObject({glue42core:{type:e,args:r,transactionId:t}})}handleTransportSwitchRequest(e,t){this.logger.trace(`Received a transport switch request with id: ${t} and data: ${JSON.stringify(e)}`),this.coreGlue.connection.switchTransport(e.switchSettings).then(e=>{this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(e)}`),this.setConnected(),this.sendPlatformMessage(Glue42CoreMessageTypes$1.transportSwitchResponse.name,t,{success:e.success})}).catch(e=>{this.logger.error(e),this.sendPlatformMessage(Glue42CoreMessageTypes$1.transportSwitchResponse.name,t,{success:!1})})}handlePlatformUnload(){this.reconnectCounter=5,this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."),this.reEstablishPlatformPort()}handleGetCurrentTransportResponse(e,t){this.logger.trace(`Got a current transport response from the platform with id: ${t} and data: ${JSON.stringify(e)}`);const r=e.transportState,n=this.transactionLocks[t];n?.lift(r)}handleCheckPreferredLogic(e){setTimeout(()=>this.sendPlatformMessage(Glue42CoreMessageTypes$1.checkPreferredLogicResponse.name,e),0)}handleCheckPreferredConnection(e,t){const r=e.url;this.logger.trace(`Testing the possible connection to: ${r}`),this.checkPreferredConnection(r).then(e=>{this.logger.trace(`The connection to ${r} is possible`),this.sendPlatformMessage(Glue42CoreMessageTypes$1.checkPreferredConnectionResponse.name,t,e)}).catch(e=>{this.logger.trace(`The connection to ${r} is not possible`),this.sendPlatformMessage(Glue42CoreMessageTypes$1.checkPreferredConnectionResponse.name,t,{error:e})})}checkPreferredConnection(e){return new Promise(t=>{const r=new WebSocket(e);r.onerror=()=>t({live:!1}),r.onopen=()=>{r.close(),t({live:!0})}})}setConnected(){this.webPlatformTransport.manualSetReadyState()}};const operations$2={getCurrent:{name:"getCurrent",resultDecoder:simpleThemeResponseDecoder$1},list:{name:"list",resultDecoder:allThemesResponseDecoder$1},select:{name:"select",dataDecoder:selectThemeConfigDecoder$1}};let ThemesController$1=class{logger;bridge;registry=CallbackRegistryFactory$1$1();themesSubscription;activeThemeSubs=0;async start(e,t){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=t.bridge;const r=this.toApi();e.themes=r,this.logger.trace("themes are ready")}handlePlatformShutdown(){this.registry.clear(),this.activeThemeSubs=0,this.themesSubscription?.close(),delete this.themesSubscription}async handleBridgeMessage(){}toApi(){const e={getCurrent:this.getCurrent.bind(this),list:this.list.bind(this),select:this.select.bind(this),onChanged:this.onChanged.bind(this)};return Object.freeze(e)}async getCurrent(){return(await this.bridge.send("themes",operations$2.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}async list(){return(await this.bridge.send("themes",operations$2.list,void 0,void 0,{includeOperationCheck:!0})).themes}async select(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),await this.bridge.send("themes",operations$2.select,{name:e},void 0,{includeOperationCheck:!0})}async onChanged(e){if("function"!=typeof e)return ioError$1.raiseError("onChanged requires a callback of type function");const t=this.themesSubscription?Promise.resolve():this.configureThemeSubscription();await t,++this.activeThemeSubs;const r=this.registry.add("on-theme-change",e);return()=>this.themeUnsub(r)}async configureThemeSubscription(){this.themesSubscription||(this.themesSubscription=await this.bridge.createNotificationsSteam(),this.themesSubscription.onData(e=>{const t=e.data,r=simpleThemeResponseDecoder$1.run(t);if(!r.ok)return void this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(r.error)}`);const n=r.result;this.registry.execute("on-theme-change",n.theme)}),this.themesSubscription.onClosed(()=>{this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),this.activeThemeSubs=0,delete this.themesSubscription}))}themeUnsub(e){e(),--this.activeThemeSubs,this.activeThemeSubs||(this.themesSubscription?.close(),delete this.themesSubscription)}};class ChannelsStorage{sessionStorage=window.sessionStorage;_mode=DEFAULT_STORAGE_MODE;inMemoryChannels=[];inMemoryRestrictions=[];_unsubscribeDict={};clear(){this._mode=DEFAULT_STORAGE_MODE,this.inMemoryChannels=[],this.inMemoryRestrictions=[],this._unsubscribeDict={},this.sessionStorage.setItem(STORAGE_NAMESPACE,JSON.stringify([]))}get mode(){return this._mode}set mode(e){this._mode=e}get channels(){return"inMemory"===this.mode?this.inMemoryChannels.slice():this.getSessionStorageData()?.channels??[]}set channels(e){"inMemory"===this.mode&&(this.inMemoryChannels=e),this.setSessionStorageChannels(e)}get restrictions(){return"inMemory"===this.mode?this.inMemoryRestrictions.slice():this.getSessionStorageData()?.restrictions??[]}set restrictions(e){"inMemory"===this.mode&&(this.inMemoryRestrictions=e),this.setSessionStorageRestrictions(e)}getSessionStorageData(){return JSON.parse(this.sessionStorage.getItem(STORAGE_NAMESPACE)||"null")}addUnsubscribe(e,t){this._unsubscribeDict[e]=t}invokeUnsubscribes(e){if(e)return this._unsubscribeDict[e]?.(),void delete this._unsubscribeDict[e];Object.values(this._unsubscribeDict).forEach(e=>e()),this._unsubscribeDict={}}setSessionStorageChannels(e){const t=this.getSessionStorageData();if(t?.channels)return t.channels=e,this.setSessionStorageData(t);const r={channels:e,restrictions:t?.restrictions??[]};return this.setSessionStorageData(r)}setSessionStorageRestrictions(e){const t=this.getSessionStorageData();if(t?.restrictions)return t.restrictions=e,this.setSessionStorageData(t);const r={channels:t?.channels??[],restrictions:e};return this.setSessionStorageData(r)}setSessionStorageData(e){this.sessionStorage.setItem(STORAGE_NAMESPACE,JSON.stringify(e))}}const operations$1={clear:{name:"clear",dataDecoder:basePrefsConfigDecoder$1},clearAll:{name:"clearAll"},get:{name:"get",dataDecoder:basePrefsConfigDecoder$1,resultDecoder:getPrefsResultDecoder$1},getAll:{name:"getAll",resultDecoder:getAllPrefsResultDecoder$1},set:{name:"set",dataDecoder:changePrefsDataDecoder$1},update:{name:"update",dataDecoder:changePrefsDataDecoder$1},prefsChanged:{name:"prefsChanged",dataDecoder:getPrefsResultDecoder$1},prefsHello:{name:"prefsHello",resultDecoder:prefsHelloSuccessDecoder$1},operationCheck:{name:"operationCheck"},registerSubscriber:{name:"registerSubscriber",dataDecoder:subscriberRegisterConfigDecoder$1}};let PrefsController$1=class{supportedOperationsNames=[];bridge;config;logger;appManagerController;platformAppName;registry=CallbackRegistryFactory$1$1();validNonExistentApps;signaledSubscription=!1;interopId;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("prefs.controller.web"),this.logger.trace("starting the web prefs controller"),this.addOperationsExecutors(),this.interopId=e.interop.instance.instance,this.bridge=t.bridge,this.config=t.config,this.appManagerController=t.appManagerController;try{const e=await this.bridge.send("prefs",operations$1.prefsHello,void 0,void 0,{includeOperationCheck:!0});this.platformAppName=e.platform.app,this.validNonExistentApps=e.validNonExistentApps??[]}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support Prefs API.")}this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning");const r=this.toApi();e.prefs=r}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(prefsOperationTypesDecoder$1,e.operation),r=operations$1[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async get(e){const t=null==e?this.getMyAppName():runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),{prefs:r}=await this.bridge.send("prefs",operations$1.get,{app:t},void 0,{includeOperationCheck:!0});return r}async update(e,t){const r=runDecoderWithIOError$1(optional$2$1(basePrefsConfigDecoder$1),t),n=r?.app??this.getMyAppName();await this.updateFor(n,e)}addOperationsExecutors(){operations$1.prefsChanged.execute=this.handleOnChanged.bind(this),operations$1.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$1)}toApi(){return{clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearFor:this.clearFor.bind(this),get:this.get.bind(this),getAll:this.getAll.bind(this),set:this.set.bind(this),setFor:this.setFor.bind(this),subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),update:this.update.bind(this),updateFor:this.updateFor.bind(this)}}async clear(){const e=this.getMyAppName();await this.clearFor(e)}async clearAll(){await this.bridge.send("prefs",operations$1.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearFor(e){const t=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e);await this.bridge.send("prefs",operations$1.clear,{app:t},void 0,{includeOperationCheck:!0})}async getAll(){return await this.bridge.send("prefs",operations$1.getAll,void 0,void 0,{includeOperationCheck:!0})}async set(e,t){const r=runDecoderWithIOError$1(optional$2$1(basePrefsConfigDecoder$1),t),n=r?.app??this.getMyAppName();await this.setFor(n,e)}async setFor(e,t){const r=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),n=runDecoderWithIOError$1(object$2$1(),t);await this.bridge.send("prefs",operations$1.set,{app:r,data:n},void 0,{includeOperationCheck:!0})}subscribe(e){const t=this.getMyAppName();return this.subscribeFor(t,e)}subscribeFor(e,t){const r=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),n=this.appManagerController.getApplications();if(!(r===this.platformAppName||n.some(e=>e.name===r)||this.validNonExistentApps.includes(r)))return ioError$1.raiseError(`The provided app name "${e}" is not valid.`);if("function"!=typeof t)return ioError$1.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!");this.signaledSubscription||(this.bridge.send("prefs",operations$1.registerSubscriber,{interopId:this.interopId,appName:r},void 0,{includeOperationCheck:!0}).catch(e=>{this.logger.warn("Failed to register subscriber for prefs"),this.logger.error(e)}),this.signaledSubscription=!0);const i=this.getSubscriptionKey(r);return this.get(r).then(t),this.registry.add(i,t)}async updateFor(e,t){const r=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),n=runDecoderWithIOError$1(object$2$1(),t);await this.bridge.send("prefs",operations$1.update,{app:r,data:n},void 0,{includeOperationCheck:!0})}getMyAppName(){const e=this.config.isPlatformInternal?this.platformAppName:this.appManagerController.me?.application.name;return e||ioError$1.raiseError("App Preferences operations can not be executed for windows that do not have app!")}getSubscriptionKey(e){return`prefs-changed-${e}`}async handleOnChanged({prefs:e}){const t=this.getSubscriptionKey(e.app);this.registry.execute(t,e)}};const operations={getResources:{name:"getResources",dataDecoder:getResourcesDataDecoder$1,resultDecoder:getResourcesResultDecoder$1},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder$1,resultDecoder:operationCheckResultDecoder$1},showAlert:{name:"showAlert",dataDecoder:uiAlertRequestMessageDecoder$1},showDialog:{name:"showDialog",dataDecoder:uiDialogRequestMessageDecoder$1},alertInteropAction:{name:"alertInteropAction",dataDecoder:alertInteropActionDataDecoder$1},showResolver:{name:"showResolver",dataDecoder:uiResolverRequestMessageDecoder,resultDecoder:uiResolverResponseMessageDecoder}},DEFAULT_ALERT_TTL=5e3,MODALS_SHADOW_HOST_ID="io-modals-shadow-host",MODALS_ROOT_ELEMENT_ID="io-modals-root",WIDGET_SHADOW_HOST_ID="io-widget-shadow-host",WIDGET_ROOT_ELEMENT_ID="io-widget-root",INTENT_RESOLVER_SHADOW_HOST_ID="io-intent-resolver-shadow-host",INTENT_RESOLVER_ROOT_ELEMENT_ID="io-intent-resolver-root",SHADOW_ROOT_ELEMENT_CLASSNAME="io-body io-variables";let UIController$1=class{ioc;supportedOperationsNames=[];logger;bridge;config;zIndexDictionary={[WIDGET_SHADOW_HOST_ID]:"100",[MODALS_SHADOW_HOST_ID]:"101",[INTENT_RESOLVER_SHADOW_HOST_ID]:"100"};widgetResources;modalsResources;intentResolverResources;modalsUiApi;isDialogOpen=!1;intentResolverUiApi;isIntentResolverOpen=!1;constructor(e){this.ioc=e}async start(e,t){this.logger=e.logger.subLogger("ui.controller.web"),this.logger.trace("starting the ui controller"),this.bridge=t.bridge,this.config=t.config,this.addOperationsExecutors();const r=await this.getResources();r?(this.logger.trace(`Received UI resources from platform: ${JSON.stringify(r)}`),this.setResources(r)):this.logger.trace("No UI elements to display - platform is not initialized with any UI resources")}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(uiOperationTypesDecoder$1,e.operation),r=operations[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async showComponents(e){const t=this.widgetResources?this.initializeWidget(e,this.widgetResources):Promise.resolve(),r=this.modalsResources?this.initializeModalsUi(e,this.modalsResources):Promise.resolve(),n=this.intentResolverResources?this.initializeIntentResolverUI(e,this.intentResolverResources):Promise.resolve();await Promise.all([this.config.widget.awaitFactory?t:Promise.resolve(),this.config.modals.awaitFactory?r:Promise.resolve(),this.config.intentResolver.awaitFactory?n:Promise.resolve()])}isIntentResolverEnabled(){return!!this.intentResolverResources&&this.config.intentResolver.enable}addOperationsExecutors(){operations.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),operations.showAlert.execute=this.handleShowAlert.bind(this),operations.showDialog.execute=this.handleShowDialog.bind(this),operations.showResolver.execute=this.handleShowResolver.bind(this),this.supportedOperationsNames=getSupportedOperationsNames(operations)}async handleShowAlert({config:e}){if(!this.config.modals.alerts.enabled)return ioError$1.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return ioError$1.raiseError("Unable to perform showAlert operation because modalsUiApi is missing.");const{promise:r,resolve:n}=wrapPromise(),i=e=>{const t=alertOnClickConfigDecoder.run(e);if(!t.ok)return void this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(t.error)}.`);const{interopAction:r}=t.result;this.bridge.send("ui",operations.alertInteropAction,{interopAction:r},void 0,{includeOperationCheck:!0}).catch(e=>this.logger.warn(extractErrorMsg$2(e)))};let o;try{this.logger.trace(`Open alert with config: ${JSON.stringify(e)}`),o=t.alerts.open({...e,onClick:i,onClose:n})}catch(e){return ioError$1.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${extractErrorMsg$2(e)}.`)}const s=openAlertResultDecoder.run(o);if(!s.ok)return ioError$1.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);const a=setTimeout(()=>{n()},getSafeTimeoutDelay$1(e.ttl??DEFAULT_ALERT_TTL));r.then(()=>{clearTimeout(a);try{t.alerts.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close alert with id ${s.result.id}. Reason: ${extractErrorMsg$2(e)}`)}})}async handleShowDialog({config:e}){if(!this.config.modals.dialogs.enabled)return ioError$1.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return ioError$1.raiseError("Unable to perform showDialog operation because modalsUiApi is missing.");if(this.isDialogOpen)return ioError$1.raiseError("Cannot open a dialog because another one is already open.");const{promise:r,resolve:n}=wrapPromise();let i;try{this.logger.trace(`Open dialog with config: ${JSON.stringify(e)}`),i=t.dialogs.open({...e,onCompletion:n})}catch(e){return ioError$1.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${extractErrorMsg$2(e)}.`)}const o=openDialogResultDecoder.run(i);if(!o.ok)return ioError$1.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(o.error)}.`);let s;this.isDialogOpen=!0,e.timer&&(s=setTimeout(()=>{n({response:{isExpired:!0}})},getSafeTimeoutDelay$1(e.timer.duration)));const a=await r;clearTimeout(s),this.isDialogOpen=!1;try{t.dialogs.close({id:o.result.id})}catch(e){this.logger.warn(`Failed to close dialog with id ${o.result.id}. Reason: ${extractErrorMsg$2(e)}`)}const c=dialogOnCompletionConfigDecoder.run(a);return c.ok?{result:c.result.response}:ioError$1.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async handleShowResolver({config:e}){if(this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(e)}`),!this.config.intentResolver.enable)return ioError$1.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config.");const t=this.intentResolverUiApi;if(!t)return ioError$1.raiseError("Unable to perform showResolver operation because intentResolverApi is missing.");if(this.isIntentResolverOpen)return ioError$1.raiseError("Cannot open the intent resolver because another one is already open.");const{promise:r,resolve:n}=wrapPromise();let i;try{this.logger.trace(`Open intent resolver with config: ${JSON.stringify(e)}`),i=t.open({...e,onUserResponse:n})}catch(e){return ioError$1.raiseError(`intentResolverUI.open() failed. Reason: ${extractErrorMsg$2(e)}.`)}const o=openResolverResultDecoder.run(i);if(!o.ok)return ioError$1.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(o.error)}.`);const s=setTimeout(()=>n({response:{isExpired:!0}}),getSafeTimeoutDelay$1(e.timeout)),a=await r;clearTimeout(s),this.isIntentResolverOpen=!1;try{t.close({id:o.result.id})}catch(e){this.logger.warn(`Failed to close intent resolver with id ${o.result.id}. Reason: ${extractErrorMsg$2(e)}`)}const c=onUserResponseResponseDecoder.run(a);return c.ok?{result:c.result.response}:ioError$1.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async getResources(){const e={origin:window.origin};try{return(await this.bridge.send("ui",operations.getResources,e,void 0,{includeOperationCheck:!0})).resources}catch(e){this.logger.warn(e?.message||JSON.stringify(e))}}appendModalsResources(e){return this.logger.trace("Appending modals resources"),this.appendResources(MODALS_SHADOW_HOST_ID,MODALS_ROOT_ELEMENT_ID,e.sources)}appendWidgetResources(e){return this.logger.trace("Appending widget resources"),this.appendResources(WIDGET_SHADOW_HOST_ID,WIDGET_ROOT_ELEMENT_ID,e.sources)}appendIntentResolverResources(e){return this.logger.trace("Appending intent resolver resources"),this.appendResources(INTENT_RESOLVER_SHADOW_HOST_ID,INTENT_RESOLVER_ROOT_ELEMENT_ID,e.sources)}appendResources(e,t,r){const{bundle:n,fonts:i=[],styles:o}=r,s=document.createElement("div");s.id=e,s.style.position="fixed",s.style.zIndex=this.zIndexDictionary[e];const a=s.attachShadow({mode:"open"}),c=document.createElement("script");c.src=n,c.type="module",a.appendChild(c);const l=document.createElement("div");return l.id=t,l.className=SHADOW_ROOT_ELEMENT_CLASSNAME,a.appendChild(l),o.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,a.appendChild(t)}),i.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.insertBefore(t,document.head.firstChild)}),document.body.appendChild(s),{rootElement:l}}async initializeWidget(e,t){this.logger.trace("Initializing IOBrowserWidget.");const{rootElement:r}=this.appendWidgetResources(t);this.subscribeForThemeChanges(e,r);const n={...deepmerge$1$1(t.config,this.config.widget),rootElement:r};return PromiseWrap$1(async()=>{await this.ioc.eventsDispatcher.widgetReady(),this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(n)}`),await window.IOBrowserWidget(e,n),this.logger.trace("IOBrowserWidget was initialized successfully.")},n.timeout,`Timeout of ${n.timeout}ms hit waiting for IOBrowserWidget to initialize.`)}async initializeModalsUi(e,t){this.logger.trace("Initializing IOBrowserModalsUI.");const{rootElement:r}=this.appendModalsResources(t);this.subscribeForThemeChanges(e,r);const n={...this.config.modals,rootElement:r};return PromiseWrap$1(async()=>{await this.ioc.eventsDispatcher.modalsUIFactoryReady(),this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(n)}`),this.modalsUiApi=await window.IOBrowserModalsUI(e,n),this.logger.trace("IOBrowserModalsUI was initialized successfully.")},n.timeout,`Timeout of ${n.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`)}async initializeIntentResolverUI(e,t){this.logger.trace("Initializing IOBrowserIntentResolverUI.");const{rootElement:r}=this.appendIntentResolverResources(t);this.subscribeForThemeChanges(e,r);const n={...this.config.intentResolver,rootElement:r},i=n.timeout;return PromiseWrap$1(async()=>{await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(),this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(n)}`),this.intentResolverUiApi=await window.IOBrowserIntentResolverUI(e,n),this.logger.trace("IOBrowserIntentResolverUI initialized successfully.")},i,`Timeout of ${i}ms hit waiting for IOBrowserIntentResolverUI to initialize.`)}setResources(e){this.setWidgetResources(e.widget),this.setModalsUiResources(e.modals),this.setIntentResolverResources(e.intentResolver)}setWidgetResources(e){const t="Widget won't be displayed. Reason: ",r=widgetConfigDecoder$1.run(this.config.widget);r.ok?this.config.widget.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`):this.widgetResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'widget: { enable: false }' config`):this.logger.warn(`${t} invalid widget config. Error: ${r.error}`)}setModalsUiResources(e){const t="Modals won't be displayed. Reason: ",r=modalsConfigDecoder$1.run(this.config.modals);r.ok?this.config.modals.alerts.enabled||this.config.modals.dialogs.enabled?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`):this.modalsResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`):this.logger.warn(`${t} invalid modals config. Error: ${r.error}`)}setIntentResolverResources(e){const t="Intent Resolver UI won't be displayed. Reason: ",r=intentResolverConfigDecoder$1.run(this.config.intentResolver);r.ok?this.config.intentResolver.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`):this.intentResolverResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'intentResolver: { enable: false }' config`):this.logger.warn(`${t} invalid intent resolver config. Error: ${JSON.stringify(r.error)}`)}subscribeForThemeChanges(e,t){const r=e.themes;if(!r)return;const n=async e=>{if(t.classList.contains(e.name))return;const n=await r.list();t.classList.remove(...n.map(({name:e})=>e)),t.classList.add(e.name)};r.onChanged(n),r.getCurrent().then(n)}},IoC$3=class{_coreGlue;_communicationId;_publicWindowId;_webConfig;_windowsControllerInstance;_appManagerControllerInstance;_layoutsControllerInstance;_notificationsControllerInstance;_intentsControllerInstance;_channelsControllerInstance;_themesControllerInstance;_extensionController;_systemControllerInstance;_bridgeInstance;_eventsDispatcher;_preferredConnectionController;_channelsStorage;_prefsControllerInstance;_uiController;controllers={windows:this.windowsController,appManager:this.appManagerController,layouts:this.layoutsController,notifications:this.notificationsController,intents:this.intentsController,channels:this.channelsController,system:this.systemController,extension:this.extensionController,themes:this.themesController,prefs:this.prefsController,ui:this.uiController};get communicationId(){return this._communicationId}get publicWindowId(){return this._publicWindowId}get windowsController(){return this._windowsControllerInstance||(this._windowsControllerInstance=new WindowsController$1),this._windowsControllerInstance}get uiController(){return this._uiController||(this._uiController=new UIController$1(this)),this._uiController}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new AppManagerController),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new LayoutsController$1),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new ThemesController$1),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new NotificationsController$1),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new IntentsController$1),this._intentsControllerInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new SystemController$1),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new ChannelsController$1),this._channelsControllerInstance}get prefsController(){return this._prefsControllerInstance||(this._prefsControllerInstance=new PrefsController$1),this._prefsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new ExtController),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new EventsDispatcher(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new GlueBridge(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new PreferredConnectionController$1(this._coreGlue)),this._preferredConnectionController}get channelsStorage(){return this._channelsStorage||(this._channelsStorage=new ChannelsStorage),this._channelsStorage}get config(){return this._webConfig}defineGlue(e){this._coreGlue=e,this._publicWindowId=e.connection.transport.publicWindowId;const t=window.glue42core||window.iobrowser;this._communicationId=e.connection.transport.communicationId||t.communicationId}defineConfig(e){this._webConfig=e}async buildWebWindow(e,t,r){const n=new WebWindowModel(e,t,this.bridge,r),i=await n.toApi();return{id:e,model:n,api:i}}buildNotification(e,t){return new Notification$1(e,t)}async buildApplication(e,t){const r=new ApplicationModel(e,[],this.appManagerController).toApi(),n=t.map(e=>this.buildInstance(e,r));return r.instances.push(...n),r}buildInstance(e,t){return new InstanceModel(e,this.bridge,t).toApi()}};var version$1$1="4.2.4";const setupGlobalSystem=(e,t)=>({getContainerInfo:async()=>{if(window!==window.parent)return window.name.includes("#wsp")?{workspaceFrame:{id:"N/A"}}:window.parent===window.top?{top:{}}:{parent:{}}},getProfileData:async()=>{if(!t)throw new Error("Bridge is not available and cannot fetch the profile data");return await t.send("system",{name:"getProfileData"},void 0)}}),createFactoryFunction=e=>{let t;return r=>{if(window.glue42gd||window.iodesktop)return enterprise(r);const n=parseConfig(r);try{checkSingleton$1()}catch(e){return void 0===t?Promise.reject(new Error(e)):t}const i=(async t=>{const r=new IoC$3,n=await PromiseWrap$1(()=>e(t,{version:version$1$1}),3e4,"Glue Web initialization timed out, because core didn't resolve"),i=n.logger.subLogger("web.main.controller");r.defineGlue(n),await r.preferredConnectionController.start(t),await r.bridge.start(r.controllers),r.defineConfig(t),i.trace("the bridge has been started, initializing all controllers"),await Promise.all(Object.values(r.controllers).map(e=>e.start(n,r))),i.trace("all controllers reported started, starting all additional libraries");try{return await Promise.all(t.libraries.map(e=>e(n,t))),i.trace("all libraries were started"),r.eventsDispatcher.start(n),i.trace("start event dispatched, glue is ready, returning it"),await r.uiController.showComponents(n).catch(e=>i.warn(e?.message?e.message:JSON.stringify(e))),await Promise.all(Object.values(r.controllers).map(e=>e.postStart?e.postStart(n,r):Promise.resolve())),window.iobrowser.system=setupGlobalSystem(n,r.bridge),window.iobrowser=Object.freeze({...window.iobrowser}),n}catch(e){return ioError$1.raiseError(e,!0)}})(n);return t=r?.memoizeAPI?i:void 0,i}};var MetricTypes$1={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function getMetricTypeByValue$1(e){return e.type===MetricTypes$1.TIMESTAMP?"timestamp":e.type===MetricTypes$1.NUMBER?"number":e.type===MetricTypes$1.STRING?"string":e.type===MetricTypes$1.OBJECT?"object":"unknown"}function getTypeByValue$1(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function serializeMetric$1(e){const t={},r=getMetricTypeByValue$1(e);if("object"===r){const r=Object.keys(e.value).reduce((t,r)=>{const n=getTypeByValue$1(e.value[r]);if("object"===n){const n=defineNestedComposite$1(e.value[r]);t[r]={type:"object",description:"",context:{},composite:n}}else t[r]={type:n,description:"",context:{}};return t},{});t.composite=r}return t.name=normalizeMetricName$1(e.path.join("/")+"/"+e.name),t.type=r,t.description=e.description,t.context={},t}function defineNestedComposite$1(e){return Object.keys(e).reduce((t,r)=>{const n=getTypeByValue$1(e[r]);return t[r]="object"===n?{type:"object",description:"",context:{},composite:defineNestedComposite$1(e[r])}:{type:n,description:"",context:{}},t},{})}function normalizeMetricName$1(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function getMetricValueByType$1(e){return"timestamp"===getMetricTypeByValue$1(e)?Date.now():publishNestedComposite$1(e.value)}function publishNestedComposite$1(e){return"object"!=typeof e?e:Object.keys(e).reduce((t,r)=>{const n=e[r];return"object"==typeof n&&n.constructor!==Date?t[r]=publishNestedComposite$1(n):n.constructor===Date?t[r]=new Date(n).getTime():n.constructor===Boolean?t[r]=n.toString():t[r]=n,t},{})}function flatten$1(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?flatten$1(t):t),[])}function getHighestState$1(e){return e.sort((e,t)=>e.state?t.state?t.state-e.state:-1:1)[0]}function aggregateDescription$1(e){let t="";return e.forEach((e,r,n)=>{const i=e.path.join(".");r===n.length-1?t+=i+"."+e.name+": "+e.description:t+=i+"."+e.name+": "+e.description+","}),t.length>100?t.slice(0,100)+"...":t}function composeMsgForRootStateMetric$1(e){const t=flatten$1(e.root.getAggregateState()),r=getHighestState$1(t);return{description:aggregateDescription$1(t),value:r.state}}function gw3$1(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let r,n;const i=e=>{o(e.root)},o=e=>{s(e),e.metrics.forEach(e=>{a(e)}),e.subSystems.forEach(e=>{o(e)})},s=async e=>{if(void 0===e.parent)return;await r;const i={type:"define",metrics:[{name:normalizeMetricName$1(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};n.sendFireAndForget(i).catch(r=>{t.logger.warn(`Failed to send define for system state metric of ${e.name}: ${JSON.stringify(r)}`)})},a=async e=>{const i=l(e);await r;const o={type:"define",metrics:[serializeMetric$1(i)]};n.sendFireAndForget(o).catch(r=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(r)}`)}),void 0!==i.value&&c(i)},c=e=>{if(u()){const r=getMetricValueByType$1(e),i={type:"publish",values:[{name:normalizeMetricName$1(e.path.join("/")+"/"+e.name),value:r,timestamp:Date.now()}]};return n.sendFireAndForget(i).catch(r=>{t.logger.warn(`Failed to publish metric ${e.name}: ${JSON.stringify(r)}`)})}return Promise.resolve()},l=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},u=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:o=>{let s;r=new Promise(e=>{s=e}),n=e.domain("metrics"),n.onJoined(e=>{!e&&s&&(s(),s=void 0);const r={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};n.sendFireAndForget(r).catch(e=>{t.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(e)}`)}),e&&i(o)}),n.join({system:t.system,service:t.service,instance:t.instance})},createSystem:s,updateSystem:async(i,o)=>{await r;const s={type:"publish",values:[{name:normalizeMetricName$1(i.path.join("/")+"/"+i.name+"/State"),value:{Description:o.description,Value:o.state},timestamp:Date.now()}]};n.sendFireAndForget(s).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${i.name}: ${JSON.stringify(e)}`)});const a=composeMsgForRootStateMetric$1(i),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};n.sendFireAndForget(c).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${i.name}: ${JSON.stringify(e)}`)})},createMetric:a,updateMetric:async e=>{const t=l(e);await r,c(t)}}}var Helpers$1={validate:(e,t,r)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===r||"object"!=typeof r)throw new Error("Missing transport")}};let BaseMetric$1=class{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,r,n,i){this.definition=e,this.system=t,this.transport=r,this.value=n,this.type=i,Helpers$1.validate(e,t,r),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,r.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}},NumberMetric$1=class extends BaseMetric$1{constructor(e,t,r,n){super(e,t,r,n,MetricTypes$1.NUMBER)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}},ObjectMetric$1=class extends BaseMetric$1{constructor(e,t,r,n){super(e,t,r,n,MetricTypes$1.OBJECT)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach(t=>{void 0!==e[t]&&(this.value[t]=e[t])})}},StringMetric$1=class extends BaseMetric$1{constructor(e,t,r,n){super(e,t,r,n,MetricTypes$1.STRING)}},TimestampMetric$1=class extends BaseMetric$1{constructor(e,t,r,n){super(e,t,r,n,MetricTypes$1.TIMESTAMP)}now(){this.update(new Date)}};function system$1(e,t,r,n,i){if(!t)throw new Error("Repository is required");if(!r)throw new Error("Transport is required");const o=r,s=e,a=i||"",c=t,l=n,u=function e(t){if(!t||!t.parent)return[];const r=e(t.parent);return r.push(t.name),r}(n);let d={};const h=(g="/",((p=u)&&p.length>0?p.join(g):"")+e);var p,g;const m=t.root,f=[],y=[];function $(e,t,r,n){let i={name:""};i="string"==typeof e?{name:e}:e;const o=y.filter(e=>e.name===i.name);if(o.length>0){const e=o[0];if(e.type!==t)throw new Error(`A metric named ${i.name} is already defined with different type.`);return void 0!==r&&e.update(r).catch(()=>{}),e}const s=n(i);return y.push(s),s}const b={get name(){return s},get description(){return a},get repo(){return c},get parent(){return l},path:u,id:h,root:m,get subSystems(){return f},get metrics(){return y},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const r=f.filter(t=>t.name===e);if(r.length>0)return r[0];const n=system$1(e,c,o,b,t);return f.push(n),n},getState:()=>d,setState:function(e,t){d={state:e,description:t},o.updateSystem(b,d)},stringMetric:function(e,t){return $(e,MetricTypes$1.STRING,t,e=>new StringMetric$1(e,b,o,t))},timestampMetric:function(e,t){return $(e,MetricTypes$1.TIMESTAMP,t,e=>new TimestampMetric$1(e,b,o,t))},objectMetric:function(e,t){return $(e,MetricTypes$1.OBJECT,t,e=>new ObjectMetric$1(e,b,o,t))},numberMetric:function(e,t){return $(e,MetricTypes$1.NUMBER,t,e=>new NumberMetric$1(e,b,o,t))},getAggregateState:function(){const e=[];return Object.keys(d).length>0&&e.push({name:s,path:u,state:d.state,description:d.description}),f.forEach(t=>{const r=t.getAggregateState();r.length>0&&e.push(...r)}),e}};return o.createSystem(b),b}let Repository$1=class{root;constructor(e,t){t.init(this),this.root=system$1("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),r=e=>{if(!e.target)return;const r=e.target,n=r?r.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:n,id:r.id,type:"<"+r.tagName.toLowerCase()+">",href:r.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",r):document.attachEvent("onclick",r)}e.stringMetric("StartTime",(new Date).toString());const r=e.stringMetric("StartURL",""),n=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;r.update(e)}void 0!==window.glue42gd&&n.update(window.glue42gd.appName)}}},NullProtocol$1=class{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}},PerfTracker$1=class{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,r){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=r??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout(()=>{this.collect(),setInterval(()=>{this.collect()},this.publishInterval)},this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map(e=>e.toJSON());this.system.stringMetric("entries",JSON.stringify(t))}};var metrics$2=e=>{let t;t=e.connection&&"object"==typeof e.connection?gw3$1(e.connection,e):new NullProtocol$1;let r=new Repository$1(e,t).root;e.disableAutoAppSystem||(r=r.subSystem("App"));const n=addFAVSupport$1(r);return initPerf$1(n,e.pagePerformanceMetrics),n};function initPerf$1(e,t){if("undefined"==typeof window)return;const r=window?.glue42gd?.metrics?.pagePerformanceMetrics;r&&(t=r),t?.enabled&&new PerfTracker$1(e,t.initialPublishTimeout,t.publishInterval)}function addFAVSupport$1(e){const t=e.subSystem("reporting"),r={name:"features"};let n;return e.featureMetric=(e,i,o)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===i||""===i)throw new Error("action is mandatory");if(void 0===o||""===o)throw new Error("payload is mandatory");n?n.update({name:e,action:i,payload:o}):n=t.objectMetric(r,{name:e,action:i,payload:o})},e}var commonjsGlobal$2="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$3(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createRegistry$3(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;i{this.messageHandler(t)}).then(e=>{this.client=e})}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}},SharedWorkerTransport$1=class{logger;worker;registry=CallbackRegistryFactory$3();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}},Utils$1=class e{static isNode(){if(void 0!==e._isNode)return e._isNode;if("undefined"!=typeof window)return e._isNode=!1,!1;try{e._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(t){e._isNode=!1}return e._isNode}static _isNode},PromiseWrapper$2=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve;reject;promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};const timers$1={};function getAllTimers$1(){return timers$1}function timer$1(e){const t=timers$1[e];if(t)return t;const r=[];function n(){return(new Date).getTime()}const i=n();let o,s;function a(e,t){const i=t??n();let o=0;r.length>0&&(o=i-r[r.length-1].time),r.push({name:e,time:i,diff:o})}a("start",i);const c={get startTime(){return i},get endTime(){return o},get period(){return s},stop:function(){return o=n(),a("end",o),s=o-i,s},mark:a,marks:r};return timers$1[e]=c,c}const WebSocketConstructor$1=Utils$1.isNode()?null:window.WebSocket;let WS$1=class{ws;logger;settings;startupTimer=timer$1("connection");_running=!0;_registry=CallbackRegistryFactory$3();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise((t,r)=>{this.waitForSocketConnection(()=>{try{this.ws?.send(e),t()}catch(e){r(e)}},r)})}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise((e,t)=>{this.waitForSocketConnection(e,t)})}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new PromiseWrapper$2;return this.waitForSocketConnection(()=>{e.resolve()}),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout(()=>{const r=void 0===t?void 0:t-1;this.openSocket(e,r)},e)}}initiateSocket(){const e=new PromiseWrapper$2;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new WebSocketConstructor$1(this.settings.ws??"");let t=!1;return this.ws.onerror=r=>{let n;try{n=JSON.stringify(r)}catch(e){const t=new WeakSet,i=(e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r instanceof Error?{message:r.message,name:r.name,stack:r.stack}:r};n=JSON.stringify(r,i)}this.logger.info(`ws error - reason: ${n}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error")),this.notifyStatusChanged(!1,n)},this.ws.onclose=r=>{this.logger.info(`ws closed - code: ${r?.code} reason: ${r?.reason}`),e.reject("closed"),t&&(t=!1,this.notifyForSocketState("closed")),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),t=!0,this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach(t=>{e?t.failed&&t.failed(e):t.callback()}),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}},MessageReplayerImpl$1=class{specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const r of this.specs[t].types){let t=this.subsRefCount[r];if(t||(t=0),t+=1,this.subsRefCount[r]=t,t>1)continue;const n=e.on(r,e=>this.processMessage(r,e));this.subs[r]=n}}processMessage(e,t){if(!this.isDone&&t)for(const r of this.specsNames)if(-1!==this.specs[r].types.indexOf(e)){const e=this.messages[r]||[];this.messages[r]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}},urlAlphabet$4="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$6=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$4[64*Math.random()|0];return t};const PromisePlus$2=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});let WebPlatformTransport$1=class{settings;logger;identity;isPreferredActivated;_connectionProtocolVersion;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=CallbackRegistryFactory$3();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:()=>{}},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,r){this.settings=e,this.logger=t,this.identity=r,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId||"unknown"}, client connected: ${this.iAmConnected}`);const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=r=>{if(this.iAmConnected&&!r.data?.glue42core)return void this.registry.execute("onMessage",r.data);const n=r.data?.glue42core;n&&(n.type===this.messages.gatewayInternalConnect.name&&n.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),n.type===this.messages.gatewayInternalConnect.name&&n.error&&t(n.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))})}initiateRemoteConnection(e){return PromisePlus$2((t,r)=>{this.connectionResolve=t,this.connectionReject=r,this.myClientId=this.myClientId??nanoid$6(10);const n=this.getMyWindowId()||nanoid$6(10),i={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:n,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug(`sending connection request - clientId: ${this.myClientId}`),this.extContentConnecting)return i.glue42core.clientType="child",i.glue42core.bridgeInstanceId=this.myClientId,i.glue42core.parentWindowId=this.parentWindowId,window.postMessage(i,window.origin);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(i,this.defaultTargetString)},this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):(this.logger.debug("setting up window message listener"),window.addEventListener("message",e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const r=this.settings.allowedOrigins||[];if(r.length&&!r.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const n=t.type;this.logger.debug(`received valid glue42core message of type: ${n}`),this.messages[n].handle(e)}))}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):(this.logger.debug("setting up unload event listeners"),window.addEventListener("beforeunload",()=>{this._connectionProtocolVersion||this.signalClientDisappearing()}),window.addEventListener("pagehide",()=>{this._connectionProtocolVersion&&this.signalClientDisappearing()}))}signalClientDisappearing(){if(this.extContentConnected)return;this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`);const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent?.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId!==t.clientId?this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${t.clientId}`):this.handleAcceptanceOfMyRequest(t)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this._connectionProtocolVersion=e.connectionProtocolVersion,this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||nanoid$6(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",e=>{const t=e.data?.glue42ExtInc;if(!t)return;const r=this.settings.allowedOrigins||[];!r.length||r.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)}),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleConnectionRejected(e){if(this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"),!this.connectionReject)return;const t="string"==typeof e.data.glue42core?.error?`Connection was rejected. ${e.data.glue42core?.error}`:"The platform connection was rejected. Most likely because this window was not created by a glue API call";this.connectionReject(t),delete this.connectionReject}handleConnectionRequest(){this.extContentConnecting&&this.logger.debug("This connection request event is targeted at the extension content")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const r=e.source;this.logger.debug("responding to a parent ping with a ready message"),r.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.logger.debug("setting up platform unload listener"),this.onMessage(e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))})}handleManualUnload(){this.logger.debug("handling manual unload");const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);this.port?.postMessage(e)}handlePlatformPing(){}notifyStatusChanged(e,t){this.logger.debug(`status changed - connected: ${e}, reason: ${t||"none"}`),this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}requestConnectionPermissionFromExt(){return this.waitForContentScript().then(()=>PromisePlus$2((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},window.origin)},this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out"))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():PromisePlus$2(e=>{window.addEventListener("Glue42EXTReady",()=>{e()})},this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),r=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),n=new Set([...t,...r]);if(!n.size&&!this.extContentAvailable)throw new Error(e);if(!n.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(n)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e?.parent&&e!==e.parent?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=PromisePlus$2(t=>{this.parentPingResolve=t;const r={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval(()=>{e.forEach(e=>{e.postMessage(r,this.defaultTargetString)})},1e3)},this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch(()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)}),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${nanoid$6(10)}`,this.selfAssignedWindowId):void 0}};const waitForInvocations$1=(e,t)=>{let r=e;return()=>{r--,0===r&&t()}};let AsyncSequelizer$3=class{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}};function domainSession$1(e,t,r,n,i){null==e&&(e="global"),n=n??["success"],i=i??["error"];let o,s="global"===e,a=!1,c=!1;const l=CallbackRegistryFactory$3();t.disconnected(function(){r.debug("connection is down"),c=!1,s=!1,a=!0,Object.keys(u).forEach(e=>{const t=u[e];t&&(r.trace(`failing pending request ${e} due to connection lost`),t.error({err:"Connection lost - gateway connection was disconnected"}))}),l.execute("onLeft",{disconnected:!0})}),t.loggedIn(async function(){if(c=!0,a){r.debug("connection is now up - trying to reconnect...");try{await d(o)}catch{r.trace("failed to reconnect")}}}),t.on("success",e=>g(e)),t.on("error",e=>p(e)),t.on("result",e=>g(e)),n&&n.forEach(e=>{t.on(e,e=>g(e))}),i&&i.forEach(e=>{t.on(e,e=>p(e))});const u={};function d(t){return o=t,new Promise((n,i)=>{if(s)return void n({});let o;if("global"===e)o=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{r.debug(`joining domain ${e}`);o=y({type:"join",destination:e,domain:"global",options:t})}o.then(()=>{!function(){r.debug("did join "+e),s=!0;const t=a;a=!1,l.execute("onJoined",t)}(),n({})}).catch(t=>{r.debug("error joining "+e+" domain: "+JSON.stringify(t)),i(t)})})}function h(e){return s&&e(!1),l.add("onJoined",e)}function p(t){if(e!==t.domain)return;const r=t.request_id;if(!r)return;const n=u[r];n&&n.error(t)}function g(t){if(t.domain!==e)return;const r=t.request_id;if(!r)return;const n=u[r];n&&n.success(t)}function m(){return nanoid$6(10)}let f=[];function y(n,i,o){if(n.type&&-1===["hello","join"].indexOf(n.type)&&!s){console.warn(`trying to send a message (${n.domain} ${n.type}) but not connected, will queue`);const e=new PromiseWrapper$2;if(f.push({msg:n,tag:i,options:o,pw:e}),1===f.length){const e=h(()=>{r.info(`joined - will now send queued messages (${f.length} -> [${f.map(e=>e.msg.type)}])`),f.forEach(e=>{y(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),f=[],e()})}return e.promise}o=o??{},n.request_id=n.request_id??m(),n.domain=n.domain??e,o.skipPeerId||(n.peer_id=t.peerId);const a=n.request_id;return new Promise((e,r)=>{u[a]={success:t=>{delete u[a],t._tag=i,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete u[a],e._tag=i,r(e)}},t.send(n,o).catch(e=>{u[a]?.error({err:e})})})}return{join:d,leave:function(){return"global"===e?Promise.resolve():(r.debug("stopping session "+e+"..."),a=!1,y({type:"leave",destination:e,domain:"global"}).then(()=>{s=!1,l.execute("onLeft")}).catch(()=>{s=!1,l.execute("onLeft")}))},onJoined:h,onLeft:function(e){return s||e(),l.add("onLeft",e)},send:y,sendFireAndForget:function(r){return r.request_id=r.request_id?r.request_id:m(),r.domain=r.domain??e,r.peer_id=t.peerId,t.send(r)},on:(n,i)=>{t.on(n,t=>{if(t.domain===e)try{i(t)}catch(e){r.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}})},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}let Connection$1=class{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=CallbackRegistryFactory$3();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new AsyncSequelizer$3;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;loginRetryInProgress=!1;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new InProcTransport$1(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new SharedWorkerTransport$1(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new WebPlatformTransport$1(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new WS$1(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const r=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),n=this.transport.onMessage(this.handleTransportMessage.bind(this));this._transportSubscriptions.push(r),this._transportSubscriptions.push(n),this._defaultTransport=this.transport,this.ping()}async switchTransport(e){return this._sequelizer.enqueue(async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const r=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await r;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}})}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const r=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(r)}`),this.transport.sendObject(r,t)}{const r=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${r}`),this.transport.send(r,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const r=this.ids++;return this.messageHandlers[e][r]=t,{type:e,id:r}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn(()=>{const t=this.transport.name();e(t)})}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this.logger.debug(`Login initiated - reconnect: ${t}, transport: ${this.transport.name()}`),this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}try{await this.transport.open(),this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`),timer$1("connection").mark("transport-opened");const r=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(r)}`),timer$1("connection").mark("protocol-logged-in"),r}catch(e){throw this._switchInProgress&&(this.logger.debug("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,r){let n=this.sessions.find(t=>t.domain===e);return n||(n=domainSession$1(e,this,this.logger.subLogger(`domain=${e}`),t,r),this.sessions.push(n)),n}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then(e=>e.token):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&(this.initialLogin=!1,this.registry.execute("onLoggedIn"))}distributeMessage(e,t){const r=this.messageHandlers[t.toLowerCase()];void 0!==r&&Object.keys(r).forEach(t=>{const n=r[t];if(void 0!==n)try{n(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}})}handleConnectionChanged(e){this._connected!==e?(this.logger.info("connection state changed to "+(e?"connected":"disconnected")),this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new MessageReplayerImpl$1(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&this.attemptLoginWithRetry(),this.registry.execute("disconnected"))):this.logger.trace("connection state unchanged, skipping")}async attemptLoginWithRetry(){if(!this.loginConfig)throw new Error("no login info");if(this.loginRetryInProgress)this.logger.debug("login attempt already in progress, ignoring request...");else if(this._isLoggedIn)this.logger.debug("already logged in, ignoring request...");else{if(this.initialLogin){if(this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`),this.initialLoginAttempts<=0)return void this.logger.info("maximum initial login attempts reached, will not try to login again");this.initialLoginAttempts--}try{this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`),this.loginRetryInProgress=!0,await this.login(this.loginConfig,!0)}catch(e){this.logger.error(`error trying to login: ${e?.message}`,e),setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3)}finally{this.loginRetryInProgress=!1}}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return PromisePlus$2(e=>{let t;const r=waitForInvocations$1(2,()=>{t&&t(),e()});t=this.onLibReAnnounced(e=>"interop"===e.name||"contexts"===e.name?r():void 0)},1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new WS$1(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport.close().catch(e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`)),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,(e,t)=>{if("string"!=typeof t)return t;if(t.lengthe.leave());await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout(()=>{this.ping()},3e4))}};const order$1=["trace","debug","info","warn","error","off"];let Logger$2=class e{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,r){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!r,r&&(this.logFn=r,this.customLogFn=!0)}subLogger(t){const r=this.subLoggers.filter(e=>e.name===t)[0];if(void 0!==r)return r;Object.keys(this).forEach(e=>{if(e===t)throw new Error("This sub logger name is not allowed.")});const n=new e(t,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(n),n}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,r){this.publishMessage(t||"info",e,r)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error",t)}canPublish(e,t){return order$1.indexOf(e)>=order$1.indexOf(t||this.consoleLevel()||"trace")}publishMessage(t,r,n){const i=this.loggerFullName;if("error"===t&&!n){const e=new Error;e.stack&&(r=r+"\n"+e.stack.split("\n").slice(4).join("\n"))}if(this.canPublish(t,this.publishLevel())){const o=e.Interop;if(o)try{if(o.methods({name:e.InteropMethodName}).length>0){const s={msg:r,logger:i,level:t};n&&n instanceof Error&&(s.error={message:n.message,stack:n.stack??""}),o.invoke(e.InteropMethodName,s).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${e.message}`,e)})}}catch{}}if(this.canPublish(t)){let e="";if(this.includeTimeAndLevel){const r=new Date;e=`[${`${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}:${r.getMilliseconds()}`}] [${t}] `}const o=`${e}${i}: ${r}`;switch(t){case"trace":this.logFn.debug(o);break;case"debug":this.logFn.debug?this.logFn.debug(o):this.logFn.log(o);break;case"info":this.logFn.info(o);break;case"warn":this.logFn.warn(o);break;case"error":n?this.logFn.error(o,n):this.logFn.error(o)}}}};const GW_MESSAGE_CREATE_CONTEXT$1="create-context",GW_MESSAGE_ACTIVITY_CREATED$1="created",GW_MESSAGE_ACTIVITY_DESTROYED$1="destroyed",GW_MESSAGE_CONTEXT_CREATED$1="context-created",GW_MESSAGE_CONTEXT_ADDED$1="context-added",GW_MESSAGE_SUBSCRIBE_CONTEXT$1="subscribe-context",GW_MESSAGE_SUBSCRIBED_CONTEXT$1="subscribed-context",GW_MESSAGE_UNSUBSCRIBE_CONTEXT$1="unsubscribe-context",GW_MESSAGE_DESTROY_CONTEXT$1="destroy-context",GW_MESSAGE_CONTEXT_DESTROYED$1="context-destroyed",GW_MESSAGE_UPDATE_CONTEXT$1="update-context",GW_MESSAGE_CONTEXT_UPDATED$1="context-updated",GW_MESSAGE_JOINED_ACTIVITY$1="joined",ContextMessageReplaySpec$1={get name(){return"context"},get types(){return[GW_MESSAGE_CREATE_CONTEXT$1,GW_MESSAGE_ACTIVITY_CREATED$1,GW_MESSAGE_ACTIVITY_DESTROYED$1,GW_MESSAGE_CONTEXT_CREATED$1,GW_MESSAGE_CONTEXT_ADDED$1,GW_MESSAGE_SUBSCRIBE_CONTEXT$1,GW_MESSAGE_SUBSCRIBED_CONTEXT$1,GW_MESSAGE_UNSUBSCRIBE_CONTEXT$1,GW_MESSAGE_DESTROY_CONTEXT$1,GW_MESSAGE_CONTEXT_DESTROYED$1,GW_MESSAGE_UPDATE_CONTEXT$1,GW_MESSAGE_CONTEXT_UPDATED$1,GW_MESSAGE_JOINED_ACTIVITY$1]}};var version$4="6.8.1";function prepareConfig$1(e,t,r){let n;if(Utils$1.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{n=JSON.parse(e)}catch{}}function i(){if(e.application)return e.application;if(r)return r.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=nanoid$6(10);return Utils$1.isNode()?n?n.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const o=function(){const o=e.gateway,s=o?.protocolVersion??3,a=o?.reconnectInterval,c=o?.reconnectAttempts;let l=o?.ws;const u=o?.sharedWorker,d=o?.inproc,h=o?.webPlatform??void 0;let p,g,m,f,y;r&&(l=r.gwURL),Utils$1.isNode()&&n&&n.gwURL&&(l=n.gwURL),l||u||d||(l="ws://localhost:8385");const $=i();let b=$;void 0!==r?(g=r.windowId,m=r.pid,r.env&&(f=r.env.env,y=r.env.region),b=r.application??"glue-app",p=r.appInstanceId):Utils$1.isNode()?(m=process.pid,n&&(f=n.env,y=n.region,p=n.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,m=window?.glue42electron.pid,f=window?.glue42electron.env,y=window?.glue42electron.region,b=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const v=e.gateway?.replaySpecs??[];v.push(ContextMessageReplaySpec$1);let w={application:b,applicationName:$,windowId:g,instance:p,process:m,region:y,environment:f,api:t.version||version$4};return e.identity&&(w=Object.assign(w,e.identity)),{identity:w,reconnectInterval:a,ws:l,sharedWorker:u,webPlatform:h,inproc:d,protocolVersion:s,reconnectAttempts:c,replaySpecs:v}}();let s=i();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(s=t)}return{bus:e.bus??!1,application:s,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Utils$1.isNode()&&n&&n.gwToken?{gatewayToken:n.gwToken}:e.gateway?.webPlatform?{username:"glue42",password:""}:void 0,logger:function(){let t=e.logger;const n="warn";let i;return t||(t=n),r&&(i=r.consoleLogLevel),"string"==typeof t?{console:i??t,publish:n}:{console:i??t.console??n,publish:t.publish??n}}(),connection:o,metrics:e.metrics??!0,contexts:function(){const t={reAnnounceKnownContexts:!0,subscribeOnUpdate:!0,subscribeOnGet:!0,onlyReAnnounceSubscribedContexts:!0};return void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?t:"object"==typeof e.contexts&&{...t,...e.contexts}}(),version:t.version||version$4,libs:t.libs??[],customLogger:e.customLogger}}let GW3ContextData$1=class{name;contextId;context;isAnnounced;createdByUs;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;get hasReceivedSnapshot(){return this.snapshotPromiseWrapper.resolved}set hasReceivedSnapshot(e){e?this.snapshotPromiseWrapper.resolve():this.snapshotPromiseWrapper=new PromiseWrapper$2}get snapshotPromise(){return this.snapshotPromiseWrapper.promise}snapshotPromiseWrapper;constructor(e,t,r,n){this.contextId=e,this.name=t,this.isAnnounced=r,this.activityId=n,this.context={},this.snapshotPromiseWrapper=new PromiseWrapper$2}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}};var lodash_clonedeep$1={exports:{}};lodash_clonedeep$1.exports,function(e,t){var r="__lodash_hash_undefined__",n=9007199254740991,i="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",l="[object Map]",u="[object Number]",d="[object Object]",h="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",$="[object ArrayBuffer]",b="[object DataView]",v="[object Float32Array]",w="[object Float64Array]",S="[object Int8Array]",_="[object Int16Array]",E="[object Int32Array]",C="[object Uint8Array]",I="[object Uint8ClampedArray]",T="[object Uint16Array]",A="[object Uint32Array]",D=/\w*$/,x=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,O={};O[i]=O["[object Array]"]=O[$]=O[b]=O[o]=O[s]=O[v]=O[w]=O[S]=O[_]=O[E]=O[l]=O[u]=O[d]=O[p]=O[g]=O[m]=O[f]=O[C]=O[I]=O[T]=O[A]=!0,O["[object Error]"]=O[a]=O[y]=!1;var N="object"==typeof commonjsGlobal$2&&commonjsGlobal$2&&commonjsGlobal$2.Object===Object&&commonjsGlobal$2,P="object"==typeof self&&self&&self.Object===Object&&self,k=N||P||Function("return this")(),M=t&&!t.nodeType&&t,L=M&&e&&!e.nodeType&&e,F=L&&L.exports===M;function j(e,t){return e.set(t[0],t[1]),e}function U(e,t){return e.add(t),e}function B(e,t,r,n){for(var i=-1,o=e?e.length:0;++i-1},Ie.prototype.set=function(e,t){var r=this.__data__,n=Re(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new Ce,map:new(pe||Ie),string:new Ce}},Te.prototype.delete=function(e){return Me(this,e).delete(e)},Te.prototype.get=function(e){return Me(this,e).get(e)},Te.prototype.has=function(e){return Me(this,e).has(e)},Te.prototype.set=function(e,t){return Me(this,e).set(e,t),this},Ae.prototype.clear=function(){this.__data__=new Ie},Ae.prototype.delete=function(e){return this.__data__.delete(e)},Ae.prototype.get=function(e){return this.__data__.get(e)},Ae.prototype.has=function(e){return this.__data__.has(e)},Ae.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Ie){var n=r.__data__;if(!pe||n.length<199)return n.push([e,t]),this;r=this.__data__=new Te(n)}return r.set(e,t),this};var Fe=le?z(le,Object):function(){return[]},je=function(e){return ee.call(e)};function Ue(e,t){return!!(t=null==t?n:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=n}(e.length)&&!Je(e)}var Ge=ue||function(){return!1};function Je(e){var t=Ke(e)?ee.call(e):"";return t==a||t==c}function Ke(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ve(e){return We(e)?De(e):function(e){if(!Be(e))return de(e);var t=[];for(var r in Object(e))Q.call(e,r)&&"constructor"!=r&&t.push(r);return t}(e)}e.exports=function(e){return Oe(e,!0,!0)}}(lodash_clonedeep$1,lodash_clonedeep$1.exports);var lodash_clonedeepExports$1=lodash_clonedeep$1.exports,cloneDeep$1=getDefaultExportFromCjs$3(lodash_clonedeepExports$1);function applyContextDelta$1(e,t,r){try{if(r?.canPublish("trace")&&r?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=deepClone$1(e,void 0),t.commands){for(const r of t.commands)"remove"===r.type?deletePath$1(e,r.path):"set"===r.type&&setValueToPath$1(e,r.value,r.path);return e}const n=t.added,i=t.updated,o=t.removed;return n&&Object.keys(n).forEach(t=>{e[t]=n[t]}),i&&Object.keys(i).forEach(t=>{mergeObjectsProperties$1(t,e,i)}),o&&o.forEach(t=>{delete e[t]}),e}catch(n){return r?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,n),e}}function deepClone$1(e,t){return cloneDeep$1(e)}const mergeObjectsProperties$1=(e,t,r)=>{const n=r[e];if(void 0===n)return t;const i=t[e];return i&&n?"string"==typeof i||"number"==typeof i||"boolean"==typeof i||"string"==typeof n||"number"==typeof n||"boolean"==typeof n||Array.isArray(i)||Array.isArray(n)?(t[e]=n,t):(t[e]=Object.assign({},i,n),t):(t[e]=n,t)};function deepEqual$3(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const r in e)if(e.hasOwnProperty(r)){if(!t.hasOwnProperty(r))return!1;if(e[r]!==t[r]){if("object"!=typeof e[r])return!1;if(!deepEqual$3(e[r],t[r]))return!1}}for(const r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}function setValueToPath$1(e,t,r){const n=r.split("."),i=["__proto__","constructor","prototype"];let o;for(o=0;o"object"==typeof t[r]?isSubset$1(e?.[r]||{},t[r]||{}):t[r]===e?.[r])}function deletePath$1(e,t){const r=t.split(".");let n;for(n=0;n"context"===e.uri);this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._subscribeOnUpdate=e.subscribeOnUpdate??!0,this._subscribeOnGet=e.subscribeOnGet??!0,this._onlyReAnnounceSubscribedContexts=e.onlyReAnnounceSubscribedContexts??!0,this._gw3Session=this._connection.domain("global",[GW_MESSAGE_CONTEXT_CREATED$1,GW_MESSAGE_SUBSCRIBED_CONTEXT$1,GW_MESSAGE_CONTEXT_DESTROYED$1,GW_MESSAGE_CONTEXT_UPDATED$1]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined(e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then(()=>this._connection.setLibReAnnounced({name:"contexts"})).catch(e=>{this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(e)}`)}):(this._contextsTempCache={},this._connection.setLibReAnnounced({name:"contexts"}))}),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec$1.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED$1||t===GW_MESSAGE_CONTEXT_ADDED$1||t===GW_MESSAGE_ACTIVITY_CREATED$1?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT$1||t===GW_MESSAGE_CONTEXT_UPDATED$1||t===GW_MESSAGE_JOINED_ACTIVITY$1?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED$1&&t!==GW_MESSAGE_ACTIVITY_DESTROYED$1||this.handleContextDestroyedMessage(e))})}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:GW_MESSAGE_CREATE_CONTEXT$1,domain:"global",name:e,data:t,lifetime:"retained"}).then(r=>{this._contextNameToId[e]=r.context_id,this._contextIdToName[r.context_id]=e;const n=this._contextNameToData[e]||new GW3ContextData$1(r.context_id,e,!0,void 0);return n.isAnnounced=!0,n.name=e,n.contextId=r.context_id,n.context=r.data||deepClone$1(t),n.hasReceivedSnapshot=!0,this._contextNameToData[e]=n,delete this._creationPromises[e],n.sentExplicitSubscription=!0,n.createdByUs=!0,this.subscribe(e,()=>{}),r.context_id})),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter(e=>this._contextNameToData[e].isAnnounced)}async update(e,t){t&&(t=deepClone$1(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return void await this.createContext(e,t);const n=await this.get(r.name),i=this.setPathSupported?this.calculateContextDeltaV2(n,t):this.calculateContextDeltaV1(n,t);if(!(Object.keys(i.added).length||Object.keys(i.updated).length||i.removed.length||i.commands?.length))return Promise.resolve();const o=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT$1,domain:"global",context_id:r.contextId,delta:i},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&(await r.snapshotPromise,this.handleUpdated(r,i,{updaterId:o.peer_id}))}async set(e,t){t&&(t=deepClone$1(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return this.createContext(e,t);const n=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT$1,domain:"global",context_id:r.contextId,delta:{reset:t}},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&this.handleUpdated(r,{reset:t,added:{},removed:[],updated:{}},{updaterId:n.peer_id})}setPath(e,t,r){return this.setPathSupported?this.setPaths(e,[{path:t,value:r}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=deepClone$1(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced){const r={};for(const e of t)setValueToPath$1(r,e.value,e.path);return this.createContext(e,r)}const n=[];for(const e of t)null===e.value?n.push({type:"remove",path:e.path}):n.push({type:"set",path:e.path,value:e.value});const i=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT$1,domain:"global",context_id:r.contextId,delta:{commands:n}},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&(await r.snapshotPromise,this.handleUpdated(r,{added:{},removed:[],updated:{},commands:n},{updaterId:i.peer_id}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return!t&&this._subscribeOnGet&&this.subscribe(e,()=>{}),Promise.resolve({});if(t&&!t.sentExplicitSubscription)return new Promise((t,r)=>{this.subscribe(e,(e,r,n,i)=>{this._subscribeOnGet||this.unsubscribe(i),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):r(e)})});await t.snapshotPromise;const r=t?.context??{};return Promise.resolve(deepClone$1(r))}isInvalidContextError(e){return e.reason_uri===this.ERROR_URI_INVALID_CONTEXT||e.reason_uri===this.ERROR_URI_FAILURE&&e.reason?.startsWith("Unable to find context with id")}async subscribe(e,t,r){e in this._creationPromises&&await this._creationPromises[e];const n=void 0===r?this._nextCallbackSubscriptionNumber:r;void 0===r&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:n,callback:t}));let i=this._contextNameToData[e];if(!i||!i.isAnnounced)return i=i||new GW3ContextData$1(void 0,e,!1,void 0),this._contextNameToData[e]=i,i.updateCallbacks[n]=t,Promise.resolve(n);const o=i.hasCallbacks();if(i.updateCallbacks[n]=t,o){if(i.hasReceivedSnapshot&&!r){const e=deepClone$1(i.context);t(e,e,[],n)}return Promise.resolve(n)}if(i.joinedActivity||i.createdByUs){if(i.hasReceivedSnapshot&&!r){const e=deepClone$1(i.context);t(e,e,[],n)}return Promise.resolve(n)}if(i.context&&i.sentExplicitSubscription){if(i.hasReceivedSnapshot&&!r){const e=deepClone$1(i.context);t(e,e,[],n)}return Promise.resolve(n)}return this.sendSubscribe(i).then(()=>n,()=>(this.unsubscribe(n,!0),n))}unsubscribe(e,t){t||(this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter(t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const r=this._contextNameToData[t];if(!r)continue;const n=r.hasCallbacks();delete r.updateCallbacks[e],r.isAnnounced&&n&&!r.hasCallbacks()&&r.sentExplicitSubscription&&(r.hasReceivedSnapshot=!1,r.context={},this.sendUnsubscribe(r).catch(()=>{})),r.isAnnounced||r.hasCallbacks()||(delete this._contextNameToData[t],delete this._contextNameToId[t],r.contextId&&delete this._contextIdToName[r.contextId])}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e],r=t?.contextId;return t&&r?this._gw3Session.send({type:GW_MESSAGE_DESTROY_CONTEXT$1,domain:"global",context_id:t.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,r){const n=e.context;e.context=applyContextDelta$1(e.context,t,this._logger),this._contextNameToData[e.name]!==e||deepEqual$3(n,e.context)||this.invokeUpdateCallbacks(e,t,r)}subscribeToContextCreatedMessages(){const e=[GW_MESSAGE_CONTEXT_ADDED$1,GW_MESSAGE_CONTEXT_CREATED$1,GW_MESSAGE_ACTIVITY_CREATED$1];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===GW_MESSAGE_ACTIVITY_CREATED$1?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===GW_MESSAGE_CONTEXT_ADDED$1&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const r=this._contextIdToName[e.context_id];if(!r)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[r])throw new Error("Received created event for context with unknown id: "+e.context_id);let n=this._contextNameToData[r];if(n){if(n.isAnnounced)return;if(!n.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");n.isAnnounced=!0,n.contextId=e.context_id,n.activityId=e.activity_id,n.sentExplicitSubscription||this.sendSubscribe(n).catch(()=>{})}else this._contextNameToData[r]=n=new GW3ContextData$1(e.context_id,r,!0,e.activity_id),this._trackAllContexts&&this.subscribe(r,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[GW_MESSAGE_CONTEXT_UPDATED$1,GW_MESSAGE_SUBSCRIBED_CONTEXT$1,GW_MESSAGE_JOINED_ACTIVITY$1];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,r=e.context_id;let n=this._contextNameToData[this._contextIdToName[r]];const i=!n||!n.isAnnounced;if(t===GW_MESSAGE_JOINED_ACTIVITY$1)n||(n=this._contextNameToData[e.activity_id]||new GW3ContextData$1(r,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=n,this._contextIdToName[r]=e.activity_id,this._contextNameToId[e.activity_id]=r,n.contextId=r,n.isAnnounced=!0,n.activityId=e.activity_id,n.joinedActivity=!0;else if(!n||!n.isAnnounced)return void(t===GW_MESSAGE_SUBSCRIBED_CONTEXT$1?(n=n||new GW3ContextData$1(r,e.name,!0,void 0),n.sentExplicitSubscription=!0,this._contextNameToData[e.name]=n,this._contextIdToName[r]=e.name,this._contextNameToId[e.name]=r):this._logger.error(`Received 'update' for unknown context: ${r}`));const o=n.context;if(n.hasReceivedSnapshot=!0,t===GW_MESSAGE_SUBSCRIBED_CONTEXT$1)n.context=e.data??{};else if(t===GW_MESSAGE_JOINED_ACTIVITY$1)n.context=e.context_snapshot??{};else{if(t!==GW_MESSAGE_CONTEXT_UPDATED$1)throw new Error("Unrecognized context update message "+t);n.context=applyContextDelta$1(n.context,e.delta,this._logger)}!i&&deepEqual$3(n.context,o)&&t!==GW_MESSAGE_SUBSCRIBED_CONTEXT$1||this.invokeUpdateCallbacks(n,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,r){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),setValueToPath$1(t.updated,null,e.path)):"set"===e.type&&setValueToPath$1(t.updated,e.value,e.path)}for(const n in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(n))try{(0,e.updateCallbacks[n])(deepClone$1(e.context),deepClone$1(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(n,10),r)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[GW_MESSAGE_CONTEXT_DESTROYED$1,GW_MESSAGE_ACTIVITY_DESTROYED$1];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,r;if(e.type===GW_MESSAGE_ACTIVITY_DESTROYED$1){if(r=e.activity_id,t=this._contextNameToId[r],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,r=this._contextIdToName[t],!r)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[r];const n=this._contextNameToData[r];delete this._contextNameToData[r],n&&n.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}async sendSubscribe(e){e.sentExplicitSubscription=!0;try{return void await this._gw3Session.send({type:GW_MESSAGE_SUBSCRIBE_CONTEXT$1,domain:"global",context_id:e.contextId})}catch(t){throw e.sentExplicitSubscription=!1,t}}async sendUnsubscribe(e){const t=e.sentExplicitSubscription;e.sentExplicitSubscription=!1;try{return void await this._gw3Session.send({type:GW_MESSAGE_UNSUBSCRIBE_CONTEXT$1,domain:"global",context_id:e.contextId})}catch(r){throw e.sentExplicitSubscription=t,r}}calculateContextDeltaV1(e,t){const r={added:{},updated:{},removed:[],reset:void 0};if(e)for(const n of Object.keys(e))-1===Object.keys(t).indexOf(n)||null===t[n]||deepEqual$3(e[n],t[n])||(r.updated[n]=t[n]);for(const n of Object.keys(t))e&&-1!==Object.keys(e).indexOf(n)?null===t[n]&&r.removed.push(n):null!==t[n]&&(r.added[n]=t[n]);return r}calculateContextDeltaV2(e,t){const r={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const n of Object.keys(t))if(null!==t[n]){deepEqual$3(e?e[n]:null,t[n])||r.commands?.push({type:"set",path:n,value:t[n]})}else r.commands?.push({type:"remove",path:n});return r}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey,!0),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((e,t)=>{const r=this._contextNameToData[t];return(!this._onlyReAnnounceSubscribedContexts||r.hasReceivedSnapshot)&&(e[t]=this._contextNameToData[t].context),e},{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec$1.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED$1||t===GW_MESSAGE_CONTEXT_ADDED$1||t===GW_MESSAGE_ACTIVITY_CREATED$1?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT$1||t===GW_MESSAGE_CONTEXT_UPDATED$1||t===GW_MESSAGE_JOINED_ACTIVITY$1?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED$1&&t!==GW_MESSAGE_ACTIVITY_DESTROYED$1||this.handleContextDestroyedMessage(e))}),await Promise.all(this._contextsSubscriptionsCache.map(e=>this.subscribe(e.contextName,e.callback,e.subKey))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise(e=>setTimeout(()=>e(),0))}},ContextsModule$1=class{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new GW3Bridge$1(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,r){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(r),this.set(e,r)):this._bridge.setPath(e,t,r)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:r}of t){this.checkPath(e);""===e&&this.checkData(r)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(e,r,n,i,o)=>t(e,r,n,()=>this._bridge.unsubscribe(i),o)).then(e=>()=>{this._bridge.unsubscribe(e)})}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}};function promisify$1(e,t,r){return"function"!=typeof t&&"function"!=typeof r?e:("function"!=typeof t?t=()=>{}:"function"!=typeof r&&(r=()=>{}),e.then(t,r))}function rejectAfter$1(e=0,t,r){let n;const i=()=>{n&&clearTimeout(n)};return t.then(()=>{i()}).catch(()=>{i()}),new Promise((t,i)=>{n=setTimeout(()=>i(r),e)})}var ok$4=function(e){return{ok:!0,result:e}},err$4=function(e){return{ok:!1,error:e}},asPromise$4=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$4=function(e,t){return!0===t.ok?t.result:e},withException$4=function(e){if(!0===e.ok)return e.result;throw e.error},map$5=function(e,t){return!0===t.ok?ok$4(e(t.result)):t},map2$4=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$4(e(t.result,r.result))},mapError$4=function(e,t){return!0===t.ok?t:err$4(e(t.error))},andThen$4=function(e,t){return!0===t.ok?e(t.result):t},__assign$4=function(){return __assign$4=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{const r=typeof e;return"function"===r?anyJson$4():fail$1$1(`The provided argument as ${t} should be of type function, provided: ${typeof r}`)},nonEmptyStringDecoder$5=string$7().where(e=>e.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$4=number$7().where(e=>e>=0,"Expected a non-negative number or 0"),methodDefinitionDecoder$1=object$5({name:nonEmptyStringDecoder$5,objectTypes:optional$5(array$5(nonEmptyStringDecoder$5)),displayName:optional$5(nonEmptyStringDecoder$5),accepts:optional$5(nonEmptyStringDecoder$5),returns:optional$5(nonEmptyStringDecoder$5),description:optional$5(nonEmptyStringDecoder$5),version:optional$5(nonNegativeNumberDecoder$4),supportsStreaming:optional$5(boolean$6()),flags:optional$5(object$5()),getServers:optional$5(anyJson$4().andThen(e=>functionCheck$2(e,"method definition getServers")))}),methodFilterDecoder$1=union$3(nonEmptyStringDecoder$5,methodDefinitionDecoder$1),instanceDecoder$1=object$5({application:optional$5(nonEmptyStringDecoder$5),applicationName:optional$5(nonEmptyStringDecoder$5),pid:optional$5(nonNegativeNumberDecoder$4),machine:optional$5(nonEmptyStringDecoder$5),user:optional$5(nonEmptyStringDecoder$5),environment:optional$5(nonEmptyStringDecoder$5),region:optional$5(nonEmptyStringDecoder$5),service:optional$5(nonEmptyStringDecoder$5),instance:optional$5(nonEmptyStringDecoder$5),windowId:optional$5(nonEmptyStringDecoder$5),peerId:optional$5(nonEmptyStringDecoder$5),isLocal:optional$5(boolean$6()),api:optional$5(nonEmptyStringDecoder$5),getMethods:optional$5(anyJson$4().andThen(e=>functionCheck$2(e,"instance getMethods"))),getStreams:optional$5(anyJson$4().andThen(e=>functionCheck$2(e,"instance getStreams")))}),targetDecoder$1=union$3(constant$4("best"),constant$4("all"),constant$4("skipMine"),instanceDecoder$1,array$5(instanceDecoder$1)),invokeOptionsDecoder$1=object$5({waitTimeoutMs:optional$5(nonNegativeNumberDecoder$4),methodResponseTimeoutMs:optional$5(nonNegativeNumberDecoder$4)});var InvokeStatus$1;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(InvokeStatus$1||(InvokeStatus$1={}));let Client$1=class{protocol;repo;instance;configuration;constructor(e,t,r,n){this.protocol=e,this.repo=t,this.instance=r,this.configuration=n}subscribe(e,t,r,n,i){const o=(e,r,n,o)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(r,t,e,n,o,i)},s=new Promise((r,n)=>{const i=e=>{r(e)},s=e=>{n(e)};if(!e)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void n(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let l=0,u=this.getServerMethodsByFilterAndTarget(a,c);if(u.length>0)o(u,u[0].methods[0],i,s);else{const r=()=>{if(c&&t.waitTimeoutMs)if(l+=500,u=this.getServerMethodsByFilterAndTarget(a,c),u.length>0){const e=u[0].methods[0];o(u,e,i,s)}else if(l>=t.waitTimeoutMs){o(u,"string"==typeof e?{name:e}:e,i,s)}else setTimeout(r,500)};setTimeout(r,500)}});return promisify$1(s,r,n)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map(e=>e.server.instance)}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved((t,r)=>{e(t,r)})}serverMethodAdded(e){return this.repo.onServerMethodAdded((t,r)=>{e({server:t,method:r})})}serverMethodRemoved(e){return this.repo.onServerMethodRemoved((t,r)=>{e({server:t,method:r})})}async invoke(e,t,r,n,i,o){return promisify$1((async()=>{const s="string"==typeof e?{name:e}:{...e};t||(t={}),r||(r="best"),n||(n={});const a=methodFilterDecoder$1.run(s);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if("object"!=typeof t){const e="The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const c=targetDecoder$1.run(r);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const l=invokeOptionsDecoder$1.run(n);if(!l.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(l.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(i&&"function"!=typeof i){const e="The provided 'success' function is invalid. Error: The success should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(o&&"function"!=typeof o){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=n.method_response_timeout,void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=n.wait_for_method_timeout,void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=this.configuration.waitTimeoutMs));let u=this.getServerMethodsByFilterAndTarget(s,r);if(0===u.length)try{u=await this.tryToAwaitForMethods(s,r,n)}catch(n){const i=`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(r)}`;return Promise.reject(this.generateInvalidInputInvocationResult(i,s,t))}const d=n.methodResponseTimeoutMs,h=n,p=u.map(e=>{const r=nanoid$6(10),n=e.methods[0],i=e.server,o=this.protocol.client.invoke(r,n,t,i,h);return Promise.race([o,rejectAfter$1(d,o,{invocationId:r,message:`Invocation timeout (${d} ms) reached for method name: ${n?.name}, target instance: ${JSON.stringify(i.instance)}, options: ${JSON.stringify(h)}`,status:InvokeStatus$1.Error})])}),g=await Promise.all(p),m=this.getInvocationResultObj(g,s,t);return g.every(e=>e.status===InvokeStatus$1.Error)?Promise.reject(m):m})(),i,o)}generateInvalidInputInvocationResult(e,t,r){const n={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},i={invocationId:nanoid$6(10),status:InvokeStatus$1.Error,message:e};return this.getInvocationResultObj([i],n,r)}getInvocationResultObj(e,t,r){const n=e.filter(e=>e.status===InvokeStatus$1.Success).reduce((e,n)=>e=[...e,{executed_by:n.instance,returned:n.result,called_with:r,method:t,message:n.message,status:n.status}],[]),i=e.filter(e=>e.status===InvokeStatus$1.Error).reduce((e,n)=>e=[...e,{executed_by:n.instance,called_with:r,name:t.name,message:n.message}],[]),o=e[0];return{method:t,called_with:r,returned:o.result,executed_by:o.instance,all_return_values:n,all_errors:i,message:o.message,status:o.status}}tryToAwaitForMethods(e,t,r){return new Promise((n,i)=>{if(0===r.waitTimeoutMs)return void i();let o=0;const s=setInterval(()=>{o+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(s),n(a);else if(o>=(r.waitTimeoutMs||1e4))return clearInterval(s),void i()},500)})}filterByTarget(e,t){if("string"!=typeof e){let r;r=Array.isArray(e)?e:[e];const n=r.reduce((e,r)=>{const n=t.filter(e=>this.instanceMatch(r,e.server.instance));return e.concat(n)},[]);return n}if("all"===e)return[...t];if("best"===e){const e=t.find(e=>e.server.instance.isLocal);if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter(({server:e})=>e.instance.peerId!==this.instance.peerId);return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter(t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0]).every(r=>{let n;const i=e[r],o=t[r];switch(r){case"objectTypes":n=(i||[]).every(e=>(o||[]).includes(e));break;case"flags":n=isSubset$1(o||{},i||{});break;default:n=String(i).toLowerCase()===String(o).toLowerCase()}return n})}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter(t=>this.methodMatch(e,t))}getMethodsForInstance(e){const t=this.repo.getServers().filter(t=>this.instanceMatch(e,t.instance));if(0===t.length)return[];let r={};return 1===t.length?r=t[0].methods:t.forEach(e=>{Object.keys(e.methods).forEach(t=>{const n=e.methods[t];r[n.identifier]=n})}),Object.keys(r).map(e=>r[e])}getServers(e){const t=this.repo.getServers();return void 0===e?t.map(e=>({server:e,methods:[]})):t.reduce((t,r)=>{const n=Object.values(r.methods).filter(t=>this.methodMatch(e,t));return n.length>0&&t.push({server:r,methods:n}),t},[])}getServerMethodsByFilterAndTarget(e,t){const r=this.getServers(e);return this.filterByTarget(t,r)}},ServerSubscription$1=class{protocol;repoMethod;subscription;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.subscription=r}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}},Request$2=class{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.requestContext=r,this.arguments=r.arguments,this.instance=r.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}},ServerStreaming$1$1=class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest((e,t)=>this.handleSubRequest(e,t)),e.server.onSubAdded((e,t)=>this.handleSubAdded(e,t)),e.server.onSubRemoved((e,t)=>this.handleSubRemoved(e,t))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const r=new Request$2(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(r)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const r=new ServerSubscription$1(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(r)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const r=new ServerSubscription$1(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(r)}},ServerBranch$1=class{key;protocol;repoMethod;constructor(e,t,r){this.key=e,this.protocol=t,this.repoMethod=r}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map(e=>new ServerSubscription$1(this.protocol,this.repoMethod,e))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}},ServerStream$1=class{_protocol;_repoMethod;_server;name;constructor(e,t,r){this._protocol=e,this._repoMethod=t,this._server=r,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new ServerBranch$1(e,this._protocol,this._repoMethod):void 0:t.map(e=>new ServerBranch$1(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new ServerSubscription$1(this._protocol,this._repoMethod,e))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}close(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}},Server$1=class{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new ServerStreaming$1$1(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,r,n,i){const o=new Promise((r,n)=>{if(!e)return void n("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let o;if(o="string"==typeof e?{name:""+e}:{...e},!o.name)return n(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(o)}`);if(this.serverRepository.getList().some(e=>e.definition.name===o.name))return n(`A stream with the name "${o.name}" already exists! Please, provide a unique name for the stream.`);o.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const s=this.serverRepository.add({definition:o,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(s).then(()=>{let e;i?(e=i,i.updateRepoMethod(s)):e=new ServerStream$1(this.protocol,s,this),s.stream=e,r(e)}).catch(e=>{s.repoId&&this.serverRepository.remove(s.repoId),n(e)})});return promisify$1(o,r,n)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const r=async(e,r)=>{try{const n=t(e.args,e.instance);if(n&&"function"==typeof n.then){r(void 0,await n)}else r(void 0,n)}catch(e){r(e??"",e??"")}};return r.userCallback=t,this.registerCore(e,r)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const r=async(e,r)=>{try{let n=!1;const i=e=>{n||r(void 0,e),n=!0},o=e=>{n||(e||(e=""),r(e,e)),n=!0},s=t(e.args,e.instance,i,o);s&&"function"==typeof s.then&&s.then(i).catch(o)}catch(e){r(e,void 0)}};return r.userCallbackAsync=t,this.registerCore(e,r)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let r;if(r="string"==typeof e?{name:e}:e,void 0===r.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const n=this.serverRepository.getList().find(e=>e.definition.name===r.name&&(e.definition.supportsStreaming||!1)===t);if(!n)return Promise.reject(`Method with a name "${r.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([n])}async unregisterWithPredicate(e,t){const r=this.serverRepository.getList().filter(t=>e(t.definition)).filter(e=>(e.definition.supportsStreaming||!1)===t);if(!r||0===r.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(r)}removeMethodsOrStreams(e){const t=[];return e.forEach(e=>{const r=this.protocol.server.unregister(e).then(()=>{e.repoId&&this.serverRepository.remove(e.repoId)});t.push(r),this.addAsCurrentlyUnregistering(e.definition.name,r)}),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const r=new Promise(e=>setTimeout(e,5e3));this.currentlyUnregistering[e]=Promise.race([t,r]).then(()=>{delete this.currentlyUnregistering[e]})}async registerCore(e,t){let r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const n=this.currentlyUnregistering[r.name];void 0!==n&&await n;if(this.serverRepository.getList().some(e=>e.definition.name===r.name))return Promise.reject(`A method with the name "${r.name}" already exists! Please, provide a unique name for the method.`);if(r.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${r.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const i=this.serverRepository.add({definition:r,theFunction:t,protocolState:{}});return this.protocol.server.register(i).catch(e=>{throw i?.repoId&&this.serverRepository.remove(i.repoId),e})}onMethodInvoked(e,t,r){e&&e.theFunction&&e.theFunction(r,(r,n)=>{if(null!=r)if(r.message&&"string"==typeof r.message)r=r.message;else if("string"!=typeof r)try{r=JSON.stringify(r)}catch(e){r=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(r)}`}n?("object"!=typeof n||Array.isArray(n))&&(n={_value:n}):n={},this.protocol.server.methodInvocationResult(e,t,r,n)})}},InstanceWrapper$1=class{wrapped={};constructor(e,t,r){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter(e=>e.supportsStreaming)},t&&this.refreshWrappedObject(t),r&&(r.loggedIn(()=>{this.refresh(r)}),this.refresh(r))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,r=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(r)}refreshWrappedObject(e){Object.keys(e).forEach(t=>{this.wrapped[t]=e[t]}),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??nanoid$6(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}};const hideMethodSystemFlags$1=e=>({...e,flags:e.flags.metadata||{}});let ClientRepository$1=class{logger;API;servers={};myServer;methodsCount={};callbacks=CallbackRegistryFactory$3();constructor(e,t){this.logger=e,this.API=t;const r=this.API.instance.peerId;this.myServer={id:r,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[r]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const r=this.servers[t];if(r)return r.id;const n=new InstanceWrapper$1(this.API,e),i={id:t,methods:{},instance:n.unwrap(),wrapper:n};return this.servers[t]=i,this.callbacks.execute("onServerAdded",i.instance),t}removeServerById(e,t){const r=this.servers[e];r?(this.logger.debug(`removing server ${e}`),Object.keys(r.methods).forEach(t=>{this.removeServerMethod(e,t)}),delete this.servers[e],this.callbacks.execute("onServerRemoved",r.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");if(r.methods[t.id])return;const n=this.createMethodIdentifier(t),i=this,o={identifier:n,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>i.getServersByMethod(n)};o.object_types=o.objectTypes,o.display_name=o.displayName,o.version=o.version,r.methods[t.id]=o;const s=hideMethodSystemFlags$1(o);return this.methodsCount[n]||(this.methodsCount[n]=0,this.callbacks.execute("onMethodAdded",s)),this.methodsCount[n]=this.methodsCount[n]+1,this.callbacks.execute("onServerMethodAdded",r.instance,s),o}removeServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");const n=r.methods[t];delete r.methods[t];const i=hideMethodSystemFlags$1(n);this.methodsCount[n.identifier]=this.methodsCount[n.identifier]-1,0===this.methodsCount[n.identifier]&&this.callbacks.execute("onMethodRemoved",i),this.callbacks.execute("onServerMethodRemoved",r.instance,i)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags$1)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),r=this.getServers().map(e=>e.instance);return this.returnUnsubWithDelayedReplay(t,r,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),r=this.getMethods();return this.returnUnsubWithDelayedReplay(t,r,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let r=!1;const n=this.getServers();return setTimeout(()=>{n.forEach(t=>{const n=t.methods;Object.keys(n).forEach(i=>{r||e(t.instance,n[i])})})},0),()=>{r=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach(e=>{this.removeServerById(e,"reset")}),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",r=e.result_signature??"";return(e.name+t+r).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach(r=>{Object.values(r.methods).forEach(n=>{n.identifier===e&&t.push(r.instance)})}),t}returnUnsubWithDelayedReplay(e,t,r){let n=!1;return setTimeout(()=>{t.forEach(e=>{n||r(e)})},0),()=>{n=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach(([e,r])=>{t[e]=hideMethodSystemFlags$1(r)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}},ServerRepository$1=class{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter(t=>t.repoId!==e)}getById(e){if("string"==typeof e)return this.methods.find(t=>t.repoId===e)}getList(){return this.methods.map(e=>e)}length(){return this.methods.length}reset(){this.methods=[]}};const SUBSCRIPTION_REQUEST$1="onSubscriptionRequest",SUBSCRIPTION_ADDED$1="onSubscriptionAdded",SUBSCRIPTION_REMOVED$1="onSubscriptionRemoved";let ServerStreaming$2=class{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=CallbackRegistryFactory$3();nextStreamId=0;constructor(e,t,r,n){this.session=e,this.repository=t,this.serverRepository=r,this.logger=n,e.on("add-interest",e=>{this.handleAddInterest(e)}),e.on("remove-interest",e=>{this.handleRemoveInterest(e)})}acceptRequestOnBranch(e,t,r){if("string"!=typeof r&&(r=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const n=this.getStreamId(t,r),i=e.msg.subscription_id,o={id:i,arguments:e.arguments,instance:e.instance,branchKey:r,streamId:n,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[i]=o,this.session.sendFireAndForget({type:"accepted",subscription_id:i,stream_id:n}).catch(e=>{this.logger.warn(`Failed to send accepted message for subscription ${i}: ${JSON.stringify(e)}`)}),this.callbacks.execute(SUBSCRIPTION_ADDED$1,o,t)}rejectRequest(e,t,r){"string"!=typeof r&&(r=""),this.sendSubscriptionFailed("Subscription rejected by user. "+r,e.msg.subscription_id)}pushData(e,t,r){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof r?r=[r]:(!Array.isArray(r)||r.length<=0)&&(r=[]);const n=e.protocolState.branchKeyToStreamIdMap.filter(e=>!r||0===r.length||r.indexOf(e.key)>=0).map(e=>e.streamId);n.forEach(e=>{const r={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(r).catch(t=>{this.logger.warn(`Failed to send publish message for stream ${e}: ${JSON.stringify(t)}`)})})}pushDataToSingle(e,t,r){if("object"!=typeof r)throw new Error("Invalid arguments. Data must be an object.");const n={type:"post",subscription_id:t.id,data:r};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send post message for subscription ${t.id}: ${JSON.stringify(e)}`)})}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const r={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${t.id}: ${JSON.stringify(e)}`)}),t.instance,this.callbacks.execute(SUBSCRIPTION_REMOVED$1,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const r=e.protocolState.subscriptionsMap;let n=Object.keys(r).map(e=>r[e]);"string"==typeof t&&(n=n.filter(e=>e.branchKey===t)),n.forEach(e=>{delete r[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t).catch(t=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${e.id}: ${JSON.stringify(t)}`)})})}getSubscriptionList(e,t){if("object"!=typeof e)return[];let r=[];if(!e.protocolState.subscriptionsMap)return[];const n=e.protocolState.subscriptionsMap,i=Object.keys(n).map(e=>n[e]);return r="string"!=typeof t?i:i.filter(e=>e.branchKey===t),r}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,r=Object.keys(t).map(e=>t[e]),n=[];return r.forEach(e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===n.indexOf(t)&&n.push(t)}),n}onSubAdded(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED$1,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST$1,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED$1,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const r=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(SUBSCRIPTION_REMOVED$1,r,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),r=t?.instance??{},n={msg:e,arguments:e.arguments_kv||{},instance:r},i=this.serverRepository.getById(e.method_id);if(void 0===i){const t="No method with id "+e.method_id+" on this server.";return void this.sendSubscriptionFailed(t,e.subscription_id)}i.protocolState.subscriptionsMap&&i.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(SUBSCRIPTION_REQUEST$1,n,i)}sendSubscriptionFailed(e,t){const r={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send subscription failed message for subscription ${t}: ${JSON.stringify(e)}`)})}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const r=e.protocolState.branchKeyToStreamIdMap.filter(e=>e.key===t)[0];let n=r?r.streamId:void 0;return"string"==typeof n&&""!==n||(n=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:n})),n}},ServerProtocol$1=class{session;clientRepository;serverRepository;logger;callbacks=CallbackRegistryFactory$3();streaming;constructor(e,t,r,n){this.session=e,this.clientRepository=t,this.serverRepository=r,this.logger=n,this.streaming=new ServerStreaming$2(e,t,r,n.subLogger("streaming")),this.session.on("invoke",e=>this.handleInvokeMessage(e))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const r=e.definition,n=Object.assign({},{metadata:r.flags??{}},{streaming:t||!1}),i={type:"register",methods:[{id:e.repoId,name:r.name,display_name:r.displayName,description:r.description,version:r.version,flags:n,object_types:r.objectTypes||r.object_types,input_signature:r.accepts,result_signature:r.returns,restrictions:void 0}]};return this.session.send(i,{methodId:e.repoId}).then(()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)}).catch(t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t})}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,r,n){let i;i=r||""===r?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:r,context:n,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:n,request_id:void 0},this.session.sendFireAndForget(i).catch(r=>{this.logger.warn(`Failed to send method invocation result for method ${e.definition.name} invocation ${t} - ${JSON.stringify(r)}`)})}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,r){this.streaming.pushData(e,t,r)}pushDataToSingle(e,t,r){this.streaming.pushDataToSingle(e,t,r)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,r){this.streaming.acceptRequestOnBranch(e,t,r)}rejectRequest(e,t,r){this.streaming.rejectRequest(e,t,r)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,r=e.caller_id,n=e.method_id,i=e.arguments_kv,o=this.serverRepository.getList().filter(e=>e.repoId===n)[0];if(void 0===o)return;const s=this.clientRepository.getServerById(r)?.instance,a={args:i,instance:s};this.callbacks.execute("onInvoked",o,t,a)}},UserSubscription$1=class{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce((e,t)=>{if(t.subscriptionId){const r=this.repository.getServerById(t.serverId)?.instance;r&&e.push(r)}return e},[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach(t=>{e(t)})}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}},TimedCache$1=class{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=nanoid$6(10);this.cache.push({id:t,element:e});const r=setTimeout(()=>{const e=this.cache.findIndex(e=>e.id===t);e<0||this.cache.splice(e,1)},this.config.ELEMENT_TTL_MS);this.timeoutIds.push(r)}flush(){const e=this.cache.map(e=>e.element);return this.timeoutIds.forEach(e=>clearInterval(e)),this.cache=[],this.timeoutIds=[],e}};const STATUS_AWAITING_ACCEPT$1="awaitingAccept",STATUS_SUBSCRIBED$1="subscribed",ERR_MSG_SUB_FAILED$1="Subscription failed.",ERR_MSG_SUB_REJECTED$1="Subscription rejected.",ON_CLOSE_MSG_SERVER_INIT$1="ServerInitiated",ON_CLOSE_MSG_CLIENT_INIT$1="ClientInitiated";let ClientStreaming$1=class{session;repository;logger;subscriptionsList={};timedCache=new TimedCache$1({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,r,n,i,o){if(0===r.length)return void i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED$1+" No available servers matched the target params."});const s=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(s,e,t,n,i,t.methodResponseTimeout||1e4,o);"object"==typeof a?r.forEach(r=>{const n=r.server.id,i=r.methods.find(t=>t.name===e.name);if(!i)return void this.logger.error(`can not find method ${e.name} for target ${r.server.id}`);a.trackedServers.push({serverId:n,subscriptionId:void 0});const o={type:"subscribe",server_id:n,method_id:i.gatewayId,arguments_kv:t.arguments};this.session.send(o,{serverId:n,subLocalKey:s}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED$1+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,r,n,i,o,s){const a={localKey:e,status:STATUS_AWAITING_ACCEPT$1,method:t,params:r,success:n,error:i,trackedServers:[],handlers:{onData:s?.handlers.onData||[],onClosed:s?.handlers.onClosed||[],onConnected:s?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:s?.subscription};return s||(r.onData&&a.handlers.onData.push(r.onData),r.onClosed&&a.handlers.onClosed.push(r.onClosed),r.onConnected&&a.handlers.onConnected.push(r.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout(()=>{if(void 0===this.subscriptionsList[e])return;const n=this.subscriptionsList[e];n.status===STATUS_AWAITING_ACCEPT$1?(i({method:t,called_with:r.arguments,message:ERR_MSG_SUB_FAILED$1+" Subscription attempt timed out after "+o+" ms."}),delete this.subscriptionsList[e]):n.status===STATUS_SUBSCRIBED$1&&n.trackedServers.length>0&&(n.trackedServers=n.trackedServers.filter(e=>void 0!==e.subscriptionId),delete n.timeoutId,n.trackedServers.length<=0&&(this.callOnClosedHandlers(n),delete this.subscriptionsList[e]))},o),a}handleErrorSubscribing=e=>{const t=e._tag,r=t.subLocalKey,n=this.subscriptionsList[r];if("object"==typeof n&&(n.trackedServers=n.trackedServers.filter(e=>e.serverId!==t.serverId),n.trackedServers.length<=0)){if(clearTimeout(n.timeoutId),n.status===STATUS_AWAITING_ACCEPT$1){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",r="object"==typeof n.params.arguments?JSON.stringify(n.params.arguments):"{}";n.error({message:ERR_MSG_SUB_REJECTED$1+t+" Called with:"+r,called_with:n.params.arguments,method:n.method})}else n.status===STATUS_SUBSCRIBED$1&&this.callOnClosedHandlers(n);delete this.subscriptionsList[r]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=e._tag.serverId,i=r.trackedServers.filter(e=>e.serverId===n)[0];if("object"!=typeof i)return;i.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const o=r.status===STATUS_AWAITING_ACCEPT$1;if(r.status=STATUS_SUBSCRIBED$1,o){let e=!1,t=r.subscription;t?(t.setNewSubscription(r),r.success(t),e=!0):(t=new UserSubscription$1(this.repository,r),r.subscription=t,r.success(t));for(const n of r.handlers.onConnected)try{n(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.filter(t=>t.subscriptionId===e.subscription_id);if(1!==n.length)return;const i=e.oob,o=n[0].serverId,s=this.repository.getServerById(o),a=()=>({data:e.data,server:s?.instance??{},requestArguments:r.params.arguments,message:void 0,private:i}),c=r.handlers.onData,l=r.queued.data;c.length>0?c.forEach(e=>{"function"==typeof e&&e(a())}):l.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.length-1;r.trackedServers=r.trackedServers.filter(t=>t.subscriptionId!==e.subscription_id||(r.queued.closers.push(t.serverId),!1)),r.trackedServers.length===n&&(r.trackedServers.length<=0&&(this.timedCache.add(r),clearTimeout(r.timeoutId),this.callOnClosedHandlers(r),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const r=e.queued.closers.length,n=r>0?e.queued.closers[r-1]:null;let i;void 0!==n&&"string"==typeof n&&(i=this.repository.getServerById(n)?.instance??{}),e.handlers.onClosed.forEach(r=>{"function"==typeof r&&r({message:t||ON_CLOSE_MSG_SERVER_INIT$1,requestArguments:e.params.arguments||{},server:i,stream:e.method})})}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach(e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:ON_CLOSE_MSG_CLIENT_INIT$1}).catch(t=>{this.logger.warn(`Error sending unsubscribe for subscription id ${e.subscriptionId}: ${JSON.stringify(t)}`)}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])}),t.trackedServers=[],this.callOnClosedHandlers(t,ON_CLOSE_MSG_CLIENT_INIT$1),delete this.subscriptionsList[e])}},ClientProtocol$1=class{session;repository;logger;streaming;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("peer-added",e=>this.handlePeerAdded(e)),e.on("peer-removed",e=>this.handlePeerRemoved(e)),e.on("methods-added",e=>this.handleMethodsAddedMessage(e)),e.on("methods-removed",e=>this.handleMethodsRemovedMessage(e)),this.streaming=new ClientStreaming$1(e,t,r)}subscribe(e,t,r,n,i,o){this.streaming.subscribe(e,t,r,n,i,o)}invoke(e,t,r,n){const i=n.id,o={type:"call",server_id:i,method_id:t.gatewayId,arguments_kv:r};return this.session.send(o,{invocationId:e,serverId:i}).then(e=>this.handleResultMessage(e)).catch(e=>this.handleInvocationError(e))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,r=e.identity,n=!e.meta||e.meta.local,i=Number(r.process),o={machine:r.machine,pid:isNaN(i)?r.process:i,instance:r.instance,application:r.application,applicationName:r.applicationName,environment:r.environment,region:r.region,user:r.user,windowId:r.windowId,peerId:t,api:r.api,isLocal:n};this.repository.addServer(o,t)}handlePeerRemoved(e){const t=e.removed_id,r=e.reason;this.repository.removeServerById(t,r)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach(e=>{this.repository.addServerMethod(t,e)})}handleMethodsRemovedMessage(e){const t=e.server_id,r=e.methods,n=this.repository.getServerById(t);if(n){Object.keys(n.methods).forEach(e=>{const i=n.methods[e];r.indexOf(i.gatewayId)>-1&&this.repository.removeServerMethod(t,e)})}}handleResultMessage(e){const t=e._tag.invocationId,r=e.result,n=e._tag.serverId,i=this.repository.getServerById(n);return{invocationId:t,result:r,instance:i?.instance,status:InvokeStatus$1.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,r=e._tag.serverId,n=this.repository.getServerById(r),i=e.reason;return{invocationId:t,result:e.context,instance:n?.instance,status:InvokeStatus$1.Error,message:i}}return{invocationId:"",message:e.message,status:InvokeStatus$1.Error,error:e}}};function gW3ProtocolFactory$1(e,t,r,n,i,o){const s=i.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),l=t.domain("agm",["subscribed"]),u=new ServerProtocol$1(l,r,n,s.subLogger("server")),d=new ClientProtocol$1(l,r,s.subLogger("client"));return l.onJoined(i=>{r.addServer(e,t.peerId),i?async function(){s.info("reconnected - will replay registered methods and subscriptions"),d.drainSubscriptionsCache().forEach(e=>{const t=e.method,r=Object.assign({},e.params);s.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(r)}`),o.client.subscribe(t,r,void 0,void 0,e).then(()=>s.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>s.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=d.drainSubscriptions();for(const r of t){const t=r.method,n=Object.assign({},r.params);s.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),e.push(o.client.subscribe(t,n,void 0,void 0,r).then(()=>s.info(`subscribing to method ${t.name} DONE`)))}const r=n.getList();n.reset();for(const t of r){const r=t.definition;t.stream?e.push(o.server.createStream(r,t.streamCallbacks,void 0,void 0,t.stream).then(()=>s.info(`subscribing to method ${r.name} DONE`)).catch(()=>s.warn(`subscribing to method ${r.name} FAILED`))):t?.theFunction?.userCallback?e.push(o.register(r,t.theFunction.userCallback).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(o.registerAsync(r,t.theFunction.userCallbackAsync).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`)))}await Promise.all(e),s.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>s.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:d,server:u}),a=void 0)}),l.onLeft(()=>{r.reset()}),l.join(),c}let Interop$1=class{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let r;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new InstanceWrapper$1(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new ClientRepository$1(e.logger.subLogger("cRep"),this),this.serverRepository=new ServerRepository$1,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);r=gW3ProtocolFactory$1(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=r.then(t=>(this.protocol=t,this.client=new Client$1(this.protocol,this.clientRepository,this.instance,e),this.server=new Server$1(this.protocol,this.serverRepository),this))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,r,n){return this.client.subscribe(e,t,r,n)}createStream(e,t,r,n){return this.server.createStream(e,t,r,n)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,r,n,i,o){return this.client.invoke(e,t,r,n,i,o)}waitForMethod(e){const t=new PromiseWrapper$2,r=this.client.methodAdded(n=>{n.name===e&&(r(),t.resolve(n))});return t.promise}};const successMessages$1=["subscribed","success"];let MessageBus$1=class{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",successMessages$1),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()})}ready(){return this.readyPromise}publish=(e,t,r)=>{const{routingKey:n,target:i}=r||{},o=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:n,target_identity:i});this.session.send(o).catch(t=>{this.logger.error(`Failed to publish message to topic ${e} with routing key ${n} for ${JSON.stringify(i)}: ${JSON.stringify(t)}`)})};subscribe=(e,t,r)=>new Promise((n,i)=>{const{routingKey:o,target:s}=r||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:o,source:s});this.session.send(a).then(r=>{const{subscription_id:i}=r;this.subscriptions.push({subscription_id:i,topic:e,callback:t,source:s}),n({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:i,peer_id:this.peerId}).then(()=>{this.subscriptions=this.subscriptions.filter(e=>e.subscription_id!==i)}).catch(e=>{this.logger.warn(`Failed to send unsubscribe request for ${i}: ${JSON.stringify(e)}`)}),Promise.resolve())})}).catch(e=>i(e))});watchOnEvent=()=>{this.session.on("event",e=>{const{data:t,subscription_id:r}=e,n=e["publisher-identity"],i=this.subscriptions.find(e=>e.subscription_id===r);i&&(i.source?this.keysMatch(i.source,n)&&i.callback(t,i.topic,n):i.callback(t,i.topic,n))})};removeEmptyValues(e){const t={};return Object.keys(e).forEach(r=>{void 0!==e[r]&&null!==e[r]&&(t[r]=e[r])}),t}keysMatch(e,t){const r=Object.keys(e);let n=!0;return r.forEach(r=>{e[r]!==t[r]&&(n=!1)}),n}};const IOConnectCoreFactory$1=(e,t)=>{const r="object"==typeof window?window.iodesktop??window.glue42gd:void 0,n="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),i=timer$1("glue"),o=prepareConfig$1(e=e||{},t=t||{},r);let s,a,c,l,u,d,h;const p={};function g(e,t,r){h=c.canPublish("trace"),h&&c.trace(`registering ${e} module`);const n=n=>{if(t.initTime=r.stop(),t.initEndTime=r.endTime,t.marks=r.marks,!h)return;const i=n?`${e} failed - ${n.message}`:`${e} is ready - ${r.endTime-r.startTime}`;c.trace(i)};t.initStartTime=r.startTime,t.ready?t.ready().then(()=>{n()}).catch(e=>{const t="string"==typeof e?new Error(e):e;n(t)}):n(),Array.isArray(e)||(e=[e]),e.forEach(e=>{p[e]=t,IOConnectCoreFactory$1[e]=t})}function m(){const e=timer$1("metrics"),t=o.metrics,n=r?.getMetricsPublishingEnabled,i=o.connection.identity,a=n||(()=>!0),u=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return l=metrics$2({connection:t?s:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:i?.service??r?.applicationName??o.application,instance:i?.instance??i?.windowId??nanoid$6(10),disableAutoAppSystem:u,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",l,e),Promise.resolve()}function f(){const e=timer$1("interop"),t={connection:s,logger:c.subLogger("interop")};return a=new Interop$1(t),Logger$2.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function y(){const e=o.activities&&3===s.protocolVersion;if(o.contexts||e){const e=timer$1("contexts");u=new ContextsModule$1({connection:s,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof o.contexts&&o.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof o.contexts&&o.contexts.reAnnounceKnownContexts,subscribeOnGet:"object"!=typeof o.contexts||o.contexts.subscribeOnGet,subscribeOnUpdate:"object"!=typeof o.contexts||o.contexts.subscribeOnUpdate,onlyReAnnounceSubscribedContexts:"object"!=typeof o.contexts||o.contexts.onlyReAnnounceSubscribedContexts}),g("contexts",u,e)}else{const e=s.replayer;e&&e.drain(ContextMessageReplaySpec$1.name)}return Promise.resolve()}async function $(){if(!o.bus)return Promise.resolve();const e=timer$1("bus");return d=new MessageBus$1(s,c.subLogger("bus")),g("bus",d,e),Promise.resolve()}function b(e){try{return e.forEach(e=>{!function(e,t){const r=timer$1(e),n=t(p);n&&g(e,n,r)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return n.then(function(){const e=timer$1("logger");return c=new Logger$2(`${o.connection.identity?.application}`,void 0,o.customLogger),c.consoleLevel(o.logger.console),c.publishLevel(o.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)}).then(function(){const e=timer$1("connection");s=new Connection$1(o.connection,c.subLogger("connection"));let t=Promise.resolve(o.auth);return o.connection&&!o.auth&&(r?t=r.getGWToken().then(e=>({gatewayToken:e})):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then(t=>{let r;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return r=t,s.login(r)}).then(()=>(g("connection",s,e),o)).catch(e=>{throw s&&s.logout(),e})}).then(()=>Promise.all([m(),f(),y(),$()])).then(()=>a.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(Utils$1.isNode()&&"undefined"==="undefined".env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>b(o.libs||[])).then(function(){const e=Object.keys(p).map(e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const n={coreVersion:version$4,version:o.version};i.stop();const h={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:c,interop:a,agm:a,connection:s,metrics:l,contexts:u,bus:d,version:o.version,userConfig:e,done:()=>(c?.info("done called by user..."),s.logout())};if(h.performance={get glueVer(){return o.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=getAllTimers$1();return Object.keys(e).map(t=>{const r=e[t];return{name:t,duration:r.endTime-r.startTime,marks:r.marks,startTime:r.startTime,endTime:r.endTime}})}},Object.keys(p).forEach(e=>{const t=p[e];h[e]=t}),h.config={},Object.keys(o).forEach(e=>{h.config[e]=o[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{h.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(h),r&&r.updatePerfData&&r.updatePerfData(h.performance),h.agm){const e=(e,t,r)=>function(){return h.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${r}' instead.`),e.apply(h.agm,arguments)},t=h.agm;t.method_added=e(h.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(h.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(h.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(h.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(h.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return h}).catch(e=>Promise.reject({err:e,libs:p}))};"undefined"!=typeof window&&(window.IOConnectCore=IOConnectCoreFactory$1),IOConnectCoreFactory$1.version=version$4,IOConnectCoreFactory$1.default=IOConnectCoreFactory$1;const iOConnectBrowserFactory=createFactoryFunction(IOConnectCoreFactory$1);if("undefined"!=typeof window){const e=window;e.IOBrowser=iOConnectBrowserFactory,delete e.GlueCore,delete e.IOConnectCore}const legacyGlobal$1=window.glue42gd||window.glue42core,ioGlobal$1=window.iodesktop||window.iobrowser;legacyGlobal$1||ioGlobal$1||(window.iobrowser={webStarted:!1}),window.iodesktop||window.iobrowser.system||(window.iobrowser.system=setupGlobalSystem()),iOConnectBrowserFactory.version=version$1$1;const Glue42CoreMessageTypes={connectionRequest:{name:"connectionRequest"},connectionRejected:{name:"connectionRejected"},connectionAccepted:{name:"connectionAccepted"},platformPing:{name:"platformPing"},platformReady:{name:"platformReady"},platformUnload:{name:"platformUnload"},clientUnload:{name:"clientUnload"},parentPing:{name:"parentPing"},parentReady:{name:"parentReady"},gatewayDisconnect:{name:"gatewayDisconnect"},gatewayInternalConnect:{name:"gatewayInternalConnect"},transportSwitchRequest:{name:"transportSwitchRequest"},transportSwitchResponse:{name:"transportSwitchResponse"},getCurrentTransport:{name:"getCurrentTransport"},getCurrentTransportResponse:{name:"getCurrentTransportResponse"},checkPreferredLogic:{name:"checkPreferredLogic"},checkPreferredConnection:{name:"checkPreferredConnection"},checkPreferredLogicResponse:{name:"checkPreferredLogicResponse"},checkPreferredConnectionResponse:{name:"checkPreferredConnectionResponse"}},GlueWebPlatformControlName="T42.Web.Platform.Control",GlueWebPlatformStreamName="T42.Web.Platform.Stream",GlueClientControlName="T42.Web.Client.Control",GlueWebPlatformWorkspacesStreamName="T42.Web.Platform.WSP.Stream",GlueWorkspaceFrameClientControlName="T42.Workspaces.Control",GlueWorkspacesEventsReceiverName="T42.Workspaces.Events",GlueWebIntentsPrefix="Tick42.FDC3.Intents.",ChannelContextPrefix="___channel___",serviceWorkerBroadcastChannelName="glue42-core-worker",webPlatformTransportName="web-platform",defaultNoAppWindowComponentAppName$1="no-app-window",errorChannel=new MessageChannel,FDC3HelloRequestType="WCP1Hello",FDC3HelloResponseType="WCP2LoadUrl",FDC3ProxyUrl="https://fdc3-web-proxy.interop.io",publicLicKey="-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxY2hhPdsQVno6NwsKm0+\nnhfhHvFsapevdtPt78jZRWgSAv9nbNtcAHyAOqisL0T2FaWPwZZcMs1qQEyyyQIU\nbase/s7oVGj5jLU32kYuAf3rA7uIdCpxT8UhJtj740KFUgT946a7hTXHL2DejxV0\niJhhDKIl/2UFWfYdIygz4ECCperhBnDw4JrdbTs6BnMZNGaBmQFT/HjkFUxkKkjI\nccwQdahc+yB2azG8vVwjsvhag9lo/zfhEEEKNX7BVFDBiPK/2RswNf0yaSTBs0Cd\njo+gwFr69/gap7xWwxobAuwIGyuGZx3RfVphryB9CKPebDZE0N47FakMSS+cOrpk\nejTNzNjhGybjVxNvpHtYaP5hwRWbDeptZ+cu+nafXH8p0HiVkeIy1RqiSstiGZ3v\nOa31j0oDT4mIe7r0BuleqkCkCIDe8EB2n+xJieWJmFzooswrYMQ6ry2m0moPwYEQ\nib6v4DLw7LTsnz/kK7yWeWlv1LsPF09CEBlfJLXvT+tXWHzf/bbWxH7SU5vgil0L\nwhbe4UJwBW4Cf3QDCoFCqwnGXUbzF8EbDKxPVWeCZa0zxT2L44JwMyVz3U1z7cOp\nAzI43TpwU/6hD0LMim14XfUKhtdV7bp8ulRHxgkZoZHpz+7CuYZLT0dG5xOiwUsE\nAfLTMnm30gbSGK3vtNeXbq8CAwEAAQ==\n-----END PUBLIC KEY-----\n",noop$1=async()=>{},MAX_SET_TIMEOUT_DELAY=2147483647,DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1=3e4,DEFAULT_WAIT_TIMEOUT_MS=3e4,systemPrefsAppName="io-connect-platform",notificationsPrefsKey="_ioCB_notifications",connectionProtocolVersion="2.0.0",globalTickIntervalMSForScheduler=3e3,maxConcurrentRequestsForScheduler=4,defaultCacheDBName="io-connect-rest-cache",defaultPlatformConfig={windows:{windowResponseTimeoutMs:1e4,defaultWindowOpenBounds:{top:0,left:0,width:800,height:600}},applications:{local:[]},layouts:{mode:"idb",local:[]},channels:{definitions:[],mode:"single"},plugins:{definitions:[]},licenseKey:"",gateway:{logging:{level:"info"}},themes:{defaultTheme:"dark"},connection:{},browser:{},environment:{},workspacesFrameCache:!0},defaultNotificationsConfig={enable:!0,enableToasts:!0,sourceFilter:{allowed:["*"],blocked:[]},showNotificationBadge:!0,clearNotificationOnClick:!0},defaultManagerFeatures={applicationsStore:!0,layoutsStore:!0,preferencesStore:!0},defaultTargetString="*",defaultFetchTimeoutMs=3e3,defaultOpenerTimeoutMs=1e3,defaultPreferredDiscoveryIntervalMS=15e3,defaultClientPortRequestTimeoutMS=15e3,defaultClientPreferredLogicTestTimeoutMS=5e3,checkIsOpenerIOConnect=e=>{if(!window.opener)return Promise.resolve(!1);if(window.name.includes("g42-"))return Promise.resolve(!0);const t=e?.allowedClientFallbackOrigin||defaultTargetString;return new Promise(e=>{const r=t=>{const n=t.data?.glue42core;n&&n.type===Glue42CoreMessageTypes.platformReady.name&&(window.removeEventListener("message",r),e(!0))};window.addEventListener("message",r);const n={glue42core:{type:Glue42CoreMessageTypes.platformPing.name}};window.opener.postMessage(n,t),setTimeout(()=>e(!1),defaultOpenerTimeoutMs)})},checkIfPlacedInWorkspace=()=>-1!==window.name.indexOf("#wsp"),fallbackToEnterprise=async e=>{const t=e?.browserFactory?await(e?.browserFactory(e?.browser)):await iOConnectBrowserFactory(e?.browser);return e?.applications?.local?.length&&await t.appManager.inMemory.import(e.applications.local,"merge"),e?.layouts?.local?.length&&await t.layouts.import(e.layouts.local,"merge"),{io:t}};var commonjsGlobal$1="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var uaParser={exports:{}};!function(e,t){!function(r,n){var i="function",o="undefined",s="object",a="string",c="major",l="model",u="name",d="type",h="vendor",p="version",g="architecture",m="console",f="mobile",y="tablet",$="smarttv",b="wearable",v="embedded",w="Amazon",S="Apple",_="ASUS",E="BlackBerry",C="Browser",I="Chrome",T="Firefox",A="Google",D="Huawei",x="LG",R="Microsoft",O="Motorola",N="Opera",P="Samsung",k="Sharp",M="Sony",L="Xiaomi",F="Zebra",j="Facebook",U="Chromium OS",B="Mac OS",H=" Browser",q=function(e){for(var t={},r=0;r0?2===c.length?typeof c[1]==i?this[c[0]]=c[1].call(this,u):this[c[0]]=c[1]:3===c.length?typeof c[1]!==i||c[1].exec&&c[1].test?this[c[0]]=u?u.replace(c[1],c[2]):n:this[c[0]]=u?c[1].call(this,u,c[2]):n:4===c.length&&(this[c[0]]=u?c[3].call(this,u.replace(c[1],c[2])):n):this[c]=u||n;d+=2}},K=function(e,t){for(var r in t)if(typeof t[r]===s&&t[r].length>0){for(var i=0;i2&&(e[l]="iPad",e[d]=y),e},this.getEngine=function(){var e={};return e[u]=n,e[p]=n,J.call(e,$,v.engine),e},this.getOS=function(){var e={};return e[u]=n,e[p]=n,J.call(e,$,v.os),w&&!e[u]&&b&&b.platform&&"Unknown"!=b.platform&&(e[u]=b.platform.replace(/chrome os/i,U).replace(/macos/i,B)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return $},this.setUA=function(e){return $=typeof e===a&&e.length>500?G(e,500):e,this},this.setUA($),this};X.VERSION="1.0.40",X.BROWSER=q([u,p,c]),X.CPU=q([g]),X.DEVICE=q([l,h,d,m,f,$,y,b,v]),X.ENGINE=X.OS=q([u,p]),e.exports&&(t=e.exports=X),t.UAParser=X;var Y=typeof r!==o&&(r.jQuery||r.Zepto);if(Y&&!Y.ua){var Q=new X;Y.ua=Q.getResult(),Y.ua.get=function(){return Q.getUA()},Y.ua.set=function(e){Q.setUA(e);var t=Q.getResult();for(var r in t)Y.ua[r]=t[r]}}}("object"==typeof window?window:commonjsGlobal$1)}(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,dist={},builder$7={},_globalThis$7="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},VERSION$7="1.9.0",re$2=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _makeCompatibilityCheck(e){var t=new Set([e]),r=new Set,n=e.match(re$2);if(!n)return function(){return!1};var i=+n[1],o=+n[2],s=+n[3];if(null!=n[4])return function(t){return t===e};function a(e){return r.add(e),!1}function c(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;var n=e.match(re$2);if(!n)return a(e);var l=+n[1],u=+n[2],d=+n[3];return null!=n[4]||i!==l?a(e):0===i?o===u&&s<=d?c(e):a(e):o<=u?c(e):a(e)}}var isCompatible=_makeCompatibilityCheck(VERSION$7),major=VERSION$7.split(".")[0],GLOBAL_OPENTELEMETRY_API_KEY=Symbol.for("opentelemetry.js.api."+major),_global$6=_globalThis$7;function registerGlobal(e,t,r,n){var i;void 0===n&&(n=!1);var o=_global$6[GLOBAL_OPENTELEMETRY_API_KEY]=null!==(i=_global$6[GLOBAL_OPENTELEMETRY_API_KEY])&&void 0!==i?i:{version:VERSION$7};if(!n&&o[e]){var s=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(s.stack||s.message),!1}if(o.version!==VERSION$7){s=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+e+" does not match previously registered API v"+VERSION$7);return r.error(s.stack||s.message),!1}return o[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+VERSION$7+"."),!0}function getGlobal(e){var t,r,n=null===(t=_global$6[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===t?void 0:t.version;if(n&&isCompatible(n))return null===(r=_global$6[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===r?void 0:r[e]}function unregisterGlobal(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+VERSION$7+".");var r=_global$6[GLOBAL_OPENTELEMETRY_API_KEY];r&&delete r[e]}var __read$4=function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__spreadArray$3=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i=n?i.bind(t):function(){}}return eDiagLogLevel.ALL&&(e=DiagLogLevel.ALL),t=t||{},{error:r("error",DiagLogLevel.ERROR),warn:r("warn",DiagLogLevel.WARN),info:r("info",DiagLogLevel.INFO),debug:r("debug",DiagLogLevel.DEBUG),verbose:r("verbose",DiagLogLevel.VERBOSE)}}!function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(DiagLogLevel||(DiagLogLevel={}));var __read$3=function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__spreadArray$2=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i";a.warn("Current logger will be overwritten from "+l),c.warn("Current logger will overwrite one already registered from "+l)}return registerGlobal("diag",c,t,!0)},t.disable=function(){unregisterGlobal(API_NAME$4,t)},t.createComponentLogger=function(e){return new DiagComponentLogger(e)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}(),__read$2=function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__values=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},BaggageImpl=function(){function e(e){this._entries=e?new Map(e):new Map}return e.prototype.getEntry=function(e){var t=this._entries.get(e);if(t)return Object.assign({},t)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var t=__read$2(e,2);return[t[0],t[1]]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],i=0;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__spreadArray$1=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__spreadArray=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;iMAX_TRACE_STATE_LEN$1||(this._internalState=e.split(LIST_MEMBERS_SEPARATOR$1).reverse().reduce(function(e,t){var r=t.trim(),n=r.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER$1);if(-1!==n){var i=r.slice(0,n),o=r.slice(n+1,t.length);validateKey$1(i)&&validateValue$1(o)&&e.set(i,o)}return e},new Map),this._internalState.size>MAX_TRACE_STATE_ITEMS$1&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS$1))))},e.prototype._keys=function(){return Array.from(this._internalState.keys()).reverse()},e.prototype._clone=function(){var t=new e;return t._internalState=new Map(this._internalState),t},e}();function createTraceState(e){return new TraceStateImpl(e)}var context=ContextAPI.getInstance(),diag=DiagAPI.instance(),NoopMeterProvider=function(){function e(){}return e.prototype.getMeter=function(e,t,r){return NOOP_METER},e}(),NOOP_METER_PROVIDER=new NoopMeterProvider,API_NAME$2="metrics",MetricsAPI=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(e){return registerGlobal(API_NAME$2,e,DiagAPI.instance())},e.prototype.getMeterProvider=function(){return getGlobal(API_NAME$2)||NOOP_METER_PROVIDER},e.prototype.getMeter=function(e,t,r){return this.getMeterProvider().getMeter(e,t,r)},e.prototype.disable=function(){unregisterGlobal(API_NAME$2,DiagAPI.instance())},e}(),metrics$1=MetricsAPI.getInstance(),NoopTextMapPropagator=function(){function e(){}return e.prototype.inject=function(e,t){},e.prototype.extract=function(e,t){return e},e.prototype.fields=function(){return[]},e}(),BAGGAGE_KEY=createContextKey("OpenTelemetry Baggage Key");function getBaggage(e){return e.getValue(BAGGAGE_KEY)||void 0}function getActiveBaggage(){return getBaggage(ContextAPI.getInstance().active())}function setBaggage(e,t){return e.setValue(BAGGAGE_KEY,t)}function deleteBaggage(e){return e.deleteValue(BAGGAGE_KEY)}var API_NAME$1="propagation",NOOP_TEXT_MAP_PROPAGATOR=new NoopTextMapPropagator,PropagationAPI=function(){function e(){this.createBaggage=createBaggage,this.getBaggage=getBaggage,this.getActiveBaggage=getActiveBaggage,this.setBaggage=setBaggage,this.deleteBaggage=deleteBaggage}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(e){return registerGlobal(API_NAME$1,e,DiagAPI.instance())},e.prototype.inject=function(e,t,r){return void 0===r&&(r=defaultTextMapSetter),this._getGlobalPropagator().inject(e,t,r)},e.prototype.extract=function(e,t,r){return void 0===r&&(r=defaultTextMapGetter),this._getGlobalPropagator().extract(e,t,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){unregisterGlobal(API_NAME$1,DiagAPI.instance())},e.prototype._getGlobalPropagator=function(){return getGlobal(API_NAME$1)||NOOP_TEXT_MAP_PROPAGATOR},e}(),propagation=PropagationAPI.getInstance(),API_NAME="trace",TraceAPI=function(){function e(){this._proxyTracerProvider=new ProxyTracerProvider,this.wrapSpanContext=wrapSpanContext,this.isSpanContextValid=isSpanContextValid,this.deleteSpan=deleteSpan,this.getSpan=getSpan,this.getActiveSpan=getActiveSpan,this.getSpanContext=getSpanContext,this.setSpan=setSpan,this.setSpanContext=setSpanContext}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(e){var t=registerGlobal(API_NAME,this._proxyTracerProvider,DiagAPI.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},e.prototype.getTracerProvider=function(){return getGlobal(API_NAME)||this._proxyTracerProvider},e.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},e.prototype.disable=function(){unregisterGlobal(API_NAME,DiagAPI.instance()),this._proxyTracerProvider=new ProxyTracerProvider},e}(),trace=TraceAPI.getInstance(),index$2={context:context,diag:diag,metrics:metrics$1,propagation:propagation,trace:trace},esm$d=Object.freeze({__proto__:null,DiagConsoleLogger:DiagConsoleLogger,get DiagLogLevel(){return DiagLogLevel},INVALID_SPANID:INVALID_SPANID,INVALID_SPAN_CONTEXT:INVALID_SPAN_CONTEXT,INVALID_TRACEID:INVALID_TRACEID,ProxyTracer:ProxyTracer,ProxyTracerProvider:ProxyTracerProvider,ROOT_CONTEXT:ROOT_CONTEXT,get SamplingDecision(){return SamplingDecision$1},get SpanKind(){return SpanKind},get SpanStatusCode(){return SpanStatusCode},get TraceFlags(){return TraceFlags},get ValueType(){return ValueType},baggageEntryMetadataFromString:baggageEntryMetadataFromString,context:context,createContextKey:createContextKey,createNoopMeter:createNoopMeter,createTraceState:createTraceState,default:index$2,defaultTextMapGetter:defaultTextMapGetter,defaultTextMapSetter:defaultTextMapSetter,diag:diag,isSpanContextValid:isSpanContextValid,isValidSpanId:isValidSpanId,isValidTraceId:isValidTraceId,metrics:metrics$1,propagation:propagation,trace:trace}),require$$13$1=getAugmentedNamespace(esm$d),builder$6={},builder$5={},factoryBuilder={},validator$1={};Object.defineProperty(validator$1,"__esModule",{value:!0}),validator$1.Validator=void 0;class Validator{static isNullOrUndefined(e){return null==e}static throwIfNullOrUndefined(e,t,r){if(this.isNullOrUndefined(e))throw new Error(r||`${t} must be defined`)}}validator$1.Validator=Validator,Object.defineProperty(factoryBuilder,"__esModule",{value:!0}),factoryBuilder.MetricsFactoryBuilderValidator=void 0;const validator_1$s=validator$1;class MetricsFactoryBuilderValidator{validate(e){validator_1$s.Validator.throwIfNullOrUndefined(e,"builder"),validator_1$s.Validator.throwIfNullOrUndefined(e.logger,"logger")}validateDependencies(e){validator_1$s.Validator.throwIfNullOrUndefined(e,"dependencyContainer"),validator_1$s.Validator.throwIfNullOrUndefined(e.instanceFocusedHandler,"instanceFocusedHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.instanceReadyHandler,"instanceReadyHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.layoutRestoredHandler,"layoutRestoredHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.performanceProvider,"performanceProvider"),validator_1$s.Validator.throwIfNullOrUndefined(e.platformStartedHandler,"platformStartedHandler")}}factoryBuilder.MetricsFactoryBuilderValidator=MetricsFactoryBuilderValidator;var factory$2={},factory$1={};Object.defineProperty(factory$1,"__esModule",{value:!0}),factory$1.MetricsFactoryValidator=void 0;const validator_1$r=validator$1;class MetricsFactoryValidator{validate(e){validator_1$r.Validator.throwIfNullOrUndefined(e,"factory"),validator_1$r.Validator.throwIfNullOrUndefined(e.metricsFactories,"metricsFactories"),validator_1$r.Validator.throwIfNullOrUndefined(e.logger,"logger")}}factory$1.MetricsFactoryValidator=MetricsFactoryValidator;var _null$4={};Object.defineProperty(_null$4,"__esModule",{value:!0}),_null$4.NullMetric=void 0;class NullMetric{constructor(e,t){this.settings=e,this.logger=t,this.started=!1}start(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been started instead of ${this.settings.type} one`),this.started=!0,Promise.resolve()}stop(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been stopped instead of ${this.settings.type} one`),this.started=!1,Promise.resolve()}add(){}record(){}}_null$4.NullMetric=NullMetric;var customCounter={},base$1={},base={};Object.defineProperty(base,"__esModule",{value:!0}),base.MetricBaseValidator=void 0;const validator_1$q=validator$1;class MetricBaseValidator{validate(e){validator_1$q.Validator.throwIfNullOrUndefined(e,"base"),validator_1$q.Validator.throwIfNullOrUndefined(e.logger,"logger"),this.validateSettings(e.settings)}validateSettings(e){validator_1$q.Validator.throwIfNullOrUndefined(e,"settings"),validator_1$q.Validator.throwIfNullOrUndefined(e.enabled,"enabled"),validator_1$q.Validator.throwIfNullOrUndefined(e.name,"name"),validator_1$q.Validator.throwIfNullOrUndefined(e.type,"type"),validator_1$q.Validator.throwIfNullOrUndefined(e.description,"description"),validator_1$q.Validator.throwIfNullOrUndefined(e.platformVersion,"platformVersion")}}base.MetricBaseValidator=MetricBaseValidator;var container$1={},container={};Object.defineProperty(container,"__esModule",{value:!0}),container.ContainerValidator=void 0;const validator_1$p=validator$1;class ContainerValidator{validate(e){validator_1$p.Validator.throwIfNullOrUndefined(e,"container"),validator_1$p.Validator.throwIfNullOrUndefined(e.settings,"metrics"),validator_1$p.Validator.throwIfNullOrUndefined(e.traces,"traces"),validator_1$p.Validator.throwIfNullOrUndefined(e.logs,"logs")}}container.ContainerValidator=ContainerValidator;var safeStringify$1={},isPlainObject$6={}; -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ -function isObject$5(e){return"[object Object]"===Object.prototype.toString.call(e)}function isPlainObject$5(e){let t,r;return!1!==isObject$5(e)&&(t=e.constructor,void 0===t||(r=t.prototype,!1!==isObject$5(r)&&!1!==r.hasOwnProperty("isPrototypeOf")))}Object.defineProperty(isPlainObject$6,"__esModule",{value:!0}),isPlainObject$6.isPlainObject=void 0,isPlainObject$6.isPlainObject=isPlainObject$5,Object.defineProperty(safeStringify$1,"__esModule",{value:!0}),safeStringify$1.safeStringify=void 0;const is_plain_object_1=isPlainObject$6;function safeStringify(e){return e?JSON.stringify(e,(e,t)=>t&&"object"==typeof t?(0,is_plain_object_1.isPlainObject)(t)?t:Object.prototype.toString.call(t):t):JSON.stringify(e)}safeStringify$1.safeStringify=safeStringify;var __awaiter$b=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(container$1,"__esModule",{value:!0}),container$1.Container=void 0;const container_1$r=container,safe_stringify_1$6=safeStringify$1;class Container{static get instance(){return Container._instance}static errorless(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return Container.handleErrorlessMode(e,t)}}static errorlessDefined(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return Container.handleErrorlessMode(e,t)}}static errorlessAsync(e,t){return __awaiter$b(this,void 0,void 0,function*(){try{if("function"!=typeof e)return e;return(yield e)()}catch(e){return Container.handleErrorlessMode(e,t)}})}static handleErrorlessMode(e,t){var r,n,i,o,s;let a;try{if((null==e?void 0:e.message)&&(a=(null==e?void 0:e.message)+" "+(null!==(r=null==e?void 0:e.stack)&&void 0!==r?r:(new Error).stack)),!a)try{a=(0,safe_stringify_1$6.safeStringify)(e)+" "+(new Error).stack}catch(e){}if(!a)try{a=(null==e?void 0:e.toString())+" "+(new Error).stack}catch(e){}}catch(e){}a||(a="unknown "+(new Error).stack);try{if(!(null===(i=null===(n=Container.instance)||void 0===n?void 0:n.settings)||void 0===i?void 0:i.errorlessMode))throw null===(o=Container.instance.logger)||void 0===o||o.error("Observed error "+a),e}catch(t){throw e}try{return null===(s=Container.instance.logger)||void 0===s||s.warn("Caught error "+a),t}catch(e){return t}}constructor(e,t,r,n,i){this._settings=e,this.traces=t,this.metrics=r,this.logs=n,this.logger=i,this.started=!1;(new container_1$r.ContainerValidator).validate(this),Container._instance=this}waitForFinalExport(e){var t,r,n;return Promise.all([null===(t=this.traces)||void 0===t?void 0:t.waitForFinalExport(e),null===(r=this.metrics)||void 0===r?void 0:r.waitForFinalExport(e),null===(n=this.logs)||void 0===n?void 0:n.waitForFinalExport(e)])}get settings(){return this._settings}start(){return __awaiter$b(this,void 0,void 0,function*(){const e=this.metrics.settings.enabled?this.metrics.start():Promise.resolve(),t=this.traces.settings.enabled?this.traces.start():Promise.resolve(),r=this.logs.settings.enabled?this.logs.start():Promise.resolve();yield Promise.all([e,t,r]),this.started=!0})}stop(){return __awaiter$b(this,void 0,void 0,function*(){const e=this.metrics.started?this.metrics.stop():Promise.resolve(),t=this.traces.started?this.traces.stop():Promise.resolve(),r=this.logs.started?this.logs.stop():Promise.resolve();yield Promise.all([e,t,r]),this.started=!1})}}container$1.Container=Container;var __awaiter$a=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(base$1,"__esModule",{value:!0}),base$1.MetricBase=void 0;const base_1$h=base,container_1$q=container$1;class MetricBase{constructor(e,t,r){this.settings=e,this.meter=t,this.logger=r,this.started=!1;(new base_1$h.MetricBaseValidator).validate(this)}start(){return __awaiter$a(this,void 0,void 0,function*(){try{yield this.createMetric(),this.logger.debug(`metric ${this.settings.name} has been created`),yield this.subscribe(),this.logger.debug(`metric ${this.settings.name} has subscribed`),this.started=!0}catch(e){const t=`error while starting and subscribing for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}return Promise.resolve()})}stop(){return __awaiter$a(this,void 0,void 0,function*(){try{yield this.unsubscribe(),this.logger.debug(`metric ${this.settings.name} has unsubscribed`),yield this.destroyMetric(),this.logger.debug(`metric ${this.settings.name} has been destroyed`),this.started=!1}catch(e){const t=`error while stopping and unsubscribing for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}return Promise.resolve()})}createMetric(){const e=this.settings.name||this.settings.type+"-"+this.createUniqueName(10),t=this.settings.description,r=this.settings.unit;return this.metricAny=this.createMetricCore(e,{description:t,unit:r}),Promise.resolve()}subscribe(){return Promise.resolve()}unsubscribe(){return Promise.resolve()}destroyMetric(){return Promise.resolve()}getData(){return Object.assign({platformVersion:this.settings.platformVersion,user:this.settings.user},container_1$q.Container.errorless(this.settings.additionalAttributes))}getApplicationData(e){return Object.assign(Object.assign({},this.getData()),{application:e})}getLayoutData(e){return Object.assign(Object.assign({},this.getData()),{layout:e})}createUniqueName(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";let r="";const n=new Uint8Array(e);return crypto.getRandomValues(n),n.forEach(e=>{r+=t[e%52]}),r}}base$1.MetricBase=MetricBase,Object.defineProperty(customCounter,"__esModule",{value:!0}),customCounter.CustomCounterMetric=void 0;const base_1$g=base$1;class CustomCounterMetric extends base_1$g.MetricBase{constructor(e,t,r){super(e,t,r),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createCounter(e,t)}add(e,t){var r;null===(r=this.metric)||void 0===r||r.add(e,Object.assign(Object.assign({},this.getData()),t))}}customCounter.CustomCounterMetric=CustomCounterMetric;var customHistogram={};Object.defineProperty(customHistogram,"__esModule",{value:!0}),customHistogram.CustomHistogramMetric=void 0;const base_1$f=base$1;class CustomHistogramMetric extends base_1$f.MetricBase{constructor(e,t,r){super(e,t,r),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createHistogram(e,t)}record(e,t){var r;null===(r=this.metric)||void 0===r||r.record(e,Object.assign(Object.assign({},this.getData()),t))}}customHistogram.CustomHistogramMetric=CustomHistogramMetric;var customUpDownCounter={};Object.defineProperty(customUpDownCounter,"__esModule",{value:!0}),customUpDownCounter.CustomUpDownCounterMetric=void 0;const base_1$e=base$1;class CustomUpDownCounterMetric extends base_1$e.MetricBase{constructor(e,t,r){super(e,t,r),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createUpDownCounter(e,t)}add(e,t){var r;null===(r=this.metric)||void 0===r||r.add(e,Object.assign(Object.assign({},this.getData()),t))}}customUpDownCounter.CustomUpDownCounterMetric=CustomUpDownCounterMetric;var customObservableGauge={},observable={},__awaiter$9=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(observable,"__esModule",{value:!0}),observable.ObservableMetricBase=void 0;const base_1$d=base$1,container_1$p=container$1;class ObservableMetricBase extends base_1$d.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r),this.observeCallback=n,this.subscribeCallback=i,this.unsubcribeCallback=o}createMetric(){const e=Object.create(null,{createMetric:{get:()=>super.createMetric}});return __awaiter$9(this,void 0,void 0,function*(){yield e.createMetric.call(this),this.metric=this.metricAny})}subscribeCore(){return container_1$p.Container.errorlessAsync(()=>{var e,t;return null!==(t=null===(e=this.subscribeCallback)||void 0===e?void 0:e.call(this))&&void 0!==t?t:Promise.resolve()})}unsubscribeCore(){return container_1$p.Container.errorlessAsync(()=>{var e,t;return null!==(t=null===(e=this.unsubcribeCallback)||void 0===e?void 0:e.call(this))&&void 0!==t?t:Promise.resolve()})}observeCore(e){return container_1$p.Container.errorlessAsync(()=>{var t,r;return null!==(r=null===(t=this.observeCallback)||void 0===t?void 0:t.call(this,e))&&void 0!==r?r:Promise.resolve()})}subscribe(){return __awaiter$9(this,void 0,void 0,function*(){this.observableCallback=this.observe.bind(this),this.metric.addCallback(this.observableCallback),yield this.subscribeCore()})}destroyMetric(){return this.metric.removeCallback(this.observableCallback),Promise.resolve()}unsubscribe(){return this.unsubscribeCore()}observe(e){return __awaiter$9(this,void 0,void 0,function*(){try{this.logger.debug(`observe is being invoked for metric ${this.settings.name}`),yield this.observeCore(e),this.logger.debug(`gauge metric ${this.settings.name} has been observed`)}catch(e){const t=`error while executing observe for metric ${this.settings.name} from type: ${this.settings.type}`;this.logger.warn(t,e)}})}}observable.ObservableMetricBase=ObservableMetricBase,Object.defineProperty(customObservableGauge,"__esModule",{value:!0}),customObservableGauge.CustomObservableGaugeMetric=void 0;const observable_1$5=observable;class CustomObservableGaugeMetric extends observable_1$5.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableGauge(e,t)}}customObservableGauge.CustomObservableGaugeMetric=CustomObservableGaugeMetric;var customObservableCounter={};Object.defineProperty(customObservableCounter,"__esModule",{value:!0}),customObservableCounter.CustomObservableCounterMetric=void 0;const observable_1$4=observable;class CustomObservableCounterMetric extends observable_1$4.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableCounter(e,t)}}customObservableCounter.CustomObservableCounterMetric=CustomObservableCounterMetric;var customObservableUpDownCounter={};Object.defineProperty(customObservableUpDownCounter,"__esModule",{value:!0}),customObservableUpDownCounter.CustomObservableUpDownCounterMetric=void 0;const observable_1$3=observable;class CustomObservableUpDownCounterMetric extends observable_1$3.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableUpDownCounter(e,t)}}customObservableUpDownCounter.CustomObservableUpDownCounterMetric=CustomObservableUpDownCounterMetric;var customGauge={};Object.defineProperty(customGauge,"__esModule",{value:!0}),customGauge.CustomGaugeMetric=void 0;const base_1$c=base$1;class CustomGaugeMetric extends base_1$c.MetricBase{constructor(e,t,r){super(e,t,r),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createGauge(e,t)}record(e,t){var r;null===(r=this.metric)||void 0===r||r.record(e,Object.assign(Object.assign({},this.getData()),t))}}customGauge.CustomGaugeMetric=CustomGaugeMetric,Object.defineProperty(factory$2,"__esModule",{value:!0}),factory$2.MetricsFactory=void 0;const factory_1$1=factory$1,null_1$2=_null$4,customCounter_1=customCounter,customHistogram_1=customHistogram,customUpDownCounter_1=customUpDownCounter,customObservableGauge_1=customObservableGauge,customObservableCounter_1=customObservableCounter,customObservableUpDownCounter_1=customObservableUpDownCounter,customGauge_1=customGauge;class MetricsFactory{constructor(e,t,r){this.logger=e,this.metricsFactories=t,this.meter=r;(new factory_1$1.MetricsFactoryValidator).validate(this)}create(e,t,r,n){const i=e.type;if(~i.indexOf("observable")&&!t)throw new Error(`Metric type ${i} requires observeCallback argument to be provided.`);if(this.metricsFactories.has(i)){return this.metricsFactories.get(i)(e)}if("custom_observable_gauge"===i)return new customObservableGauge_1.CustomObservableGaugeMetric(e,this.meter,this.logger,t,r,n);if("custom_observable_counter"===i)return new customObservableCounter_1.CustomObservableCounterMetric(e,this.meter,this.logger,t,r,n);if("custom_observable_up_down_counter"===i)return new customObservableUpDownCounter_1.CustomObservableUpDownCounterMetric(e,this.meter,this.logger,t,r,n);if("custom_counter"===i)return new customCounter_1.CustomCounterMetric(e,this.meter,this.logger);if("custom_gauge"===i)return new customGauge_1.CustomGaugeMetric(e,this.meter,this.logger);if("custom_up_down_counter"===i)return new customUpDownCounter_1.CustomUpDownCounterMetric(e,this.meter,this.logger);if("custom_histogram"===i)return new customHistogram_1.CustomHistogramMetric(e,this.meter,this.logger);return this.createNullMetric(e,"not supported")}createNullMetric(e,t){this.logger.debug(`cannot create ${e.name} metric, reason: ${t}`);return new null_1$2.NullMetric(e,this.logger)}}factory$2.MetricsFactory=MetricsFactory;var count$3={},count$2={};Object.defineProperty(count$2,"__esModule",{value:!0}),count$2.ApplicationCountMetricValidator=void 0;const validator_1$o=validator$1;class ApplicationCountMetricValidator{validate(e){validator_1$o.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$o.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler"),validator_1$o.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler")}validateInstanceStarted(e){validator_1$o.Validator.throwIfNullOrUndefined(e,"args"),validator_1$o.Validator.throwIfNullOrUndefined(e.application,"application")}validateInstanceStopped(e){validator_1$o.Validator.throwIfNullOrUndefined(e,"args"),validator_1$o.Validator.throwIfNullOrUndefined(e.application,"application")}}count$2.ApplicationCountMetricValidator=ApplicationCountMetricValidator,Object.defineProperty(count$3,"__esModule",{value:!0}),count$3.ApplicationCountMetric=void 0;const base_1$b=base$1,count_1$2=count$2,container_1$o=container$1;class ApplicationCountMetric extends base_1$b.MetricBase{constructor(e,t,r,n,i){super(e,t,r),this.meter=t,this.instanceStartedHandler=n,this.instanceStoppedHandler=i,this.validator=new count_1$2.ApplicationCountMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appCountMetric=this.meter.createUpDownCounter(e,t)}subscribe(){return this.instanceStartedUn=container_1$o.Container.errorless(()=>this.instanceStartedHandler(this.handleInstanceStarted.bind(this))),this.instanceStoppedUn=container_1$o.Container.errorless(()=>this.instanceStoppedHandler(this.handleInstanceStopped.bind(this))),Promise.resolve()}unsubscribe(){return container_1$o.Container.errorless(()=>this.instanceStartedUn),container_1$o.Container.errorless(()=>this.instanceStoppedUn),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceStarted(e){try{this.validator.validateInstanceStarted(e),this.logger.debug(`instance started for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appCountMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleInstanceStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}handleInstanceStopped(e){try{this.validator.validateInstanceStopped(e),this.logger.debug(`instance stopped for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appCountMetric.add(-1,t),this.logger.debug(`metric ${this.settings.name} sent 1 less for app ${t.application}`)}catch(e){const t=`error while executing handleInstanceStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}count$3.ApplicationCountMetric=ApplicationCountMetric;var cpu$1={},perf={};Object.defineProperty(perf,"__esModule",{value:!0}),perf.PerformanceProviderValidator=void 0;const validator_1$n=validator$1;class PerformanceProviderValidator{validate(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"performanceProvider")}validateAppsCPU(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"data"),e.forEach(e=>{validator_1$n.Validator.throwIfNullOrUndefined(e,"item"),validator_1$n.Validator.throwIfNullOrUndefined(e.app,"app"),validator_1$n.Validator.throwIfNullOrUndefined(e.instance,"instance"),validator_1$n.Validator.throwIfNullOrUndefined(e.cpu,"cpu")})}validateAppsMemory(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"data"),e.forEach(e=>{validator_1$n.Validator.throwIfNullOrUndefined(e,"item"),validator_1$n.Validator.throwIfNullOrUndefined(e.app,"app"),validator_1$n.Validator.throwIfNullOrUndefined(e.instance,"instance"),validator_1$n.Validator.throwIfNullOrUndefined(e.memory,"memory")})}validateSystemCPU(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"data"),validator_1$n.Validator.throwIfNullOrUndefined(e.current,"current"),validator_1$n.Validator.throwIfNullOrUndefined(e.average,"average"),validator_1$n.Validator.throwIfNullOrUndefined(e.platform,"platform")}validateSystemMemory(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"data"),validator_1$n.Validator.throwIfNullOrUndefined(e.platformTotal,"platformTotal"),validator_1$n.Validator.throwIfNullOrUndefined(e.systemFree,"systemFree"),validator_1$n.Validator.throwIfNullOrUndefined(e.systemTotal,"systemTotal")}}perf.PerformanceProviderValidator=PerformanceProviderValidator;var zeroOutClosedAppGaugeMetricBase={},__awaiter$8=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(zeroOutClosedAppGaugeMetricBase,"__esModule",{value:!0}),zeroOutClosedAppGaugeMetricBase.ZeroOutClosedAppGaugeMetricBase=void 0;const observable_1$2=observable;class ZeroOutClosedAppGaugeMetricBase extends observable_1$2.ObservableMetricBase{observeCore(e){return __awaiter$8(this,void 0,void 0,function*(){const t=yield this.observeCoreCore(e);if(this.reported)for(const r of this.reported.filter(e=>!t.some(t=>e.instance===t.instance))){const t=Object.assign({applicationInstance:r.instance},this.getApplicationData(r.app));e.observe(0,t),this.logger.debug(`metric ${this.settings.name} sent 0 for closed app ${t.application} and instance ${t.applicationInstance}`)}this.reported=t})}createMetricCore(e,t){return this.meter.createObservableGauge(e,t)}}zeroOutClosedAppGaugeMetricBase.ZeroOutClosedAppGaugeMetricBase=ZeroOutClosedAppGaugeMetricBase;var __awaiter$7=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(cpu$1,"__esModule",{value:!0}),cpu$1.ApplicationCPUMetric=void 0;const perf_1$3=perf,validator_1$m=validator$1,zeroOutClosedAppGaugeMetricBase_1$1=zeroOutClosedAppGaugeMetricBase,container_1$n=container$1;class ApplicationCPUMetric extends zeroOutClosedAppGaugeMetricBase_1$1.ZeroOutClosedAppGaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.perfProvider=n}subscribeCore(){return Promise.resolve()}observeCoreCore(e){return __awaiter$7(this,void 0,void 0,function*(){const t=new perf_1$3.PerformanceProviderValidator;t.validate(this.perfProvider);const r=yield container_1$n.Container.errorlessAsync(()=>this.perfProvider.getAppsCPU());return validator_1$m.Validator.isNullOrUndefined(r)?[]:(t.validateAppsCPU(r),r.forEach(t=>{const r=Object.assign({applicationInstance:t.instance},this.getApplicationData(t.app));e.observe(t.cpu,r),this.logger.debug(`metric ${this.settings.name} sent cpu ${t.cpu} for app ${r.application} and instance ${r.applicationInstance}`)}),r)})}unsubscribeCore(){return Promise.resolve()}}cpu$1.ApplicationCPUMetric=ApplicationCPUMetric;var crash$1={},crash={};Object.defineProperty(crash,"__esModule",{value:!0}),crash.PlatformCrashMetricValidator=void 0;const validator_1$l=validator$1;class PlatformCrashMetricValidator{validate(e){validator_1$l.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$l.Validator.throwIfNullOrUndefined(e.instanceCrashHandler,"applicationCrashHandler")}validateApplicationCrash(e){validator_1$l.Validator.throwIfNullOrUndefined(e,"args"),validator_1$l.Validator.throwIfNullOrUndefined(e.application,"application")}}crash.PlatformCrashMetricValidator=PlatformCrashMetricValidator,Object.defineProperty(crash$1,"__esModule",{value:!0}),crash$1.ApplicationCrashMetric=void 0;const base_1$a=base$1,crash_1$1=crash,container_1$m=container$1;class ApplicationCrashMetric extends base_1$a.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceCrashHandler=n,this.validator=new crash_1$1.PlatformCrashMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.applicationCrashMetric=this.meter.createCounter(e,t)}subscribe(){return this.applicationCrashUn=container_1$m.Container.errorless(()=>this.instanceCrashHandler(this.handleInstanceCrash.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return container_1$m.Container.errorless(()=>{var e;return null===(e=this.applicationCrashUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleInstanceCrash(e){try{this.validator.validateApplicationCrash(e),this.logger.debug(`crash for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=Object.assign({reason:e.reason},this.getApplicationData(e.application));this.applicationCrashMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleApplicationCrash for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}crash$1.ApplicationCrashMetric=ApplicationCrashMetric;var duration$3={},duration$2={};Object.defineProperty(duration$2,"__esModule",{value:!0}),duration$2.ApplicationDurationMetricValidator=void 0;const validator_1$k=validator$1;class ApplicationDurationMetricValidator{validate(e){validator_1$k.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceFocusHandler,"instanceFocusHandler")}validateFocusChanged(e){validator_1$k.Validator.throwIfNullOrUndefined(e,"args"),validator_1$k.Validator.throwIfNullOrUndefined(e.application,"application"),validator_1$k.Validator.throwIfNullOrUndefined(e.focused,"focused")}}duration$2.ApplicationDurationMetricValidator=ApplicationDurationMetricValidator,Object.defineProperty(duration$3,"__esModule",{value:!0}),duration$3.ApplicationDurationMetric=void 0;const validator_1$j=validator$1,duration_1$2=duration$2,observable_1$1=observable,container_1$l=container$1;class ApplicationDurationMetric extends observable_1$1.ObservableMetricBase{constructor(e,t,r,n){super(e,t,r),this.instanceFocusHandler=n,this.focusedTimes=new Map,this.validator=new duration_1$2.ApplicationDurationMetricValidator,this.validator.validate(this)}createMetricCore(){const e={explicitBucketBoundaries:this.settings.buckets};return this.appDurationMetric=this.meter.createHistogram(this.settings.name,{description:this.settings.description,unit:this.settings.unit,advice:e}),this.meter.createObservableGauge(this.createUniqueName(10))}sendMetric(e,t){e.forEach(e=>{this.appDurationMetric.record(e,t),this.logger.debug(`metric ${this.settings.name} sent focused time ${e} for app ${t.application}`)})}observeCore(){return this.focusedTimes.forEach((e,t)=>{const r=this.getApplicationData(t);this.sendMetric(e,r),e.splice(0)}),Promise.resolve()}subscribeCore(){return this.unInstanceFocusHandler=container_1$l.Container.errorless(()=>this.instanceFocusHandler(this.handleFocusChanged.bind(this))),Promise.resolve()}unsubscribeCore(){return container_1$l.Container.errorless(()=>{var e;return null===(e=this.unInstanceFocusHandler)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleFocusChanged(e){try{return this.validator.validateFocusChanged(e),this.logger.debug(`focused changed is being invoked for metric ${this.settings.name} with ${JSON.stringify(e)}`),this.handleFocusChangedCore(e)}catch(e){const t=`error while executing handleFocusChanges for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}handleFocusChangedCore(e){const t=e.focused,r=e.application;if(t)this.handleGotFocus(r);else try{this.handleLostFocus(r)}finally{this.currentFocusedApp=void 0}}handleGotFocus(e){const t=(new Date).getTime();this.currentFocusedApp={name:e,gotFocusTime:t},this.focusedTimes.has(this.currentFocusedApp.name)||this.focusedTimes.set(this.currentFocusedApp.name,[]),this.logger.debug(`got focus event has been added for metric ${this.settings.name}`)}handleLostFocus(e){if(validator_1$j.Validator.isNullOrUndefined(this.currentFocusedApp))throw new Error(`cannot handle focus lost for application ${e} since there is no previous got focus event`);const t=this.currentFocusedApp.name,r=this.currentFocusedApp.gotFocusTime;if(e!==t)throw new Error(`cannot handle focus lost for application ${e} since the previous got focus event had come from application ${t}`);if(!this.focusedTimes.has(e))throw new Error(`there is no got focus event for ${e}`);this.addFocusLostEventCore(t,r),this.logger.debug(`lost focus event has been added for metric ${this.settings.name}`)}addFocusLostEventCore(e,t){const r=(new Date).getTime()-t;this.focusedTimes.get(e).push(r)}}duration$3.ApplicationDurationMetric=ApplicationDurationMetric;var durationSoft={},__awaiter$6=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(durationSoft,"__esModule",{value:!0}),durationSoft.ApplicationDurationSoftMetric=void 0;const duration_1$1=duration$3;class ApplicationDurationSoftMetric extends duration_1$1.ApplicationDurationMetric{observeCore(){const e=Object.create(null,{observeCore:{get:()=>super.observeCore}});return __awaiter$6(this,void 0,void 0,function*(){const t=void 0!==this.currentFocusedApp,r=t?this.currentFocusedApp.name:void 0;return t&&this.handleFocusChanged({application:r,focused:!1}),yield e.observeCore.call(this),t&&this.handleFocusChanged({application:r,focused:!0}),Promise.resolve()})}}durationSoft.ApplicationDurationSoftMetric=ApplicationDurationSoftMetric;var error$J={},error$I={};Object.defineProperty(error$I,"__esModule",{value:!0}),error$I.ApplicationErrorMetricValidator=void 0;const validator_1$i=validator$1;class ApplicationErrorMetricValidator{validate(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$i.Validator.throwIfNullOrUndefined(e.instanceErrorHandler,"appErrorHandler")}validateApplicationError(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"args"),validator_1$i.Validator.throwIfNullOrUndefined(e.application,"application")}}error$I.ApplicationErrorMetricValidator=ApplicationErrorMetricValidator,Object.defineProperty(error$J,"__esModule",{value:!0}),error$J.ApplicationErrorMetric=void 0;const base_1$9=base$1,error_1$2=error$I,container_1$k=container$1;class ApplicationErrorMetric extends base_1$9.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceErrorHandler=n,this.validator=new error_1$2.ApplicationErrorMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appErrorMetric=this.meter.createCounter(e,t)}subscribe(){return this.appErrorUn=container_1$k.Container.errorless(()=>this.instanceErrorHandler(this.instanceApplicationError.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return container_1$k.Container.errorless(()=>{var e;return null===(e=this.appErrorUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}instanceApplicationError(e){try{this.validator.validateApplicationError(e),this.logger.debug(`app error for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appErrorMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleAppError for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}error$J.ApplicationErrorMetric=ApplicationErrorMetric;var memory$1={},__awaiter$5=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(memory$1,"__esModule",{value:!0}),memory$1.ApplicationMemoryMetric=void 0;const perf_1$2=perf,validator_1$h=validator$1,zeroOutClosedAppGaugeMetricBase_1=zeroOutClosedAppGaugeMetricBase,container_1$j=container$1;class ApplicationMemoryMetric extends zeroOutClosedAppGaugeMetricBase_1.ZeroOutClosedAppGaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.perfProvider=n,this.validator=new perf_1$2.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}subscribeCore(){return Promise.resolve()}observeCoreCore(e){return __awaiter$5(this,void 0,void 0,function*(){const t=yield container_1$j.Container.errorlessAsync(()=>this.perfProvider.getAppsMemory());return validator_1$h.Validator.isNullOrUndefined(t)?[]:(this.validator.validateAppsMemory(t),t.forEach(t=>{var r;const n=Object.assign({applicationInstance:t.instance},this.getApplicationData(t.app));e.observe(null!==(r=t.memory)&&void 0!==r?r:0,n),this.logger.debug(`metric ${this.settings.name} sent memory ${t.memory} for app ${n.application} and instance ${n.applicationInstance}`)}),t)})}unsubscribeCore(){return Promise.resolve()}}memory$1.ApplicationMemoryMetric=ApplicationMemoryMetric;var started$2={},started$1={};Object.defineProperty(started$1,"__esModule",{value:!0}),started$1.ApplicationStartedMetricValidator=void 0;const validator_1$g=validator$1;class ApplicationStartedMetricValidator{validate(e){validator_1$g.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$g.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler")}validateInstanceStarted(e){validator_1$g.Validator.throwIfNullOrUndefined(e,"args"),validator_1$g.Validator.throwIfNullOrUndefined(e.application,"application")}}started$1.ApplicationStartedMetricValidator=ApplicationStartedMetricValidator,Object.defineProperty(started$2,"__esModule",{value:!0}),started$2.ApplicationStartedMetric=void 0;const base_1$8=base$1,started_1$1=started$1,container_1$i=container$1;class ApplicationStartedMetric extends base_1$8.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceStartedHandler=n,this.validator=new started_1$1.ApplicationStartedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStartedMetric=this.meter.createCounter(e,t)}subscribe(){return this.instanceStartedUn=container_1$i.Container.errorless(()=>this.instanceStartedHandler(this.handleInstanceStarted.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return container_1$i.Container.errorless(()=>{var e;return null===(e=this.instanceStartedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleInstanceStarted(e){try{this.validator.validateInstanceStarted(e),this.logger.debug(`instance started for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appStartedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleInstanceStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}started$2.ApplicationStartedMetric=ApplicationStartedMetric;var startup$4={},startupHistogram$1={};Object.defineProperty(startupHistogram$1,"__esModule",{value:!0}),startupHistogram$1.ApplicationStartupHistogramMetricValidator=void 0;const validator_1$f=validator$1;class ApplicationStartupHistogramMetricValidator{validate(e){validator_1$f.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$f.Validator.throwIfNullOrUndefined(e.instanceReadyHandler,"instanceReadyHandler")}validateInstanceReady(e){validator_1$f.Validator.throwIfNullOrUndefined(e,"args"),validator_1$f.Validator.throwIfNullOrUndefined(e.application,"application"),validator_1$f.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$f.Validator.throwIfNullOrUndefined(e.endTime,"endTime")}}startupHistogram$1.ApplicationStartupHistogramMetricValidator=ApplicationStartupHistogramMetricValidator,Object.defineProperty(startup$4,"__esModule",{value:!0}),startup$4.ApplicationStartupMetric=void 0;const startupHistogram_1$1=startupHistogram$1,base_1$7=base$1,container_1$h=container$1;class ApplicationStartupMetric extends base_1$7.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceReadyHandler=n,this.validator=new startupHistogram_1$1.ApplicationStartupHistogramMetricValidator,this.validator.validate(this)}createMetricCore(e,t){const r={explicitBucketBoundaries:this.settings.buckets};return this.appStartupMetric=this.meter.createHistogram(e,Object.assign(Object.assign({},t),{advice:r}))}subscribe(){return this.instanceReadyUn=container_1$h.Container.errorless(()=>this.instanceReadyHandler(this.handleInstanceReady.bind(this))),Promise.resolve()}unsubscribe(){return container_1$h.Container.errorless(()=>{var e;return null===(e=this.instanceReadyUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceReady(e){try{this.validator.validateInstanceReady(e),this.logger.debug(`instance ready for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=e.endTime.getTime()-e.startTime.getTime(),r=Object.assign({api:e.api},this.getApplicationData(e.application));this.appStartupMetric.record(t,r),this.logger.debug(`start up time ${t} has been added for metric ${this.settings.name}`)}catch(e){const t=`error while executing handleInstanceReady for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}startup$4.ApplicationStartupMetric=ApplicationStartupMetric;var stopped$2={},stopped$1={};Object.defineProperty(stopped$1,"__esModule",{value:!0}),stopped$1.ApplicationStoppedMetricValidator=void 0;const validator_1$e=validator$1;class ApplicationStoppedMetricValidator{validate(e){validator_1$e.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$e.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler")}validateInstanceStopped(e){validator_1$e.Validator.throwIfNullOrUndefined(e,"args"),validator_1$e.Validator.throwIfNullOrUndefined(e.application,"application")}}stopped$1.ApplicationStoppedMetricValidator=ApplicationStoppedMetricValidator,Object.defineProperty(stopped$2,"__esModule",{value:!0}),stopped$2.ApplicationStoppedMetric=void 0;const base_1$6=base$1,stopped_1$1=stopped$1,container_1$g=container$1;class ApplicationStoppedMetric extends base_1$6.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceStoppedHandler=n,this.validator=new stopped_1$1.ApplicationStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStoppedMetric=this.meter.createCounter(e,t)}subscribe(){return this.instanceStoppedUn=container_1$g.Container.errorless(()=>this.instanceStoppedHandler(this.handleInstanceStopped.bind(this))),Promise.resolve()}unsubscribe(){return container_1$g.Container.errorless(()=>{var e;return null===(e=this.instanceStoppedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceStopped(e){try{this.validator.validateInstanceStopped(e),this.logger.debug(`instance stopped for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appStoppedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleInstanceStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}stopped$2.ApplicationStoppedMetric=ApplicationStoppedMetric;var startup$3={},startupHistogram={};Object.defineProperty(startupHistogram,"__esModule",{value:!0}),startupHistogram.LayoutStartupMetricHistogramValidator=void 0;const validator_1$d=validator$1;class LayoutStartupMetricHistogramValidator{validate(e){validator_1$d.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$d.Validator.throwIfNullOrUndefined(e.layoutRestoredHandler,"layoutRestoredHandler")}validateLayoutRestored(e){validator_1$d.Validator.throwIfNullOrUndefined(e,"args"),validator_1$d.Validator.throwIfNullOrUndefined(e.layout,"layout"),validator_1$d.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$d.Validator.throwIfNullOrUndefined(e.endTime,"endTime")}}startupHistogram.LayoutStartupMetricHistogramValidator=LayoutStartupMetricHistogramValidator,Object.defineProperty(startup$3,"__esModule",{value:!0}),startup$3.LayoutStartupMetric=void 0;const startupHistogram_1=startupHistogram,base_1$5=base$1,container_1$f=container$1;class LayoutStartupMetric extends base_1$5.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.layoutRestoredHandler=n,this.validator=new startupHistogram_1.LayoutStartupMetricHistogramValidator,this.validator.validate(this)}createMetricCore(e,t){const r={explicitBucketBoundaries:this.settings.buckets};return this.layoutStartupMetric=this.meter.createHistogram(e,Object.assign(Object.assign({},t),{advice:r}))}subscribe(){return this.layoutRestoredUn=container_1$f.Container.errorless(()=>this.layoutRestoredHandler(this.handleLayoutRestored.bind(this))),Promise.resolve()}unsubscribe(){return container_1$f.Container.errorless(()=>{var e;return null===(e=this.layoutRestoredUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleLayoutRestored(e){try{this.validator.validateLayoutRestored(e),this.logger.debug(`layout restored is being invoked for metric ${this.settings.name}`);const t=e.endTime.getTime()-e.startTime.getTime(),r=this.getLayoutData(e.layout);this.layoutStartupMetric.record(t,r),this.logger.debug(`metric ${this.settings.name} sent startup time ${t} for layout ${r.layout}`)}catch(e){const t=`error while executing handleLayoutRestored for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}startup$3.LayoutStartupMetric=LayoutStartupMetric;var error$H={},error$G={};Object.defineProperty(error$G,"__esModule",{value:!0}),error$G.PlatformErrorMetricValidator=void 0;const validator_1$c=validator$1;class PlatformErrorMetricValidator{validate(e){validator_1$c.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$c.Validator.throwIfNullOrUndefined(e.platformErrorHandler,"platformErrorHandler")}validatePlatformError(e){validator_1$c.Validator.throwIfNullOrUndefined(e,"args")}}error$G.PlatformErrorMetricValidator=PlatformErrorMetricValidator,Object.defineProperty(error$H,"__esModule",{value:!0}),error$H.PlatformErrorMetric=void 0;const base_1$4=base$1,error_1$1=error$G,container_1$e=container$1;class PlatformErrorMetric extends base_1$4.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.platformErrorHandler=n,this.validator=new error_1$1.PlatformErrorMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.platformErrorMetric=this.meter.createCounter(e,t)}subscribe(){return this.platformErrorUn=container_1$e.Container.errorless(()=>this.platformErrorHandler(this.handlePlatformError.bind(this))),Promise.resolve()}unsubscribe(){var e;return null===(e=this.platformErrorUn)||void 0===e||e.call(this),Promise.resolve()}handlePlatformError(e){try{this.validator.validatePlatformError(e),this.logger.debug(`platform error for metric ${this.settings.name} is being invoked`);const t=this.getData();this.platformErrorMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handlePlatformError for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}error$H.PlatformErrorMetric=PlatformErrorMetric;var startup$2={},gauge={};Object.defineProperty(gauge,"__esModule",{value:!0}),gauge.GaugeMetricBase=void 0;const observable_1=observable;class GaugeMetricBase extends observable_1.ObservableMetricBase{createMetricCore(e,t){return this.meter.createObservableGauge(e,t)}}gauge.GaugeMetricBase=GaugeMetricBase;var startup$1={};Object.defineProperty(startup$1,"__esModule",{value:!0}),startup$1.PlatformStartupMetricValidator=void 0;const validator_1$b=validator$1;class PlatformStartupMetricValidator{validate(e){validator_1$b.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$b.Validator.throwIfNullOrUndefined(e.platformStartedHandler,"platformStartedHandler")}validatePlatformStarted(e){validator_1$b.Validator.throwIfNullOrUndefined(e,"args"),validator_1$b.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$b.Validator.throwIfNullOrUndefined(e.endTime,"endTime"),validator_1$b.Validator.throwIfNullOrUndefined(e.api,"api")}}startup$1.PlatformStartupMetricValidator=PlatformStartupMetricValidator;var __awaiter$4=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(startup$2,"__esModule",{value:!0}),startup$2.PlatformStartupMetric=void 0;const gauge_1$2=gauge,validator_1$a=validator$1,startup_1$2=startup$1,container_1$d=container$1;class PlatformStartupMetric extends gauge_1$2.GaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.platformStartedHandler=n,this.validator=new startup_1$2.PlatformStartupMetricValidator,this.validator.validate(this)}subscribeCore(){return this.platformStartedUn=container_1$d.Container.errorless(()=>this.platformStartedHandler(this.handlePlatformStarted.bind(this))),Promise.resolve()}observeCore(e){return __awaiter$4(this,void 0,void 0,function*(){if(!validator_1$a.Validator.isNullOrUndefined(this.startupTime)){const t=Object.assign({api:this.apiVersion},this.getData());this.sendMetric(this.startupTime,t,e)}})}unsubscribeCore(){return container_1$d.Container.errorless(()=>{var e;return null===(e=this.platformStartedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}sendMetric(e,t,r){r.observe(e,t),this.logger.debug(`metric ${this.settings.name} sent startup time ${e}`)}handlePlatformStarted(e){try{this.validator.validatePlatformStarted(e),this.logger.debug(`platform started is being invoked for metric ${this.settings.name}`),this.startupTime=e.endTime.getTime()-e.startTime.getTime(),this.apiVersion=e.api,this.logger.debug(`start up time ${this.startupTime} has been added for metric ${this.settings.name}`)}catch(e){const t=`error while executing handlePlatformStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}startup$2.PlatformStartupMetric=PlatformStartupMetric;var cpu={},__awaiter$3=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(cpu,"__esModule",{value:!0}),cpu.SystemCPUMetric=void 0;const gauge_1$1=gauge,perf_1$1=perf,validator_1$9=validator$1,container_1$c=container$1;class SystemCPUMetric extends gauge_1$1.GaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.perfProvider=n,this.validator=new perf_1$1.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}observeCore(e){return __awaiter$3(this,void 0,void 0,function*(){const t=yield container_1$c.Container.errorlessAsync(()=>this.perfProvider.getSystemCPU());validator_1$9.Validator.isNullOrUndefined(t)||(this.validator.validateSystemCPU(t),this.sendMetrics(t,e))})}sendMetrics(e,t){const r=this.getData(),n=this.settings.name;t.observe(e.current,Object.assign({type:"current_system_cpu"},r)),this.logger.debug(`metric ${n} sent current system cpu ${e.current}`),t.observe(e.average,Object.assign({type:"average_system_cpu"},r)),this.logger.debug(`metric ${n} sent average system cpu ${e.average}`),t.observe(e.platform,Object.assign({type:"average_platform_cpu"},r)),this.logger.debug(`metric ${n} sent average platform cpu ${e.platform}`)}}cpu.SystemCPUMetric=SystemCPUMetric;var memory={},__awaiter$2=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(memory,"__esModule",{value:!0}),memory.SystemMemoryMetric=void 0;const gauge_1=gauge,perf_1=perf,validator_1$8=validator$1,container_1$b=container$1;class SystemMemoryMetric extends gauge_1.GaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.perfProvider=n,this.validator=new perf_1.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}observeCore(e){return __awaiter$2(this,void 0,void 0,function*(){const t=yield container_1$b.Container.errorlessAsync(()=>this.perfProvider.getSystemMemory());validator_1$8.Validator.isNullOrUndefined(t)||(this.validator.validateSystemMemory(t),this.sendMetrics(t,e))})}sendMetrics(e,t){const r=this.getData(),n=this.settings.name;t.observe(e.platformTotal,Object.assign({type:"used_platform_memory"},r)),this.logger.debug(`metric ${n} sent used platform memory ${e.platformTotal}`);const i=e.systemTotal-e.systemFree;t.observe(i,Object.assign({type:"used_system_memory"},r)),this.logger.debug(`metric ${n} sent used system memory ${i}`),t.observe(e.systemFree,Object.assign({type:"free_system_memory"},r)),this.logger.debug(`metric ${n} sent free system memory ${e.systemFree}`)}}memory.SystemMemoryMetric=SystemMemoryMetric;var count$1={},count={};Object.defineProperty(count,"__esModule",{value:!0}),count.WorkspaceCountMetricValidator=void 0;const validator_1$7=validator$1;class WorkspaceCountMetricValidator{validate(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$7.Validator.throwIfNullOrUndefined(e.workspaceStartedHandler,"workspaceStartedHandler"),validator_1$7.Validator.throwIfNullOrUndefined(e.workspaceStoppedHandler,"workspaceStoppedHandler")}validateWorkspaceSaved(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"args"),validator_1$7.Validator.throwIfNullOrUndefined(e.layout,"layout")}validateWorkspaceStarted(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"args"),validator_1$7.Validator.throwIfNullOrUndefined(e.layout,"layout")}validateWorkspaceStopped(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"args"),validator_1$7.Validator.throwIfNullOrUndefined(e.layout,"layout")}}count.WorkspaceCountMetricValidator=WorkspaceCountMetricValidator,Object.defineProperty(count$1,"__esModule",{value:!0}),count$1.WorkspaceCountMetric=void 0;const base_1$3=base$1,count_1$1=count,container_1$a=container$1;class WorkspaceCountMetric extends base_1$3.MetricBase{constructor(e,t,r,n,i,o,s){super(e,t,r),this.meter=t,this.workspaceSavedHandler=n,this.workspaceStartedHandler=i,this.workspaceRestoredHandler=o,this.workspaceStoppedHandler=s,this.validator=new count_1$1.WorkspaceCountMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceCountMetric=this.meter.createUpDownCounter(e,t)}subscribe(){return this.workspaceStartedUn=container_1$a.Container.errorless(()=>this.workspaceStartedHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceRestoredUn=container_1$a.Container.errorless(()=>this.workspaceRestoredHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceStoppedUn=container_1$a.Container.errorless(()=>this.workspaceStoppedHandler(this.handleWorkspaceStopped.bind(this))),this.workspaceSavedUn=container_1$a.Container.errorless(()=>this.workspaceSavedHandler(this.handleWorkspaceSaved.bind(this))),Promise.resolve()}unsubscribe(){return container_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceStartedUn)||void 0===e?void 0:e.call(this)}),container_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceRestoredUn)||void 0===e?void 0:e.call(this)}),container_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceStoppedUn)||void 0===e?void 0:e.call(this)}),container_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceSavedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceSaved(e){try{if(this.validator.validateWorkspaceSaved(e),this.logger.debug(`workspace saved for layout ${e.layout}, old layout ${e.oldLayout} and metric ${this.settings.name} is being invoked`),e.oldLayout){const t=this.getLayoutData(e.oldLayout);this.workspaceCountMetric.add(-1,t),this.logger.debug(`metric ${this.settings.name} sent 1 less for app ${t.application}`)}const t=this.getLayoutData(e.layout);this.workspaceCountMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleWorkspaceSaved for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}handleWorkspaceStarted(e){try{this.validator.validateWorkspaceStarted(e),this.logger.debug(`workspace started for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceCountMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleWorkspaceStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}handleWorkspaceStopped(e){try{this.validator.validateWorkspaceStopped(e),this.logger.debug(`workspace stopped for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceCountMetric.add(-1,t),this.logger.debug(`metric ${this.settings.name} sent 1 less for app ${t.application}`)}catch(e){const t=`error while executing handleWorkspaceStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}count$1.WorkspaceCountMetric=WorkspaceCountMetric;var started={},startedOrStoppedMetric={};Object.defineProperty(startedOrStoppedMetric,"__esModule",{value:!0}),startedOrStoppedMetric.WorkspaceStartedOrStoppedMetricValidator=void 0;const validator_1$6=validator$1;class WorkspaceStartedOrStoppedMetricValidator{validate(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$6.Validator.throwIfNullOrUndefined(e.workspaceActionHandler,"workspaceActionHandler")}validateWorkspaceStarted(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"args")}validateWorkspaceStopped(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"args"),validator_1$6.Validator.throwIfNullOrUndefined(e.layout,"layout")}}startedOrStoppedMetric.WorkspaceStartedOrStoppedMetricValidator=WorkspaceStartedOrStoppedMetricValidator,Object.defineProperty(started,"__esModule",{value:!0}),started.WorkspaceStartedMetric=void 0;const base_1$2=base$1,startedOrStoppedMetric_1$1=startedOrStoppedMetric,container_1$9=container$1;class WorkspaceStartedMetric extends base_1$2.MetricBase{constructor(e,t,r,n,i){super(e,t,r),this.meter=t,this.workspaceActionHandler=n,this.workspaceRestoredHandler=i,this.validator=new startedOrStoppedMetric_1$1.WorkspaceStartedOrStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceStartedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceStartedUn=container_1$9.Container.errorless(()=>this.workspaceActionHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceRestoredUn=container_1$9.Container.errorless(()=>this.workspaceRestoredHandler(this.handleWorkspaceStarted.bind(this))),Promise.resolve()}unsubscribe(){return container_1$9.Container.errorless(()=>{var e;return null===(e=this.workspaceStartedUn)||void 0===e?void 0:e.call(this)}),container_1$9.Container.errorless(()=>{var e;return null===(e=this.workspaceRestoredUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceStarted(e){try{this.validator.validateWorkspaceStarted(e),this.logger.debug(`workspace Started for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceStartedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for workspace layout ${t.layout}`)}catch(e){const t=`error while executing handleWorkspaceStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}started.WorkspaceStartedMetric=WorkspaceStartedMetric;var startup={};Object.defineProperty(startup,"__esModule",{value:!0}),startup.WorkspaceStartupHistogramMetric=void 0;const startup_1$1=startup$3;class WorkspaceStartupHistogramMetric extends startup_1$1.LayoutStartupMetric{constructor(e,t,r,n,i){super(e,t,r,e=>{const t=this.workspaceLoadedHandler(e),r=this.workspaceRestoredHandler(e);return()=>{t(),r()}}),this.workspaceLoadedHandler=n,this.workspaceRestoredHandler=i}}startup.WorkspaceStartupHistogramMetric=WorkspaceStartupHistogramMetric;var stopped={};Object.defineProperty(stopped,"__esModule",{value:!0}),stopped.WorkspaceStoppedMetric=void 0;const base_1$1=base$1,startedOrStoppedMetric_1=startedOrStoppedMetric,container_1$8=container$1;class WorkspaceStoppedMetric extends base_1$1.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.workspaceActionHandler=n,this.validator=new startedOrStoppedMetric_1.WorkspaceStartedOrStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceStoppedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceStoppedUn=container_1$8.Container.errorless(()=>this.workspaceActionHandler(this.handleWorkspaceStopped.bind(this))),Promise.resolve()}unsubscribe(){return container_1$8.Container.errorless(()=>{var e;return null===(e=this.workspaceStoppedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceStopped(e){try{this.validator.validateWorkspaceStopped(e),this.logger.debug(`workspace stopped for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceStoppedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for workspace layout ${t.layout}`)}catch(e){const t=`error while executing handleWorkspaceStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}stopped.WorkspaceStoppedMetric=WorkspaceStoppedMetric;var selected={};Object.defineProperty(selected,"__esModule",{value:!0}),selected.WorkspaceSelectedMetric=void 0;const base_1=base$1,container_1$7=container$1;class WorkspaceSelectedMetric extends base_1.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.workspaceActionHandler=n}createMetricCore(e,t){return this.workspaceSelectedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceSelectedUn=container_1$7.Container.errorless(()=>this.workspaceActionHandler(this.handleSelectedStopped.bind(this))),Promise.resolve()}unsubscribe(){return container_1$7.Container.errorless(()=>{var e;return null===(e=this.workspaceSelectedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleSelectedStopped(e){try{this.logger.debug(`workspace selected for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceSelectedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for workspace layout ${t.layout}`)}catch(e){const t=`error while executing handleSelectedStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}selected.WorkspaceSelectedMetric=WorkspaceSelectedMetric,Object.defineProperty(builder$5,"__esModule",{value:!0}),builder$5.MetricsFactoryBuilder=void 0;const factoryBuilder_1=factoryBuilder,factory_1=factory$2,count_1=count$3,cpu_1=cpu$1,crash_1=crash$1,duration_1=duration$3,durationSoft_1=durationSoft,error_1=error$J,memory_1=memory$1,started_1=started$2,startup_1=startup$4,stopped_1=stopped$2,startup_2=startup$3,error_2=error$H,startup_3=startup$2,cpu_2=cpu,memory_2=memory,count_2=count$1,started_2=started,startup_4=startup,stopped_2=stopped,selected_1=selected;class MetricsFactoryBuilder{constructor(e,t,r){this.lazyMeterProvider=e,this.dependencyContainer=t,this.logger=r,this.metricsFactories=new Map,this.metricsFactories=new Map}get meter(){return this.lazyMeterProvider.getMeter()}build(){(new factoryBuilder_1.MetricsFactoryBuilderValidator).validate(this);return new factory_1.MetricsFactory(this.logger,this.metricsFactories,this.meter)}withDefaults(){return this.withAppStarted().withAppStopped().withAppStartupHistogram().withAppCount().withAppDurationHistogram().withAppDurationSoftHistogram().withAppMemory().withAppCPU().withSystemMemory().withSystemCPU().withAppError().withAppCrash().withLayoutStartupHistogram().withWorkspaceStartupHistogram().withWorkspaceStarted().withWorkspaceStopped().withWorkspaceSelected().withWorkspaceCount().withPlatformStartup().withPlatformError()}withAppStarted(){return this.metricsFactories.set("app_started",(e=>new started_1.ApplicationStartedMetric(e,this.meter,this.logger,this.dependencyContainer.instanceStartedHandler)).bind(this)),this}withAppStopped(){return this.metricsFactories.set("app_stopped",(e=>new stopped_1.ApplicationStoppedMetric(e,this.meter,this.logger,this.dependencyContainer.instanceStoppedHandler)).bind(this)),this}withAppStartupHistogram(){return this.metricsFactories.set("app_startup",(e=>new startup_1.ApplicationStartupMetric(e,this.meter,this.logger,this.dependencyContainer.instanceReadyHandler)).bind(this)),this}withAppCount(){return this.metricsFactories.set("app_count",(e=>new count_1.ApplicationCountMetric(e,this.meter,this.logger,this.dependencyContainer.instanceStartedHandler,this.dependencyContainer.instanceStoppedHandler)).bind(this)),this}withAppDurationHistogram(){return this.metricsFactories.set("app_duration",(e=>new duration_1.ApplicationDurationMetric(e,this.meter,this.logger,this.dependencyContainer.instanceFocusedHandler)).bind(this)),this}withAppDurationSoftHistogram(){return this.metricsFactories.set("app_duration_soft",(e=>new durationSoft_1.ApplicationDurationSoftMetric(e,this.meter,this.logger,this.dependencyContainer.instanceFocusedHandler)).bind(this)),this}withAppMemory(){return this.metricsFactories.set("app_memory",(e=>new memory_1.ApplicationMemoryMetric(e,this.meter,this.logger,this.dependencyContainer.performanceProvider)).bind(this)),this}withAppCPU(){return this.metricsFactories.set("app_cpu",(e=>new cpu_1.ApplicationCPUMetric(e,this.meter,this.logger,this.dependencyContainer.performanceProvider)).bind(this)),this}withAppError(){return this.metricsFactories.set("app_error",(e=>new error_1.ApplicationErrorMetric(e,this.meter,this.logger,this.dependencyContainer.instanceErrorHandler)).bind(this)),this}withAppCrash(){return this.metricsFactories.set("app_crash",(e=>new crash_1.ApplicationCrashMetric(e,this.meter,this.logger,this.dependencyContainer.instanceCrashHandler)).bind(this)),this}withSystemMemory(){return this.metricsFactories.set("system_memory",(e=>new memory_2.SystemMemoryMetric(e,this.meter,this.logger,this.dependencyContainer.performanceProvider)).bind(this)),this}withSystemCPU(){return this.metricsFactories.set("system_cpu",(e=>new cpu_2.SystemCPUMetric(e,this.meter,this.logger,this.dependencyContainer.performanceProvider)).bind(this)),this}withLayoutStartupHistogram(){return this.metricsFactories.set("layout_startup",(e=>new startup_2.LayoutStartupMetric(e,this.meter,this.logger,this.dependencyContainer.layoutRestoredHandler)).bind(this)),this}withWorkspaceStartupHistogram(){return this.metricsFactories.set("workspace_startup",(e=>new startup_4.WorkspaceStartupHistogramMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceLoadedHandler,this.dependencyContainer.workspaceRestoredHandler)).bind(this)),this}withWorkspaceStarted(){return this.metricsFactories.set("workspace_started",(e=>new started_2.WorkspaceStartedMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceStartedHandler,this.dependencyContainer.workspaceRestoredHandler)).bind(this)),this}withWorkspaceStopped(){return this.metricsFactories.set("workspace_stopped",(e=>new stopped_2.WorkspaceStoppedMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceStoppedHandler)).bind(this)),this}withWorkspaceSelected(){return this.metricsFactories.set("workspace_selected",(e=>new selected_1.WorkspaceSelectedMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceSelectedHandler)).bind(this)),this}withWorkspaceCount(){return this.metricsFactories.set("workspace_count",(e=>new count_2.WorkspaceCountMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceSavedHandler,this.dependencyContainer.workspaceStartedHandler,this.dependencyContainer.workspaceRestoredHandler,this.dependencyContainer.workspaceStoppedHandler)).bind(this)),this}withPlatformStartup(){return this.metricsFactories.set("platform_startup",(e=>new startup_3.PlatformStartupMetric(e,this.meter,this.logger,this.dependencyContainer.platformStartedHandler)).bind(this)),this}withPlatformError(){return this.metricsFactories.set("platform_error",(e=>new error_2.PlatformErrorMetric(e,this.meter,this.logger,this.dependencyContainer.platformErrorHandler)).bind(this)),this}}builder$5.MetricsFactoryBuilder=MetricsFactoryBuilder;var manager$4={},manager$3={};Object.defineProperty(manager$3,"__esModule",{value:!0}),manager$3.MetricsManagerValidator=void 0;const validator_1$5=validator$1;class MetricsManagerValidator{validate(e){validator_1$5.Validator.throwIfNullOrUndefined(e,"manager"),validator_1$5.Validator.throwIfNullOrUndefined(e.settings,"settings"),validator_1$5.Validator.throwIfNullOrUndefined(e.metricsFactory,"metricsFactory"),validator_1$5.Validator.throwIfNullOrUndefined(e.meterProvider,"meterProvider"),validator_1$5.Validator.throwIfNullOrUndefined(e.logger,"logger")}}manager$3.MetricsManagerValidator=MetricsManagerValidator;var constants$3={};Object.defineProperty(constants$3,"__esModule",{value:!0}),constants$3.Defaults=void 0,constants$3.Defaults={TRACE_VERSION:"00",DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version",DEFAULT_METRIC_DESCRIPTION:"unknown-metric",stopPropagationIfSpanIsDisabled:!1,countMetric:!1,durationMetric:!1,resultMetric:!1,countMetricOnDisabledSpans:!1,durationMetricOnDisabledSpans:!1,resultMetricOnDisabledSpans:!1,maxAttributeDepth:5,otelSpanOptions:{},disablePropagation:!1,addContextToTrace:!0,level:"INFO",forceChildTracing:!1,canBeRoot:!0,currentTracingStateGetterContextName:"interopio.insights.currentTracingStateGetter",minDurationMs:0,log:!1,logOnDisabledSpans:!1};var __awaiter$1=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(manager$4,"__esModule",{value:!0}),manager$4.MetricsManager=void 0;const manager_1$4=manager$3,safe_stringify_1$5=safeStringify$1,container_1$6=container$1,constants_1$3=constants$3;class MetricsManager{constructor(e,t,r,n,i){this.otelSettings=e,this.settings=t,this.metricsFactory=r,this.meterProvider=n,this.logger=i,this.metrics=new Map,this.started=!1,!1!==(null==e?void 0:e.logSettingsOnStartup)&&(null==i||i.info(`Starting MetricsManager with settings ${(0,safe_stringify_1$5.safeStringify)(t)}`));(new manager_1$4.MetricsManagerValidator).validate(this)}get(e){return this.getOrCreateMetric(e)}getFromSettings(e){return this.getOrCreateMetricFromSettings(e)}getObservable(e,t,r,n){return this.getOrCreateMetric(e,t,r,n)}getObservableFromSettings(e,t,r,n){return this.getOrCreateMetricFromSettings(e,t,r,n)}start(){var e;return __awaiter$1(this,void 0,void 0,function*(){try{this.createEnabledMetrics(null!==(e=this.settings.metrics)&&void 0!==e?e:[]);for(const e of this.metrics){const t=e[1];yield this.startMetric(t)}this.started=!0,this.logger.debug("metrics manager has been started")}catch(e){const t="error while starting metrics manager";this.logger.warn(t,e)}})}stop(){return __awaiter$1(this,void 0,void 0,function*(){try{for(const e of this.metrics){const t=e[1];yield this.stopMetric(t)}yield this.meterProvider.forceFlush(),this.started=!1,this.logger.debug("metrics manager has been stopped")}catch(e){const t="error while stopping metrics manager";this.logger.warn(t,e)}})}waitForFinalExport(e){return __awaiter$1(this,void 0,void 0,function*(){const t=new Date;this.meterProvider.metricReader.collect({timeoutMillis:e});const r=e?e-((new Date).getTime()-t.getTime()):void 0;this.meterProvider.metricReader.forceFlush({timeoutMillis:r})})}createEnabledMetrics(e){const t=e.filter(e=>!this.metrics.has(e.name)),r=t.filter(e=>e.enabled);r.forEach(e=>this.createMetric(e))}getOrCreateMetric(e,t,r,n){var i;if(this.metrics.has(e))return this.metrics.get(e);{let o;const s=null===(i=this.settings.metrics)||void 0===i?void 0:i.find(t=>t.name===e);return s&&(o=this.createMetric(s,t,r,n)),o}}getOrCreateMetricFromSettings(e,t,r,n){var i;if(!e.name)throw new Error("settings.name not defined");return this.metrics.has(e.name)?this.metrics.get(e.name):this.createMetric(Object.assign(Object.assign({},e),{enabled:null===(i=e.enabled)||void 0===i||i}),t,r,n)}createMetric(e,t,r,n){try{const i=e.additionalAttributes;e=Object.assign(Object.assign({},e),{description:e.description||constants_1$3.Defaults.DEFAULT_METRIC_DESCRIPTION,platformVersion:e.platformVersion||this.otelSettings.platformVersion||"unknown",user:e.user||this.otelSettings.userId||constants_1$3.Defaults.DEFAULT_USER,additionalAttributes:()=>Object.assign(Object.assign(Object.assign({},container_1$6.Container.errorless(this.otelSettings.additionalAttributes)),container_1$6.Container.errorless(this.settings.additionalAttributes)),container_1$6.Container.errorless(i))});const o=this.metricsFactory.create(e,t,r,n);return o&&this.metrics.set(e.name,o),o}catch(t){const r=`error while creating metric from type: ${e.type}`;return void this.logger.warn(r,t)}}startMetric(e){return __awaiter$1(this,void 0,void 0,function*(){try{yield e.start()}catch(t){const r=`error while starting metric from type: ${e.settings.type}`;this.logger.warn(r,t)}})}stopMetric(e){return __awaiter$1(this,void 0,void 0,function*(){try{yield e.stop()}catch(t){const r=`error while stopping metric from type: ${e.settings.type}`;this.logger.warn(r,t)}})}}manager$4.MetricsManager=MetricsManager;var builder$4={},settingsBuilder={};Object.defineProperty(settingsBuilder,"__esModule",{value:!0}),settingsBuilder.MetricsSettingsBuilderValidator=void 0;const validator_1$4=validator$1;class MetricsSettingsBuilderValidator{validate(e){validator_1$4.Validator.throwIfNullOrUndefined(e,"builder"),validator_1$4.Validator.throwIfNullOrUndefined(e.enabled,"enabled"),validator_1$4.Validator.throwIfNullOrUndefined(e.metrics,"metrics")}}settingsBuilder.MetricsSettingsBuilderValidator=MetricsSettingsBuilderValidator;var _default$2={};Object.defineProperty(_default$2,"__esModule",{value:!0}),_default$2.DefaultMetricsSettings=void 0;class DefaultMetricsSettings{constructor(){this.unknown="unknown"}get enabled(){return!0}get platformMetricsEnabled(){return!0}get userId(){return this.unknown}get platformVersion(){return this.unknown}get additionalAttributes(){return{}}get metrics(){return[this.getAppCount(),this.getAppCPU(),this.getAppCrash(),this.getAppDuration(),this.getAppDurationSoft(),this.getAppError(),this.getAppMemory(),this.getAppStarted(),this.getAppStartup(),this.getAppStopped(),this.getLayoutStartup(),this.getPlatformError(),this.getPlatformStartup(),this.getSystemCPU(),this.getSystemMemory(),this.getWorkspaceCount(),this.getWorkspaceSelected(),this.getWorkspaceStarted(),this.getWorkspaceStartup(),this.getWorkspaceStopped()]}getAppStarted(){return this.getSettings("app_started","Number of times an application has been started during each platform session","app_started")}getAppStopped(){return this.getSettings("app_stopped","Number of times an application has been stopped during each platform session","app_stopped")}getAppCount(){return this.getSettings("app_count","Number of application instances running in the platform during each platform session","app_count")}getAppStartup(){return this.getSettings("app_startup","Time to load an application","app_startup","ms",[100,1e3,1e4,3e4,6e4])}getAppDuration(){return this.getSettings("app_duration","How long an application has been focused during each platform session","app_duration","ms",[1e3,1e4,3e4,6e4,6e5])}getAppDurationSoft(){return this.getSettings("app_duration_soft","How long an application has been focused during each platform session (without the currently focused application)","app_duration_soft","ms",[1e3,1e4,3e4,6e4,6e5])}getAppMemory(){return this.getSettings("app_memory","Current app memory usage","app_memory","kb")}getAppCPU(){return this.getSettings("app_cpu","Percentage of CPU used for the last interval.","app_cpu","%")}getAppError(){return this.getSettings("app_error","Number of times app error was received during each platform session","app_error")}getAppCrash(){return this.getSettings("app_crash","Number of times an application crashed during each platform session","app_crash")}getLayoutStartup(){return this.getSettings("layout_startup","Time to load a layout","layout_startup","ms",[100,1e3,1e4,3e4,6e4])}getWorkspaceStartup(){return this.getSettings("workspace_startup","Time to load the workspace layout","workspace_startup","ms",[100,1e3,1e4,3e4,6e4])}getWorkspaceStarted(){return this.getSettings("workspace_started","Number of times a workspace has been stopped during each platform session","workspace_started")}getWorkspaceStopped(){return this.getSettings("workspace_stopped","Number of times a workspace has been stopped during each platform session","workspace_stopped")}getWorkspaceSelected(){return this.getSettings("workspace_selected","TBD","workspace_selected")}getWorkspaceCount(){return this.getSettings("workspace_count","Number of workspace running in the platform during each platform session","workspace_count")}getPlatformStartup(){return this.getSettings("platform_startup","Time to load the platform","platform_startup","ms")}getPlatformError(){return this.getSettings("platform_error","Number of times platform error was received during each platform session","platform_error")}getSystemMemory(){return this.getSettings("system_memory","Free system memory, used system memory and used platform memory","system_memory","gb")}getSystemCPU(){return this.getSettings("system_cpu","Current and average system CPU and average platform CPU","system_cpu","%")}getSettings(e,t,r,n,i){return{enabled:!0,name:e,description:t,user:this.unknown,platformVersion:this.unknown,type:r,unit:n,buckets:i}}}_default$2.DefaultMetricsSettings=DefaultMetricsSettings,Object.defineProperty(builder$4,"__esModule",{value:!0}),builder$4.MetricsSettingsBuilder=void 0;const settingsBuilder_1=settingsBuilder,default_1=_default$2,container_1$5=container$1,constants_1$2=constants$3;class MetricsSettingsBuilder{constructor(){this.metrics=new Map,this.defaultSettings=new default_1.DefaultMetricsSettings,this.withSettings({enabled:!1,platformVersion:constants_1$2.Defaults.DEFAULT_PLATFORM_VERSION,serviceId:constants_1$2.Defaults.DEFAULT_SERVICE_ID,serviceName:constants_1$2.Defaults.DEFAULT_SERVICE_NAME,userId:constants_1$2.Defaults.DEFAULT_USER,serviceVersion:constants_1$2.Defaults.DEFAULT_SERVICE_VERSION,metrics:this.defaultSettings})}build(){var e,t,r,n,i,o,s,a,c,l,u,d,h,p,g,m,f,y,$,b;if(!this.platformMetricsEnabled)for(const e of this.defaultSettings.metrics)this.metrics.delete(e.name);this.metrics.forEach(e=>{this.metrics.set(e.name,this.convert(e))});const v=null!==(t=null===(e=this.meter)||void 0===e?void 0:e.headers)&&void 0!==t?t:Object.assign(Object.assign({},container_1$5.Container.errorless(null===(r=this.otelSettings)||void 0===r?void 0:r.headers)),container_1$5.Container.errorless(null===(n=this.settings)||void 0===n?void 0:n.headers)),w=Object.assign(Object.assign({},this.settings),{enabled:this.enabled,platformMetricsEnabled:this.platformMetricsEnabled,url:null!==(s=null!==(i=this.meter.url)&&void 0!==i?i:null===(o=this.settings)||void 0===o?void 0:o.url)&&void 0!==s?s:"http://localhost:4318/v1/metrics",publishInterval:null!==(l=null!==(a=this.meter.publishInterval)&&void 0!==a?a:null===(c=this.settings)||void 0===c?void 0:c.publishInterval)&&void 0!==l?l:3e4,compression:null!==(u=this.meter.compression)&&void 0!==u?u:null===(d=this.settings)||void 0===d?void 0:d.compression,headers:v,hostname:null!==(h=this.meter.hostname)&&void 0!==h?h:null===(p=this.settings)||void 0===p?void 0:p.hostname,keepAlive:null!==(g=this.meter.keepAlive)&&void 0!==g?g:null===(m=this.settings)||void 0===m?void 0:m.keepAlive,concurrencyLimit:null!==(f=this.meter.concurrencyLimit)&&void 0!==f?f:null===(y=this.settings)||void 0===y?void 0:y.concurrencyLimit,timeoutMillis:null!==($=this.meter.concurrencyLimit)&&void 0!==$?$:null===(b=this.settings)||void 0===b?void 0:b.timeoutMillis,metrics:[...this.metrics.values()],additionalAttributes:()=>{var e,t;return Object.assign(Object.assign({},container_1$5.Container.errorless(null===(e=this.otelSettings)||void 0===e?void 0:e.additionalAttributes)),container_1$5.Container.errorless(null===(t=this.settings)||void 0===t?void 0:t.additionalAttributes))}});return(new settingsBuilder_1.MetricsSettingsBuilderValidator).validate(w),w}withSettings(e){var t,r,n,i,o,s,a,c,l,u,d,h;const p=this.otelSettings;this.otelSettings=e;const g=this.settings;return this.settings=null==e?void 0:e.metrics,this.withEnabled(null!==(r=null===(t=this.settings)||void 0===t?void 0:t.enabled)&&void 0!==r?r:null==g?void 0:g.enabled).withPlatformMetricsEnabled(null!==(i=null===(n=this.settings)||void 0===n?void 0:n.platformMetricsEnabled)&&void 0!==i?i:null==g?void 0:g.platformMetricsEnabled).withUser(null!==(s=null===(o=this.otelSettings)||void 0===o?void 0:o.userId)&&void 0!==s?s:null==p?void 0:p.userId).withPlatformVersion(null!==(c=null===(a=this.otelSettings)||void 0===a?void 0:a.platformVersion)&&void 0!==c?c:null==p?void 0:p.platformVersion).withAdditionalAttributes(null===(l=this.settings)||void 0===l?void 0:l.additionalAttributes).withCustomMetrics(null===(u=this.settings)||void 0===u?void 0:u.metrics).withMeter(null!==(h=null===(d=this.settings)||void 0===d?void 0:d.meter)&&void 0!==h?h:this.meter)}withEnabled(e){return this.enabled=null!=e?e:this.enabled,this}withUser(e){return this.userId=null!=e?e:this.userId,this.metrics.forEach(e=>{e.user=this.userId,this.metrics.set(e.name,e)}),this}withAdditionalAttributes(e){return this.additionalAttributes=null!=e?e:this.additionalAttributes,this.metrics.forEach(e=>{e.additionalAttributes=this.additionalAttributes,this.metrics.set(e.type,e)}),this}withPlatformVersion(e){return this.platformVersion=null!=e?e:this.platformVersion,this.metrics.forEach(e=>{e.platformVersion=this.platformVersion,this.metrics.set(e.name,e)}),this}withPlatformMetricsEnabled(e){return this.platformMetricsEnabled=null!=e?e:this.platformMetricsEnabled,this}withMeter(e){var t,r,n,i,o,s,a,c,l,u;const d=this.meter;return this.meter=Object.assign(Object.assign(Object.assign({},d),null!=e?e:{}),{url:null!==(t=null==e?void 0:e.url)&&void 0!==t?t:null==d?void 0:d.url,publishInterval:null!==(r=null==e?void 0:e.publishInterval)&&void 0!==r?r:null==d?void 0:d.publishInterval,compression:null!==(o=null!==(n=null==e?void 0:e.compression)&&void 0!==n?n:null===(i=this.settings)||void 0===i?void 0:i.compression)&&void 0!==o?o:null==d?void 0:d.compression,headers:null!==(s=null==e?void 0:e.headers)&&void 0!==s?s:null==d?void 0:d.headers,hostname:null!==(a=null==e?void 0:e.hostname)&&void 0!==a?a:null==d?void 0:d.hostname,keepAlive:null!==(c=null==e?void 0:e.keepAlive)&&void 0!==c?c:null==d?void 0:d.keepAlive,concurrencyLimit:null!==(l=null==e?void 0:e.concurrencyLimit)&&void 0!==l?l:null==d?void 0:d.concurrencyLimit,timeoutMillis:null!==(u=null==e?void 0:e.timeoutMillis)&&void 0!==u?u:null==d?void 0:d.timeoutMillis}),this}withCustomMetrics(e){return(null!=e?e:[]).forEach(e=>this.withCustomMetric(e)),this}withCustomMetric(e){if(!e.name)throw new Error("settings.name is not defined");if(this.metrics.has(e.name)){const t=this.metrics.get(e.type),r=this.mergeSettings(e,t);this.metrics.set(r.name,r)}else{const t=this.convert(e);this.metrics.set(e.name,t)}return this}convert(e){var t,r,n,i;return Object.assign(Object.assign(Object.assign({},this.settings),e),{type:e.type,user:this.userId,enabled:null===(t=e.enabled)||void 0===t||t,name:null!==(r=e.name)&&void 0!==r?r:e.type,description:null!==(n=e.description)&&void 0!==n?n:null!==(i=e.name)&&void 0!==i?i:e.type,platformVersion:this.platformVersion,unit:e.unit,buckets:e.buckets,additionalAttributes:e.additionalAttributes})}mergeSettings(e,t){var r,n,i,o,s;return Object.assign(Object.assign(Object.assign({},t),this.settings),{type:e.type,user:this.userId,enabled:null!==(r=e.enabled)&&void 0!==r?r:t.enabled,name:null!==(n=e.name)&&void 0!==n?n:t.name,description:null!==(i=e.description)&&void 0!==i?i:t.description,platformVersion:this.platformVersion,unit:t.unit,buckets:null!==(o=e.buckets)&&void 0!==o?o:t.buckets,additionalAttributes:null!==(s=e.additionalAttributes)&&void 0!==s?s:t.additionalAttributes})}}builder$4.MetricsSettingsBuilder=MetricsSettingsBuilder;var builder$3={};Object.defineProperty(builder$3,"__esModule",{value:!0}),builder$3.MetricsBuilderValidator=void 0;const validator_1$3=validator$1;class MetricsBuilderValidator{validate(e){var t,r;validator_1$3.Validator.throwIfNullOrUndefined(e,"builder"),validator_1$3.Validator.throwIfNullOrUndefined(e.logger,"logger"),(null===(r=null===(t=e.settings)||void 0===t?void 0:t.metrics)||void 0===r?void 0:r.platformMetricsEnabled)&&validator_1$3.Validator.throwIfNullOrUndefined(e.dependencyContainer,"dependencyContainer",".withDependencyContainer() must be called to initialize metrics")}}builder$3.MetricsBuilderValidator=MetricsBuilderValidator;var providerFactory={};const VERSION$6="2.0.1",TMP_HTTP_URL="http.url",TMP_HTTP_USER_AGENT="http.user_agent",SEMATTRS_HTTP_URL=TMP_HTTP_URL,SEMATTRS_HTTP_USER_AGENT=TMP_HTTP_USER_AGENT,TMP_PROCESS_RUNTIME_NAME="process.runtime.name",TMP_TELEMETRY_SDK_NAME="telemetry.sdk.name",TMP_TELEMETRY_SDK_LANGUAGE="telemetry.sdk.language",TMP_TELEMETRY_SDK_VERSION="telemetry.sdk.version",SEMRESATTRS_PROCESS_RUNTIME_NAME=TMP_PROCESS_RUNTIME_NAME,SEMRESATTRS_TELEMETRY_SDK_NAME=TMP_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE=TMP_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION=TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS="webjs",TELEMETRYSDKLANGUAGEVALUES_WEBJS=TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,ATTR_ERROR_TYPE="error.type",ATTR_EXCEPTION_MESSAGE="exception.message",ATTR_EXCEPTION_STACKTRACE="exception.stacktrace",ATTR_EXCEPTION_TYPE="exception.type",ATTR_HTTP_REQUEST_METHOD="http.request.method",ATTR_HTTP_REQUEST_METHOD_ORIGINAL="http.request.method_original",ATTR_HTTP_RESPONSE_STATUS_CODE="http.response.status_code",ATTR_SERVER_ADDRESS="server.address",ATTR_SERVER_PORT="server.port",ATTR_SERVICE_NAME="service.name",ATTR_TELEMETRY_SDK_LANGUAGE="telemetry.sdk.language",TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS="webjs",ATTR_TELEMETRY_SDK_NAME="telemetry.sdk.name",ATTR_TELEMETRY_SDK_VERSION="telemetry.sdk.version",ATTR_URL_FULL="url.full",ATTR_PROCESS_RUNTIME_NAME="process.runtime.name",SDK_INFO$1={[ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[ATTR_PROCESS_RUNTIME_NAME]:"browser",[ATTR_TELEMETRY_SDK_LANGUAGE]:TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,[ATTR_TELEMETRY_SDK_VERSION]:VERSION$6};function defaultServiceName$1(){return"unknown_service"}const isPromiseLike$1=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;let ResourceImpl$1=class e{_rawAttributes;_asyncAttributesPending=!1;_memoizedAttributes;static FromAttributeList(t){const r=new e({});return r._rawAttributes=guardedRawAttributes(t),r._asyncAttributesPending=t.filter(([e,t])=>isPromiseLike$1(t)).length>0,r}constructor(e){const t=e.attributes??{};this._rawAttributes=Object.entries(t).map(([e,t])=>(isPromiseLike$1(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=guardedRawAttributes(this._rawAttributes)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;eisPromiseLike$1(t)?[e,t.catch(t=>{diag.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}const detectResources=(e={})=>{const t=(e.detectors||[]).map(t=>{try{const r=resourceFromDetectedResource(t.detect(e));return diag.debug(`${t.constructor.name} found resource.`,r),r}catch(e){return diag.debug(`${t.constructor.name} failed: ${e.message}`),emptyResource()}});return t.reduce((e,t)=>e.merge(t),emptyResource())};class EnvDetector{_MAX_LENGTH=255;_COMMA_SEPARATOR=",";_LABEL_KEY_VALUE_SPLITTER="=";_ERROR_MESSAGE_INVALID_CHARS="should be a ASCII string with a length greater than 0 and not exceed "+this._MAX_LENGTH+" characters.";_ERROR_MESSAGE_INVALID_VALUE="should be a ASCII string with a length not exceed "+this._MAX_LENGTH+" characters.";detect(e){return{attributes:{}}}_parseResourceAttributes(e){if(!e)return{};const t={},r=e.split(this._COMMA_SEPARATOR,-1);for(const e of r){const r=e.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(2!==r.length)continue;let[n,i]=r;if(n=n.trim(),i=i.trim().split(/^"|"$/).join(""),!this._isValidAndNotEmpty(n))throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(i))throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);t[n]=decodeURIComponent(i)}return t}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let t=0;t126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}}const envDetector=new EnvDetector;class NoopDetector{detect(){return{attributes:{}}}}const noopDetector=new NoopDetector,hostDetector=noopDetector,osDetector=noopDetector,processDetector=noopDetector,serviceInstanceIdDetector=noopDetector;var esm$c=Object.freeze({__proto__:null,defaultResource:defaultResource$1,defaultServiceName:defaultServiceName$1,detectResources:detectResources,emptyResource:emptyResource,envDetector:envDetector,hostDetector:hostDetector,osDetector:osDetector,processDetector:processDetector,resourceFromAttributes:resourceFromAttributes$1,serviceInstanceIdDetector:serviceInstanceIdDetector}),require$$2=getAugmentedNamespace(esm$c);const SUPPRESS_TRACING_KEY$2=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing$2(e){return e.setValue(SUPPRESS_TRACING_KEY$2,!0)}function unsuppressTracing(e){return e.deleteValue(SUPPRESS_TRACING_KEY$2)}function isTracingSuppressed$1(e){return!0===e.getValue(SUPPRESS_TRACING_KEY$2)}const BAGGAGE_KEY_PAIR_SEPARATOR="=",BAGGAGE_PROPERTIES_SEPARATOR=";",BAGGAGE_ITEMS_SEPARATOR=",",BAGGAGE_HEADER="baggage",BAGGAGE_MAX_NAME_VALUE_PAIRS=180,BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,BAGGAGE_MAX_TOTAL_LENGTH=8192;function serializeKeyPairs(e){return e.reduce((e,t)=>{const r=`${e}${""!==e?BAGGAGE_ITEMS_SEPARATOR:""}${t}`;return r.length>BAGGAGE_MAX_TOTAL_LENGTH?e:r},"")}function getKeyPairs(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return void 0!==t.metadata&&(r+=BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),r})}function parsePairKeyValue(e){const t=e.split(BAGGAGE_PROPERTIES_SEPARATOR);if(t.length<=0)return;const r=t.shift();if(!r)return;const n=r.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;const i=decodeURIComponent(r.substring(0,n).trim()),o=decodeURIComponent(r.substring(n+1).trim());let s;return t.length>0&&(s=baggageEntryMetadataFromString(t.join(BAGGAGE_PROPERTIES_SEPARATOR))),{key:i,value:o,metadata:s}}function parseKeyPairsIntoRecord(e){return"string"!=typeof e||0===e.length?{}:e.split(BAGGAGE_ITEMS_SEPARATOR).map(e=>parsePairKeyValue(e)).filter(e=>void 0!==e&&e.value.length>0).reduce((e,t)=>(e[t.key]=t.value,e),{})}class W3CBaggagePropagator{inject(e,t,r){const n=propagation.getBaggage(e);if(!n||isTracingSuppressed$1(e))return;const i=serializeKeyPairs(getKeyPairs(n).filter(e=>e.length<=BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,BAGGAGE_MAX_NAME_VALUE_PAIRS));i.length>0&&r.set(t,BAGGAGE_HEADER,i)}extract(e,t,r){const n=r.get(t,BAGGAGE_HEADER),i=Array.isArray(n)?n.join(BAGGAGE_ITEMS_SEPARATOR):n;if(!i)return e;const o={};if(0===i.length)return e;return i.split(BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{const t=parsePairKeyValue(e);if(t){const e={value:t.value};t.metadata&&(e.metadata=t.metadata),o[t.key]=e}}),0===Object.entries(o).length?e:propagation.setBaggage(e,propagation.createBaggage(o))}fields(){return[BAGGAGE_HEADER]}}class AnchoredClock{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){const e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}function sanitizeAttributes$1(e){const t={};if("object"!=typeof e||null==e)return t;for(const[r,n]of Object.entries(e))isAttributeKey$1(r)?isAttributeValue$1(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:diag.warn(`Invalid attribute value set for key: ${r}`):diag.warn(`Invalid attribute key: ${r}`);return t}function isAttributeKey$1(e){return"string"==typeof e&&e.length>0}function isAttributeValue$1(e){return null==e||(Array.isArray(e)?isHomogeneousAttributeValueArray$1(e):isValidPrimitiveAttributeValue$1(e))}function isHomogeneousAttributeValueArray$1(e){let t;for(const r of e)if(null!=r){if(!t){if(isValidPrimitiveAttributeValue$1(r)){t=typeof r;continue}return!1}if(typeof r!==t)return!1}return!0}function isValidPrimitiveAttributeValue$1(e){switch(typeof e){case"number":case"boolean":case"string":return!0}return!1}function loggingErrorHandler$2(){return e=>{diag.error(stringifyException$2(e))}}function stringifyException$2(e){return"string"==typeof e?e:JSON.stringify(flattenException$2(e))}function flattenException$2(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler$2=loggingErrorHandler$2();function setGlobalErrorHandler(e){delegateHandler$2=e}function globalErrorHandler$2(e){try{delegateHandler$2(e)}catch{}}function getStringFromEnv(e){}function getBooleanFromEnv(e){}function getNumberFromEnv$1(e){}function getStringListFromEnv(e){}const _globalThis$6="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},otperformance$4=performance,VERSION$5="2.0.0",SDK_INFO={[SEMRESATTRS_TELEMETRY_SDK_NAME]:"opentelemetry",[SEMRESATTRS_PROCESS_RUNTIME_NAME]:"browser",[SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]:TELEMETRYSDKLANGUAGEVALUES_WEBJS,[SEMRESATTRS_TELEMETRY_SDK_VERSION]:VERSION$5};function unrefTimer$2(e){}const NANOSECOND_DIGITS$4=9,NANOSECOND_DIGITS_IN_MILLIS$5=6,MILLISECONDS_TO_NANOSECONDS$5=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$5),SECOND_TO_NANOSECONDS$4=Math.pow(10,NANOSECOND_DIGITS$4);function millisToHrTime$5(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$5)]}function getTimeOrigin$4(){let e=otperformance$4.timeOrigin;if("number"!=typeof e){const t=otperformance$4;e=t.timing&&t.timing.fetchStart}return e}function hrTime$4(e){return addHrTimes$4(millisToHrTime$5(getTimeOrigin$4()),millisToHrTime$5("number"==typeof e?e:otperformance$4.now()))}function timeInputToHrTime$1(e){if(isTimeInputHrTime$2(e))return e;if("number"==typeof e)return e=SECOND_TO_NANOSECONDS$4&&(r[1]-=SECOND_TO_NANOSECONDS$4,r[0]+=1),r}var ExportResultCode$2;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode$2||(ExportResultCode$2={}));class CompositePropagator{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>"function"==typeof e.fields?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,t,r){for(const n of this._propagators)try{n.inject(e,t,r)}catch(e){diag.warn(`Failed to inject with ${n.constructor.name}. Err: ${e.message}`)}}extract(e,t,r){return this._propagators.reduce((e,n)=>{try{return n.extract(e,t,r)}catch(e){diag.warn(`Failed to extract with ${n.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}const VALID_KEY_CHAR_RANGE="[_0-9a-z-*/]",VALID_KEY=`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`,VALID_VENDOR_KEY=`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`,VALID_KEY_REGEX=new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`),VALID_VALUE_BASE_REGEX=/^[ -~]{0,255}[!-~]$/,INVALID_VALUE_COMMA_EQUAL_REGEX=/,|=/;function validateKey(e){return VALID_KEY_REGEX.test(e)}function validateValue(e){return VALID_VALUE_BASE_REGEX.test(e)&&!INVALID_VALUE_COMMA_EQUAL_REGEX.test(e)}const MAX_TRACE_STATE_ITEMS=32,MAX_TRACE_STATE_LEN=512,LIST_MEMBERS_SEPARATOR=",",LIST_MEMBER_KEY_VALUE_SPLITTER="=";class TraceState{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){const r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+LIST_MEMBER_KEY_VALUE_SPLITTER+this.get(t)),e),[]).join(LIST_MEMBERS_SEPARATOR)}_parse(e){e.length>MAX_TRACE_STATE_LEN||(this._internalState=e.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((e,t)=>{const r=t.trim(),n=r.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);if(-1!==n){const i=r.slice(0,n),o=r.slice(n+1,t.length);validateKey(i)&&validateValue(o)&&e.set(i,o)}return e},new Map),this._internalState.size>MAX_TRACE_STATE_ITEMS&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new TraceState;return e._internalState=new Map(this._internalState),e}}const TRACE_PARENT_HEADER="traceparent",TRACE_STATE_HEADER="tracestate",VERSION$4="00",VERSION_PART="(?!ff)[\\da-f]{2}",TRACE_ID_PART="(?![0]{32})[\\da-f]{32}",PARENT_ID_PART="(?![0]{16})[\\da-f]{16}",FLAGS_PART="[\\da-f]{2}",TRACE_PARENT_REGEX=new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`);function parseTraceParent(e){const t=TRACE_PARENT_REGEX.exec(e);return t?"00"===t[1]&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}:null}class W3CTraceContextPropagator{inject(e,t,r){const n=trace.getSpanContext(e);if(!n||isTracingSuppressed$1(e)||!isSpanContextValid(n))return;const i=`${VERSION$4}-${n.traceId}-${n.spanId}-0${Number(n.traceFlags||TraceFlags.NONE).toString(16)}`;r.set(t,TRACE_PARENT_HEADER,i),n.traceState&&r.set(t,TRACE_STATE_HEADER,n.traceState.serialize())}extract(e,t,r){const n=r.get(t,TRACE_PARENT_HEADER);if(!n)return e;const i=Array.isArray(n)?n[0]:n;if("string"!=typeof i)return e;const o=parseTraceParent(i);if(!o)return e;o.isRemote=!0;const s=r.get(t,TRACE_STATE_HEADER);if(s){const e=Array.isArray(s)?s.join(","):s;o.traceState=new TraceState("string"==typeof e?e:void 0)}return trace.setSpanContext(e,o)}fields(){return[TRACE_PARENT_HEADER,TRACE_STATE_HEADER]}}const RPC_METADATA_KEY=createContextKey("OpenTelemetry SDK Context Key RPC_METADATA");var RPCType;function setRPCMetadata(e,t){return e.setValue(RPC_METADATA_KEY,t)}function deleteRPCMetadata(e){return e.deleteValue(RPC_METADATA_KEY)}function getRPCMetadata(e){return e.getValue(RPC_METADATA_KEY)}!function(e){e.HTTP="http"}(RPCType||(RPCType={}));const objectTag$1="[object Object]",nullTag$1="[object Null]",undefinedTag$1="[object Undefined]",funcProto$1=Function.prototype,funcToString$1=funcProto$1.toString,objectCtorString$2=funcToString$1.call(Object),getPrototypeOf$3=Object.getPrototypeOf,objectProto$1=Object.prototype,hasOwnProperty$3=objectProto$1.hasOwnProperty,symToStringTag$1=Symbol?Symbol.toStringTag:void 0,nativeObjectToString$1=objectProto$1.toString;function isPlainObject$4(e){if(!isObjectLike$1(e)||baseGetTag$1(e)!==objectTag$1)return!1;const t=getPrototypeOf$3(e);if(null===t)return!0;const r=hasOwnProperty$3.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString$1.call(r)===objectCtorString$2}function isObjectLike$1(e){return null!=e&&"object"==typeof e}function baseGetTag$1(e){return null==e?void 0===e?undefinedTag$1:nullTag$1:symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag$1(e):objectToString$2(e)}function getRawTag$1(e){const t=hasOwnProperty$3.call(e,symToStringTag$1),r=e[symToStringTag$1];let n=!1;try{e[symToStringTag$1]=void 0,n=!0}catch(e){}const i=nativeObjectToString$1.call(e);return n&&(t?e[symToStringTag$1]=r:delete e[symToStringTag$1]),i}function objectToString$2(e){return nativeObjectToString$1.call(e)}const MAX_LEVEL$1=20;function merge$3(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=mergeTwoObjects$1(t,e.shift(),0,r);return t}function takeValue$1(e){return isArray$7(e)?e.slice():e}function mergeTwoObjects$1(e,t,r=0,n){let i;if(!(r>MAX_LEVEL$1)){if(r++,isPrimitive$1(e)||isPrimitive$1(t)||isFunction$5(t))i=takeValue$1(t);else if(isArray$7(e)){if(i=e.slice(),isArray$7(t))for(let e=0,r=t.length;e(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}function urlMatches$3(e,t){return"string"==typeof t?e===t:!!e.match(t)}function isUrlIgnored$2(e,t){if(!t)return!1;for(const r of t)if(urlMatches$3(e,r))return!0;return!1}let Deferred$1=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}},BindOnceFuture$1=class{_callback;_that;_isCalled=!1;_deferred=new Deferred$1;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}};const logLevelMap={ALL:DiagLogLevel.ALL,VERBOSE:DiagLogLevel.VERBOSE,DEBUG:DiagLogLevel.DEBUG,INFO:DiagLogLevel.INFO,WARN:DiagLogLevel.WARN,ERROR:DiagLogLevel.ERROR,NONE:DiagLogLevel.NONE};function diagLogLevelFromString(e){if(null==e)return;const t=logLevelMap[e.toUpperCase()];return null==t?(diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(logLevelMap)}, using default`),DiagLogLevel.INFO):t}function _export$2(e,t){return new Promise(r=>{context.with(suppressTracing$2(context.active()),()=>{e.export(t,e=>{r(e)})})})}const internal$2={_export:_export$2};var esm$b=Object.freeze({__proto__:null,AnchoredClock:AnchoredClock,BindOnceFuture:BindOnceFuture$1,CompositePropagator:CompositePropagator,get ExportResultCode(){return ExportResultCode$2},get RPCType(){return RPCType},SDK_INFO:SDK_INFO,TRACE_PARENT_HEADER:TRACE_PARENT_HEADER,TRACE_STATE_HEADER:TRACE_STATE_HEADER,TimeoutError:TimeoutError$1,TraceState:TraceState,W3CBaggagePropagator:W3CBaggagePropagator,W3CTraceContextPropagator:W3CTraceContextPropagator,_globalThis:_globalThis$6,addHrTimes:addHrTimes$4,callWithTimeout:callWithTimeout$1,deleteRPCMetadata:deleteRPCMetadata,diagLogLevelFromString:diagLogLevelFromString,getBooleanFromEnv:getBooleanFromEnv,getNumberFromEnv:getNumberFromEnv$1,getRPCMetadata:getRPCMetadata,getStringFromEnv:getStringFromEnv,getStringListFromEnv:getStringListFromEnv,getTimeOrigin:getTimeOrigin$4,globalErrorHandler:globalErrorHandler$2,hrTime:hrTime$4,hrTimeDuration:hrTimeDuration$1,hrTimeToMicroseconds:hrTimeToMicroseconds$2,hrTimeToMilliseconds:hrTimeToMilliseconds,hrTimeToNanoseconds:hrTimeToNanoseconds$1,hrTimeToTimeStamp:hrTimeToTimeStamp,internal:internal$2,isAttributeValue:isAttributeValue$1,isTimeInput:isTimeInput$1,isTimeInputHrTime:isTimeInputHrTime$2,isTracingSuppressed:isTracingSuppressed$1,isUrlIgnored:isUrlIgnored$2,loggingErrorHandler:loggingErrorHandler$2,merge:merge$3,millisToHrTime:millisToHrTime$5,otperformance:otperformance$4,parseKeyPairsIntoRecord:parseKeyPairsIntoRecord,parseTraceParent:parseTraceParent,sanitizeAttributes:sanitizeAttributes$1,setGlobalErrorHandler:setGlobalErrorHandler,setRPCMetadata:setRPCMetadata,suppressTracing:suppressTracing$2,timeInputToHrTime:timeInputToHrTime$1,unrefTimer:unrefTimer$2,unsuppressTracing:unsuppressTracing,urlMatches:urlMatches$3}),AggregationTemporality$2,InstrumentType$2,DataPointType$2,AggregationType$1,AggregationTemporalityPreference;!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality$2||(AggregationTemporality$2={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType$2||(InstrumentType$2={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType$2||(DataPointType$2={})),function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(AggregationType$1||(AggregationType$1={})),function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE",e[e.LOWMEMORY=2]="LOWMEMORY"}(AggregationTemporalityPreference||(AggregationTemporalityPreference={}));class OTLPExporterBase{_delegate;constructor(e){this._delegate=e}export(e,t){this._delegate.export(e,t)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class OTLPExporterError extends Error{code;name="OTLPExporterError";data;constructor(e,t,r){super(e),this.data=r,this.code=t}}function validateTimeoutMillis(e){if(Number.isFinite(e)&&e>0)return e;throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${e}')`)}function wrapStaticHeadersInFunction(e){if(null!=e)return()=>e}function mergeOtlpSharedConfigurationWithDefaults(e,t,r){return{timeoutMillis:validateTimeoutMillis(e.timeoutMillis??t.timeoutMillis??r.timeoutMillis),concurrencyLimit:e.concurrencyLimit??t.concurrencyLimit??r.concurrencyLimit,compression:e.compression??t.compression??r.compression}}function getSharedConfigurationDefaults(){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none"}}class BoundedQueueExportPromiseHandler{_concurrencyLimit;_sendingPromises=[];constructor(e){this._concurrencyLimit=e}pushPromise(e){if(this.hasReachedLimit())throw new Error("Concurrency Limit reached");this._sendingPromises.push(e);const t=()=>{const t=this._sendingPromises.indexOf(e);this._sendingPromises.splice(t,1)};e.then(t,t)}hasReachedLimit(){return this._sendingPromises.length>=this._concurrencyLimit}async awaitAll(){await Promise.all(this._sendingPromises)}}function createBoundedQueueExportPromiseHandler(e){return new BoundedQueueExportPromiseHandler(e.concurrencyLimit)}function isPartialSuccessResponse(e){return Object.prototype.hasOwnProperty.call(e,"partialSuccess")}function createLoggingPartialSuccessResponseHandler(){return{handleResponse(e){null!=e&&isPartialSuccessResponse(e)&&null!=e.partialSuccess&&0!==Object.keys(e.partialSuccess).length&&diag.warn("Received Partial Success response:",JSON.stringify(e.partialSuccess))}}}class OTLPExportDelegate{_transport;_serializer;_responseHandler;_promiseQueue;_timeout;_diagLogger;constructor(e,t,r,n,i){this._transport=e,this._serializer=t,this._responseHandler=r,this._promiseQueue=n,this._timeout=i,this._diagLogger=diag.createComponentLogger({namespace:"OTLPExportDelegate"})}export(e,t){if(this._diagLogger.debug("items to be sent",e),this._promiseQueue.hasReachedLimit())return void t({code:ExportResultCode$2.FAILED,error:new Error("Concurrent export limit reached")});const r=this._serializer.serializeRequest(e);null!=r?this._promiseQueue.pushPromise(this._transport.send(r,this._timeout).then(e=>{if("success"!==e.status)"failure"===e.status&&e.error?t({code:ExportResultCode$2.FAILED,error:e.error}):"retryable"===e.status?t({code:ExportResultCode$2.FAILED,error:new OTLPExporterError("Export failed with retryable status")}):t({code:ExportResultCode$2.FAILED,error:new OTLPExporterError("Export failed with unknown error")});else{if(null!=e.data)try{this._responseHandler.handleResponse(this._serializer.deserializeResponse(e.data))}catch(t){this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?",t,e.data)}t({code:ExportResultCode$2.SUCCESS})}},e=>t({code:ExportResultCode$2.FAILED,error:e}))):t({code:ExportResultCode$2.FAILED,error:new Error("Nothing to send")})}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started"),await this.forceFlush(),this._transport.shutdown()}}function createOtlpExportDelegate(e,t){return new OTLPExportDelegate(e.transport,e.serializer,createLoggingPartialSuccessResponseHandler(),e.promiseHandler,t.timeout)}function createOtlpNetworkExportDelegate(e,t,r){return createOtlpExportDelegate({transport:r,serializer:t,promiseHandler:createBoundedQueueExportPromiseHandler(e)},{timeout:e.timeoutMillis})}const CumulativeTemporalitySelector=()=>AggregationTemporality$2.CUMULATIVE,DeltaTemporalitySelector=e=>{switch(e){case InstrumentType$2.COUNTER:case InstrumentType$2.OBSERVABLE_COUNTER:case InstrumentType$2.GAUGE:case InstrumentType$2.HISTOGRAM:case InstrumentType$2.OBSERVABLE_GAUGE:return AggregationTemporality$2.DELTA;case InstrumentType$2.UP_DOWN_COUNTER:case InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER:return AggregationTemporality$2.CUMULATIVE}},LowMemoryTemporalitySelector=e=>{switch(e){case InstrumentType$2.COUNTER:case InstrumentType$2.HISTOGRAM:return AggregationTemporality$2.DELTA;case InstrumentType$2.GAUGE:case InstrumentType$2.UP_DOWN_COUNTER:case InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER:case InstrumentType$2.OBSERVABLE_COUNTER:case InstrumentType$2.OBSERVABLE_GAUGE:return AggregationTemporality$2.CUMULATIVE}};function chooseTemporalitySelectorFromEnvironment(){const e="cumulative".toLowerCase();return"cumulative"===e?CumulativeTemporalitySelector:"delta"===e?DeltaTemporalitySelector:"lowmemory"===e?LowMemoryTemporalitySelector:(diag.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),CumulativeTemporalitySelector)}function chooseTemporalitySelector(e){return null!=e?e===AggregationTemporalityPreference.DELTA?DeltaTemporalitySelector:e===AggregationTemporalityPreference.LOWMEMORY?LowMemoryTemporalitySelector:CumulativeTemporalitySelector:chooseTemporalitySelectorFromEnvironment()}const DEFAULT_AGGREGATION$1=Object.freeze({type:AggregationType$1.DEFAULT});function chooseAggregationSelector(e){return e?.aggregationPreference??(()=>DEFAULT_AGGREGATION$1)}class OTLPMetricExporterBase extends OTLPExporterBase{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=chooseAggregationSelector(t),this._aggregationTemporalitySelector=chooseTemporalitySelector(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}}function intValue(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-87:e-55}function hexToBinary(e){const t=new Uint8Array(e.length/2);let r=0;for(let n=0;n>BigInt(32)))}}function encodeAsLongBits(e){return toLongBits(hrTimeToNanos(e))}function encodeAsString(e){return hrTimeToNanos(e).toString()}const encodeTimestamp="undefined"!=typeof BigInt?encodeAsString:hrTimeToNanoseconds$1;function identity(e){return e}function optionalHexToBinary(e){if(void 0!==e)return hexToBinary(e)}const DEFAULT_ENCODER={encodeHrTime:encodeAsLongBits,encodeSpanContext:hexToBinary,encodeOptionalSpanContext:optionalHexToBinary};function getOtlpEncoder(e){if(void 0===e)return DEFAULT_ENCODER;const t=e.useLongBits??!0,r=e.useHex??!1;return{encodeHrTime:t?encodeAsLongBits:encodeTimestamp,encodeSpanContext:r?identity:hexToBinary,encodeOptionalSpanContext:r?identity:optionalHexToBinary}}function createResource(e){return{attributes:toAttributes(e.attributes),droppedAttributesCount:0}}function createInstrumentationScope(e){return{name:e.name,version:e.version}}function toAttributes(e){return Object.keys(e).map(t=>toKeyValue(t,e[t]))}function toKeyValue(e,t){return{key:e,value:toAnyValue(t)}}function toAnyValue(e){const t=typeof e;return"string"===t?{stringValue:e}:"number"===t?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:"boolean"===t?{boolValue:e}:e instanceof Uint8Array?{bytesValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(toAnyValue)}}:"object"===t&&null!=e?{kvlistValue:{values:Object.entries(e).map(([e,t])=>toKeyValue(e,t))}}:{}}function createExportLogsServiceRequest(e,t){return{resourceLogs:logRecordsToResourceLogs(e,getOtlpEncoder(t))}}function createResourceMap$1(e){const t=new Map;for(const r of e){const{resource:e,instrumentationScope:{name:n,version:i="",schemaUrl:o=""}}=r;let s=t.get(e);s||(s=new Map,t.set(e,s));const a=`${n}@${i}:${o}`;let c=s.get(a);c||(c=[],s.set(a,c)),c.push(r)}return t}function logRecordsToResourceLogs(e,t){const r=createResourceMap$1(e);return Array.from(r,([e,r])=>({resource:createResource(e),scopeLogs:Array.from(r,([,e])=>({scope:createInstrumentationScope(e[0].instrumentationScope),logRecords:e.map(e=>toLogRecord(e,t)),schemaUrl:e[0].instrumentationScope.schemaUrl})),schemaUrl:void 0}))}function toLogRecord(e,t){return{timeUnixNano:t.encodeHrTime(e.hrTime),observedTimeUnixNano:t.encodeHrTime(e.hrTimeObserved),severityNumber:toSeverityNumber(e.severityNumber),severityText:e.severityText,body:toAnyValue(e.body),attributes:toLogAttributes(e.attributes),droppedAttributesCount:e.droppedAttributesCount,flags:e.spanContext?.traceFlags,traceId:t.encodeOptionalSpanContext(e.spanContext?.traceId),spanId:t.encodeOptionalSpanContext(e.spanContext?.spanId)}}function toSeverityNumber(e){return e}function toLogAttributes(e){return Object.keys(e).map(t=>toKeyValue(t,e[t]))}var AggregationTemporality$1,InstrumentType$1,DataPointType$1;function toResourceMetrics(e,t){const r=getOtlpEncoder(t);return{resource:createResource(e.resource),schemaUrl:void 0,scopeMetrics:toScopeMetrics(e.scopeMetrics,r)}}function toScopeMetrics(e,t){return Array.from(e.map(e=>({scope:createInstrumentationScope(e.scope),metrics:e.metrics.map(e=>toMetric(e,t)),schemaUrl:e.scope.schemaUrl})))}function toMetric(e,t){const r={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},n=toAggregationTemporality(e.aggregationTemporality);switch(e.dataPointType){case DataPointType$1.SUM:r.sum={aggregationTemporality:n,isMonotonic:e.isMonotonic,dataPoints:toSingularDataPoints(e,t)};break;case DataPointType$1.GAUGE:r.gauge={dataPoints:toSingularDataPoints(e,t)};break;case DataPointType$1.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:toHistogramDataPoints(e,t)};break;case DataPointType$1.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:toExponentialHistogramDataPoints(e,t)}}return r}function toSingularDataPoint(e,t,r){const n={attributes:toAttributes(e.attributes),startTimeUnixNano:r.encodeHrTime(e.startTime),timeUnixNano:r.encodeHrTime(e.endTime)};switch(t){case ValueType.INT:n.asInt=e.value;break;case ValueType.DOUBLE:n.asDouble=e.value}return n}function toSingularDataPoints(e,t){return e.dataPoints.map(r=>toSingularDataPoint(r,e.descriptor.valueType,t))}function toHistogramDataPoints(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:toAttributes(e.attributes),bucketCounts:r.buckets.counts,explicitBounds:r.buckets.boundaries,count:r.count,sum:r.sum,min:r.min,max:r.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function toExponentialHistogramDataPoints(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:toAttributes(e.attributes),count:r.count,min:r.min,max:r.max,sum:r.sum,positive:{offset:r.positive.offset,bucketCounts:r.positive.bucketCounts},negative:{offset:r.negative.offset,bucketCounts:r.negative.bucketCounts},scale:r.scale,zeroCount:r.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function toAggregationTemporality(e){switch(e){case AggregationTemporality$1.DELTA:return 1;case AggregationTemporality$1.CUMULATIVE:return 2}}function createExportMetricsServiceRequest(e,t){return{resourceMetrics:e.map(e=>toResourceMetrics(e,t))}}function sdkSpanToOtlpSpan(e,t){const r=e.spanContext(),n=e.status,i=e.parentSpanContext?.spanId?t.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:t.encodeSpanContext(r.traceId),spanId:t.encodeSpanContext(r.spanId),parentSpanId:i,traceState:r.traceState?.serialize(),name:e.name,kind:null==e.kind?0:e.kind+1,startTimeUnixNano:t.encodeHrTime(e.startTime),endTimeUnixNano:t.encodeHrTime(e.endTime),attributes:toAttributes(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>toOtlpSpanEvent(e,t)),droppedEventsCount:e.droppedEventsCount,status:{code:n.code,message:n.message},links:e.links.map(e=>toOtlpLink(e,t)),droppedLinksCount:e.droppedLinksCount}}function toOtlpLink(e,t){return{attributes:e.attributes?toAttributes(e.attributes):[],spanId:t.encodeSpanContext(e.context.spanId),traceId:t.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}function toOtlpSpanEvent(e,t){return{attributes:e.attributes?toAttributes(e.attributes):[],name:e.name,timeUnixNano:t.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}function createExportTraceServiceRequest(e,t){return{resourceSpans:spanRecordsToResourceSpans(e,getOtlpEncoder(t))}}function createResourceMap(e){const t=new Map;for(const r of e){let e=t.get(r.resource);e||(e=new Map,t.set(r.resource,e));const n=`${r.instrumentationScope.name}@${r.instrumentationScope.version||""}:${r.instrumentationScope.schemaUrl||""}`;let i=e.get(n);i||(i=[],e.set(n,i)),i.push(r)}return t}function spanRecordsToResourceSpans(e,t){const r=[],n=createResourceMap(e).entries();let i=n.next();for(;!i.done;){const[e,o]=i.value,s=[],a=o.values();let c=a.next();for(;!c.done;){const e=c.value;if(e.length>0){const r=e.map(e=>sdkSpanToOtlpSpan(e,t));s.push({scope:createInstrumentationScope(e[0].instrumentationScope),spans:r,schemaUrl:e[0].instrumentationScope.schemaUrl})}c=a.next()}const l={resource:createResource(e),scopeSpans:s,schemaUrl:void 0};r.push(l),i=n.next()}return r}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality$1||(AggregationTemporality$1={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType$1||(InstrumentType$1={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType$1||(DataPointType$1={}));const JsonLogsSerializer={serializeRequest:e=>{const t=createExportLogsServiceRequest(e,{useHex:!0,useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},JsonMetricsSerializer={serializeRequest:e=>{const t=createExportMetricsServiceRequest([e],{useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},JsonTraceSerializer={serializeRequest:e=>{const t=createExportTraceServiceRequest(e,{useHex:!0,useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},MAX_ATTEMPTS=5,INITIAL_BACKOFF=1e3,MAX_BACKOFF=5e3,BACKOFF_MULTIPLIER=1.5,JITTER=.2;function getJitter(){return Math.random()*(2*JITTER)-JITTER}class RetryingTransport{_transport;constructor(e){this._transport=e}retry(e,t,r){return new Promise((n,i)=>{setTimeout(()=>{this._transport.send(e,t).then(n,i)},r)})}async send(e,t){const r=Date.now()+t;let n=await this._transport.send(e,t),i=MAX_ATTEMPTS,o=INITIAL_BACKOFF;for(;"retryable"===n.status&&i>0;){i--;const t=Math.max(Math.min(o,MAX_BACKOFF)+getJitter(),0);o*=BACKOFF_MULTIPLIER;const s=n.retryInMillis??t,a=r-Date.now();if(s>a)return n;n=await this.retry(e,a,s)}return n}shutdown(){return this._transport.shutdown()}}function createRetryingTransport(e){return new RetryingTransport(e.transport)}function isExportRetryable(e){return[429,502,503,504].includes(e)}function parseRetryAfterToMills(e){if(null==e)return;const t=Number.parseInt(e,10);if(Number.isInteger(t))return t>0?1e3*t:-1;const r=new Date(e).getTime()-Date.now();return r>=0?r:0}class XhrTransport{_parameters;constructor(e){this._parameters=e}send(e,t){return new Promise(r=>{const n=new XMLHttpRequest;n.timeout=t,n.open("POST",this._parameters.url);const i=this._parameters.headers();Object.entries(i).forEach(([e,t])=>{n.setRequestHeader(e,t)}),n.ontimeout=e=>{r({status:"failure",error:new Error("XHR request timed out")})},n.onreadystatechange=()=>{n.status>=200&&n.status<=299?(diag.debug("XHR success"),r({status:"success"})):n.status&&isExportRetryable(n.status)?r({status:"retryable",retryInMillis:parseRetryAfterToMills(n.getResponseHeader("Retry-After"))}):0!==n.status&&r({status:"failure",error:new Error("XHR request failed with non-retryable status")})},n.onabort=()=>{r({status:"failure",error:new Error("XHR request aborted")})},n.onerror=()=>{r({status:"failure",error:new Error("XHR request errored")})},n.send(e)})}shutdown(){}}function createXhrTransport(e){return new XhrTransport(e)}class SendBeaconTransport{_params;constructor(e){this._params=e}send(e){return new Promise(t=>{navigator.sendBeacon(this._params.url,new Blob([e],{type:this._params.blobType}))?(diag.debug("SendBeacon success"),t({status:"success"})):t({status:"failure",error:new Error("SendBeacon failed")})})}shutdown(){}}function createSendBeaconTransport(e){return new SendBeaconTransport(e)}function createOtlpXhrExportDelegate(e,t){return createOtlpNetworkExportDelegate(e,t,createRetryingTransport({transport:createXhrTransport(e)}))}function createOtlpSendBeaconExportDelegate(e,t){return createOtlpNetworkExportDelegate(e,t,createRetryingTransport({transport:createSendBeaconTransport({url:e.url,blobType:e.headers()["Content-Type"]})}))}function validateAndNormalizeHeaders(e){return()=>{const t={};return Object.entries(e?.()??{}).forEach(([e,r])=>{void 0!==r?t[e]=String(r):diag.warn(`Header "${e}" has invalid value (${r}) and will be ignored`)}),t}}function mergeHeaders(e,t,r){const n={...r()},i={};return()=>(null!=t&&Object.assign(i,t()),null!=e&&Object.assign(i,e()),Object.assign(i,n))}function validateUserProvidedUrl(e){if(null!=e)try{return new URL(e),e}catch(t){throw new Error(`Configuration: Could not parse user-provided export URL: '${e}'`)}}function mergeOtlpHttpConfigurationWithDefaults(e,t,r){return{...mergeOtlpSharedConfigurationWithDefaults(e,t,r),headers:mergeHeaders(validateAndNormalizeHeaders(e.headers),t.headers,r.headers),url:validateUserProvidedUrl(e.url)??t.url??r.url,agentOptions:e.agentOptions??t.agentOptions??r.agentOptions}}function getHttpConfigurationDefaults(e,t){return{...getSharedConfigurationDefaults(),headers:()=>e,url:"http://localhost:4318/"+t,agentOptions:{keepAlive:!0}}}function convertLegacyBrowserHttpOptions(e,t,r){return mergeOtlpHttpConfigurationWithDefaults({url:e.url,timeoutMillis:e.timeoutMillis,headers:wrapStaticHeadersInFunction(e.headers),concurrencyLimit:e.concurrencyLimit},{},getHttpConfigurationDefaults(r,t))}function createLegacyOtlpBrowserExportDelegate(e,t,r,n){const i=!!e.headers||"function"!=typeof navigator.sendBeacon,o=convertLegacyBrowserHttpOptions(e,r,n);return i?createOtlpXhrExportDelegate(o,t):createOtlpSendBeaconExportDelegate(o,t)}class OTLPMetricExporter extends OTLPMetricExporterBase{constructor(e){super(createLegacyOtlpBrowserExportDelegate(e??{},JsonMetricsSerializer,"v1/metrics",{"Content-Type":"application/json"}),e)}}var esm$a=Object.freeze({__proto__:null,get AggregationTemporalityPreference(){return AggregationTemporalityPreference},CumulativeTemporalitySelector:CumulativeTemporalitySelector,DeltaTemporalitySelector:DeltaTemporalitySelector,LowMemoryTemporalitySelector:LowMemoryTemporalitySelector,OTLPMetricExporter:OTLPMetricExporter,OTLPMetricExporterBase:OTLPMetricExporterBase}),require$$5=getAugmentedNamespace(esm$a),AggregationTemporality,InstrumentType,DataPointType,AggregatorKind;function isNotNullish(e){return null!=e}function hashAttributes(e){let t=Object.keys(e);return 0===t.length?"":(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function instrumentationScopeId(e){return`${e.name}:${e.version??""}:${e.schemaUrl??""}`}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality||(AggregationTemporality={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType||(InstrumentType={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType||(DataPointType={}));class TimeoutError extends Error{constructor(e){super(e),Object.setPrototypeOf(this,TimeoutError.prototype)}}function callWithTimeout(e,t){let r;const n=new Promise(function(e,n){r=setTimeout(function(){n(new TimeoutError("Operation timed out."))},t)});return Promise.race([e,n]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}async function PromiseAllSettled(e){return Promise.all(e.map(async e=>{try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}))}function isPromiseAllSettledRejectionResult(e){return"rejected"===e.status}function FlatMap(e,t){const r=[];return e.forEach(e=>{r.push(...t(e))}),r}function setEquals(e,t){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}function binarySearchUB(e,t){let r=0,n=e.length-1,i=e.length;for(;n>=r;){const o=r+Math.trunc((n-r)/2);e[o]0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}class HistogramAccumulation{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,r=!0,n=createNewEmptyCheckpoint(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=r,this._current=n}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);const t=binarySearchUB(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class HistogramAggregator{_boundaries;_recordMinMax;kind=AggregatorKind.HISTOGRAM;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new HistogramAccumulation(e,this._boundaries,this._recordMinMax)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue(),i=r.buckets.counts,o=n.buckets.counts,s=new Array(i.length);for(let e=0;e{const i=r.toPointValue(),o=e.type===InstrumentType.GAUGE||e.type===InstrumentType.UP_DOWN_COUNTER||e.type===InstrumentType.OBSERVABLE_GAUGE||e.type===InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:o?void 0:i.sum,buckets:i.buckets,count:i.count}}})}}}class Buckets{backing;indexBase;indexStart;indexEnd;constructor(e=new BucketsBacking,t=0,r=0,n=0){this.backing=e,this.indexBase=t,this.indexStart=r,this.indexEnd=n}get offset(){return this.indexStart}get length(){return 0===this.backing.length||this.indexEnd===this.indexStart&&0===this.at(0)?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){const t=this.indexBase-this.indexStart;return e=0;e--)if(0!==this.at(e)){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();const t=1+this.indexEnd-this.indexStart,r=1<>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new Buckets(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const e=this.indexBase-this.indexStart;0!==e&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}}class BucketsBacking{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,r){const n=new Array(e).fill(0);n.splice(r,this._counts.length-t,...this._counts.slice(t)),n.splice(0,t,...this._counts.slice(0,t)),this._counts=n}reverse(e,t){const r=Math.floor((e+t)/2)-e;for(let n=0;n=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new BucketsBacking([...this._counts])}}const SIGNIFICAND_WIDTH=52,EXPONENT_MASK=2146435072,SIGNIFICAND_MASK=1048575,EXPONENT_BIAS=1023,MIN_NORMAL_EXPONENT=1-EXPONENT_BIAS,MAX_NORMAL_EXPONENT=EXPONENT_BIAS,MIN_VALUE=Math.pow(2,-1022);function getNormalBase2(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);return((t.getUint32(0)&EXPONENT_MASK)>>20)-EXPONENT_BIAS}function getSignificand(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);const r=t.getUint32(0),n=t.getUint32(4);return(r&SIGNIFICAND_MASK)*Math.pow(2,32)+n}function ldexp(e,t){return 0===e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY||Number.isNaN(e)?e:e*Math.pow(2,t)}function nextGreaterSquare(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}class MappingError extends Error{}class ExponentMapping{_shift;constructor(e){this._shift=-e}mapToIndex(e){if(e>this._shift}lowerBoundary(e){const t=this._minNormalLowerBoundaryIndex();if(er)throw new MappingError(`overflow: ${e} is > maximum lower boundary: ${r}`);return ldexp(1,e<>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return MAX_NORMAL_EXPONENT>>this._shift}_rightShift(e,t){return Math.floor(e*Math.pow(2,-t))}}class LogarithmMapping{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=ldexp(Math.LOG2E,e),this._inverseFactor=ldexp(Math.LN2,-e)}mapToIndex(e){if(e<=MIN_VALUE)return this._minNormalLowerBoundaryIndex()-1;if(0===getSignificand(e)){return(getNormalBase2(e)<=r?r:t}lowerBoundary(e){const t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1< maximum lower boundary: ${t}`)}const r=this._minNormalLowerBoundaryIndex();if(e<=r){if(e===r)return MIN_VALUE;if(e===r-1)return Math.exp((e+(1<t>10?new LogarithmMapping(t-10):new ExponentMapping(t-10));function getMapping(e){if(e>MAX_SCALE$1||e= ${MIN_SCALE} && <= ${MAX_SCALE$1}, got: ${e}`);return PREBUILT_MAPPINGS[e+10]}class HighLow{low;high;static combine(e,t){return new HighLow(Math.min(e.low,t.low),Math.max(e.high,t.high))}constructor(e,t){this.low=e,this.high=t}}const MAX_SCALE=20,DEFAULT_MAX_SIZE=160,MIN_MAX_SIZE=2;class ExponentialHistogramAccumulation{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e=e,t=DEFAULT_MAX_SIZE,r=!0,n=0,i=0,o=0,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new Buckets,l=new Buckets,u=getMapping(MAX_SCALE)){this.startTime=e,this._maxSize=t,this._recordMinMax=r,this._sum=n,this._count=i,this._zeroCount=o,this._min=s,this._max=a,this._positive=c,this._negative=l,this._mapping=u,this._maxSizethis._max&&(this._max=e),e0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)):this._zeroCount+=t)}merge(e){0===this._count?(this._min=e.min,this._max=e.max):0!==e.count&&(e.minthis.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new ExponentialHistogramAccumulation(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,r){let n=this._mapping.mapToIndex(t),i=!1,o=0,s=0;if(0===e.length?(e.indexStart=n,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):n=this._maxSize?(i=!0,s=n,o=e.indexEnd):n>e.indexEnd&&n-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,o=n),i){const e=this._changeScale(o,s);this._downscale(e),n=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,n,r)}_incrementIndexBy(e,t,r){if(0===r)return;if(0===e.length&&(e.indexStart=e.indexEnd=e.indexBase=t),t=e.backing.length&&this._grow(e,r+1),e.indexStart=t}else if(t>e.indexEnd){const r=t-e.indexStart;r>=e.backing.length&&this._grow(e,r+1),e.indexEnd=t}let n=t-e.indexBase;n<0&&(n+=e.backing.length),e.incrementBucket(n,r)}_grow(e,t){const r=e.backing.length,n=e.indexBase-e.indexStart,i=r-n;let o=nextGreaterSquare(t);o>this._maxSize&&(o=this._maxSize);const s=o-n;e.backing.growTo(o,i,s)}_changeScale(e,t){let r=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,r++;return r}_downscale(e){if(0===e)return;if(e<0)throw new Error(`impossible change of scale: ${this.scale}`);const t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=getMapping(t)}_minScale(e){const t=Math.min(this.scale,e.scale),r=HighLow.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),n=HighLow.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(r.high,r.low),t-this._changeScale(n.high,n.low))}_highLowAtScale(e,t,r){if(0===e.length)return new HighLow(0,-1);const n=t-r;return new HighLow(e.indexStart>>n,e.indexEnd>>n)}_mergeBuckets(e,t,r,n){const i=r.offset,o=t.scale-n;for(let t=0;t>o,r.at(t))}_diffBuckets(e,t,r,n){const i=r.offset,o=t.scale-n;for(let t=0;t>o)-e.indexBase;n<0&&(n+=e.backing.length),e.decrementBucket(n,r.at(t))}e.trim()}}class ExponentialHistogramAggregator{_maxSize;_recordMinMax;kind=AggregatorKind.EXPONENTIAL_HISTOGRAM;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new ExponentialHistogramAccumulation(e,this._maxSize,this._recordMinMax)}merge(e,t){const r=t.clone();return r.merge(e),r}diff(e,t){const r=t.clone();return r.diff(e),r}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType.EXPONENTIAL_HISTOGRAM,dataPoints:r.map(([t,r])=>{const i=r.toPointValue(),o=e.type===InstrumentType.GAUGE||e.type===InstrumentType.UP_DOWN_COUNTER||e.type===InstrumentType.OBSERVABLE_GAUGE||e.type===InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:o?void 0:i.sum,positive:{offset:i.positive.offset,bucketCounts:i.positive.bucketCounts},negative:{offset:i.negative.offset,bucketCounts:i.negative.bucketCounts},count:i.count,scale:i.scale,zeroCount:i.zeroCount}}})}}}const SUPPRESS_TRACING_KEY$1=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing$1(e){return e.setValue(SUPPRESS_TRACING_KEY$1,!0)}function loggingErrorHandler$1(){return e=>{diag.error(stringifyException$1(e))}}function stringifyException$1(e){return"string"==typeof e?e:JSON.stringify(flattenException$1(e))}function flattenException$1(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler$1=loggingErrorHandler$1();function globalErrorHandler$1(e){try{delegateHandler$1(e)}catch{}}function unrefTimer$1(e){}const NANOSECOND_DIGITS_IN_MILLIS$4=6,MILLISECONDS_TO_NANOSECONDS$4=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$4);function millisToHrTime$4(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$4)]}function hrTimeToMicroseconds$1(e){return 1e6*e[0]+e[1]/1e3}var ExportResultCode$1;function _export$1(e,t){return new Promise(r=>{context.with(suppressTracing$1(context.active()),()=>{e.export(t,e=>{r(e)})})})}!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode$1||(ExportResultCode$1={}));const internal$1={_export:_export$1};class LastValueAccumulation{startTime;_current;sampleTime;constructor(e,t=0,r=[0,0]){this.startTime=e,this._current=t,this.sampleTime=r}record(e){this._current=e,this.sampleTime=millisToHrTime$4(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class LastValueAggregator{kind=AggregatorKind.LAST_VALUE;createAccumulation(e){return new LastValueAccumulation(e)}merge(e,t){const r=hrTimeToMicroseconds$1(t.sampleTime)>=hrTimeToMicroseconds$1(e.sampleTime)?t:e;return new LastValueAccumulation(e.startTime,r.toPointValue(),r.sampleTime)}diff(e,t){const r=hrTimeToMicroseconds$1(t.sampleTime)>=hrTimeToMicroseconds$1(e.sampleTime)?t:e;return new LastValueAccumulation(t.startTime,r.toPointValue(),r.sampleTime)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType.GAUGE,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()}))}}}class SumAccumulation{startTime;monotonic;_current;reset;constructor(e,t,r=0,n=!1){this.startTime=e,this.monotonic=t,this._current=r,this.reset=n}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class SumAggregator{monotonic;kind=AggregatorKind.SUM;constructor(e){this.monotonic=e}createAccumulation(e){return new SumAccumulation(e,this.monotonic)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue();return t.reset?new SumAccumulation(t.startTime,this.monotonic,n,t.reset):new SumAccumulation(e.startTime,this.monotonic,r+n)}diff(e,t){const r=e.toPointValue(),n=t.toPointValue();return this.monotonic&&r>n?new SumAccumulation(t.startTime,this.monotonic,n,!0):new SumAccumulation(t.startTime,this.monotonic,n-r)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType.SUM,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()})),isMonotonic:this.monotonic}}}class DropAggregation{static DEFAULT_INSTANCE=new DropAggregator;createAggregator(e){return DropAggregation.DEFAULT_INSTANCE}}class SumAggregation{static MONOTONIC_INSTANCE=new SumAggregator(!0);static NON_MONOTONIC_INSTANCE=new SumAggregator(!1);createAggregator(e){switch(e.type){case InstrumentType.COUNTER:case InstrumentType.OBSERVABLE_COUNTER:case InstrumentType.HISTOGRAM:return SumAggregation.MONOTONIC_INSTANCE;default:return SumAggregation.NON_MONOTONIC_INSTANCE}}}class LastValueAggregation{static DEFAULT_INSTANCE=new LastValueAggregator;createAggregator(e){return LastValueAggregation.DEFAULT_INSTANCE}}class HistogramAggregation{static DEFAULT_INSTANCE=new HistogramAggregator([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(e){return HistogramAggregation.DEFAULT_INSTANCE}}class ExplicitBucketHistogramAggregation{_recordMinMax;_boundaries;constructor(e,t=!0){if(this._recordMinMax=t,null==e)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");e=(e=e.concat()).sort((e,t)=>e-t);const r=e.lastIndexOf(-1/0);let n=e.indexOf(1/0);-1===n&&(n=void 0),this._boundaries=e.slice(r+1,n)}createAggregator(e){return new HistogramAggregator(this._boundaries,this._recordMinMax)}}class ExponentialHistogramAggregation{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new ExponentialHistogramAggregator(this._maxSize,this._recordMinMax)}}class DefaultAggregation{_resolve(e){switch(e.type){case InstrumentType.COUNTER:case InstrumentType.UP_DOWN_COUNTER:case InstrumentType.OBSERVABLE_COUNTER:case InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:return SUM_AGGREGATION;case InstrumentType.GAUGE:case InstrumentType.OBSERVABLE_GAUGE:return LAST_VALUE_AGGREGATION;case InstrumentType.HISTOGRAM:return e.advice.explicitBucketBoundaries?new ExplicitBucketHistogramAggregation(e.advice.explicitBucketBoundaries):HISTOGRAM_AGGREGATION}return diag.warn(`Unable to recognize instrument type: ${e.type}`),DROP_AGGREGATION}createAggregator(e){return this._resolve(e).createAggregator(e)}}const DROP_AGGREGATION=new DropAggregation,SUM_AGGREGATION=new SumAggregation,LAST_VALUE_AGGREGATION=new LastValueAggregation,HISTOGRAM_AGGREGATION=new HistogramAggregation,DEFAULT_AGGREGATION=new DefaultAggregation;var AggregationType;function toAggregation(e){switch(e.type){case AggregationType.DEFAULT:return DEFAULT_AGGREGATION;case AggregationType.DROP:return DROP_AGGREGATION;case AggregationType.SUM:return SUM_AGGREGATION;case AggregationType.LAST_VALUE:return LAST_VALUE_AGGREGATION;case AggregationType.EXPONENTIAL_HISTOGRAM:{const t=e;return new ExponentialHistogramAggregation(t.options?.maxSize,t.options?.recordMinMax)}case AggregationType.EXPLICIT_BUCKET_HISTOGRAM:{const t=e;return null==t.options?HISTOGRAM_AGGREGATION:new ExplicitBucketHistogramAggregation(t.options?.boundaries,t.options?.recordMinMax)}default:throw new Error("Unsupported Aggregation")}}!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(AggregationType||(AggregationType={}));const DEFAULT_AGGREGATION_SELECTOR=e=>({type:AggregationType.DEFAULT}),DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR=e=>AggregationTemporality.CUMULATIVE;class MetricReader{_shutdown=!1;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(e){this._aggregationSelector=e?.aggregationSelector??DEFAULT_AGGREGATION_SELECTOR,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(void 0===this._sdkMetricProducer)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");const[t,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),n=t.errors.concat(FlatMap(r,e=>e.errors));return{resourceMetrics:{resource:t.resourceMetrics.resource,scopeMetrics:t.resourceMetrics.scopeMetrics.concat(FlatMap(r,e=>e.resourceMetrics.scopeMetrics))},errors:n}}async shutdown(e){this._shutdown?diag.error("Cannot call shutdown twice."):(null==e?.timeoutMillis?await this.onShutdown():await callWithTimeout(this.onShutdown(),e.timeoutMillis),this._shutdown=!0)}async forceFlush(e){this._shutdown?diag.warn("Cannot forceFlush on already shutdown MetricReader."):null!=e?.timeoutMillis?await callWithTimeout(this.onForceFlush(),e.timeoutMillis):await this.onForceFlush()}}class PeriodicExportingMetricReader extends MetricReader{_interval;_exporter;_exportInterval;_exportTimeout;constructor(e){if(super({aggregationSelector:e.exporter.selectAggregation?.bind(e.exporter),aggregationTemporalitySelector:e.exporter.selectAggregationTemporality?.bind(e.exporter),metricProducers:e.metricProducers}),void 0!==e.exportIntervalMillis&&e.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(void 0!==e.exportTimeoutMillis&&e.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(void 0!==e.exportTimeoutMillis&&void 0!==e.exportIntervalMillis&&e.exportIntervalMillis0&&diag.error("PeriodicExportingMetricReader: metrics collection errors",...t),e.resource.asyncAttributesPending)try{await(e.resource.waitForAsyncAttributes?.())}catch(e){diag.debug("Error while resolving async portion of resource: ",e),globalErrorHandler$1(e)}if(0===e.scopeMetrics.length)return;const r=await internal$1._export(this._exporter,e);if(r.code!==ExportResultCode$1.SUCCESS)throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${r.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),unrefTimer$1(this._interval)}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}class InMemoryMetricExporter{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,t){this._shutdown?setTimeout(()=>t({code:ExportResultCode$1.FAILED}),0):(this._metrics.push(e),setTimeout(()=>t({code:ExportResultCode$1.SUCCESS}),0))}getMetrics(){return this._metrics}forceFlush(){return Promise.resolve()}reset(){this._metrics=[]}selectAggregationTemporality(e){return this._aggregationTemporality}shutdown(){return this._shutdown=!0,Promise.resolve()}}class ConsoleMetricExporter{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR}export(e,t){if(!this._shutdown)return ConsoleMetricExporter._sendMetrics(e,t);setImmediate(t,{code:ExportResultCode$1.FAILED})}forceFlush(){return Promise.resolve()}selectAggregationTemporality(e){return this._temporalitySelector(e)}shutdown(){return this._shutdown=!0,Promise.resolve()}static _sendMetrics(e,t){for(const t of e.scopeMetrics)for(const e of t.metrics)console.dir({descriptor:e.descriptor,dataPointType:e.dataPointType,dataPoints:e.dataPoints},{depth:null});t({code:ExportResultCode$1.SUCCESS})}}class ViewRegistry{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(r=>this._matchInstrument(r.instrumentSelector,e)&&this._matchMeter(r.meterSelector,t))}_matchInstrument(e,t){return(void 0===e.getType()||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(void 0===t.version||e.getVersionFilter().match(t.version))&&(void 0===t.schemaUrl||e.getSchemaUrlFilter().match(t.schemaUrl))}}function createInstrumentDescriptor(e,t,r){return isValidName(e)||diag.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:t,description:r?.description??"",unit:r?.unit??"",valueType:r?.valueType??ValueType.DOUBLE,advice:r?.advice??{}}}function createInstrumentDescriptorWithView(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}function isDescriptorCompatibleWith(e,t){return equalsCaseInsensitive(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}const NAME_REGEXP=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function isValidName(e){return null!=e.match(NAME_REGEXP)}class SyncInstrument{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},r=context.active()){"number"==typeof e?(this._descriptor.valueType!==ValueType.INT||Number.isInteger(e)||(diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._writableMetricStorage.record(e,t,r,millisToHrTime$4(Date.now())):diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`)}}class UpDownCounterInstrument extends SyncInstrument{add(e,t,r){this._record(e,t,r)}}class CounterInstrument extends SyncInstrument{add(e,t,r){e<0?diag.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class GaugeInstrument extends SyncInstrument{record(e,t,r){this._record(e,t,r)}}class HistogramInstrument extends SyncInstrument{record(e,t,r){e<0?diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class ObservableInstrument{_observableRegistry;_metricStorages;_descriptor;constructor(e,t,r){this._observableRegistry=r,this._descriptor=e,this._metricStorages=t}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}}class ObservableCounterInstrument extends ObservableInstrument{}class ObservableGaugeInstrument extends ObservableInstrument{}class ObservableUpDownCounterInstrument extends ObservableInstrument{}function isObservableInstrument(e){return e instanceof ObservableInstrument}class Meter{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){const r=createInstrumentDescriptor(e,InstrumentType.GAUGE,t),n=this._meterSharedState.registerMetricStorage(r);return new GaugeInstrument(n,r)}createHistogram(e,t){const r=createInstrumentDescriptor(e,InstrumentType.HISTOGRAM,t),n=this._meterSharedState.registerMetricStorage(r);return new HistogramInstrument(n,r)}createCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType.COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new CounterInstrument(n,r)}createUpDownCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType.UP_DOWN_COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new UpDownCounterInstrument(n,r)}createObservableGauge(e,t){const r=createInstrumentDescriptor(e,InstrumentType.OBSERVABLE_GAUGE,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableGaugeInstrument(r,n,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType.OBSERVABLE_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableCounterInstrument(r,n,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType.OBSERVABLE_UP_DOWN_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableUpDownCounterInstrument(r,n,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}class MetricStorage{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=createInstrumentDescriptor(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class HashMap{_hash;_valueMap=new Map;_keyMap=new Map;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){const r=this._hash(e);if(this._valueMap.has(r))return this._valueMap.get(r);const n=t();return this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,n),n}set(e,t,r){r??=this._hash(e),this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){const e=this._keyMap.entries();let t=e.next();for(;!0!==t.done;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){const e=this._valueMap.entries();let t=e.next();for(;!0!==t.done;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}}class AttributeHashMap extends HashMap{constructor(){super(hashAttributes)}}class DeltaMetricProcessor{_aggregator;_activeCollectionStorage=new AttributeHashMap;_cumulativeMemoStorage=new AttributeHashMap;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=hashAttributes(this._overflowAttributes)}record(e,t,r,n){let i=this._activeCollectionStorage.get(t);if(!i){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const t=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(n));return void t?.record(e)}i=this._aggregator.createAccumulation(n),this._activeCollectionStorage.set(t,i)}i?.record(e)}batchCumulate(e,t){Array.from(e.entries()).forEach(([e,r,n])=>{const i=this._aggregator.createAccumulation(t);i?.record(r);let o=i;if(this._cumulativeMemoStorage.has(e,n)){const t=this._cumulativeMemoStorage.get(e,n);o=this._aggregator.diff(t,i)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,n=this._overflowHashCode,this._cumulativeMemoStorage.has(e,n))){const t=this._cumulativeMemoStorage.get(e,n);o=this._aggregator.diff(t,i)}if(this._activeCollectionStorage.has(e,n)){const t=this._activeCollectionStorage.get(e,n);o=this._aggregator.merge(t,o)}this._cumulativeMemoStorage.set(e,i,n),this._activeCollectionStorage.set(e,o,n)})}collect(){const e=this._activeCollectionStorage;return this._activeCollectionStorage=new AttributeHashMap,e}}class TemporalMetricProcessor{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(e,t,r,n){this._stashAccumulations(r);const i=this._getMergedUnreportedAccumulations(e);let o,s=i;if(this._reportHistory.has(e)){const t=this._reportHistory.get(e),r=t.collectionTime;o=t.aggregationTemporality,s=o===AggregationTemporality.CUMULATIVE?TemporalMetricProcessor.merge(t.accumulations,i,this._aggregator):TemporalMetricProcessor.calibrateStartTime(t.accumulations,i,r)}else o=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:s,collectionTime:n,aggregationTemporality:o});const a=AttributesMapToAccumulationRecords(s);if(0!==a.length)return this._aggregator.toMetricData(t,o,a,n)}_stashAccumulations(e){const t=this._unreportedAccumulations.keys();for(const r of t){let t=this._unreportedAccumulations.get(r);void 0===t&&(t=[],this._unreportedAccumulations.set(r,t)),t.push(e)}}_getMergedUnreportedAccumulations(e){let t=new AttributeHashMap;const r=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),void 0===r)return t;for(const e of r)t=TemporalMetricProcessor.merge(t,e,this._aggregator);return t}static merge(e,t,r){const n=e,i=t.entries();let o=i.next();for(;!0!==o.done;){const[t,s,a]=o.value;if(e.has(t,a)){const i=e.get(t,a),o=r.merge(i,s);n.set(t,o,a)}else n.set(t,s,a);o=i.next()}return n}static calibrateStartTime(e,t,r){for(const[n,i]of e.keys()){const e=t.get(n,i);e?.setStartTime(r)}return t}}function AttributesMapToAccumulationRecords(e){return Array.from(e.entries())}class AsyncMetricStorage extends MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,r,n,i){super(e),this._attributesProcessor=r,this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new TemporalMetricProcessor(t,n)}record(e,t){const r=new AttributeHashMap;Array.from(e.entries()).forEach(([e,t])=>{r.set(this._attributesProcessor.process(e),t)}),this._deltaMetricStorage.batchCumulate(r,t)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}function getIncompatibilityDetails(e,t){let r="";return e.unit!==t.unit&&(r+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(r+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(r+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(r+=`\t- Description '${e.description}' does not match '${t.description}'\n`),r}function getValueTypeConflictResolutionRecipe(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function getUnitConflictResolutionRecipe(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function getTypeConflictResolutionRecipe(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'`}function getDescriptionResolutionRecipe(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'\n \t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${n}\n \t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${n}`}function getConflictResolutionRecipe(e,t){return e.valueType!==t.valueType?getValueTypeConflictResolutionRecipe(e,t):e.unit!==t.unit?getUnitConflictResolutionRecipe(e,t):e.type!==t.type?getTypeConflictResolutionRecipe(e,t):e.description!==t.description?getDescriptionResolutionRecipe(e,t):""}class MetricStorageRegistry{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new MetricStorageRegistry}getStorages(e){let t=[];for(const e of this._sharedRegistry.values())t=t.concat(e);const r=this._perCollectorRegistry.get(e);if(null!=r)for(const e of r.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let r=this._perCollectorRegistry.get(e);null==r&&(r=new Map,this._perCollectorRegistry.set(e,r)),this._registerStorage(t,r)}findOrUpdateCompatibleStorage(e){const t=this._sharedRegistry.get(e.name);return void 0===t?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){const r=this._perCollectorRegistry.get(e);if(void 0===r)return null;const n=r.get(t.name);return void 0===n?null:this._findOrUpdateCompatibleStorage(t,n)}_registerStorage(e,t){const r=e.getInstrumentDescriptor(),n=t.get(r.name);void 0!==n?n.push(e):t.set(r.name,[e])}_findOrUpdateCompatibleStorage(e,t){let r=null;for(const n of t){const t=n.getInstrumentDescriptor();isDescriptorCompatibleWith(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&n.updateDescription(e.description),diag.warn("A view or instrument with the name ",e.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",getIncompatibilityDetails(t,e),"The longer description will be used.\nTo resolve the conflict:",getConflictResolutionRecipe(t,e))),r=n):diag.warn("A view or instrument with the name ",e.name," has already been registered and is incompatible with another registered view.\n","Details:\n",getIncompatibilityDetails(t,e),"To resolve the conflict:\n",getConflictResolutionRecipe(t,e))}return r}}class MultiMetricStorage{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,r,n){this._backingStorages.forEach(i=>{i.record(e,t,r,n)})}}class ObservableResultImpl{_instrumentName;_valueType;_buffer=new AttributeHashMap;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){"number"==typeof e?(this._valueType!==ValueType.INT||Number.isInteger(e)||(diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._buffer.set(t,e):diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`)}}class BatchObservableResultImpl{_buffer=new Map;observe(e,t,r={}){if(!isObservableInstrument(e))return;let n=this._buffer.get(e);null==n&&(n=new AttributeHashMap,this._buffer.set(e,n)),"number"==typeof t?(e._descriptor.valueType!==ValueType.INT||Number.isInteger(t)||(diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),Number.isInteger(t)))&&n.set(r,t):diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`)}}class ObservableRegistry{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){const r=this._findCallback(e,t);r<0||this._callbacks.splice(r,1)}addBatchCallback(e,t){const r=new Set(t.filter(isObservableInstrument));if(0===r.size)return void diag.error("BatchObservableCallback is not associated with valid instruments",t);this._findBatchCallback(e,r)>=0||this._batchCallbacks.push({callback:e,instruments:r})}removeBatchCallback(e,t){const r=new Set(t.filter(isObservableInstrument)),n=this._findBatchCallback(e,r);n<0||this._batchCallbacks.splice(n,1)}async observe(e,t){const r=this._observeCallbacks(e,t),n=this._observeBatchCallbacks(e,t),i=(await PromiseAllSettled([...r,...n])).filter(isPromiseAllSettledRejectionResult).map(e=>e.reason);return i}_observeCallbacks(e,t){return this._callbacks.map(async({callback:r,instrument:n})=>{const i=new ObservableResultImpl(n._descriptor.name,n._descriptor.valueType);let o=Promise.resolve(r(i));null!=t&&(o=callWithTimeout(o,t)),await o,n._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:r,instruments:n})=>{const i=new BatchObservableResultImpl;let o=Promise.resolve(r(i));null!=t&&(o=callWithTimeout(o,t)),await o,n.forEach(t=>{const r=i._buffer.get(t);null!=r&&t._metricStorages.forEach(t=>{t.record(r,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(r=>r.callback===e&&r.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(r=>r.callback===e&&setEquals(r.instruments,t))}}class SyncMetricStorage extends MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,r,n,i){super(e),this._attributesProcessor=r,this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new TemporalMetricProcessor(t,n)}record(e,t,r,n){t=this._attributesProcessor.process(t,r),this._deltaMetricStorage.record(e,t,r,n)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}class NoopAttributesProcessor{process(e,t){return e}}class MultiAttributesProcessor{_processors;constructor(e){this._processors=e}process(e,t){let r=e;for(const e of this._processors)r=e.process(r,t);return r}}class AllowListProcessor{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){const r={};return Object.keys(e).filter(e=>this._allowedAttributeNames.includes(e)).forEach(t=>r[t]=e[t]),r}}class DenyListProcessor{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){const r={};return Object.keys(e).filter(e=>!this._deniedAttributeNames.includes(e)).forEach(t=>r[t]=e[t]),r}}function createNoopAttributesProcessor(){return NOOP}function createMultiAttributesProcessor(e){return new MultiAttributesProcessor(e)}function createAllowListAttributesProcessor(e){return new AllowListProcessor(e)}function createDenyListAttributesProcessor(e){return new DenyListProcessor(e)}const NOOP=new NoopAttributesProcessor;class MeterSharedState{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new MetricStorageRegistry;observableRegistry=new ObservableRegistry;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new Meter(this)}registerMetricStorage(e){const t=this._registerMetricStorage(e,SyncMetricStorage);return 1===t.length?t[0]:new MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,AsyncMetricStorage)}async collect(e,t,r){const n=await this.observableRegistry.observe(t,r?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(0===i.length)return null;const o=i.map(r=>r.collect(e,t)).filter(isNotNullish);return 0===o.length?{errors:n}:{scopeMetrics:{scope:this._instrumentationScope,metrics:o},errors:n}}_registerMetricStorage(e,t){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{const n=createInstrumentDescriptorWithView(r,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(n);if(null!=i)return i;const o=r.aggregation.createAggregator(n),s=new t(n,o,r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(s),s});if(0===r.length){const n=this._meterProviderSharedState.selectAggregations(e.type).map(([r,n])=>{const i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(r,e);if(null!=i)return i;const o=n.createAggregator(e),s=r.selectCardinalityLimit(e.type),a=new t(e,o,createNoopAttributesProcessor(),[r],s);return this.metricStorageRegistry.registerForCollector(r,a),a});r=r.concat(n)}return r}}class MeterProviderSharedState{resource;viewRegistry=new ViewRegistry;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){const t=instrumentationScopeId(e);let r=this.meterSharedStates.get(t);return null==r&&(r=new MeterSharedState(this,e),this.meterSharedStates.set(t,r)),r}selectAggregations(e){const t=[];for(const r of this.metricCollectors)t.push([r,toAggregation(r.selectAggregation(e))]);return t}}class MetricCollector{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){const t=millisToHrTime$4(Date.now()),r=[],n=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{const o=await i.collect(this,t,e);null!=o?.scopeMetrics&&r.push(o.scopeMetrics),null!=o?.errors&&n.push(...o.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:n}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}const ESCAPE=/[\^$\\.+?()[\]{}|]/g;class PatternPredicate{_matchAll;_regexp;constructor(e){"*"===e?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(PatternPredicate.escapePattern(e)))}match(e){return!!this._matchAll||this._regexp.test(e)}static escapePattern(e){return`^${e.replace(ESCAPE,"\\$&").replace("*",".*")}$`}static hasWildcard(e){return e.includes("*")}}class ExactPredicate{_matchAll;_pattern;constructor(e){this._matchAll=void 0===e,this._pattern=e}match(e){return!!this._matchAll||e===this._pattern}}class InstrumentSelector{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new PatternPredicate(e?.name??"*"),this._type=e?.type,this._unitFilter=new ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class MeterSelector{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new ExactPredicate(e?.name),this._versionFilter=new ExactPredicate(e?.version),this._schemaUrlFilter=new ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function isSelectorNotProvided(e){return null==e.instrumentName&&null==e.instrumentType&&null==e.instrumentUnit&&null==e.meterName&&null==e.meterVersion&&null==e.meterSchemaUrl}function validateViewOptions(e){if(isSelectorNotProvided(e))throw new Error("Cannot create view with no selector arguments supplied");if(null!=e.name&&(null==e?.instrumentName||PatternPredicate.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}class View{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){validateViewOptions(e),null!=e.attributesProcessors?this.attributesProcessor=createMultiAttributesProcessor(e.attributesProcessors):this.attributesProcessor=createNoopAttributesProcessor(),this.name=e.name,this.description=e.description,this.aggregation=toAggregation(e.aggregation??{type:AggregationType.DEFAULT}),this.instrumentSelector=new InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}class MeterProvider{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new MeterProviderSharedState(e?.resource??defaultResource$1()),null!=e?.views&&e.views.length>0)for(const t of e.views)this._sharedState.viewRegistry.addView(new View(t));if(null!=e?.readers&&e.readers.length>0)for(const t of e.readers){const e=new MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,t="",r={}){return this._shutdown?(diag.warn("A shutdown MeterProvider cannot provide a Meter"),createNoopMeter()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:r.schemaUrl}).meter}async shutdown(e){this._shutdown?diag.warn("shutdown may only be called once per MeterProvider"):(this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e))))}async forceFlush(e){this._shutdown?diag.warn("invalid attempt to force flush after MeterProvider shutdown"):await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}var esm$9=Object.freeze({__proto__:null,get AggregationTemporality(){return AggregationTemporality},get AggregationType(){return AggregationType},ConsoleMetricExporter:ConsoleMetricExporter,get DataPointType(){return DataPointType},InMemoryMetricExporter:InMemoryMetricExporter,get InstrumentType(){return InstrumentType},MeterProvider:MeterProvider,MetricReader:MetricReader,PeriodicExportingMetricReader:PeriodicExportingMetricReader,TimeoutError:TimeoutError,createAllowListAttributesProcessor:createAllowListAttributesProcessor,createDenyListAttributesProcessor:createDenyListAttributesProcessor}),require$$4=getAugmentedNamespace(esm$9),meterFactory={};Object.defineProperty(meterFactory,"__esModule",{value:!0}),meterFactory.MetricsMeterFactoryValidator=void 0;class MetricsMeterFactoryValidator{}meterFactory.MetricsMeterFactoryValidator=MetricsMeterFactoryValidator,Object.defineProperty(providerFactory,"__esModule",{value:!0}),providerFactory.MetricsMeterProviderFactory=void 0;const resources_1$1=require$$2,exporter_metrics_otlp_http_1=require$$5,sdk_metrics_1=require$$4,meterFactory_1=meterFactory,container_1$4=container$1;class MetricsMeterProviderFactory{create(e,t){let r;new meterFactory_1.MetricsMeterFactoryValidator,r=e.metricExporter?e.metricExporter:new exporter_metrics_otlp_http_1.OTLPMetricExporter(Object.assign(Object.assign({},e),{headers:Object.assign(Object.assign({},container_1$4.Container.errorless(t.headers)),container_1$4.Container.errorless(e.headers))}));const n=new sdk_metrics_1.PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:e.publishInterval});return{meterProvider:this.createMeterProvider(e,t,n),metricReader:n}}createMeterProvider(e,t,r){var n;return new sdk_metrics_1.MeterProvider({resource:(0,resources_1$1.resourceFromAttributes)(null!==(n=container_1$4.Container.errorless(e.additionalResourceAttributes))&&void 0!==n?n:{}),readers:[r]})}}providerFactory.MetricsMeterProviderFactory=MetricsMeterProviderFactory;var lazyProvider={};Object.defineProperty(lazyProvider,"__esModule",{value:!0}),lazyProvider.LazyMetricsMeterProvider=void 0;class LazyMetricsMeterProvider{get metricReader(){return this._metricReader||this.buildMeterProvider(),this._metricReader}constructor(e,t){this.meterProviderCreateFunc=e,this.serviceName=t}getMeter(){return this.getMeterProvider().getMeter(this.serviceName)}forceFlush(){return this.getMeterProvider().forceFlush()}getMeterProvider(){return this.meterProvider||this.buildMeterProvider(),this.meterProvider}buildMeterProvider(){const e=this.meterProviderCreateFunc();this.meterProvider=e.meterProvider,this._metricReader=e.metricReader}}lazyProvider.LazyMetricsMeterProvider=LazyMetricsMeterProvider;var nullMetricsManager={},nullManager$1={};Object.defineProperty(nullManager$1,"__esModule",{value:!0}),nullManager$1.NullManager=void 0;class NullManager{constructor(){this.started=!1}waitForFinalExport(e){return Promise.resolve()}get settings(){return{}}start(){return this.started=!0,Promise.resolve()}stop(){return this.started=!1,Promise.resolve()}}nullManager$1.NullManager=NullManager,Object.defineProperty(nullMetricsManager,"__esModule",{value:!0}),nullMetricsManager.NullMetricsManager=void 0;const nullManager_1$3=nullManager$1,null_1$1=_null$4,safe_stringify_1$4=safeStringify$1;class NullMetricsManager extends nullManager_1$3.NullManager{constructor(e,t,r){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==r||r.info(`Starting NullMetrcsManager with settings ${(0,safe_stringify_1$4.safeStringify)(e)}`)),super()}waitForFinalExport(e){return Promise.resolve()}getFromSettings(e){return new null_1$1.NullMetric(e)}get(e){return new null_1$1.NullMetric({name:e,type:e,enabled:!1,description:e})}}nullMetricsManager.NullMetricsManager=NullMetricsManager,Object.defineProperty(builder$6,"__esModule",{value:!0}),builder$6.MetricsManagerBuilder=void 0;const builder_1$1=builder$5,manager_1$3=manager$4,builder_2$1=builder$4,builder_3$1=builder$3,providerFactory_1=providerFactory,lazyProvider_1=lazyProvider,nullMetricsManager_1$1=nullMetricsManager;class MetricsManagerBuilder{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}withMeterProvider(e){return this.meterProviderCreateFunc=e,this}withDependencyContainer(e){return this.dependencyContainer=e,this}build(){return(new builder_3$1.MetricsBuilderValidator).validate(this),this.buildCore()}buildCore(){var e,t,r,n;const i=this.createMetricsSettings();if(!0!==(null===(e=this.settings)||void 0===e?void 0:e.enabled)||!0!==(null==i?void 0:i.enabled))return new nullMetricsManager_1$1.NullMetricsManager(i,this.settings,this.logger);this.dependencyContainer=null!==(r=null===(t=this.settings.metrics)||void 0===t?void 0:t.dependencyContainerOverride)&&void 0!==r?r:this.dependencyContainer;const o=null!==(n=this.meterProviderCreateFunc)&&void 0!==n?n:this.createMeterProviderCreateFunc(i,this.settings),s=new lazyProvider_1.LazyMetricsMeterProvider(o,this.settings.serviceName||"io.Insights"),a=this.createMetricsFactory(s);return new manager_1$3.MetricsManager(this.settings,i,a,s,this.logger)}createMetricsSettings(){return(new builder_2$1.MetricsSettingsBuilder).withSettings(this.settings).build()}createMetricsFactory(e){return new builder_1$1.MetricsFactoryBuilder(e,this.dependencyContainer,this.logger).withDefaults().build()}createMeterProviderCreateFunc(e,t){return()=>(new providerFactory_1.MetricsMeterProviderFactory).create(e,t)}}builder$6.MetricsManagerBuilder=MetricsManagerBuilder;var builder$2={},manager$2={},utils$7={};class OTLPTraceExporter extends OTLPExporterBase{constructor(e={}){super(createLegacyOtlpBrowserExportDelegate(e,JsonTraceSerializer,"v1/traces",{"Content-Type":"application/json"}))}}var esm$8=Object.freeze({__proto__:null,OTLPTraceExporter:OTLPTraceExporter}),require$$15=getAugmentedNamespace(esm$8);const SUPPRESS_TRACING_KEY=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing(e){return e.setValue(SUPPRESS_TRACING_KEY,!0)}function isTracingSuppressed(e){return!0===e.getValue(SUPPRESS_TRACING_KEY)}function sanitizeAttributes(e){const t={};if("object"!=typeof e||null==e)return t;for(const[r,n]of Object.entries(e))isAttributeKey(r)?isAttributeValue(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:diag.warn(`Invalid attribute value set for key: ${r}`):diag.warn(`Invalid attribute key: ${r}`);return t}function isAttributeKey(e){return"string"==typeof e&&e.length>0}function isAttributeValue(e){return null==e||(Array.isArray(e)?isHomogeneousAttributeValueArray(e):isValidPrimitiveAttributeValue(e))}function isHomogeneousAttributeValueArray(e){let t;for(const r of e)if(null!=r){if(!t){if(isValidPrimitiveAttributeValue(r)){t=typeof r;continue}return!1}if(typeof r!==t)return!1}return!0}function isValidPrimitiveAttributeValue(e){switch(typeof e){case"number":case"boolean":case"string":return!0}return!1}function loggingErrorHandler(){return e=>{diag.error(stringifyException(e))}}function stringifyException(e){return"string"==typeof e?e:JSON.stringify(flattenException(e))}function flattenException(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler=loggingErrorHandler();function globalErrorHandler(e){try{delegateHandler(e)}catch{}}function getNumberFromEnv(e){}const otperformance$3=performance;function unrefTimer(e){}const NANOSECOND_DIGITS$3=9,NANOSECOND_DIGITS_IN_MILLIS$3=6,MILLISECONDS_TO_NANOSECONDS$3=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$3),SECOND_TO_NANOSECONDS$3=Math.pow(10,NANOSECOND_DIGITS$3);function millisToHrTime$3(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$3)]}function getTimeOrigin$3(){let e=otperformance$3.timeOrigin;if("number"!=typeof e){const t=otperformance$3;e=t.timing&&t.timing.fetchStart}return e}function hrTime$3(e){return addHrTimes$3(millisToHrTime$3(getTimeOrigin$3()),millisToHrTime$3("number"==typeof e?e:otperformance$3.now()))}function hrTimeDuration(e,t){let r=t[0]-e[0],n=t[1]-e[1];return n<0&&(r-=1,n+=SECOND_TO_NANOSECONDS$3),[r,n]}function hrTimeToMicroseconds(e){return 1e6*e[0]+e[1]/1e3}function isTimeInputHrTime$1(e){return Array.isArray(e)&&2===e.length&&"number"==typeof e[0]&&"number"==typeof e[1]}function isTimeInput(e){return isTimeInputHrTime$1(e)||"number"==typeof e||e instanceof Date}function addHrTimes$3(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS$3&&(r[1]-=SECOND_TO_NANOSECONDS$3,r[0]+=1),r}var ExportResultCode;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode||(ExportResultCode={}));const objectTag="[object Object]",nullTag="[object Null]",undefinedTag="[object Undefined]",funcProto=Function.prototype,funcToString=funcProto.toString,objectCtorString$1=funcToString.call(Object),getPrototypeOf$2=Object.getPrototypeOf,objectProto=Object.prototype,hasOwnProperty$2=objectProto.hasOwnProperty,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeObjectToString=objectProto.toString;function isPlainObject$3(e){if(!isObjectLike(e)||baseGetTag(e)!==objectTag)return!1;const t=getPrototypeOf$2(e);if(null===t)return!0;const r=hasOwnProperty$2.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString.call(r)===objectCtorString$1}function isObjectLike(e){return null!=e&&"object"==typeof e}function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString$1(e)}function getRawTag(e){const t=hasOwnProperty$2.call(e,symToStringTag),r=e[symToStringTag];let n=!1;try{e[symToStringTag]=void 0,n=!0}catch(e){}const i=nativeObjectToString.call(e);return n&&(t?e[symToStringTag]=r:delete e[symToStringTag]),i}function objectToString$1(e){return nativeObjectToString.call(e)}const MAX_LEVEL=20;function merge$2(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=mergeTwoObjects(t,e.shift(),0,r);return t}function takeValue(e){return isArray$6(e)?e.slice():e}function mergeTwoObjects(e,t,r=0,n){let i;if(!(r>MAX_LEVEL)){if(r++,isPrimitive(e)||isPrimitive(t)||isFunction$4(t))i=takeValue(t);else if(isArray$6(e)){if(i=e.slice(),isArray$6(t))for(let e=0,r=t.length;e{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}class BindOnceFuture{_callback;_that;_isCalled=!1;_deferred=new Deferred;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}function _export(e,t){return new Promise(r=>{context.with(suppressTracing(context.active()),()=>{e.export(t,e=>{r(e)})})})}const internal={_export:_export},ExceptionEventName="exception";class SpanImpl{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){const t=Date.now();this._spanContext=e.spanContext,this._performanceStartTime=otperformance$3.now(),this._performanceOffset=t-(this._performanceStartTime+getTimeOrigin$3()),this._startTimeProvided=null!=e.startTime,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,this.links=e.links||[],this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,null!=e.attributes&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,t){if(null==t||this._isSpanEnded())return this;if(0===e.length)return diag.warn(`Invalid attribute key: ${e}`),this;if(!isAttributeValue(t))return diag.warn(`Invalid attribute value set for key: ${e}`),this;const{attributeCountLimit:r}=this._spanLimits;return void 0!==r&&Object.keys(this.attributes).length>=r&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(t),this)}setAttributes(e){for(const[t,r]of Object.entries(e))this.setAttribute(t,r);return this}addEvent(e,t,r){if(this._isSpanEnded())return this;const{eventCountLimit:n}=this._spanLimits;if(0===n)return diag.warn("No events allowed."),this._droppedEventsCount++,this;void 0!==n&&this.events.length>=n&&(0===this._droppedEventsCount&&diag.debug("Dropping extra events."),this.events.shift(),this._droppedEventsCount++),isTimeInput(t)&&(isTimeInput(r)||(r=t),t=void 0);const i=sanitizeAttributes(t);return this.events.push({name:e,attributes:i,time:this._getTime(r),droppedAttributesCount:0}),this}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}setStatus(e){return this._isSpanEnded()||(this.status={...e},null!=this.status.message&&"string"!=typeof e.message&&(diag.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`),delete this.status.message)),this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){this._isSpanEnded()?diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`):(this._ended=!0,this.endTime=this._getTime(e),this._duration=hrTimeDuration(this.startTime,this.endTime),this._duration[0]<0&&(diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._spanProcessor.onEnd(this))}_getTime(e){if("number"==typeof e&&e<=otperformance$3.now())return hrTime$3(e+this._performanceOffset);if("number"==typeof e)return millisToHrTime$3(e);if(e instanceof Date)return millisToHrTime$3(e.getTime());if(isTimeInputHrTime$1(e))return e;if(this._startTimeProvided)return millisToHrTime$3(Date.now());const t=otperformance$3.now()-this._performanceStartTime;return addHrTimes$3(this.startTime,millisToHrTime$3(t))}isRecording(){return!1===this._ended}recordException(e,t){const r={};"string"==typeof e?r[ATTR_EXCEPTION_MESSAGE]=e:e&&(e.code?r[ATTR_EXCEPTION_TYPE]=e.code.toString():e.name&&(r[ATTR_EXCEPTION_TYPE]=e.name),e.message&&(r[ATTR_EXCEPTION_MESSAGE]=e.message),e.stack&&(r[ATTR_EXCEPTION_STACKTRACE]=e.stack)),r[ATTR_EXCEPTION_TYPE]||r[ATTR_EXCEPTION_MESSAGE]?this.addEvent(ExceptionEventName,r,t):diag.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){const e=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){const t=this._attributeValueLengthLimit;return t<=0?(diag.warn(`Attribute value limit must be positive, got ${t}`),e):"string"==typeof e?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>"string"==typeof e?this._truncateToLimitUtil(e,t):e):e}}var SamplingDecision;!function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(SamplingDecision||(SamplingDecision={}));class AlwaysOffSampler{shouldSample(){return{decision:SamplingDecision.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class AlwaysOnSampler{shouldSample(){return{decision:SamplingDecision.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class ParentBasedSampler{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||(globalErrorHandler(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new AlwaysOnSampler),this._remoteParentSampled=e.remoteParentSampled??new AlwaysOnSampler,this._remoteParentNotSampled=e.remoteParentNotSampled??new AlwaysOffSampler,this._localParentSampled=e.localParentSampled??new AlwaysOnSampler,this._localParentNotSampled=e.localParentNotSampled??new AlwaysOffSampler}shouldSample(e,t,r,n,i,o){const s=trace.getSpanContext(e);return s&&isSpanContextValid(s)?s.isRemote?s.traceFlags&TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,t,r,n,i,o):this._remoteParentNotSampled.shouldSample(e,t,r,n,i,o):s.traceFlags&TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,t,r,n,i,o):this._localParentNotSampled.shouldSample(e,t,r,n,i,o):this._root.shouldSample(e,t,r,n,i,o)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}class TraceIdRatioBasedSampler{_ratio;_upperBound;constructor(e=0){this._ratio=e,this._ratio=this._normalize(e),this._upperBound=Math.floor(4294967295*this._ratio)}shouldSample(e,t){return{decision:isValidTraceId(t)&&this._accumulate(t)=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let r=0;r>>0}return t}}const DEFAULT_RATIO=1;function loadDefaultConfig$1(){return{sampler:buildSamplerFromEnv(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function buildSamplerFromEnv(){const e="parentbased_always_on";switch(e){case"always_on":return new AlwaysOnSampler;case"always_off":return new AlwaysOffSampler;case"parentbased_always_on":return new ParentBasedSampler({root:new AlwaysOnSampler});case"parentbased_always_off":return new ParentBasedSampler({root:new AlwaysOffSampler});case"traceidratio":return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());case"parentbased_traceidratio":return new ParentBasedSampler({root:new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv())});default:return diag.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "parentbased_always_on".`),new ParentBasedSampler({root:new AlwaysOnSampler})}}function getSamplerProbabilityFromEnv(){return diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`),DEFAULT_RATIO}const DEFAULT_ATTRIBUTE_COUNT_LIMIT=128,DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=1/0;function mergeConfig$2(e){const t={sampler:buildSamplerFromEnv()},r=loadDefaultConfig$1(),n=Object.assign({},r,t,e);return n.generalLimits=Object.assign({},r.generalLimits,e.generalLimits||{}),n.spanLimits=Object.assign({},r.spanLimits,e.spanLimits||{}),n}function reconfigureLimits$1(e){const t=Object.assign({},e.spanLimits);return t.attributeCountLimit=e.spanLimits?.attributeCountLimit??e.generalLimits?.attributeCountLimit??getNumberFromEnv()??getNumberFromEnv()??DEFAULT_ATTRIBUTE_COUNT_LIMIT,t.attributeValueLengthLimit=e.spanLimits?.attributeValueLengthLimit??e.generalLimits?.attributeValueLengthLimit??getNumberFromEnv()??getNumberFromEnv()??DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,Object.assign({},e,{spanLimits:t})}class BatchSpanProcessorBase{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,t){this._exporter=e,this._maxExportBatchSize="number"==typeof t?.maxExportBatchSize?t.maxExportBatchSize:512,this._maxQueueSize="number"==typeof t?.maxQueueSize?t.maxQueueSize:2048,this._scheduledDelayMillis="number"==typeof t?.scheduledDelayMillis?t.scheduledDelayMillis:5e3,this._exportTimeoutMillis="number"==typeof t?.exportTimeoutMillis?t.exportTimeoutMillis:3e4,this._shutdownOnce=new BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||0!==(e.spanContext().traceFlags&TraceFlags.SAMPLED)&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize)return 0===this._droppedSpansCount&&diag.debug("maxQueueSize reached, dropping spans"),void this._droppedSpansCount++;this._droppedSpansCount>0&&(diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{const r=[];for(let e=0,t=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);e{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),0===this._finishedSpans.length?Promise.resolve():new Promise((e,t)=>{const r=setTimeout(()=>{t(new Error("Timeout"))},this._exportTimeoutMillis);context.with(suppressTracing(context.active()),()=>{let n;this._finishedSpans.length<=this._maxExportBatchSize?(n=this._finishedSpans,this._finishedSpans=[]):n=this._finishedSpans.splice(0,this._maxExportBatchSize);const i=()=>this._exporter.export(n,n=>{clearTimeout(r),n.code===ExportResultCode.SUCCESS?e():t(n.error??new Error("BatchSpanProcessor: span export failed"))});let o=null;for(let e=0,t=n.length;e{globalErrorHandler(e),t(e)})})})}_maybeStartTimer(){if(this._isExporting)return;const e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,globalErrorHandler(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();void 0===this._timer&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),unrefTimer(this._timer))}_clearTimer(){void 0!==this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}class BatchSpanProcessor extends BatchSpanProcessorBase{_visibilityChangeListener;_pageHideListener;constructor(e,t){super(e,t),this.onInit(t)}onInit(e){!0!==e?.disableAutoFlushOnDocumentHide&&"undefined"!=typeof document&&(this._visibilityChangeListener=()=>{"hidden"===document.visibilityState&&this.forceFlush().catch(e=>{globalErrorHandler(e)})},this._pageHideListener=()=>{this.forceFlush().catch(e=>{globalErrorHandler(e)})},document.addEventListener("visibilitychange",this._visibilityChangeListener),document.addEventListener("pagehide",this._pageHideListener))}onShutdown(){"undefined"!=typeof document&&(this._visibilityChangeListener&&document.removeEventListener("visibilitychange",this._visibilityChangeListener),this._pageHideListener&&document.removeEventListener("pagehide",this._pageHideListener))}}const SPAN_ID_BYTES=8,TRACE_ID_BYTES=16;class RandomIdGenerator{generateTraceId=getIdGenerator(TRACE_ID_BYTES);generateSpanId=getIdGenerator(SPAN_ID_BYTES)}const SHARED_CHAR_CODES_ARRAY=Array(32);function getIdGenerator(e){return function(){for(let t=0;t<2*e;t++)SHARED_CHAR_CODES_ARRAY[t]=Math.floor(16*Math.random())+48,SHARED_CHAR_CODES_ARRAY[t]>=58&&(SHARED_CHAR_CODES_ARRAY[t]+=39);return String.fromCharCode.apply(null,SHARED_CHAR_CODES_ARRAY.slice(0,2*e))}}class Tracer{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(e,t,r,n){const i=mergeConfig$2(t);this._sampler=i.sampler,this._generalLimits=i.generalLimits,this._spanLimits=i.spanLimits,this._idGenerator=t.idGenerator||new RandomIdGenerator,this._resource=r,this._spanProcessor=n,this.instrumentationScope=e}startSpan(e,t={},r=context.active()){t.root&&(r=trace.deleteSpan(r));const n=trace.getSpan(r);if(isTracingSuppressed(r)){diag.debug("Instrumentation suppressed, returning Noop Span");return trace.wrapSpanContext(INVALID_SPAN_CONTEXT)}const i=n?.spanContext(),o=this._idGenerator.generateSpanId();let s,a,c;i&&trace.isSpanContextValid(i)?(a=i.traceId,c=i.traceState,s=i):a=this._idGenerator.generateTraceId();const l=t.kind??SpanKind.INTERNAL,u=(t.links??[]).map(e=>({context:e.context,attributes:sanitizeAttributes(e.attributes)})),d=sanitizeAttributes(t.attributes),h=this._sampler.shouldSample(r,a,e,l,d,u);c=h.traceState??c;const p={traceId:a,spanId:o,traceFlags:h.decision===SamplingDecision$1.RECORD_AND_SAMPLED?TraceFlags.SAMPLED:TraceFlags.NONE,traceState:c};if(h.decision===SamplingDecision$1.NOT_RECORD){diag.debug("Recording is off, propagating context in a non-recording span");return trace.wrapSpanContext(p)}const g=sanitizeAttributes(Object.assign(d,h.attributes));return new SpanImpl({resource:this._resource,scope:this.instrumentationScope,context:r,spanContext:p,name:e,kind:l,links:u,parentSpanContext:s,attributes:g,startTime:t.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits})}startActiveSpan(e,t,r,n){let i,o,s;if(arguments.length<2)return;2===arguments.length?s=t:3===arguments.length?(i=t,s=r):(i=t,o=r,s=n);const a=o??context.active(),c=this.startSpan(e,i,a),l=trace.setSpan(a,c);return context.with(l,s,void 0,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class MultiSpanProcessor{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){const e=[];for(const t of this._spanProcessors)e.push(t.forceFlush());return new Promise(t=>{Promise.all(e).then(()=>{t()}).catch(e=>{globalErrorHandler(e||new Error("MultiSpanProcessor: forceFlush failed")),t()})})}onStart(e,t){for(const r of this._spanProcessors)r.onStart(e,t)}onEnd(e){for(const t of this._spanProcessors)t.onEnd(e)}shutdown(){const e=[];for(const t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,r)=>{Promise.all(e).then(()=>{t()},r)})}}var ForceFlushState;!function(e){e[e.resolved=0]="resolved",e[e.timeout=1]="timeout",e[e.error=2]="error",e[e.unresolved=3]="unresolved"}(ForceFlushState||(ForceFlushState={}));class BasicTracerProvider{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){const t=merge$2({},loadDefaultConfig$1(),reconfigureLimits$1(e));this._resource=t.resource??defaultResource$1(),this._config=Object.assign({},t,{resource:this._resource});const r=[];e.spanProcessors?.length&&r.push(...e.spanProcessors),this._activeSpanProcessor=new MultiSpanProcessor(r)}getTracer(e,t,r){const n=`${e}@${t||""}:${r?.schemaUrl||""}`;return this._tracers.has(n)||this._tracers.set(n,new Tracer({name:e,version:t,schemaUrl:r?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(n)}forceFlush(){const e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(r=>{let n;const i=setTimeout(()=>{r(new Error(`Span processor did not completed within timeout period of ${e} ms`)),n=ForceFlushState.timeout},e);t.forceFlush().then(()=>{clearTimeout(i),n!==ForceFlushState.timeout&&(n=ForceFlushState.resolved,r(n))}).catch(e=>{clearTimeout(i),n=ForceFlushState.error,r(e)})}));return new Promise((e,r)=>{Promise.all(t).then(t=>{const n=t.filter(e=>e!==ForceFlushState.resolved);n.length>0?r(n):e()}).catch(e=>r([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}class ConsoleSpanExporter{export(e,t){return this._sendSpans(e,t)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,traceId:e.spanContext().traceId,parentSpanContext:e.parentSpanContext,traceState:e.spanContext().traceState?.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:hrTimeToMicroseconds(e.startTime),duration:hrTimeToMicroseconds(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,t){for(const t of e)console.dir(this._exportInfo(t),{depth:3});if(t)return t({code:ExportResultCode.SUCCESS})}}class InMemorySpanExporter{_finishedSpans=[];_stopped=!1;export(e,t){if(this._stopped)return t({code:ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedSpans.push(...e),setTimeout(()=>t({code:ExportResultCode.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}class SimpleSpanProcessor{_exporter;_shutdownOnce;_pendingExports;constructor(e){this._exporter=e,this._shutdownOnce=new BindOnceFuture(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,t){}onEnd(e){if(this._shutdownOnce.isCalled)return;if(0===(e.spanContext().traceFlags&TraceFlags.SAMPLED))return;const t=this._doExport(e).catch(e=>globalErrorHandler(e));this._pendingExports.add(t),t.finally(()=>this._pendingExports.delete(t))}async _doExport(e){e.resource.asyncAttributesPending&&await(e.resource.waitForAsyncAttributes?.());const t=await internal._export(this._exporter,[e]);if(t.code!==ExportResultCode.SUCCESS)throw t.error??new Error(`SimpleSpanProcessor: span export failed (status ${t})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}class NoopSpanProcessor{onStart(e,t){}onEnd(e){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}var esm$7=Object.freeze({__proto__:null,AlwaysOffSampler:AlwaysOffSampler,AlwaysOnSampler:AlwaysOnSampler,BasicTracerProvider:BasicTracerProvider,BatchSpanProcessor:BatchSpanProcessor,ConsoleSpanExporter:ConsoleSpanExporter,InMemorySpanExporter:InMemorySpanExporter,NoopSpanProcessor:NoopSpanProcessor,ParentBasedSampler:ParentBasedSampler,RandomIdGenerator:RandomIdGenerator,get SamplingDecision(){return SamplingDecision},SimpleSpanProcessor:SimpleSpanProcessor,TraceIdRatioBasedSampler:TraceIdRatioBasedSampler}),require$$14$1=getAugmentedNamespace(esm$7),filter={};Object.defineProperty(filter,"__esModule",{value:!0}),filter.TracesFilterValidator=void 0;class TracesFilterValidator{validate(e){if(!(e.source||e.context&&Object.keys(e.context).length))throw new Error("At least one of source / context need to be specified.")}}filter.TracesFilterValidator=TracesFilterValidator;var attributeData={};Object.defineProperty(attributeData,"__esModule",{value:!0}),attributeData.TracesAttributeDataValidator=void 0;const validator_1$2=validator$1;class TracesAttributeDataValidator{validate(e){if(validator_1$2.Validator.throwIfNullOrUndefined(e,"data"),"object"!=typeof e)throw new Error("'data' must be an object")}}attributeData.TracesAttributeDataValidator=TracesAttributeDataValidator;var ioInsightsSampler={},hasRequiredIoInsightsSampler;function requireIoInsightsSampler(){if(hasRequiredIoInsightsSampler)return ioInsightsSampler;hasRequiredIoInsightsSampler=1,Object.defineProperty(ioInsightsSampler,"__esModule",{value:!0}),ioInsightsSampler.ioInsightsSampler=void 0;const e=require$$14$1,t=requireUtils();return ioInsightsSampler.ioInsightsSampler=class{constructor(e,t,r,n){this.settings=e,this.defaults=t,this.filteringContextGetter=r,this.logger=n}shouldSample(t,r,n,i,o,s){var a,c,l,u,d,h,p,g,m,f,y,$,b;const v=(null===(a=this.filteringContextGetter)||void 0===a?void 0:a.call(null))||{};for(const e of this.settings||[]){let t=!0;if(t&&e.name&&(this.matchObjects("name",{name:e.name},{name:n})||(t=!1)),t&&e.attributes&&(this.matchObjects("attributes",e.attributes,o)||(t=!1)),t&&e.context&&(this.matchObjects("context",e.context,v,!0)||(t=!1)),t)return(null===(d=this.logger)||void 0===d?void 0:d.level)&&(null===(h=this.logger)||void 0===h?void 0:h.level)>=80&&(null===(p=this.logger)||void 0===p||p.verbose("sampling rule matched: "+JSON.stringify(e))),this.maybeSample(r,e.sample);(null===(c=this.logger)||void 0===c?void 0:c.level)&&(null===(l=this.logger)||void 0===l?void 0:l.level)>=80&&(null===(u=this.logger)||void 0===u||u.verbose("sampling rule didn't match: "+JSON.stringify(e)))}return(null===(g=this.logger)||void 0===g?void 0:g.level)&&(null===(m=this.logger)||void 0===m?void 0:m.level)>=80&&(null===(f=this.logger)||void 0===f||f.verbose("no sampling rule matched, will fall back to defaults "+JSON.stringify(this.defaults||{}))),this.defaults?this.maybeSample(r,this.defaults.sample||!0):((null===(y=this.logger)||void 0===y?void 0:y.level)&&(null===($=this.logger)||void 0===$?void 0:$.level)>=80&&(null===(b=this.logger)||void 0===b||b.verbose("no sampling rule matched, no defaults - will sample")),{decision:e.SamplingDecision.RECORD_AND_SAMPLED})}toString(){try{return"ioInsightsSampler: "+JSON.stringify({settings:this.settings,defaults:this.defaults})}catch(e){return"ioInsightsSampler: (error) "+e.message}}matchObjects(e,r,n,i){var o,s,a,c,l,u;for(const[d,h]of Object.entries(r)){const r=i?(0,t.deep_value)(n,d):n[d];if("string"==typeof h&&"#"===h[0]&&(null==r||!new RegExp(h.substring(1),"i").test(r+"")))return(null===(o=this.logger)||void 0===o?void 0:o.level)&&(null===(s=this.logger)||void 0===s?void 0:s.level)>=80&&(null===(a=this.logger)||void 0===a||a.verbose(`matching ${e}: regex ${h} doesn't match ${r}`)),!1;if(h!==r)return(null===(c=this.logger)||void 0===c?void 0:c.level)&&(null===(l=this.logger)||void 0===l?void 0:l.level)>=80&&(null===(u=this.logger)||void 0===u||u.verbose(`matching ${e}: ${h} doesn't match ${r}`)),!1}return!0}maybeSample(t,r){var n,i,o;let s;if(!0===r||"number"==typeof r&&r>=1)s={decision:e.SamplingDecision.RECORD_AND_SAMPLED};else if(!1===r||"number"==typeof r&&r<=0)s={decision:e.SamplingDecision.NOT_RECORD};else{const n=((e,t=0)=>{let r=3735928559^t,n=1103547991^t;for(let t,i=0;i>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)})(t);s={decision:n/1e3-Math.floor(n/1e3)<=r?e.SamplingDecision.RECORD_AND_SAMPLED:e.SamplingDecision.NOT_RECORD}}return(null===(n=this.logger)||void 0===n?void 0:n.level)&&(null===(i=this.logger)||void 0===i?void 0:i.level)>=80&&(null===(o=this.logger)||void 0===o||o.verbose(`sampling decision with value ${r}: ${JSON.stringify(s)}`)),s}},ioInsightsSampler}var otelUtils={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getOTELData=e.flattenOtelAtributes=void 0;e.flattenOtelAtributes=(t,r)=>{if(null==t)return{};"object"!=typeof t&&(t={unknownAttribute:t});const n={};for(const[i,o]of Object.entries(t)){const t=(0,e.getOTELData)(i,o,0,r);for(const[e,r]of t)n[e]=r}return n};e.getOTELData=(e,n,i,o)=>{if((i+=1)>o)return[[e,""]];const s=Boolean(n&&"object"==typeof n);return"number"==typeof n||"string"==typeof n||"boolean"==typeof n?[[e,n]]:r(n)?[[e,n]].concat(t(e,n,i,o)):s?t(e,n,i,o):"function"==typeof n?[]:n?[[e,n+""]]:[]};const t=(t,r,n,i)=>{const o=[];for(const[s,a]of Object.entries(r))for(const[r,c]of(0,e.getOTELData)(s,a,n,i))o.push([t+"."+r,c]);return o},r=e=>!!Array.isArray(e)&&e.every(e=>null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)}(otelUtils);var require$$8=getAugmentedNamespace(esm$b),durationFilterProcessor={},hasRequiredUtils;Object.defineProperty(durationFilterProcessor,"__esModule",{value:!0}),durationFilterProcessor.DurationFilterProcessor=void 0;class DurationFilterProcessor{constructor(e){this._innerProcessor=e}onStart(e,t){this._innerProcessor.onStart(e,t)}onEnd(e){const t=e.attributes.insightsMinDurationMs&&parseInt(e.attributes.insightsMinDurationMs+"",10);if(t){1e9*e.endTime[0]+e.endTime[1]-(1e9*e.startTime[0]+e.startTime[1])>=1e6*t&&this._innerProcessor.onEnd(e)}else this._innerProcessor.onEnd(e)}shutdown(){return this._innerProcessor.shutdown()}forceFlush(){return this._innerProcessor.forceFlush()}}function requireUtils(){return hasRequiredUtils||(hasRequiredUtils=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extractFilteringContextFromArgs=e.deep_value=e.saveDataInAttribute=e.isFunctionType=e.setTracerProvider=e.isFilterMatch=e.findMatchingFilters=e.isSpanEnabled=void 0;const t=require$$15,r=require$$14$1,n=require$$13$1,i=require$$2,o=filter,s=attributeData,a=requireIoInsightsSampler(),c=otelUtils,l=require$$8,u=durationFilterProcessor,d=container$1;e.isSpanEnabled=(e,t,r)=>{var n,i;let o;return o=e?void 0===e.enabled||e.enabled:null===(i=null!==(n=null==t?void 0:t.enabled)&&void 0!==n?n:null==r?void 0:r.enabled)||void 0===i||i,o};e.findMatchingFilters=(t,r,n)=>{let i=!1;const o={},s={source:"",context:{},enabled:!1,stopPropagationIfSpanIsDisabled:!1,level:"INFO",addContextToTrace:!1,autoSetSuccessStatus:!1,sample:0,disablePropagation:!1,disableNesting:!1,countMetric:!1,countMetricOnDisabledSpans:!1,resultMetric:!1,resultMetricOnDisabledSpans:!1,durationMetric:!1,durationMetricOnDisabledSpans:!1,canBeRoot:!1,maxAttributeDepth:0,forceChildTracing:!1,otelSpanOptions:{},minDurationMs:0,log:!1,logOnDisabledSpans:!1};for(const a of t)if((0,e.isFilterMatch)(a,r,n)){i=!0;for(const e of Object.keys(s))void 0===o[e]&&(o[e]=a[e])}return i?o:void 0};e.isFilterMatch=(t,r,n)=>{let i=!0;if(t){(new o.TracesFilterValidator).validate(t)}if(t.source&&t.source.startsWith("#")){if(!new RegExp(t.source.substring(1),"i").test(n))return 0}else if(t.source&&n!==t.source&&!n.startsWith(t.source+".")&&n+"."!==t.source)return 0;if(!t.context)return 1;for(const n of Object.keys(t.context)){const o=t.context[n],s=(0,e.deep_value)(r,n);if("string"!=typeof o||"#"!==o[0]){o!==s&&(i=!1);break}if(null==s||!new RegExp(o.substring(1),"i").test(s+"")){i=!1;break}}return i?2:0};e.setTracerProvider=(e,o,s,c,h,p,g,m,f)=>{var y;if(!s&&!f)throw new Error("Required arguments not provided");const $=null==f?void 0:f.traces;if(!s){const e=new r.ParentBasedSampler({root:new a.ioInsightsSampler((null==$?void 0:$.sampling)||[],null==$?void 0:$.defaults,()=>Object.assign(Object.assign({},d.Container.errorless(null==$?void 0:$.additionalResourceAttributes)),d.Container.errorless(null==$?void 0:$.additionalAttributes)),m)}),n=[];if(h)for(const e of h)n.push(new u.DurationFilterProcessor(e));if(p)for(const e of p)n.push(new u.DurationFilterProcessor(new r.BatchSpanProcessor(e)));(null==$?void 0:$.url)&&n.push(new u.DurationFilterProcessor(new r.BatchSpanProcessor(new t.OTLPTraceExporter(Object.assign(Object.assign({},$.otlpExporterConfig),{url:$.url,headers:Object.assign(Object.assign({},d.Container.errorless(null==f?void 0:f.headers)),d.Container.errorless($.headers))}))))),(null==$?void 0:$.console)&&n.push(new u.DurationFilterProcessor(new r.BatchSpanProcessor(new r.ConsoleSpanExporter))),s=new r.BasicTracerProvider(Object.assign({sampler:"function"==typeof c?c(e):e,resource:(0,i.resourceFromAttributes)(null!==(y=d.Container.errorless(null==$?void 0:$.additionalResourceAttributes))&&void 0!==y?y:{}),spanProcessors:n},null==$?void 0:$.tracerProviderConfig))}n.trace.setGlobalTracerProvider(s),e&&n.context.setGlobalContextManager(null!=e?e:null==g?void 0:g.contextManager),o?n.propagation.setGlobalPropagator(null!=o?o:null==g?void 0:g.propagator):n.propagation.setGlobalPropagator(new l.W3CTraceContextPropagator),"function"==typeof s.register&&s.register(g||{})};e.isFunctionType=e=>"function"==typeof e;e.saveDataInAttribute=(e,t,r)=>{if(null==e)return;"object"!=typeof e&&(e={unknownAttribute:e});(new s.TracesAttributeDataValidator).validate(e);for(const[n,i]of Object.entries(e)){const e=(0,c.getOTELData)(n,i,0,r);for(const[r,n]of e)t.setAttribute(r,n)}};e.deep_value=function(e,t){if(!t)return null;for(var r=0,n=(t=t.split(".")).length;r{let i={};return"function"==typeof t.thisMapping?i=Object.assign(Object.assign({},i),t.thisMapping.apply(n,[n])):Object.keys(t.thisMapping||{}).forEach(r=>{if(!r||!t.thisMapping)return;const o=t.thisMapping[r];i[o]=(0,e.deep_value)(n,r)}),"function"==typeof t.argMapping?i=Object.assign(Object.assign({},i),t.argMapping.apply(n,r)):Object.keys(t.argMapping||{}).forEach(n=>{if(!n||!t.argMapping)return;const o=t.argMapping[n],s=(0,e.deep_value)(r,n);"string"!=typeof s&&"number"!=typeof s||(i[o]=s)}),i}}(utils$7)),utils$7}durationFilterProcessor.DurationFilterProcessor=DurationFilterProcessor;var manager$1={};Object.defineProperty(manager$1,"__esModule",{value:!0}),manager$1.TracesManagerValidator=void 0;const validator_1$1=validator$1;class TracesManagerValidator{validate(e){validator_1$1.Validator.throwIfNullOrUndefined(e,"manager"),validator_1$1.Validator.throwIfNullOrUndefined(e.settings,"settings")}}manager$1.TracesManagerValidator=TracesManagerValidator;var tracingState={},types$1={};!function(e){var t;Object.defineProperty(e,"__esModule",{value:!0}),e.SpanVerbosity=void 0,(t=e.SpanVerbosity||(e.SpanVerbosity={}))[t.OFF=0]="OFF",t[t.LOWEST=1]="LOWEST",t[t.DIAGNOSTIC=2]="DIAGNOSTIC",t[t.DEBUG=3]="DEBUG",t[t.INFO=4]="INFO",t[t.WARN=5]="WARN",t[t.HIGHEST=6]="HIGHEST"}(types$1),Object.defineProperty(tracingState,"__esModule",{value:!0}),tracingState.TracingState=void 0;const types_1=types$1,api_1$3=require$$13$1,utils_1$2=requireUtils();class TracingState{constructor(e,t,r,n,i,o,s,a,c){this.source=e,this.level=t,this.span=r,this.logger=n,this.version=i,this.disablePropagation=o,this.forceChildTracing=s,this.maxAttributeDepth=a,this.context=c,this.currentSpanStatus={code:api_1$3.SpanStatusCode.UNSET},this.hasEnded=!1,this.spanContextField=r.spanContext()}endSpan(){var e;return this.hasEnded?null===(e=this.logger)||void 0===e||e.debug(`Span ended more than once: ${this.source}`):(this.hasEnded=!0,this.span.end()),Promise.resolve()}get enabled(){return!0}get id(){return this.spanContextField.spanId}get traceId(){return this.spanContextField.traceId}set status(e){this.currentSpanStatus=Object.assign({},e),this.span.setStatus.call(this.span,e)}get status(){return this.currentSpanStatus}addEvent(e,t,r){return this.span.addEvent.call(this.span,e,t,r),this}recordException(e,t){this.span.recordException.call(this.span,e,t)}isRecording(){return this.span.isRecording.call(this.span)}updateName(e){return this.span.updateName.call(this.span,e),this}spanContext(){return this.span.spanContext.call(this.span)}addData(e,t){var r;"string"==typeof e&&(e=types_1.SpanVerbosity[e]),e>=types_1.SpanVerbosity[this.level]&&(0,utils_1$2.saveDataInAttribute)(t,this.span,null!==(r=this.maxAttributeDepth)&&void 0!==r?r:5)}end(){this.span.end()}getPropagationInfo(){const e={traceparent:`${this.version}-${this.spanContextField.traceId}-${this.spanContextField.spanId}-0${this.spanContextField.traceFlags}`,tracestate:this.spanContextField.traceState&&String(this.spanContextField.traceState)};return this.forceChildTracing&&(e.forceTracing=!0),e}injectPropagationInfo(e){if(this.disablePropagation)return;const t=this.getPropagationInfo();t&&(e.__interopIOTracePropagationInfo=t)}}tracingState.TracingState=TracingState;var withSpan={};Object.defineProperty(withSpan,"__esModule",{value:!0}),withSpan.TracesWithSpanValidator=void 0;const utils_1$1=requireUtils();class TracesWithSpanValidator{validate(e,t,r,n,i){if(!e)throw new Error("Missing required argument 'source' in withSpan(). Expected a string.");if(!(i||(0,utils_1$1.isFunctionType)(t)||(0,utils_1$1.isFunctionType)(r)||(0,utils_1$1.isFunctionType)(n)))throw new Error("Missing required argument 'callback' in withSpan(). Expected a function.")}}withSpan.TracesWithSpanValidator=TracesWithSpanValidator;var nullTracingState={};Object.defineProperty(nullTracingState,"__esModule",{value:!0});const api_1$2=require$$13$1;class NullTracingState{constructor(e,t,r){this.source=e,this.propagationInfo=t,this.disablePropagation=r,this.currentSpanStatus={code:api_1$2.SpanStatusCode.UNSET},this.level="OFF"}endSpan(){return Promise.resolve()}get enabled(){return!1}get id(){}get traceId(){}set status(e){this.currentSpanStatus=Object.assign({},e)}get status(){return this.currentSpanStatus}addEvent(e,t,r){return this}recordException(e,t){}isRecording(){return!1}updateName(e){return this}spanContext(){}addData(e,t){}end(){}getPropagationInfo(){return this.propagationInfo?this.propagationInfo:null}injectPropagationInfo(e){this.propagationInfo&&!this.disablePropagation&&(e.__interopIOTracePropagationInfo=this.propagationInfo)}}nullTracingState.default=NullTracingState;var traces={},nullTracesManager={},hasRequiredNullTracesManager,hasRequiredTraces;function requireNullTracesManager(){if(hasRequiredNullTracesManager)return nullTracesManager;hasRequiredNullTracesManager=1;var e=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nullTracesManager,"__esModule",{value:!0}),nullTracesManager.NullTracesManager=void 0;const t=nullManager$1,r=safeStringify$1,n=e(nullTracingState),i=e(requireTraces());class o extends t.NullManager{get settings(){return this._settings||{}}set settings(e){this._settings=e}constructor(e,t,n){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==n||n.info(`Starting NullTracesManager with settings ${(0,r.safeStringify)(e)}`)),super(),this._settings=e,this.logger=n}get currentTracingState(){return new n.default("nullTracingState",null,!0)}set currentTracingState(e){}waitForFinalExport(e){return Promise.resolve()}withSpan(e,t,r,o,s){var a;const c="function"==typeof t?t:"function"==typeof r?r:"function"==typeof o?o:s;if(!c)throw new Error("callback must be provided");null===(a=this.logger)||void 0===a||a.debug("nullTracesManager.withSpan: "+e);const l=new n.default(e,null,!0);i.default.currentTracingState=l;try{return c(l)}finally{i.default.currentTracingState=null}}}return nullTracesManager.NullTracesManager=o,nullTracesManager}function requireTraces(){if(hasRequiredTraces)return traces;hasRequiredTraces=1;var e=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(traces,"__esModule",{value:!0}),traces.withSpan=traces.getCurrentTracingStateInternal=void 0;const t=requireNullTracesManager(),r=e(nullTracingState),n=requireUtils();let i;traces.getCurrentTracingStateInternal=()=>i;class o{static get instance(){return o._instance}static set instance(e){o._instance=e}static get currentTracingState(){var e;return(null===(e=o._instance)||void 0===e?void 0:e.currentTracingState)||new r.default("unknown",null,!0)}static set currentTracingState(e){i=e}static removePropagationInfo(e){return o.extractPropagationInfo(e,!0),e}static extractPropagationInfo(e,t){if(null==e?void 0:e.traceparent)return e;const r=null==e?void 0:e.__interopIOTracePropagationInfo;return r?(!0===t&&delete e.__interopIOTracePropagationInfo,r):null}static withSpan(e,t,r,i,s){return t instanceof Function||t&&!t.argMapping&&!t.thisMapping&&!t.defaults||r||i||s?o.instance.withSpan(e,t,r,i,s):function(r,i,s){let a;a=s?s.value:r;const c=function(...r){return o.withSpan(e,t?(0,n.extractFilteringContextFromArgs)(t,r,this):{},null,t,()=>a.apply(this,r))};if(!s)return c;s.value=c}}static withSpans(e,t){for(const r in e)if("function"==typeof t[r]){const n=t[r],i=e[r];if(!i)continue;let s;s="string"==typeof i?o.withSpan(i):o.withSpan(i.source,i.decoratorOptions),t[r]=s(n)}return t}}return traces.default=o,o._instance=new t.NullTracesManager(void 0,void 0,void 0),traces.withSpan=o.withSpan,traces}const otperformance$2=performance,NANOSECOND_DIGITS$2=9,NANOSECOND_DIGITS_IN_MILLIS$2=6,MILLISECONDS_TO_NANOSECONDS$2=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$2),SECOND_TO_NANOSECONDS$2=Math.pow(10,NANOSECOND_DIGITS$2);function millisToHrTime$2(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$2)]}function getTimeOrigin$2(){let e=otperformance$2.timeOrigin;if("number"!=typeof e){const t=otperformance$2;e=t.timing&&t.timing.fetchStart}return e}function hrTime$2(e){return addHrTimes$2(millisToHrTime$2(getTimeOrigin$2()),millisToHrTime$2("number"==typeof e?e:otperformance$2.now()))}function timeInputToHrTime(e){if(isTimeInputHrTime(e))return e;if("number"==typeof e)return e=SECOND_TO_NANOSECONDS$2&&(r[1]-=SECOND_TO_NANOSECONDS$2,r[0]+=1),r}function urlMatches$2(e,t){return"string"==typeof t?e===t:!!e.match(t)}var PerformanceTimingNames;!function(e){e.CONNECT_END="connectEnd",e.CONNECT_START="connectStart",e.DECODED_BODY_SIZE="decodedBodySize",e.DOM_COMPLETE="domComplete",e.DOM_CONTENT_LOADED_EVENT_END="domContentLoadedEventEnd",e.DOM_CONTENT_LOADED_EVENT_START="domContentLoadedEventStart",e.DOM_INTERACTIVE="domInteractive",e.DOMAIN_LOOKUP_END="domainLookupEnd",e.DOMAIN_LOOKUP_START="domainLookupStart",e.ENCODED_BODY_SIZE="encodedBodySize",e.FETCH_START="fetchStart",e.LOAD_EVENT_END="loadEventEnd",e.LOAD_EVENT_START="loadEventStart",e.NAVIGATION_START="navigationStart",e.REDIRECT_END="redirectEnd",e.REDIRECT_START="redirectStart",e.REQUEST_START="requestStart",e.RESPONSE_END="responseEnd",e.RESPONSE_START="responseStart",e.SECURE_CONNECTION_START="secureConnectionStart",e.START_TIME="startTime",e.UNLOAD_EVENT_END="unloadEventEnd",e.UNLOAD_EVENT_START="unloadEventStart"}(PerformanceTimingNames||(PerformanceTimingNames={}));const ATTR_HTTP_RESPONSE_CONTENT_LENGTH="http.response_content_length",ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED="http.response_content_length_uncompressed";let urlNormalizingAnchor;function getUrlNormalizingAnchor(){return urlNormalizingAnchor||(urlNormalizingAnchor=document.createElement("a")),urlNormalizingAnchor}function hasKey(e,t){return t in e}function addSpanNetworkEvent(e,t,r,n=!0){if(hasKey(r,t)&&"number"==typeof r[t]&&(!n||0!==r[t]))return e.addEvent(t,r[t])}function addSpanNetworkEvents(e,t,r=!1,n,i){if(void 0===n&&(n=0!==t[PerformanceTimingNames.START_TIME]),r||(addSpanNetworkEvent(e,PerformanceTimingNames.FETCH_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.DOMAIN_LOOKUP_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.DOMAIN_LOOKUP_END,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.CONNECT_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.SECURE_CONNECTION_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.CONNECT_END,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.REQUEST_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.RESPONSE_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.RESPONSE_END,t,n)),!i){const r=t[PerformanceTimingNames.ENCODED_BODY_SIZE];void 0!==r&&e.setAttribute(ATTR_HTTP_RESPONSE_CONTENT_LENGTH,r);const n=t[PerformanceTimingNames.DECODED_BODY_SIZE];void 0!==n&&r!==n&&e.setAttribute(ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,n)}}function sortResources(e){return e.slice().sort((e,t)=>{const r=e[PerformanceTimingNames.FETCH_START],n=t[PerformanceTimingNames.FETCH_START];return r>n?1:r1){let e=c[0],t=findMainRequest(c,e[PerformanceTimingNames.RESPONSE_END],r);const n=e[PerformanceTimingNames.RESPONSE_END];return t[PerformanceTimingNames.FETCH_START]=i&&(!o||c{const r=hrTimeToNanoseconds(timeInputToHrTime(t[PerformanceTimingNames.FETCH_START])),n=hrTimeToNanoseconds(timeInputToHrTime(t[PerformanceTimingNames.RESPONSE_END]));return t.initiatorType.toLowerCase()===(o||"xmlhttprequest")&&t.name===e&&r>=s&&n<=a});return c.length>0&&(c=c.filter(e=>!i.has(e))),c}function parseUrl(e){if("function"==typeof URL)return new URL(e,"undefined"!=typeof document?document.baseURI:"undefined"!=typeof location?location.href:void 0);const t=getUrlNormalizingAnchor();return t.href=e,t}function getElementXPath(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return"/";const r=getNodeValue(e,t);if(t&&r.indexOf("@id")>0)return r;let n="";return e.parentNode&&(n+=getElementXPath(e.parentNode,!1)),n+=r,n}function getNodeIndex(e){if(!e.parentNode)return 0;const t=[e.nodeType];e.nodeType===Node.CDATA_SECTION_NODE&&t.push(Node.TEXT_NODE);let r=Array.from(e.parentNode.childNodes);return r=r.filter(r=>{const n=r.localName;return t.indexOf(r.nodeType)>=0&&n===e.localName}),r.length>=1?r.indexOf(e)+1:0}function getNodeValue(e,t){const r=e.nodeType,n=getNodeIndex(e);let i="";if(r===Node.ELEMENT_NODE){const r=e.getAttribute("id");if(t&&r)return`//*[@id="${r}"]`;i=e.localName}else if(r===Node.TEXT_NODE||r===Node.CDATA_SECTION_NODE)i="text()";else{if(r!==Node.COMMENT_NODE)return"";i="comment()"}return i&&n>1?`/${i}[${n}]`:`/${i}`}function shouldPropagateTraceHeaders(e,t){let r=t||[];("string"==typeof r||r instanceof RegExp)&&(r=[r]);return parseUrl(e).origin===getOrigin()||r.some(t=>urlMatches$2(e,t))}let NoopLogger$5=class{emit(e){}};const NOOP_LOGGER$5=new NoopLogger$5;let NoopLoggerProvider$4=class{getLogger(e,t,r){return new NoopLogger$5}};const NOOP_LOGGER_PROVIDER$4=new NoopLoggerProvider$4;let ProxyLogger$4=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$5}},ProxyLoggerProvider$4=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger$4(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER$4}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const _globalThis$5="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY$4=Symbol.for("io.opentelemetry.js.api.logs"),_global$5=_globalThis$5;function makeGetter$4(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION$4=1;let LogsAPI$4=class e{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider$4}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return _global$5[GLOBAL_LOGS_API_KEY$4]?this.getLoggerProvider():(_global$5[GLOBAL_LOGS_API_KEY$4]=makeGetter$4(API_BACKWARDS_COMPATIBILITY_VERSION$4,e,NOOP_LOGGER_PROVIDER$4),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$5[GLOBAL_LOGS_API_KEY$4])||void 0===e?void 0:e.call(_global$5,API_BACKWARDS_COMPATIBILITY_VERSION$4))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$5[GLOBAL_LOGS_API_KEY$4],this._proxyLoggerProvider=new ProxyLoggerProvider$4}};const logs$5=LogsAPI$4.getInstance();let logger$5=console.error.bind(console);function defineProperty$6(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$5=(e,t,r)=>{if(!e||!e[t])return void logger$5("no original function "+String(t)+" to wrap");if(!r)return logger$5("no wrapper function"),void logger$5((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$5("original object and wrapper must be functions");const i=r(n,t);return defineProperty$6(i,"__original",n),defineProperty$6(i,"__unwrap",()=>{e[t]===i&&defineProperty$6(e,t,n)}),defineProperty$6(i,"__wrapped",!0),defineProperty$6(e,t,i),i},massWrap$4=(e,t,r)=>{if(!e)return logger$5("must provide one or more modules to patch"),void logger$5((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$5(e,t,r)})}):logger$5("must provide one or more functions to wrap on modules")},unwrap$5=(e,t)=>{if(!e||!e[t])return logger$5("no function to unwrap."),void logger$5((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$5("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap$4=(e,t)=>{if(!e)return logger$5("must provide one or more modules to patch"),void logger$5((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$5(e,t)})}):logger$5("must provide one or more functions to unwrap on modules")};let InstrumentationAbstract$4=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$5.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$5;_unwrap=unwrap$5;_massWrap=massWrap$4;_massUnwrap=massUnwrap$4;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},InstrumentationBase$4=class extends InstrumentationAbstract$4{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function safeExecuteInTheMiddle$3(e,t,r){let n,i;try{i=e()}catch(e){n=e}finally{return t(n,i),i}}var AttributeNames$3;!function(e){e.DOCUMENT_LOAD="documentLoad",e.DOCUMENT_FETCH="documentFetch",e.RESOURCE_FETCH="resourceFetch"}(AttributeNames$3||(AttributeNames$3={}));const PACKAGE_VERSION$1="0.47.1",PACKAGE_NAME$1="@opentelemetry/instrumentation-document-load";var EventNames$1;!function(e){e.FIRST_PAINT="firstPaint",e.FIRST_CONTENTFUL_PAINT="firstContentfulPaint"}(EventNames$1||(EventNames$1={}));const getPerformanceNavigationEntries=()=>{const e={},t=otperformance$4.getEntriesByType?.("navigation")[0];if(t){Object.values(PerformanceTimingNames).forEach(r=>{if(hasKey(t,r)){const n=t[r];"number"==typeof n&&(e[r]=n)}})}else{const t=otperformance$4.timing;if(t){Object.values(PerformanceTimingNames).forEach(r=>{if(hasKey(t,r)){const n=t[r];"number"==typeof n&&(e[r]=n)}})}}return e},performancePaintNames={"first-paint":EventNames$1.FIRST_PAINT,"first-contentful-paint":EventNames$1.FIRST_CONTENTFUL_PAINT},addSpanPerformancePaintEvents=e=>{const t=otperformance$4.getEntriesByType?.("paint");t&&t.forEach(({name:t,startTime:r})=>{hasKey(performancePaintNames,t)&&e.addEvent(performancePaintNames[t],r)})};class DocumentLoadInstrumentation extends InstrumentationBase$4{component="document-load";version="1";moduleName=this.component;constructor(e={}){super(PACKAGE_NAME$1,PACKAGE_VERSION$1,e)}init(){}_onDocumentLoaded(){window.setTimeout(()=>{this._collectPerformance()})}_addResourcesSpans(e){const t=otperformance$4.getEntriesByType?.("resource");t&&t.forEach(t=>{this._initResourceSpan(t,e)})}_collectPerformance(){const e=Array.from(document.getElementsByTagName("meta")).find(e=>e.getAttribute("name")===TRACE_PARENT_HEADER),t=getPerformanceNavigationEntries(),r=e&&e.content||"";context.with(propagation.extract(ROOT_CONTEXT,{traceparent:r}),()=>{const e=this._startSpan(AttributeNames$3.DOCUMENT_LOAD,PerformanceTimingNames.FETCH_START,t);e&&(context.with(trace.setSpan(context.active(),e),()=>{const e=this._startSpan(AttributeNames$3.DOCUMENT_FETCH,PerformanceTimingNames.FETCH_START,t);e&&(e.setAttribute(SEMATTRS_HTTP_URL,location.href),context.with(trace.setSpan(context.active(),e),()=>{addSpanNetworkEvents(e,t,this.getConfig().ignoreNetworkEvents),this._addCustomAttributesOnSpan(e,this.getConfig().applyCustomAttributesOnSpan?.documentFetch),this._endSpan(e,PerformanceTimingNames.RESPONSE_END,t)}))}),e.setAttribute(SEMATTRS_HTTP_URL,location.href),e.setAttribute(SEMATTRS_HTTP_USER_AGENT,navigator.userAgent),this._addResourcesSpans(e),this.getConfig().ignoreNetworkEvents||(addSpanNetworkEvent(e,PerformanceTimingNames.FETCH_START,t),addSpanNetworkEvent(e,PerformanceTimingNames.UNLOAD_EVENT_START,t),addSpanNetworkEvent(e,PerformanceTimingNames.UNLOAD_EVENT_END,t),addSpanNetworkEvent(e,PerformanceTimingNames.DOM_INTERACTIVE,t),addSpanNetworkEvent(e,PerformanceTimingNames.DOM_CONTENT_LOADED_EVENT_START,t),addSpanNetworkEvent(e,PerformanceTimingNames.DOM_CONTENT_LOADED_EVENT_END,t),addSpanNetworkEvent(e,PerformanceTimingNames.DOM_COMPLETE,t),addSpanNetworkEvent(e,PerformanceTimingNames.LOAD_EVENT_START,t),addSpanNetworkEvent(e,PerformanceTimingNames.LOAD_EVENT_END,t)),this.getConfig().ignorePerformancePaintEvents||addSpanPerformancePaintEvents(e),this._addCustomAttributesOnSpan(e,this.getConfig().applyCustomAttributesOnSpan?.documentLoad),this._endSpan(e,PerformanceTimingNames.LOAD_EVENT_END,t))})}_endSpan(e,t,r){e&&(hasKey(r,t)?e.end(r[t]):e.end())}_initResourceSpan(e,t){const r=this._startSpan(AttributeNames$3.RESOURCE_FETCH,PerformanceTimingNames.FETCH_START,e,t);r&&(r.setAttribute(SEMATTRS_HTTP_URL,e.name),addSpanNetworkEvents(r,e,this.getConfig().ignoreNetworkEvents),this._addCustomAttributesOnResourceSpan(r,e,this.getConfig().applyCustomAttributesOnSpan?.resourceFetch),this._endSpan(r,PerformanceTimingNames.RESPONSE_END,e))}_startSpan(e,t,r,n){if(hasKey(r,t)&&"number"==typeof r[t]){return this.tracer.startSpan(e,{startTime:r[t]},n?trace.setSpan(context.active(),n):void 0)}}_waitForPageLoad(){"complete"===window.document.readyState?this._onDocumentLoaded():(this._onDocumentLoaded=this._onDocumentLoaded.bind(this),window.addEventListener("load",this._onDocumentLoaded))}_addCustomAttributesOnSpan(e,t){t&&safeExecuteInTheMiddle$3(()=>t(e),e=>{e&&this._diag.error("addCustomAttributesOnSpan",e)})}_addCustomAttributesOnResourceSpan(e,t,r){r&&safeExecuteInTheMiddle$3(()=>r(e,t),e=>{e&&this._diag.error("addCustomAttributesOnResourceSpan",e)})}enable(){window.removeEventListener("load",this._onDocumentLoaded),this._waitForPageLoad()}disable(){window.removeEventListener("load",this._onDocumentLoaded)}}var esm$6=Object.freeze({__proto__:null,get AttributeNames(){return AttributeNames$3},DocumentLoadInstrumentation:DocumentLoadInstrumentation}),require$$10=getAugmentedNamespace(esm$6);let NoopLogger$4=class{emit(e){}};const NOOP_LOGGER$4=new NoopLogger$4;let NoopLoggerProvider$3=class{getLogger(e,t,r){return new NoopLogger$4}};const NOOP_LOGGER_PROVIDER$3=new NoopLoggerProvider$3;let ProxyLogger$3=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$4}},ProxyLoggerProvider$3=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger$3(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER$3}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const _globalThis$4="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY$3=Symbol.for("io.opentelemetry.js.api.logs"),_global$4=_globalThis$4;function makeGetter$3(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION$3=1;let LogsAPI$3=class e{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider$3}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return _global$4[GLOBAL_LOGS_API_KEY$3]?this.getLoggerProvider():(_global$4[GLOBAL_LOGS_API_KEY$3]=makeGetter$3(API_BACKWARDS_COMPATIBILITY_VERSION$3,e,NOOP_LOGGER_PROVIDER$3),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$4[GLOBAL_LOGS_API_KEY$3])||void 0===e?void 0:e.call(_global$4,API_BACKWARDS_COMPATIBILITY_VERSION$3))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$4[GLOBAL_LOGS_API_KEY$3],this._proxyLoggerProvider=new ProxyLoggerProvider$3}};const logs$4=LogsAPI$3.getInstance();let logger$4=console.error.bind(console);function defineProperty$5(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$4=(e,t,r)=>{if(!e||!e[t])return void logger$4("no original function "+String(t)+" to wrap");if(!r)return logger$4("no wrapper function"),void logger$4((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$4("original object and wrapper must be functions");const i=r(n,t);return defineProperty$5(i,"__original",n),defineProperty$5(i,"__unwrap",()=>{e[t]===i&&defineProperty$5(e,t,n)}),defineProperty$5(i,"__wrapped",!0),defineProperty$5(e,t,i),i},massWrap$3=(e,t,r)=>{if(!e)return logger$4("must provide one or more modules to patch"),void logger$4((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$4(e,t,r)})}):logger$4("must provide one or more functions to wrap on modules")},unwrap$4=(e,t)=>{if(!e||!e[t])return logger$4("no function to unwrap."),void logger$4((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$4("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap$3=(e,t)=>{if(!e)return logger$4("must provide one or more modules to patch"),void logger$4((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$4(e,t)})}):logger$4("must provide one or more functions to unwrap on modules")};let InstrumentationAbstract$3=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$4.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$4;_unwrap=unwrap$4;_massWrap=massWrap$3;_massUnwrap=massUnwrap$3;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},InstrumentationBase$3=class extends InstrumentationAbstract$3{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function isWrapped$3(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var AttributeNames$2;!function(e){e.EVENT_TYPE="event_type",e.TARGET_ELEMENT="target_element",e.TARGET_XPATH="target_xpath",e.HTTP_URL="http.url"}(AttributeNames$2||(AttributeNames$2={}));const PACKAGE_VERSION="0.47.0",PACKAGE_NAME="@opentelemetry/instrumentation-user-interaction",ZONE_CONTEXT_KEY="OT_ZONE_CONTEXT",EVENT_NAVIGATION_NAME="Navigation:",DEFAULT_EVENT_NAMES=["click"];function defaultShouldPreventSpanCreation(){return!1}class UserInteractionInstrumentation extends InstrumentationBase$3{version=PACKAGE_VERSION;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(e={}){super(PACKAGE_NAME,PACKAGE_VERSION,e),this._eventNames=new Set(e?.eventNames??DEFAULT_EVENT_NAMES),this._shouldPreventSpanCreation="function"==typeof e?.shouldPreventSpanCreation?e.shouldPreventSpanCreation:defaultShouldPreventSpanCreation}init(){}_checkForTimeout(e,t){const r=this._spansData.get(t);r&&("setTimeout"===e.source?r.hrTimeLastTimeout=hrTime$4():"Promise.then"!==e.source&&"setTimeout"!==e.source&&(r.hrTimeLastTimeout=void 0))}_allowEventName(e){return this._eventNames.has(e)}_createSpan(e,t,r){if(!(e instanceof HTMLElement))return;if(!e.getAttribute)return;if(e.hasAttribute("disabled"))return;if(!this._allowEventName(t))return;const n=getElementXPath(e,!0);try{const i=this.tracer.startSpan(t,{attributes:{[AttributeNames$2.EVENT_TYPE]:t,[AttributeNames$2.TARGET_ELEMENT]:e.tagName,[AttributeNames$2.TARGET_XPATH]:n,[AttributeNames$2.HTTP_URL]:window.location.href}},r?trace.setSpan(context.active(),r):void 0);if(!0===this._shouldPreventSpanCreation(t,e,i))return;return this._spansData.set(i,{taskCount:0}),i}catch(e){this._diag.error("failed to start create new user interaction span",e)}}_decrementTask(e){const t=this._spansData.get(e);t&&(t.taskCount--,0===t.taskCount&&this._tryToEndSpan(e,t.hrTimeLastTimeout))}_getCurrentSpan(e){const t=e.get(ZONE_CONTEXT_KEY);return t?trace.getSpan(t):t}_incrementTask(e){const t=this._spansData.get(e);t&&t.taskCount++}addPatchedListener(e,t,r,n){let i=this._wrappedListeners.get(r);i||(i=new Map,this._wrappedListeners.set(r,i));let o=i.get(t);return o||(o=new Map,i.set(t,o)),!o.has(e)&&(o.set(e,n),!0)}removePatchedListener(e,t,r){const n=this._wrappedListeners.get(r);if(!n)return;const i=n.get(t);if(!i)return;const o=i.get(e);return o&&(i.delete(e),0===i.size&&(n.delete(t),0===n.size&&this._wrappedListeners.delete(r))),o}_invokeListener(e,t,r){return"function"==typeof e?e.apply(t,r):e.handleEvent(r[0])}_patchAddEventListener(){const e=this;return t=>function(r,n,i){if(!n)return t.call(this,r,n,i);const o=i&&"object"==typeof i&&i.once,s=function(...t){let i;const s=t[0],a=s?.target;s&&(i=e._eventsSpanMap.get(s)),o&&e.removePatchedListener(this,r,n);const c=e._createSpan(a,r,i);return c?(s&&e._eventsSpanMap.set(s,c),context.with(trace.setSpan(context.active(),c),()=>{const r=e._invokeListener(n,this,t);return c.end(),r})):e._invokeListener(n,this,t)};return e.addPatchedListener(this,r,n,s)?t.call(this,r,s,i):void 0}}_patchRemoveEventListener(){const e=this;return t=>function(r,n,i){const o=e.removePatchedListener(this,r,n);return o?t.call(this,r,o,i):t.call(this,r,n,i)}}_getPatchableEventTargets(){return window.EventTarget?[EventTarget.prototype]:[Node.prototype,Window.prototype]}_patchHistoryApi(){this._unpatchHistoryApi(),this._wrap(history,"replaceState",this._patchHistoryMethod()),this._wrap(history,"pushState",this._patchHistoryMethod()),this._wrap(history,"back",this._patchHistoryMethod()),this._wrap(history,"forward",this._patchHistoryMethod()),this._wrap(history,"go",this._patchHistoryMethod())}_patchHistoryMethod(){const e=this;return t=>function(...r){const n=`${location.pathname}${location.hash}${location.search}`,i=t.apply(this,r),o=`${location.pathname}${location.hash}${location.search}`;return n!==o&&e._updateInteractionName(o),i}}_unpatchHistoryApi(){isWrapped$3(history.replaceState)&&this._unwrap(history,"replaceState"),isWrapped$3(history.pushState)&&this._unwrap(history,"pushState"),isWrapped$3(history.back)&&this._unwrap(history,"back"),isWrapped$3(history.forward)&&this._unwrap(history,"forward"),isWrapped$3(history.go)&&this._unwrap(history,"go")}_updateInteractionName(e){const t=trace.getSpan(context.active());t&&"function"==typeof t.updateName&&t.updateName(`${EVENT_NAVIGATION_NAME} ${e}`)}_patchZoneCancelTask(){const e=this;return t=>function(r){const n=Zone.current,i=e._getCurrentSpan(n);return i&&e._shouldCountTask(r,n)&&e._decrementTask(i),t.call(this,r)}}_patchZoneScheduleTask(){const e=this;return t=>function(r){const n=Zone.current,i=e._getCurrentSpan(n);return i&&e._shouldCountTask(r,n)&&(e._incrementTask(i),e._checkForTimeout(r,i)),t.call(this,r)}}_patchZoneRunTask(){const e=this;return t=>function(r,n,i){const o=Array.isArray(i)&&i[0]instanceof Event?i[0]:void 0,s=o?.target;let a;const c=this;if(s){if(a=e._createSpan(s,r.eventName),a)return e._incrementTask(a),c.run(()=>{try{return context.with(trace.setSpan(context.active(),a),()=>{const e=Zone.current;return r._zone=e,t.call(e,r,n,i)})}finally{e._decrementTask(a)}})}else a=e._getCurrentSpan(c);try{return t.call(c,r,n,i)}finally{a&&e._shouldCountTask(r,c)&&e._decrementTask(a)}}}_shouldCountTask(e,t){if(e._zone&&(t=e._zone),!t||!e.data||e.data.isPeriodic)return!1;const r=this._getCurrentSpan(t);return!!r&&(!!this._spansData.get(r)&&("macroTask"===e.type||"microTask"===e.type))}_tryToEndSpan(e,t){if(e){this._spansData.get(e)&&(e.end(t),this._spansData.delete(e))}}enable(){const e=this._getZoneWithPrototype();if(this._diag.debug("applying patch to",this.moduleName,this.version,"zone:",!!e),e)isWrapped$3(e.prototype.runTask)&&(this._unwrap(e.prototype,"runTask"),this._diag.debug("removing previous patch from method runTask")),isWrapped$3(e.prototype.scheduleTask)&&(this._unwrap(e.prototype,"scheduleTask"),this._diag.debug("removing previous patch from method scheduleTask")),isWrapped$3(e.prototype.cancelTask)&&(this._unwrap(e.prototype,"cancelTask"),this._diag.debug("removing previous patch from method cancelTask")),this._zonePatched=!0,this._wrap(e.prototype,"runTask",this._patchZoneRunTask()),this._wrap(e.prototype,"scheduleTask",this._patchZoneScheduleTask()),this._wrap(e.prototype,"cancelTask",this._patchZoneCancelTask());else{this._zonePatched=!1;this._getPatchableEventTargets().forEach(e=>{isWrapped$3(e.addEventListener)&&(this._unwrap(e,"addEventListener"),this._diag.debug("removing previous patch from method addEventListener")),isWrapped$3(e.removeEventListener)&&(this._unwrap(e,"removeEventListener"),this._diag.debug("removing previous patch from method removeEventListener")),this._wrap(e,"addEventListener",this._patchAddEventListener()),this._wrap(e,"removeEventListener",this._patchRemoveEventListener())})}this._patchHistoryApi()}disable(){const e=this._getZoneWithPrototype();if(this._diag.debug("removing patch from",this.moduleName,this.version,"zone:",!!e),e&&this._zonePatched)isWrapped$3(e.prototype.runTask)&&this._unwrap(e.prototype,"runTask"),isWrapped$3(e.prototype.scheduleTask)&&this._unwrap(e.prototype,"scheduleTask"),isWrapped$3(e.prototype.cancelTask)&&this._unwrap(e.prototype,"cancelTask");else{this._getPatchableEventTargets().forEach(e=>{isWrapped$3(e.addEventListener)&&this._unwrap(e,"addEventListener"),isWrapped$3(e.removeEventListener)&&this._unwrap(e,"removeEventListener")})}this._unpatchHistoryApi()}_getZoneWithPrototype(){return window.Zone}}var esm$5=Object.freeze({__proto__:null,get AttributeNames(){return AttributeNames$2},UserInteractionInstrumentation:UserInteractionInstrumentation}),require$$11=getAugmentedNamespace(esm$5);let NoopLogger$3=class{emit(e){}};const NOOP_LOGGER$3=new NoopLogger$3;let NoopLoggerProvider$2=class{getLogger(e,t,r){return new NoopLogger$3}};const NOOP_LOGGER_PROVIDER$2=new NoopLoggerProvider$2;let ProxyLogger$2=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$3}},ProxyLoggerProvider$2=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger$2(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER$2}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const _globalThis$3="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY$2=Symbol.for("io.opentelemetry.js.api.logs"),_global$3=_globalThis$3;function makeGetter$2(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION$2=1;let LogsAPI$2=class e{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider$2}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return _global$3[GLOBAL_LOGS_API_KEY$2]?this.getLoggerProvider():(_global$3[GLOBAL_LOGS_API_KEY$2]=makeGetter$2(API_BACKWARDS_COMPATIBILITY_VERSION$2,e,NOOP_LOGGER_PROVIDER$2),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$3[GLOBAL_LOGS_API_KEY$2])||void 0===e?void 0:e.call(_global$3,API_BACKWARDS_COMPATIBILITY_VERSION$2))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$3[GLOBAL_LOGS_API_KEY$2],this._proxyLoggerProvider=new ProxyLoggerProvider$2}};const logs$3=LogsAPI$2.getInstance();let logger$3=console.error.bind(console);function defineProperty$4(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$3=(e,t,r)=>{if(!e||!e[t])return void logger$3("no original function "+String(t)+" to wrap");if(!r)return logger$3("no wrapper function"),void logger$3((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$3("original object and wrapper must be functions");const i=r(n,t);return defineProperty$4(i,"__original",n),defineProperty$4(i,"__unwrap",()=>{e[t]===i&&defineProperty$4(e,t,n)}),defineProperty$4(i,"__wrapped",!0),defineProperty$4(e,t,i),i},massWrap$2=(e,t,r)=>{if(!e)return logger$3("must provide one or more modules to patch"),void logger$3((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$3(e,t,r)})}):logger$3("must provide one or more functions to wrap on modules")},unwrap$3=(e,t)=>{if(!e||!e[t])return logger$3("no function to unwrap."),void logger$3((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$3("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap$2=(e,t)=>{if(!e)return logger$3("must provide one or more modules to patch"),void logger$3((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$3(e,t)})}):logger$3("must provide one or more functions to unwrap on modules")};let InstrumentationAbstract$2=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$3.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$3;_unwrap=unwrap$3;_massWrap=massWrap$2;_massUnwrap=massUnwrap$2;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},InstrumentationBase$2=class extends InstrumentationAbstract$2{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function safeExecuteInTheMiddle$2(e,t,r){let n,i;try{i=e()}catch(e){n=e}finally{return t(n,i),i}}function isWrapped$2(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var SemconvStability$2;function semconvStabilityFromStr$2(e,t){let r=SemconvStability$2.OLD;const n=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of n??[]){if(t.toLowerCase()===e+"/dup"){r=SemconvStability$2.DUPLICATE;break}t.toLowerCase()===e&&(r=SemconvStability$2.STABLE)}return r}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(SemconvStability$2||(SemconvStability$2={}));const _globalThis$2="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},otperformance$1=performance,NANOSECOND_DIGITS$1=9,NANOSECOND_DIGITS_IN_MILLIS$1=6,MILLISECONDS_TO_NANOSECONDS$1=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$1),SECOND_TO_NANOSECONDS$1=Math.pow(10,NANOSECOND_DIGITS$1);function millisToHrTime$1(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$1)]}function getTimeOrigin$1(){let e=otperformance$1.timeOrigin;if("number"!=typeof e){const t=otperformance$1;e=t.timing&&t.timing.fetchStart}return e}function hrTime$1(e){return addHrTimes$1(millisToHrTime$1(getTimeOrigin$1()),millisToHrTime$1(otperformance$1.now()))}function addHrTimes$1(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS$1&&(r[1]-=SECOND_TO_NANOSECONDS$1,r[0]+=1),r}function urlMatches$1(e,t){return"string"==typeof t?e===t:!!e.match(t)}function isUrlIgnored$1(e,t){if(!t)return!1;for(const r of t)if(urlMatches$1(e,r))return!0;return!1}var AttributeNames$1;!function(e){e.COMPONENT="component",e.HTTP_STATUS_TEXT="http.status_text"}(AttributeNames$1||(AttributeNames$1={}));var semconv={};Object.defineProperty(semconv,"__esModule",{value:!0});var ATTR_HTTP_USER_AGENT$1=semconv.ATTR_HTTP_USER_AGENT=ATTR_HTTP_URL$1=semconv.ATTR_HTTP_URL=ATTR_HTTP_STATUS_CODE$1=semconv.ATTR_HTTP_STATUS_CODE=ATTR_HTTP_SCHEME$1=semconv.ATTR_HTTP_SCHEME=semconv.ATTR_HTTP_RESPONSE_CONTENT_LENGTH=ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED$1=semconv.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=ATTR_HTTP_REQUEST_BODY_SIZE$1=semconv.ATTR_HTTP_REQUEST_BODY_SIZE=ATTR_HTTP_METHOD$1=semconv.ATTR_HTTP_METHOD=ATTR_HTTP_HOST$1=semconv.ATTR_HTTP_HOST=void 0,ATTR_HTTP_HOST$1=semconv.ATTR_HTTP_HOST="http.host",ATTR_HTTP_METHOD$1=semconv.ATTR_HTTP_METHOD="http.method",ATTR_HTTP_REQUEST_BODY_SIZE$1=semconv.ATTR_HTTP_REQUEST_BODY_SIZE="http.request.body.size",ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED$1=semconv.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED="http.request_content_length_uncompressed";semconv.ATTR_HTTP_RESPONSE_CONTENT_LENGTH="http.response_content_length";var ATTR_HTTP_SCHEME$1=semconv.ATTR_HTTP_SCHEME="http.scheme",ATTR_HTTP_STATUS_CODE$1=semconv.ATTR_HTTP_STATUS_CODE="http.status_code",ATTR_HTTP_URL$1=semconv.ATTR_HTTP_URL="http.url";ATTR_HTTP_USER_AGENT$1=semconv.ATTR_HTTP_USER_AGENT="http.user_agent";const DIAG_LOGGER$1=diag.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-fetch/utils"});function getFetchBodyLength(...e){if(e[0]instanceof URL||"string"==typeof e[0]){const t=e[1];if(!t?.body)return Promise.resolve();if(t.body instanceof ReadableStream){const{body:e,length:r}=_getBodyNonDestructively(t.body);return t.body=e,r}return Promise.resolve(getXHRBodyLength$1(t.body))}{const t=e[0];return t?.body?t.clone().text().then(e=>getByteLength$1(e)):Promise.resolve()}}function _getBodyNonDestructively(e){if(!e.pipeThrough)return DIAG_LOGGER$1.warn("Platform has ReadableStream but not pipeThrough!"),{body:e,length:Promise.resolve(void 0)};let t,r=0;const n=new Promise(e=>{t=e}),i=new TransformStream({start(){},async transform(e,t){const n=await e;r+=n.byteLength,t.enqueue(e)},flush(){t(r)}});return{body:e.pipeThrough(i),length:n}}function isDocument$1(e){return"undefined"!=typeof Document&&e instanceof Document}function getXHRBodyLength$1(e){return isDocument$1(e)?(new XMLSerializer).serializeToString(document).length:"string"==typeof e?getByteLength$1(e):e instanceof Blob?e.size:e instanceof FormData?getFormDataSize$1(e):e instanceof URLSearchParams?getByteLength$1(e.toString()):void 0!==e.byteLength?e.byteLength:void DIAG_LOGGER$1.warn("unknown body type")}const TEXT_ENCODER$1=new TextEncoder;function getByteLength$1(e){return TEXT_ENCODER$1.encode(e).byteLength}function getFormDataSize$1(e){let t=0;for(const[r,n]of e.entries())t+=r.length,n instanceof Blob?t+=n.size:t+=n.length;return t}function normalizeHttpRequestMethod$1(e){const t=getKnownMethods$1(),r=e.toUpperCase();return r in t?r:"_OTHER"}const DEFAULT_KNOWN_METHODS$1={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let knownMethods$1;function getKnownMethods$1(){return void 0===knownMethods$1&&(knownMethods$1=DEFAULT_KNOWN_METHODS$1),knownMethods$1}const HTTP_PORT_FROM_PROTOCOL$1={"https:":"443","http:":"80"};function serverPortFromUrl$1(e){const t=Number(e.port||HTTP_PORT_FROM_PROTOCOL$1[e.protocol]);return t&&!isNaN(t)?t:void 0}const VERSION$3="0.202.0",OBSERVER_WAIT_TIME_MS$1=300;class FetchInstrumentation extends InstrumentationBase$2{component="fetch";version=VERSION$3;moduleName=this.component;_usedResources=new WeakSet;_tasksCount=0;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-fetch",VERSION$3,e),this._semconvStability=semconvStabilityFromStr$2("http",e?.semconvStabilityOptIn)}init(){}_addChildSpan(e,t){const r=this.tracer.startSpan("CORS Preflight",{startTime:t[PerformanceTimingNames.FETCH_START]},trace.setSpan(context.active(),e)),n=!(this._semconvStability&SemconvStability$2.OLD);addSpanNetworkEvents(r,t,this.getConfig().ignoreNetworkEvents,void 0,n),r.end(t[PerformanceTimingNames.RESPONSE_END])}_addFinalSpanAttributes(e,t){const r=parseUrl(t.url);if(this._semconvStability&SemconvStability$2.OLD&&(e.setAttribute(ATTR_HTTP_STATUS_CODE$1,t.status),null!=t.statusText&&e.setAttribute(AttributeNames$1.HTTP_STATUS_TEXT,t.statusText),e.setAttribute(ATTR_HTTP_HOST$1,r.host),e.setAttribute(ATTR_HTTP_SCHEME$1,r.protocol.replace(":","")),"undefined"!=typeof navigator&&e.setAttribute(ATTR_HTTP_USER_AGENT$1,navigator.userAgent)),this._semconvStability&SemconvStability$2.STABLE){e.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,t.status),e.setAttribute(ATTR_SERVER_ADDRESS,r.hostname);const n=serverPortFromUrl$1(r);n&&e.setAttribute(ATTR_SERVER_PORT,n)}}_addHeaders(e,t){if(!shouldPropagateTraceHeaders(t,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return propagation.inject(context.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}if(e instanceof Request)propagation.inject(context.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else if(e.headers instanceof Headers)propagation.inject(context.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else if(e.headers instanceof Map)propagation.inject(context.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else{const t={};propagation.inject(context.active(),t),e.headers=Object.assign({},t,e.headers||{})}}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(performance.clearResourceTimings(),this._usedResources=new WeakSet)}_createSpan(e,t={}){if(isUrlIgnored$1(e,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let r="";const n={};if(this._semconvStability&SemconvStability$2.OLD){const i=(t.method||"GET").toUpperCase();r=`HTTP ${i}`,n[AttributeNames$1.COMPONENT]=this.moduleName,n[ATTR_HTTP_METHOD$1]=i,n[ATTR_HTTP_URL$1]=e}if(this._semconvStability&SemconvStability$2.STABLE){const i=t.method,o=normalizeHttpRequestMethod$1(t.method||"GET");r||(r=o),n[ATTR_HTTP_REQUEST_METHOD]=o,o!==i&&(n[ATTR_HTTP_REQUEST_METHOD_ORIGINAL]=i),n[ATTR_URL_FULL]=e}return this.tracer.startSpan(r,{kind:SpanKind.CLIENT,attributes:n})}_findResourceAndAddNetworkEvents(e,t,r){let n=t.entries;if(!n.length){if(!performance.getEntriesByType)return;n=performance.getEntriesByType("resource")}const i=getResource(t.spanUrl,t.startTime,r,n,this._usedResources,"fetch");if(i.mainRequest){const t=i.mainRequest;this._markResourceAsUsed(t);const r=i.corsPreFlightRequest;r&&(this._addChildSpan(e,r),this._markResourceAsUsed(r));const n=!(this._semconvStability&SemconvStability$2.OLD);addSpanNetworkEvents(e,t,this.getConfig().ignoreNetworkEvents,void 0,n)}}_markResourceAsUsed(e){this._usedResources.add(e)}_endSpan(e,t,r){const n=millisToHrTime$1(Date.now()),i=hrTime$1();this._addFinalSpanAttributes(e,r),this._semconvStability&SemconvStability$2.STABLE&&r.status>=400&&(e.setStatus({code:SpanStatusCode.ERROR}),e.setAttribute(ATTR_ERROR_TYPE,String(r.status))),setTimeout(()=>{t.observer?.disconnect(),this._findResourceAndAddNetworkEvents(e,t,i),this._tasksCount--,this._clearResources(),e.end(n)},OBSERVER_WAIT_TIME_MS$1)}_patchConstructor(){return e=>{const t=this;return function(...r){const n=this,i=parseUrl(r[0]instanceof Request?r[0].url:String(r[0])).href,o=r[0]instanceof Request?r[0]:r[1]||{},s=t._createSpan(i,o);if(!s)return e.apply(this,r);const a=t._prepareSpanData(i);function c(e,r){t._applyAttributesAfterFetch(e,o,r),t._endSpan(e,a,{status:r.status||0,statusText:r.message,url:i})}function l(e,r){t._applyAttributesAfterFetch(e,o,r),r.status>=200&&r.status<400?t._endSpan(e,a,r):t._endSpan(e,a,{status:r.status,statusText:r.statusText,url:i})}function u(e,t,r){try{const t=r.clone().body;if(t){const n=t.getReader(),i=()=>{n.read().then(({done:t})=>{t?l(e,r):i()},t=>{c(e,t)})};i()}else l(e,r)}finally{t(r)}}function d(e,t,r){try{c(e,r)}finally{t(r)}}return t.getConfig().measureRequestSize&&getFetchBodyLength(...r).then(e=>{e&&(t._semconvStability&SemconvStability$2.OLD&&s.setAttribute(ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED$1,e),t._semconvStability&SemconvStability$2.STABLE&&s.setAttribute(ATTR_HTTP_REQUEST_BODY_SIZE$1,e))}).catch(e=>{t._diag.warn("getFetchBodyLength",e)}),new Promise((r,a)=>context.with(trace.setSpan(context.active(),s),()=>(t._addHeaders(o,i),t._callRequestHook(s,o),t._tasksCount++,e.apply(n,o instanceof Request?[o]:[i,o]).then(u.bind(n,s,r),d.bind(n,s,a)))))}}}_applyAttributesAfterFetch(e,t,r){const n=this.getConfig().applyCustomAttributesOnSpan;n&&safeExecuteInTheMiddle$2(()=>n(e,t,r),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)})}_callRequestHook(e,t){const r=this.getConfig().requestHook;r&&safeExecuteInTheMiddle$2(()=>r(e,t),e=>{e&&this._diag.error("requestHook",e)})}_prepareSpanData(e){const t=hrTime$1(),r=[];if("function"!=typeof PerformanceObserver)return{entries:r,startTime:t,spanUrl:e};const n=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{"fetch"===t.initiatorType&&t.name===e&&r.push(t)})});return n.observe({entryTypes:["resource"]}),{entries:r,observer:n,startTime:t,spanUrl:e}}enable(){isWrapped$2(fetch)&&(this._unwrap(_globalThis$2,"fetch"),this._diag.debug("removing previous patch for constructor")),this._wrap(_globalThis$2,"fetch",this._patchConstructor())}disable(){this._unwrap(_globalThis$2,"fetch"),this._usedResources=new WeakSet}}var esm$4=Object.freeze({__proto__:null,FetchInstrumentation:FetchInstrumentation}),require$$12=getAugmentedNamespace(esm$4);let NoopLogger$2=class{emit(e){}};const NOOP_LOGGER$2=new NoopLogger$2;let NoopLoggerProvider$1=class{getLogger(e,t,r){return new NoopLogger$2}};const NOOP_LOGGER_PROVIDER$1=new NoopLoggerProvider$1;let ProxyLogger$1=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$2}},ProxyLoggerProvider$1=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger$1(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER$1}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const _globalThis$1="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY$1=Symbol.for("io.opentelemetry.js.api.logs"),_global$2=_globalThis$1;function makeGetter$1(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION$1=1;let LogsAPI$1=class e{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider$1}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return _global$2[GLOBAL_LOGS_API_KEY$1]?this.getLoggerProvider():(_global$2[GLOBAL_LOGS_API_KEY$1]=makeGetter$1(API_BACKWARDS_COMPATIBILITY_VERSION$1,e,NOOP_LOGGER_PROVIDER$1),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$2[GLOBAL_LOGS_API_KEY$1])||void 0===e?void 0:e.call(_global$2,API_BACKWARDS_COMPATIBILITY_VERSION$1))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$2[GLOBAL_LOGS_API_KEY$1],this._proxyLoggerProvider=new ProxyLoggerProvider$1}};const logs$2=LogsAPI$1.getInstance();let logger$2=console.error.bind(console);function defineProperty$3(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$2=(e,t,r)=>{if(!e||!e[t])return void logger$2("no original function "+String(t)+" to wrap");if(!r)return logger$2("no wrapper function"),void logger$2((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$2("original object and wrapper must be functions");const i=r(n,t);return defineProperty$3(i,"__original",n),defineProperty$3(i,"__unwrap",()=>{e[t]===i&&defineProperty$3(e,t,n)}),defineProperty$3(i,"__wrapped",!0),defineProperty$3(e,t,i),i},massWrap$1=(e,t,r)=>{if(!e)return logger$2("must provide one or more modules to patch"),void logger$2((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$2(e,t,r)})}):logger$2("must provide one or more functions to wrap on modules")},unwrap$2=(e,t)=>{if(!e||!e[t])return logger$2("no function to unwrap."),void logger$2((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$2("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap$1=(e,t)=>{if(!e)return logger$2("must provide one or more modules to patch"),void logger$2((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$2(e,t)})}):logger$2("must provide one or more functions to unwrap on modules")};let InstrumentationAbstract$1=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$2.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$2;_unwrap=unwrap$2;_massWrap=massWrap$1;_massUnwrap=massUnwrap$1;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},InstrumentationBase$1=class extends InstrumentationAbstract$1{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function safeExecuteInTheMiddle$1(e,t,r){let n,i;try{i=e()}catch(e){n=e}finally{return t(n,i),i}}function isWrapped$1(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var SemconvStability$1;function semconvStabilityFromStr$1(e,t){let r=SemconvStability$1.OLD;const n=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of n??[]){if(t.toLowerCase()===e+"/dup"){r=SemconvStability$1.DUPLICATE;break}t.toLowerCase()===e&&(r=SemconvStability$1.STABLE)}return r}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(SemconvStability$1||(SemconvStability$1={}));const otperformance=performance,NANOSECOND_DIGITS=9,NANOSECOND_DIGITS_IN_MILLIS=6,MILLISECONDS_TO_NANOSECONDS=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS),SECOND_TO_NANOSECONDS=Math.pow(10,NANOSECOND_DIGITS);function millisToHrTime(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS)]}function getTimeOrigin(){let e=otperformance.timeOrigin;if("number"!=typeof e){const t=otperformance;e=t.timing&&t.timing.fetchStart}return e}function hrTime(e){return addHrTimes(millisToHrTime(getTimeOrigin()),millisToHrTime(otperformance.now()))}function addHrTimes(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS&&(r[1]-=SECOND_TO_NANOSECONDS,r[0]+=1),r}function urlMatches(e,t){return"string"==typeof t?e===t:!!e.match(t)}function isUrlIgnored(e,t){if(!t)return!1;for(const r of t)if(urlMatches(e,r))return!0;return!1}const ATTR_HTTP_HOST="http.host",ATTR_HTTP_METHOD="http.method",ATTR_HTTP_REQUEST_BODY_SIZE="http.request.body.size",ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED="http.request_content_length_uncompressed",ATTR_HTTP_SCHEME="http.scheme",ATTR_HTTP_STATUS_CODE="http.status_code",ATTR_HTTP_URL="http.url",ATTR_HTTP_USER_AGENT="http.user_agent";var EventNames;!function(e){e.METHOD_OPEN="open",e.METHOD_SEND="send",e.EVENT_ABORT="abort",e.EVENT_ERROR="error",e.EVENT_LOAD="loaded",e.EVENT_TIMEOUT="timeout"}(EventNames||(EventNames={}));const DIAG_LOGGER=diag.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-xml-http-request/utils"});function isDocument(e){return"undefined"!=typeof Document&&e instanceof Document}function getXHRBodyLength(e){return isDocument(e)?(new XMLSerializer).serializeToString(document).length:"string"==typeof e?getByteLength(e):e instanceof Blob?e.size:e instanceof FormData?getFormDataSize(e):e instanceof URLSearchParams?getByteLength(e.toString()):void 0!==e.byteLength?e.byteLength:void DIAG_LOGGER.warn("unknown body type")}const TEXT_ENCODER=new TextEncoder;function getByteLength(e){return TEXT_ENCODER.encode(e).byteLength}function getFormDataSize(e){let t=0;for(const[r,n]of e.entries())t+=r.length,n instanceof Blob?t+=n.size:t+=n.length;return t}function normalizeHttpRequestMethod(e){const t=getKnownMethods(),r=e.toUpperCase();return r in t?r:"_OTHER"}const DEFAULT_KNOWN_METHODS={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let knownMethods;function getKnownMethods(){return void 0===knownMethods&&(knownMethods=DEFAULT_KNOWN_METHODS),knownMethods}const HTTP_PORT_FROM_PROTOCOL={"https:":"443","http:":"80"};function serverPortFromUrl(e){const t=Number(e.port||HTTP_PORT_FROM_PROTOCOL[e.protocol]);return t&&!isNaN(t)?t:void 0}const VERSION$2="0.202.0";var AttributeNames;!function(e){e.HTTP_STATUS_TEXT="http.status_text"}(AttributeNames||(AttributeNames={}));const OBSERVER_WAIT_TIME_MS=300;class XMLHttpRequestInstrumentation extends InstrumentationBase$1{component="xml-http-request";version=VERSION$2;moduleName=this.component;_tasksCount=0;_xhrMem=new WeakMap;_usedResources=new WeakSet;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-xml-http-request",VERSION$2,e),this._semconvStability=semconvStabilityFromStr$1("http",e?.semconvStabilityOptIn)}init(){}_addHeaders(e,t){if(!shouldPropagateTraceHeaders(parseUrl(t).href,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return propagation.inject(context.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}const r={};propagation.inject(context.active(),r),Object.keys(r).forEach(t=>{e.setRequestHeader(t,String(r[t]))})}_addChildSpan(e,t){context.with(trace.setSpan(context.active(),e),()=>{const e=this.tracer.startSpan("CORS Preflight",{startTime:t[PerformanceTimingNames.FETCH_START]}),r=!(this._semconvStability&SemconvStability$1.OLD);addSpanNetworkEvents(e,t,this.getConfig().ignoreNetworkEvents,void 0,r),e.end(t[PerformanceTimingNames.RESPONSE_END])})}_addFinalSpanAttributes(e,t,r){if(this._semconvStability&SemconvStability$1.OLD){if(void 0!==t.status&&e.setAttribute(ATTR_HTTP_STATUS_CODE,t.status),void 0!==t.statusText&&e.setAttribute(AttributeNames.HTTP_STATUS_TEXT,t.statusText),"string"==typeof r){const t=parseUrl(r);e.setAttribute(ATTR_HTTP_HOST,t.host),e.setAttribute(ATTR_HTTP_SCHEME,t.protocol.replace(":",""))}e.setAttribute(ATTR_HTTP_USER_AGENT,navigator.userAgent)}this._semconvStability&SemconvStability$1.STABLE&&t.status&&e.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,t.status)}_applyAttributesAfterXHR(e,t){const r=this.getConfig().applyCustomAttributesOnSpan;"function"==typeof r&&safeExecuteInTheMiddle$1(()=>r(e,t),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)})}_addResourceObserver(e,t){const r=this._xhrMem.get(e);r&&"function"==typeof PerformanceObserver&&"function"==typeof PerformanceResourceTiming&&(r.createdResources={observer:new PerformanceObserver(e=>{const n=e.getEntries(),i=parseUrl(t);n.forEach(e=>{"xmlhttprequest"===e.initiatorType&&e.name===i.href&&r.createdResources&&r.createdResources.entries.push(e)})}),entries:[]},r.createdResources.observer.observe({entryTypes:["resource"]}))}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(otperformance.clearResourceTimings(),this._xhrMem=new WeakMap,this._usedResources=new WeakSet)}_findResourceAndAddNetworkEvents(e,t,r,n,i){if(!(r&&n&&i&&e.createdResources))return;let o=e.createdResources.entries;o&&o.length||(o=otperformance.getEntriesByType("resource"));const s=getResource(parseUrl(r).href,n,i,o,this._usedResources);if(s.mainRequest){const e=s.mainRequest;this._markResourceAsUsed(e);const r=s.corsPreFlightRequest;r&&(this._addChildSpan(t,r),this._markResourceAsUsed(r));const n=!(this._semconvStability&SemconvStability$1.OLD);addSpanNetworkEvents(t,e,this.getConfig().ignoreNetworkEvents,void 0,n)}}_cleanPreviousSpanInformation(e){const t=this._xhrMem.get(e);if(t){const r=t.callbackToRemoveEvents;r&&r(),this._xhrMem.delete(e)}}_createSpan(e,t,r){if(isUrlIgnored(t,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let n="";const i=parseUrl(t),o={};if(this._semconvStability&SemconvStability$1.OLD&&(n=r.toUpperCase(),o[ATTR_HTTP_METHOD]=r,o[ATTR_HTTP_URL]=i.toString()),this._semconvStability&SemconvStability$1.STABLE){const e=r,t=normalizeHttpRequestMethod(r);n||(n=t),o[ATTR_HTTP_REQUEST_METHOD]=t,t!==e&&(o[ATTR_HTTP_REQUEST_METHOD_ORIGINAL]=e),o[ATTR_URL_FULL]=i.toString(),o[ATTR_SERVER_ADDRESS]=i.hostname;const s=serverPortFromUrl(i);s&&(o[ATTR_SERVER_PORT]=s)}const s=this.tracer.startSpan(n,{kind:SpanKind.CLIENT,attributes:o});return s.addEvent(EventNames.METHOD_OPEN),this._cleanPreviousSpanInformation(e),this._xhrMem.set(e,{span:s,spanUrl:t}),s}_markResourceAsUsed(e){this._usedResources.add(e)}_patchOpen(){return e=>{const t=this;return function(...r){const n=r[0],i=r[1];return t._createSpan(this,i,n),e.apply(this,r)}}}_patchSend(){const e=this;function t(t,r,n,i){const o=e._xhrMem.get(r);if(!o)return;if(o.status=r.status,o.statusText=r.statusText,e._xhrMem.delete(r),o.span){const t=o.span;e._applyAttributesAfterXHR(t,r),e._semconvStability&SemconvStability$1.STABLE&&(n?i&&(t.setStatus({code:SpanStatusCode.ERROR,message:i}),t.setAttribute(ATTR_ERROR_TYPE,i)):o.status&&o.status>=400&&(t.setStatus({code:SpanStatusCode.ERROR}),t.setAttribute(ATTR_ERROR_TYPE,String(o.status))))}const s=hrTime(),a=Date.now();setTimeout(()=>{!function(t,r,n,i){const o=r.callbackToRemoveEvents;"function"==typeof o&&o();const{span:s,spanUrl:a,sendStartTime:c}=r;s&&(e._findResourceAndAddNetworkEvents(r,s,a,c,n),s.addEvent(t,i),e._addFinalSpanAttributes(s,r,a),s.end(i),e._tasksCount--),e._clearResources()}(t,o,s,a)},OBSERVER_WAIT_TIME_MS)}function r(){t(EventNames.EVENT_ERROR,this,!0,"error")}function n(){t(EventNames.EVENT_ABORT,this,!1)}function i(){t(EventNames.EVENT_TIMEOUT,this,!0,"timeout")}function o(){this.status<299?t(EventNames.EVENT_LOAD,this,!1):t(EventNames.EVENT_ERROR,this,!1)}return t=>function(...s){const a=e._xhrMem.get(this);if(!a)return t.apply(this,s);const c=a.span,l=a.spanUrl;if(c&&l){if(e.getConfig().measureRequestSize&&s?.[0]){const t=getXHRBodyLength(s[0]);void 0!==t&&(e._semconvStability&SemconvStability$1.OLD&&c.setAttribute(ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,t),e._semconvStability&SemconvStability$1.STABLE&&c.setAttribute(ATTR_HTTP_REQUEST_BODY_SIZE,t))}context.with(trace.setSpan(context.active(),c),()=>{e._tasksCount++,a.sendStartTime=hrTime(),c.addEvent(EventNames.METHOD_SEND),this.addEventListener("abort",n),this.addEventListener("error",r),this.addEventListener("load",o),this.addEventListener("timeout",i),a.callbackToRemoveEvents=()=>{!function(t){t.removeEventListener("abort",n),t.removeEventListener("error",r),t.removeEventListener("load",o),t.removeEventListener("timeout",i);const s=e._xhrMem.get(t);s&&(s.callbackToRemoveEvents=void 0)}(this),a.createdResources&&a.createdResources.observer.disconnect()},e._addHeaders(this,l),e._addResourceObserver(this,l)})}return t.apply(this,s)}}enable(){this._diag.debug("applying patch to",this.moduleName,this.version),isWrapped$1(XMLHttpRequest.prototype.open)&&(this._unwrap(XMLHttpRequest.prototype,"open"),this._diag.debug("removing previous patch from method open")),isWrapped$1(XMLHttpRequest.prototype.send)&&(this._unwrap(XMLHttpRequest.prototype,"send"),this._diag.debug("removing previous patch from method send")),this._wrap(XMLHttpRequest.prototype,"open",this._patchOpen()),this._wrap(XMLHttpRequest.prototype,"send",this._patchSend())}disable(){this._diag.debug("removing patch from",this.moduleName,this.version),this._unwrap(XMLHttpRequest.prototype,"open"),this._unwrap(XMLHttpRequest.prototype,"send"),this._tasksCount=0,this._xhrMem=new WeakMap,this._usedResources=new WeakSet}}var esm$3=Object.freeze({__proto__:null,XMLHttpRequestInstrumentation:XMLHttpRequestInstrumentation}),require$$13=getAugmentedNamespace(esm$3);let NoopLogger$1=class{emit(e){}};const NOOP_LOGGER$1=new NoopLogger$1;class NoopLoggerProvider{getLogger(e,t,r){return new NoopLogger$1}}const NOOP_LOGGER_PROVIDER=new NoopLoggerProvider;class ProxyLogger{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$1}}class ProxyLoggerProvider{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}}const _globalThis="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY=Symbol.for("io.opentelemetry.js.api.logs"),_global$1=_globalThis;function makeGetter(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION=1;class LogsAPI{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider}static getInstance(){return this._instance||(this._instance=new LogsAPI),this._instance}setGlobalLoggerProvider(e){return _global$1[GLOBAL_LOGS_API_KEY]?this.getLoggerProvider():(_global$1[GLOBAL_LOGS_API_KEY]=makeGetter(API_BACKWARDS_COMPATIBILITY_VERSION,e,NOOP_LOGGER_PROVIDER),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$1[GLOBAL_LOGS_API_KEY])||void 0===e?void 0:e.call(_global$1,API_BACKWARDS_COMPATIBILITY_VERSION))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$1[GLOBAL_LOGS_API_KEY],this._proxyLoggerProvider=new ProxyLoggerProvider}}const logs$1=LogsAPI.getInstance();function enableInstrumentations(e,t,r,n){for(let i=0,o=e.length;ie.disable())}function registerInstrumentations(e){const t=e.tracerProvider||trace.getTracerProvider(),r=e.meterProvider||metrics$1.getMeterProvider(),n=e.loggerProvider||logs$1.getLoggerProvider(),i=e.instrumentations?.flat()??[];return enableInstrumentations(i,t,r,n),()=>{disableInstrumentations(i)}}let logger$1=console.error.bind(console);function defineProperty$2(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$1=(e,t,r)=>{if(!e||!e[t])return void logger$1("no original function "+String(t)+" to wrap");if(!r)return logger$1("no wrapper function"),void logger$1((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$1("original object and wrapper must be functions");const i=r(n,t);return defineProperty$2(i,"__original",n),defineProperty$2(i,"__unwrap",()=>{e[t]===i&&defineProperty$2(e,t,n)}),defineProperty$2(i,"__wrapped",!0),defineProperty$2(e,t,i),i},massWrap=(e,t,r)=>{if(!e)return logger$1("must provide one or more modules to patch"),void logger$1((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$1(e,t,r)})}):logger$1("must provide one or more functions to wrap on modules")},unwrap$1=(e,t)=>{if(!e||!e[t])return logger$1("no function to unwrap."),void logger$1((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$1("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap=(e,t)=>{if(!e)return logger$1("must provide one or more modules to patch"),void logger$1((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$1(e,t)})}):logger$1("must provide one or more functions to unwrap on modules")};class InstrumentationAbstract{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$1.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$1;_unwrap=unwrap$1;_massWrap=massWrap;_massUnwrap=massUnwrap;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}}class InstrumentationBase extends InstrumentationAbstract{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}}function normalize(e){return diag.warn("Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)"),e}class InstrumentationNodeModuleDefinition{name;supportedVersions;patch;unpatch;files;constructor(e,t,r,n,i){this.name=e,this.supportedVersions=t,this.patch=r,this.unpatch=n,this.files=i||[]}}class InstrumentationNodeModuleFile{supportedVersions;patch;unpatch;name;constructor(e,t,r,n){this.supportedVersions=t,this.patch=r,this.unpatch=n,this.name=normalize(e)}}function safeExecuteInTheMiddle(e,t,r){let n,i;try{i=e()}catch(e){n=e}finally{if(t(n,i),n&&!r)throw n;return i}}async function safeExecuteInTheMiddleAsync(e,t,r){let n,i;try{i=await e()}catch(e){n=e}finally{if(t(n,i),n&&!r)throw n;return i}}function isWrapped(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var SemconvStability;function semconvStabilityFromStr(e,t){let r=SemconvStability.OLD;const n=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of n??[]){if(t.toLowerCase()===e+"/dup"){r=SemconvStability.DUPLICATE;break}t.toLowerCase()===e&&(r=SemconvStability.STABLE)}return r}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(SemconvStability||(SemconvStability={}));var esm$2=Object.freeze({__proto__:null,InstrumentationBase:InstrumentationBase,InstrumentationNodeModuleDefinition:InstrumentationNodeModuleDefinition,InstrumentationNodeModuleFile:InstrumentationNodeModuleFile,get SemconvStability(){return SemconvStability},isWrapped:isWrapped,registerInstrumentations:registerInstrumentations,safeExecuteInTheMiddle:safeExecuteInTheMiddle,safeExecuteInTheMiddleAsync:safeExecuteInTheMiddleAsync,semconvStabilityFromStr:semconvStabilityFromStr}),require$$14=getAugmentedNamespace(esm$2),__createBinding=commonjsGlobal$1&&commonjsGlobal$1.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),__setModuleDefault=commonjsGlobal$1&&commonjsGlobal$1.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=commonjsGlobal$1&&commonjsGlobal$1.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&__createBinding(t,e,r);return __setModuleDefault(t,e),t},__awaiter=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},__importDefault=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(manager$2,"__esModule",{value:!0}),manager$2.TracesManager=void 0;const api_1$1=require$$13$1,utils_1=requireUtils(),manager_1$2=manager$1,tracingState_1=tracingState,withSpan_1=withSpan,nullTracingState_1=__importDefault(nullTracingState),traces_1=__importStar(requireTraces()),constants_1$1=constants$3,otelUtils_1$1=otelUtils,safe_stringify_1$3=safeStringify$1,instrumentation_document_load_1=require$$10,instrumentation_user_interaction_1=require$$11,instrumentation_fetch_1=require$$12,instrumentation_xml_http_request_1=require$$13,instrumentation_1=require$$14,container_1$3=container$1;class TracesManager{constructor(e,t,r,n,i,o,s,a,c,l,u){var d,h,p,g,m,f;this.otelSettings=e,this.logger=t,this.traceLogger=r,this.started=!1,this.traceLogger=null!==(d=this.traceLogger)&&void 0!==d?d:this.logger,this.settings=e.traces||{enabled:!1},!1!==e.logSettingsOnStartup&&(null==t||t.info(`Starting TracesManager with settings ${(0,safe_stringify_1$3.safeStringify)(this.settings)}`)),this.filters=this.settings.filters||[];if((new manager_1$2.TracesManagerValidator).validate(this),(0,utils_1.setTracerProvider)(n,i,o,s,a,c,l,this.logger,e),this.settings.autoInstrumentations){const e=this.settings.autoInstrumentations,t="object"==typeof e.documentLoad?e.documentLoad:void 0,r="object"==typeof e.userInteraction?e.userInteraction:void 0,n="object"==typeof e.fetch?e.fetch:void 0,i="object"==typeof e.xhr?e.xhr:void 0;(0,instrumentation_1.registerInstrumentations)({instrumentations:[e.documentLoad&&new instrumentation_document_load_1.DocumentLoadInstrumentation(t),e.userInteraction&&new instrumentation_user_interaction_1.UserInteractionInstrumentation(Object.assign(Object.assign({eventNames:["submit","click","keypress"]},r),{shouldPreventSpanCreation:(e,t,n)=>{var i;return n.setAttribute("target.id",t.id),null===(i=null==r?void 0:r.shouldPreventSpanCreation)||void 0===i?void 0:i.call(r,e,t,n)}})),e.fetch&&new instrumentation_fetch_1.FetchInstrumentation(n),e.xhr&&new instrumentation_xml_http_request_1.XMLHttpRequestInstrumentation(Object.assign(Object.assign({},i),{ignoreUrls:!1!==e.ignoreObservabilityUrls?[...(null==i?void 0:i.ignoreUrls)||[],this.settings.url,null===(h=this.otelSettings.metrics)||void 0===h?void 0:h.url,null===(p=this.otelSettings.logs)||void 0===p?void 0:p.url].filter(e=>e):null==i?void 0:i.ignoreUrls}))].filter(e=>e)})}traces_1.default.instance=this,null!==this.settings.countMetric&&(this.traceMetric=null==u?void 0:u.getFromSettings({enabled:!0,description:"Counts number of hits for io.Insights spans",name:null!==(g=this.settings.countMetric)&&void 0!==g?g:"insights_trace_count",type:"custom_counter"})),null!==this.settings.resultMetric&&(this.traceMetricResult=null==u?void 0:u.getFromSettings({enabled:!0,description:"Counts results of io.Insights spans",name:null!==(m=this.settings.resultMetric)&&void 0!==m?m:"insights_trace_result",type:"custom_counter"})),null!==this.settings.durationMetric&&(this.traceMetricDuration=null==u?void 0:u.getFromSettings({enabled:!0,description:"Counts durations of io.Insights spans",name:null!==(f=this.settings.durationMetric)&&void 0!==f?f:"insights_trace_duration",type:"custom_histogram"}))}waitForFinalExport(e){return Promise.resolve()}get currentTracingState(){return this.resolveCurrentTracingState()}set currentTracingState(e){traces_1.default.currentTracingState=e}resolveCurrentTracingState(){if(this.settings.useOTELContextManager){const e=api_1$1.context.active(),t=null==e?void 0:e.getValue(Symbol.for("interopio.insights.currentTracingStateGetter"));return"function"==typeof t?t():null}return(0,traces_1.getCurrentTracingStateInternal)()}withSpan(e,t,r,n,i){var o,s,a,c,l,u,d,h,p,g,m,f;(new withSpan_1.TracesWithSpanValidator).validate(e,t,r,n,i);let y={};(0,utils_1.isFunctionType)(t)||(y=Object.assign({},t));const $=Object.assign(Object.assign({},container_1$3.Container.errorless(this.settings.additionalAttributes)),y),b=Object.assign(Object.assign({},container_1$3.Container.errorless(this.settings.additionalResourceAttributes)),$),v=n,w=this.filters.concat((!1!==this.settings.useDefaultFilters&&null!==(o=null==v?void 0:v.defaultFilters)&&void 0!==o?o:[]).map(t=>Object.assign(Object.assign({},t),{source:e}))),S=(0,utils_1.findMatchingFilters)(w,b,e);null===(s=this.logger)||void 0===s||s.debug(`beginSpan() source:${e} context:${b} `+(S?"filter: "+JSON.stringify(S):"default: "+JSON.stringify(this.settings.defaults)));let _=api_1$1.context.active(),E=null;!0!==(null==S?void 0:S.disableNesting)&&!0!==(null==v?void 0:v.disableNesting)&&(E||r&&"function"!=typeof r&&(E=traces_1.default.extractPropagationInfo(r)),E||"function"!=typeof(null==v?void 0:v.getPropagationInfo)||(E=null==v?void 0:v.getPropagationInfo(e,b)),E||"function"!=typeof(null===(c=null===(a=this.settings)||void 0===a?void 0:a.defaults)||void 0===c?void 0:c.getPropagationInfo)||(E=null===(u=null===(l=this.settings)||void 0===l?void 0:l.defaults)||void 0===u?void 0:u.getPropagationInfo(e,b)),E||(traces_1.default.currentTracingState&&!0!==this.settings.useOTELContextManager?E=traces_1.default.currentTracingState.getPropagationInfo():this.settings.useOTELContextManager&&(E=(null===(d=this.resolveCurrentTracingState())||void 0===d?void 0:d.getPropagationInfo())||null))),_=E?api_1$1.propagation.extract(api_1$1.context.active(),E):api_1$1.ROOT_CONTEXT;const C=this.resolveProperty("canBeRoot",S,v),I=this.started&&((null==E?void 0:E.forceTracing)||(0,utils_1.isSpanEnabled)(S,v,this.settings.defaults))&&(C||!!E),T=I&&(null!==(h=null==E?void 0:E.forceTracing)&&void 0!==h?h:this.resolveProperty("forceChildTracing",S,v)),A=this.resolveProperty("level",S,v),D=this.resolveProperty(I?"countMetric":"countMetricOnDisabledSpans",S,v),x=this.resolveProperty("maxAttributeDepth",S,v);D&&(null===(g=null===(p=this.traceMetric)||void 0===p?void 0:p.add)||void 0===g||g.call(p,1,Object.assign({source:e},(0,otelUtils_1$1.flattenOtelAtributes)($,x))));const R=this.resolveProperty(I?"resultMetric":"resultMetricOnDisabledSpans",S,v),O=this.resolveProperty(I?"durationMetric":"durationMetricOnDisabledSpans",S,v),N=this.resolveProperty(I?"log":"logOnDisabledSpans",S,v),P=this.resolveProperty("minDurationMs",S,v);let k;if(null===(m=this.logger)||void 0===m||m.debug(JSON.stringify({started:this.started,enabled:I,level:A})),"function"==typeof t)k=i=t;else if("function"==typeof r)k=i=r;else if("function"==typeof n)k=i=n;else{if(!i)throw new Error("callback agument must be provided");k=i}const M=this.resolveProperty("disablePropagation",S,v);if(I){const t=api_1$1.trace.getTracer(e);let r=null;_=_.setValue(Symbol.for(constants_1$1.Defaults.currentTracingStateGetterContextName),()=>r);const n=this.resolveProperty("otelSpanOptions",S,v);return t.startActiveSpan(e,n,_,t=>{r=new tracingState_1.TracingState(e,A,t,this.logger,constants_1$1.Defaults.TRACE_VERSION,M,T,x,_),P&&(0,utils_1.saveDataInAttribute)({insightsMinDurationMs:P},t,x),this.otelSettings.platformVersion&&(0,utils_1.saveDataInAttribute)({platformVersion:this.otelSettings.platformVersion},t,x),this.otelSettings.additionalAttributes&&(0,utils_1.saveDataInAttribute)(container_1$3.Container.errorlessDefined(this.otelSettings.additionalAttributes,{}),t,x),this.settings.additionalAttributes&&(0,utils_1.saveDataInAttribute)(container_1$3.Container.errorlessDefined(this.settings.additionalAttributes,{}),t,x);return this.resolveProperty("addContextToTrace",S,v)&&(0,utils_1.saveDataInAttribute)($,t,x),this.handleCallbackAndResult(r,k,S,v,R,O,N,$,x)})}{let t=null;if(!this.resolveProperty("stopPropagationIfSpanIsDisabled",S,v))if(r){let e={};(0,utils_1.isFunctionType)(r)||(e=Object.assign({},r)),t=traces_1.default.extractPropagationInfo(e)}else traces_1.default.currentTracingState&&!0!==this.settings.useOTELContextManager?t=traces_1.default.currentTracingState.getPropagationInfo():this.settings.useOTELContextManager&&(E=(null===(f=this.resolveCurrentTracingState())||void 0===f?void 0:f.getPropagationInfo())||null);const n=new nullTracingState_1.default(e,t,M);return _=_.setValue(Symbol.for(constants_1$1.Defaults.currentTracingStateGetterContextName),()=>n),api_1$1.context.with(_,()=>this.handleCallbackAndResult(n,k,S,v,R,O,N,$,x))}}handleCallbackAndResult(e,t,r,n,i,o,s,a,c){var l,u,d,h,p;const g=new Date,m=null===(p=null!==(u=null!==(l=null==r?void 0:r.autoSetSuccessStatus)&&void 0!==l?l:null==n?void 0:n.addContextToTrace)&&void 0!==u?u:null===(h=null===(d=this.settings)||void 0===d?void 0:d.defaults)||void 0===h?void 0:h.autoSetSuccessStatus)||void 0===p||p;let f;try{traces_1.default.currentTracingState=e;const r=t(e);return traces_1.default.currentTracingState=null,f=r&&"function"==typeof r.then&&"function"==typeof r.catch&&"function"==typeof r.finally,f?r.then(y.bind(this)).catch($.bind(this)).finally(b.bind(this)):y.apply(this,[r])}catch(e){$.call(this,e)}finally{f||b.apply(this)}function y(t){var r;return m&&(null===(r=e.status)||void 0===r?void 0:r.code)===api_1$1.SpanStatusCode.UNSET&&(e.status={code:api_1$1.SpanStatusCode.OK}),t}function $(t){throw e.status={message:"string"==typeof t?t:null==t?void 0:t.message,code:api_1$1.SpanStatusCode.ERROR},e.recordException(t),t}function b(){var t,r,n,l,u,d,h,p,m,f,y,$,b,v,w,S;if(i&&(null===(r=null===(t=this.traceMetricResult)||void 0===t?void 0:t.add)||void 0===r||r.call(t,1,Object.assign(Object.assign({source:e.source},(0,otelUtils_1$1.flattenOtelAtributes)(a,c)),{code:e.status.code}))),o&&(null===(l=null===(n=this.traceMetricDuration)||void 0===n?void 0:n.record)||void 0===l||l.call(n,(new Date).getTime()-g.getTime(),Object.assign({source:e.source},(0,otelUtils_1$1.flattenOtelAtributes)(a,c)))),e.end(),s){let t="none";switch(e.level){case"OFF":t="none";break;case"LOWEST":case"DIAGNOSTIC":t="verbose";break;case"DEBUG":t="debug";break;case"INFO":t="info";break;case"WARN":t="warn";break;case"HIGHEST":t="error"}if("none"!==t){const r=null!==(h=null===(d=null===(u=null==e?void 0:e.span)||void 0===u?void 0:u.parentSpanContext)||void 0===d?void 0:d.spanId)&&void 0!==h?h:"0000000000000000",n=`${e.traceId}-${e.id}-${r}`,i=1e3*(null===(m=null===(p=e.span)||void 0===p?void 0:p.endTime)||void 0===m?void 0:m[0])+(null===(y=null===(f=e.span)||void 0===f?void 0:f.endTime)||void 0===y?void 0:y[1])/1e6-1e3*(null===(b=null===($=e.span)||void 0===$?void 0:$.startTime)||void 0===b?void 0:b[0])-(null===(w=null===(v=e.span)||void 0===v?void 0:v.startTime)||void 0===w?void 0:w[1])/1e6;this.traceLogger[t](`span ${n} ${e.source} ${Math.floor(i)} ${JSON.stringify(null===(S=null==e?void 0:e.span)||void 0===S?void 0:S.attributes)}`)}}}}start(){return __awaiter(this,void 0,void 0,function*(){this.started=!0})}stop(){return __awaiter(this,void 0,void 0,function*(){this.started=!1})}resolveProperty(e,t,r,n){var i,o,s,a,c,l;return null!==(l=null!==(c=null!==(o=null!==(i=null==t?void 0:t[e])&&void 0!==i?i:null==r?void 0:r[e])&&void 0!==o?o:null===(a=null===(s=this.settings)||void 0===s?void 0:s.defaults)||void 0===a?void 0:a[e])&&void 0!==c?c:constants_1$1.Defaults[e])&&void 0!==l?l:n}}manager$2.TracesManager=TracesManager,Object.defineProperty(builder$2,"__esModule",{value:!0}),builder$2.TracesManagerBuilder=void 0;const manager_1$1=manager$2,nullTracesManager_1$1=requireNullTracesManager(),container_1$2=container$1;class TracesManagerBuilder{constructor(){this.traceLogger=null}withLogger(e){return this.logger=e,this}withTraceLogger(e){return this.traceLogger=e,this}withSettings(e){return this.settings=e,this}withMetrics(e){return this.metrics=e,this}withTracerProvider(e){return this.tracerProvider=e,this}withSamplerGetter(e){return this.samplerGetter=e,this}withSpanProcessors(e){return this.spanProcessors=e,this}withSpanExporters(e){return this.spanExporters=e,this}withProviderRegistrationSettings(e){var t;return this.providerRegistrationSettings=Object.assign({contextManager:null===(t=this.providerRegistrationSettings)||void 0===t?void 0:t.contextManager},e),this}withContextManager(e){return this.providerRegistrationSettings=Object.assign(Object.assign({},this.providerRegistrationSettings),{contextManager:e}),this.contextManager=e,this}withPropagator(e){return this.providerRegistrationSettings=Object.assign(Object.assign({},this.providerRegistrationSettings),{propagator:e}),this.propagator=e,this}build(){return this.contextManager&&this.settings.traces&&(this.settings.traces.useOTELContextManager=!0),this.buildCore()}buildCore(){var e,t,r,n,i,o;if(!0!==(null===(e=this.settings)||void 0===e?void 0:e.enabled)||!0!==(null===(r=null===(t=this.settings)||void 0===t?void 0:t.traces)||void 0===r?void 0:r.enabled))return new nullTracesManager_1$1.NullTracesManager(null===(n=this.settings)||void 0===n?void 0:n.traces,this.settings,this.logger);return new manager_1$1.TracesManager(this.settings,this.logger,null!==(i=this.traceLogger)&&void 0!==i?i:this.logger,this.getOrMake("contextManager"),this.getOrMake("propagator"),this.getOrMake("tracerProvider"),null===(o=this.settings.traces)||void 0===o?void 0:o.samplerGetter,this.getOrMake("spanProcessors"),this.getOrMake("spanExporters"),this.getOrMake("providerRegistrationSettings"),this.metrics)}getOrMake(e,t){var r,n,i,o;return this[e]?this[e]:!1!==t&&"function"==typeof(null===(n=null===(r=this.settings)||void 0===r?void 0:r.traces)||void 0===n?void 0:n[e])?container_1$2.Container.errorless(()=>{var t,r;return null===(r=(t=this.settings.traces)[e])||void 0===r?void 0:r.call(t)}):null===(o=null===(i=this.settings)||void 0===i?void 0:i.traces)||void 0===o?void 0:o[e]}}builder$2.TracesManagerBuilder=TracesManagerBuilder;var _null$3={};Object.defineProperty(_null$3,"__esModule",{value:!0}),_null$3.NullLogger=void 0;class NullLogger{get level(){return 60}error(){}warn(){}info(){}debug(){}verbose(){}}_null$3.NullLogger=NullLogger;var builder$1={};Object.defineProperty(builder$1,"__esModule",{value:!0}),builder$1.BuilderValidator=void 0;const validator_1=validator$1;class BuilderValidator{validate(e){validator_1.Validator.throwIfNullOrUndefined(e,"builder"),validator_1.Validator.throwIfNullOrUndefined(e.logger,"logger")}}builder$1.BuilderValidator=BuilderValidator;var nullManager={};Object.defineProperty(nullManager,"__esModule",{value:!0}),nullManager.NullLogsManager=void 0;const nullManager_1$2=nullManager$1,safe_stringify_1$2=safeStringify$1;class NullLogsManager extends nullManager_1$2.NullManager{constructor(e,t,r){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==r||r.info(`Starting NullLogsManager with settings ${(0,safe_stringify_1$2.safeStringify)(e)}`)),super()}emit(e){return null}}nullManager.NullLogsManager=NullLogsManager;var manager={};class OTLPLogExporter extends OTLPExporterBase{constructor(e={}){super(createLegacyOtlpBrowserExportDelegate(e,JsonLogsSerializer,"v1/logs",{"Content-Type":"application/json"}))}}var esm$1=Object.freeze({__proto__:null,OTLPLogExporter:OTLPLogExporter}),require$$0$1=getAugmentedNamespace(esm$1);class NoopLogger{emit(e){}}const NOOP_LOGGER=new NoopLogger;function defaultServiceName(){return"unknown_service"}const isPromiseLike=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;class ResourceImpl{_rawAttributes;_asyncAttributesPending=!1;_memoizedAttributes;static FromAttributeList(e){const t=new ResourceImpl({});return t._rawAttributes=e,t._asyncAttributesPending=e.filter(([e,t])=>isPromiseLike(t)).length>0,t}constructor(e){const t=e.attributes??{};this._rawAttributes=Object.entries(t).map(([e,t])=>(isPromiseLike(t)&&(this._asyncAttributesPending=!0),[e,t]))}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e0?(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(1===this.droppedAttributesCount&&diag.warn("Dropping extra attributes."),this):(isAttributeValue$1(t)?this.attributes[e]=this._truncateToSize(t):this.attributes[e]=t,this)):(diag.warn(`Invalid attribute value set for key: ${e}`),this)}setAttributes(e){for(const[t,r]of Object.entries(e))this.setAttribute(t,r);return this}setBody(e){return this.body=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){const t=this._logRecordLimits.attributeValueLengthLimit;return t<=0?(diag.warn(`Attribute value limit must be positive, got ${t}`),e):"string"==typeof e?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>"string"==typeof e?this._truncateToLimitUtil(e,t):e):e}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_isLogRecordReadonly(){return this._isReadonly&&diag.warn("Can not execute the operation on emitted log record"),this._isReadonly}}let Logger$1=class{instrumentationScope;_sharedState;constructor(e,t){this.instrumentationScope=e,this._sharedState=t}emit(e){const t=e.context||context.active(),r=new LogRecord(this._sharedState,this.instrumentationScope,{context:t,...e});this._sharedState.activeProcessor.onEmit(r,t),r._makeReadonly()}};function loadDefaultConfig(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128},includeTraceContext:!0}}function reconfigureLimits(e){return{attributeCountLimit:e.attributeCountLimit??getNumberFromEnv$1()??getNumberFromEnv$1()??128,attributeValueLengthLimit:e.attributeValueLengthLimit??getNumberFromEnv$1()??getNumberFromEnv$1()??1/0}}class MultiLogRecordProcessor{processors;forceFlushTimeoutMillis;constructor(e,t){this.processors=e,this.forceFlushTimeoutMillis=t}async forceFlush(){const e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(t=>callWithTimeout$1(t.forceFlush(),e)))}onEmit(e,t){this.processors.forEach(r=>r.onEmit(e,t))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}}class NoopLogRecordProcessor{forceFlush(){return Promise.resolve()}onEmit(e,t){}shutdown(){return Promise.resolve()}}class LoggerProviderSharedState{resource;forceFlushTimeoutMillis;logRecordLimits;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,t,r){this.resource=e,this.forceFlushTimeoutMillis=t,this.logRecordLimits=r,this.activeProcessor=new NoopLogRecordProcessor}}const DEFAULT_LOGGER_NAME="unknown";class LoggerProvider{_shutdownOnce;_sharedState;constructor(e={}){const t=merge$3({},loadDefaultConfig(),e),r=e.resource??defaultResource();this._sharedState=new LoggerProviderSharedState(r,t.forceFlushTimeoutMillis,reconfigureLimits(t.logRecordLimits)),this._shutdownOnce=new BindOnceFuture$1(this._shutdown,this)}getLogger(e,t,r){if(this._shutdownOnce.isCalled)return diag.warn("A shutdown LoggerProvider cannot provide a Logger"),NOOP_LOGGER;e||diag.warn("Logger requested without instrumentation scope name.");const n=e||DEFAULT_LOGGER_NAME,i=`${n}@${t||""}:${r?.schemaUrl||""}`;return this._sharedState.loggers.has(i)||this._sharedState.loggers.set(i,new Logger$1({name:n,version:t,schemaUrl:r?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(i)}addLogRecordProcessor(e){0===this._sharedState.registeredLogRecordProcessors.length&&this._sharedState.activeProcessor.shutdown().catch(e=>diag.error("Error while trying to shutdown current log record processor",e)),this._sharedState.registeredLogRecordProcessors.push(e),this._sharedState.activeProcessor=new MultiLogRecordProcessor(this._sharedState.registeredLogRecordProcessors,this._sharedState.forceFlushTimeoutMillis)}forceFlush(){return this._shutdownOnce.isCalled?(diag.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(diag.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}}class ConsoleLogRecordExporter{export(e,t){this._sendLogRecords(e,t)}shutdown(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,timestamp:hrTimeToMicroseconds$2(e.hrTime),traceId:e.spanContext?.traceId,spanId:e.spanContext?.spanId,traceFlags:e.spanContext?.traceFlags,severityText:e.severityText,severityNumber:e.severityNumber,body:e.body,attributes:e.attributes}}_sendLogRecords(e,t){for(const t of e)console.dir(this._exportInfo(t),{depth:3});t?.({code:ExportResultCode$2.SUCCESS})}}class SimpleLogRecordProcessor{_exporter;_shutdownOnce;_unresolvedExports;constructor(e){this._exporter=e,this._shutdownOnce=new BindOnceFuture$1(this._shutdown,this),this._unresolvedExports=new Set}onEmit(e){if(this._shutdownOnce.isCalled)return;const t=()=>internal$2._export(this._exporter,[e]).then(e=>{e.code!==ExportResultCode$2.SUCCESS&&globalErrorHandler$2(e.error??new Error(`SimpleLogRecordProcessor: log record export failed (status ${e})`))}).catch(globalErrorHandler$2);if(e.resource.asyncAttributesPending){const r=e.resource.waitForAsyncAttributes?.().then(()=>(this._unresolvedExports.delete(r),t()),globalErrorHandler$2);null!=r&&this._unresolvedExports.add(r)}else t()}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports))}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}class InMemoryLogRecordExporter{_finishedLogRecords=[];_stopped=!1;export(e,t){if(this._stopped)return t({code:ExportResultCode$2.FAILED,error:new Error("Exporter has been stopped")});this._finishedLogRecords.push(...e),t({code:ExportResultCode$2.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}}class BatchLogRecordProcessorBase{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,t){this._exporter=e,this._maxExportBatchSize=t?.maxExportBatchSize??getNumberFromEnv$1()??512,this._maxQueueSize=t?.maxQueueSize??getNumberFromEnv$1()??2048,this._scheduledDelayMillis=t?.scheduledDelayMillis??getNumberFromEnv$1()??5e3,this._exportTimeoutMillis=t?.exportTimeoutMillis??getNumberFromEnv$1()??3e4,this._shutdownOnce=new BindOnceFuture$1(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}onEmit(e){this._shutdownOnce.isCalled||this._addToBuffer(e)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}_addToBuffer(e){this._finishedLogRecords.length>=this._maxQueueSize||(this._finishedLogRecords.push(e),this._maybeStartTimer())}_flushAll(){return new Promise((e,t)=>{const r=[],n=Math.ceil(this._finishedLogRecords.length/this._maxExportBatchSize);for(let e=0;e{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),0===this._finishedLogRecords.length?Promise.resolve():new Promise((e,t)=>{callWithTimeout$1(this._export(this._finishedLogRecords.splice(0,this._maxExportBatchSize)),this._exportTimeoutMillis).then(()=>e()).catch(t)})}_maybeStartTimer(){void 0===this._timer&&(this._timer=setTimeout(()=>{this._flushOneBatch().then(()=>{this._finishedLogRecords.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{globalErrorHandler$2(e)})},this._scheduledDelayMillis),unrefTimer$2(this._timer))}_clearTimer(){void 0!==this._timer&&(clearTimeout(this._timer),this._timer=void 0)}_export(e){const t=()=>internal$2._export(this._exporter,e).then(e=>{e.code!==ExportResultCode$2.SUCCESS&&globalErrorHandler$2(e.error??new Error(`BatchLogRecordProcessor: log record export failed (status ${e})`))}).catch(globalErrorHandler$2),r=e.map(e=>e.resource).filter(e=>e.asyncAttributesPending);return 0===r.length?t():Promise.all(r.map(e=>e.waitForAsyncAttributes?.())).then(t,globalErrorHandler$2)}}class BatchLogRecordProcessor extends BatchLogRecordProcessorBase{_visibilityChangeListener;_pageHideListener;constructor(e,t){super(e,t),this._onInit(t)}onShutdown(){"undefined"!=typeof document&&(this._visibilityChangeListener&&document.removeEventListener("visibilitychange",this._visibilityChangeListener),this._pageHideListener&&document.removeEventListener("pagehide",this._pageHideListener))}_onInit(e){!0!==e?.disableAutoFlushOnDocumentHide&&"undefined"!=typeof document&&(this._visibilityChangeListener=()=>{"hidden"===document.visibilityState&&this.forceFlush()},this._pageHideListener=()=>{this.forceFlush()},document.addEventListener("visibilitychange",this._visibilityChangeListener),document.addEventListener("pagehide",this._pageHideListener))}}var esm=Object.freeze({__proto__:null,BatchLogRecordProcessor:BatchLogRecordProcessor,ConsoleLogRecordExporter:ConsoleLogRecordExporter,InMemoryLogRecordExporter:InMemoryLogRecordExporter,LogRecord:LogRecord,LoggerProvider:LoggerProvider,NoopLogRecordProcessor:NoopLogRecordProcessor,SimpleLogRecordProcessor:SimpleLogRecordProcessor}),require$$1=getAugmentedNamespace(esm),logs={};Object.defineProperty(logs,"__esModule",{value:!0}),logs.Logs=void 0;const nullManager_1$1=nullManager;class Logs{static get instance(){return Logs._instance}static set instance(e){Logs._instance=e}static emit(e){return Logs._instance.emit(e)}}logs.Logs=Logs,Logs._instance=new nullManager_1$1.NullLogsManager(void 0,void 0,void 0),Object.defineProperty(manager,"__esModule",{value:!0}),manager.LogsManager=void 0;const exporter_logs_otlp_http_1=require$$0$1,sdk_logs_1=require$$1,resources_1=require$$2,logs_1=logs,otelUtils_1=otelUtils,safe_stringify_1$1=safeStringify$1,container_1$1=container$1;class LogsManager{constructor(e,t,r){var n,i,o,s;this.logger=e,this.settings=t,this.otelSettings=r,this.started=!1,!1!==r.logSettingsOnStartup&&(null==e||e.info(`Starting LogManager with settings ${(0,safe_stringify_1$1.safeStringify)(t)}`));const a=(0,resources_1.resourceFromAttributes)(null!==(n=container_1$1.Container.errorless(t.additionalResourceAttributes))&&void 0!==n?n:{});this.additionalAttributes=()=>{var e,r;return(0,otelUtils_1.flattenOtelAtributes)(null!==(e=container_1$1.Container.errorless(this.settings.additionalAttributes))&&void 0!==e?e:{},null!==(r=t.maxAttributeDepth)&&void 0!==r?r:5)};const c=null!==(i=t.loggerProvider)&&void 0!==i?i:new sdk_logs_1.LoggerProvider(Object.assign({resource:a},t.providerSettings));if(null===(o=t.logExporters)||void 0===o?void 0:o.length)for(const e of t.logExporters)c.addLogRecordProcessor(new sdk_logs_1.BatchLogRecordProcessor(e,t.batchSettings));if(null===(s=t.logProcessors)||void 0===s?void 0:s.length)for(const e of t.logProcessors)c.addLogRecordProcessor(e);t.url&&c.addLogRecordProcessor(new sdk_logs_1.BatchLogRecordProcessor(new exporter_logs_otlp_http_1.OTLPLogExporter(Object.assign({url:t.url,keepAlive:t.keepAlive,headers:Object.assign(Object.assign({},container_1$1.Container.errorless(r.headers)),container_1$1.Container.errorless(t.headers))},t.exporterSettings)),t.batchSettings)),this.loggerOtel=c.getLogger("default"),logs_1.Logs.instance=this}emit(e){if(this.started){if(!this.applyFilters(e))return Promise.resolve();this.loggerOtel.emit(e)}return Promise.resolve()}applyFilters(e){var t,r,n,i,o;if(!(null===(t=this.settings.filters)||void 0===t?void 0:t.length)&&!this.settings.defaults)return!0;const s=null!==(n=null===(r=this.settings.filters)||void 0===r?void 0:r.find(t=>{var r;return(!t.categoryName||(null===(r=e.attributes)||void 0===r?void 0:r.categoryName)===t.categoryName)&&(!!(!t.severity||e.severityText&&asSevereOrMore(e.severityText,t.severity))&&!(t.bodyRegex&&!new RegExp(t.bodyRegex).test(e.body+"")))}))&&void 0!==n?n:this.settings.defaults;if(!s)return!0;if(!1===s.enabled)return!1;const a=null===(i=this.additionalAttributes)||void 0===i?void 0:i.call(this);for(const t in null!=a?a:{})e.setAttribute(t,a[t]);if(null===(o=s.allowedAttributes)||void 0===o?void 0:o.length)for(const t of Object.keys(e.attributes))~s.allowedAttributes.indexOf(t)||delete e.attributes[t];return s.hideRegex&&(e.body=(e.body+"").replace(new RegExp(s.hideRegex),"*****")),!0}start(){return this.started=!0,Promise.resolve()}stop(){return this.started=!1,Promise.resolve()}waitForFinalExport(e){return Promise.resolve()}}manager.LogsManager=LogsManager;const severityHierarchy=["TRACE","DEBUG","INFO","WARN","ERROR","FATAL"];function asSevereOrMore(e,t){const r=severityHierarchy.indexOf(e.toUpperCase());if(r<0)return!1;const n=severityHierarchy.indexOf(t.toUpperCase());return!(n<0)&&r>=n}Object.defineProperty(builder$7,"__esModule",{value:!0}),builder$7.Builder=void 0;const api_1=require$$13$1,builder_1=builder$6,builder_2=builder$2,null_1=_null$3,builder_3=builder$1,container_1=container$1,nullMetricsManager_1=nullMetricsManager,nullTracesManager_1=requireNullTracesManager(),nullManager_1=nullManager,manager_1=manager,safe_stringify_1=safeStringify$1,constants_1=constants$3;let Builder$1=class e{constructor(){this.logger=new null_1.NullLogger}withLogger(e){var t;if(this.logger=null!=e?e:this.logger,this.logger.level){const e=null===(t=this.logger.level)||void 0===t?void 0:t.valueOf();api_1.diag.setLogger(this.logger,e)}else api_1.diag.setLogger(this.logger,70);return this}withSettings(e){return this.settings=e,this}withMetrics(){return this.metricsBuilder=new builder_1.MetricsManagerBuilder,this.metricsBuilder.withLogger(this.logger),this.metricsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.metricsBuilder}withTraces(){return this.tracesBuilder=new builder_2.TracesManagerBuilder,this.tracesBuilder.withLogger(this.logger),this.tracesBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.tracesBuilder}build(){return(new builder_3.BuilderValidator).validate(this),this.buildCore()}buildCore(){var t,r,n,i,o,s,a,c,l,u;this.settings=null!==(t=this.settings)&&void 0!==t?t:{enabled:!1};const d=Object.assign({enabled:!1},this.settings);if(!1!==(null===(r=this.settings)||void 0===r?void 0:r.logSettingsOnStartup)&&this.logger.info(`Starting interop.io OTEL with settings ${(0,safe_stringify_1.safeStringify)(this.settings)}`),!1!==(null===(n=this.settings)||void 0===n?void 0:n.enabled)){if((null===(o=null===(i=this.settings)||void 0===i?void 0:i.metrics)||void 0===o?void 0:o.enabled)&&(null===(s=this.settings)||void 0===s?void 0:s.metrics.platformMetricsEnabled)&&!this.metricsBuilder)throw new Error("metrics.platformMetricsEnabled is true, but .withMetrics() method not called.");const t=this.settings.additionalResourceAttributes;this.settings.additionalResourceAttributes=()=>{var e,r,n,i,o,s,a,c,l,u,d,h,p,g,m,f,y,$,b;const v=null!==(e=container_1.Container.errorlessDefined(t,{}))&&void 0!==e?e:{};return Object.assign(Object.assign({},v),{user:null!==(i=null!==(r=v.userId)&&void 0!==r?r:null===(n=this.settings)||void 0===n?void 0:n.userId)&&void 0!==i?i:constants_1.Defaults.DEFAULT_USER,"user.id":null!==(a=null!==(o=v.userId)&&void 0!==o?o:null===(s=this.settings)||void 0===s?void 0:s.userId)&&void 0!==a?a:constants_1.Defaults.DEFAULT_USER,"service.name":null!==(u=null!==(c=v.serviceName)&&void 0!==c?c:null===(l=this.settings)||void 0===l?void 0:l.serviceName)&&void 0!==u?u:constants_1.Defaults.DEFAULT_SERVICE_NAME,"service.instance.id":null!==(p=null!==(d=v.serviceId)&&void 0!==d?d:null===(h=this.settings)||void 0===h?void 0:h.serviceId)&&void 0!==p?p:constants_1.Defaults.DEFAULT_SERVICE_ID,"service.version":null!==(f=null!==(g=v.serviceVersion)&&void 0!==g?g:null===(m=this.settings)||void 0===m?void 0:m.serviceVersion)&&void 0!==f?f:constants_1.Defaults.DEFAULT_SERVICE_VERSION,platformVersion:null!==(b=null!==(y=v.platformVersion)&&void 0!==y?y:null===($=this.settings)||void 0===$?void 0:$.platformVersion)&&void 0!==b?b:constants_1.Defaults.DEFAULT_PLATFORM_VERSION})},e.maybeAddReferenceAttributes(this.settings),e.maybeAddReferenceAttributes(this.settings.logs),e.maybeAddReferenceAttributes(this.settings.metrics),e.maybeAddReferenceAttributes(this.settings.traces),e.propagateAttributesDown("additionalAttributes",this.settings,this.settings.logs),e.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.logs),e.propagateAttributesDown("additionalAttributes",this.settings,this.settings.metrics),e.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.metrics),e.propagateAttributesDown("additionalAttributes",this.settings,this.settings.traces),e.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.traces);const r=(null!==(a=this.metricsBuilder)&&void 0!==a?a:this.withMetrics()).withSettings(this.settings).build(),n=null!==(c=this.tracesBuilder)&&void 0!==c?c:this.withTraces();n.withMetrics(r);const h=n.withSettings(this.settings).build(),p=(null===(u=null===(l=null==this?void 0:this.settings)||void 0===l?void 0:l.logs)||void 0===u?void 0:u.enabled)?new manager_1.LogsManager(this.logger,this.settings.logs,d):new nullManager_1.NullLogsManager(this.settings.logs,d,this.logger);return new container_1.Container(d,h,r,p,this.logger)}return new container_1.Container(d,new nullTracesManager_1.NullTracesManager(this.settings.traces,d,this.logger),new nullMetricsManager_1.NullMetricsManager(this.settings.metrics,d,this.logger),new nullManager_1.NullLogsManager(this.settings.logs,d,this.logger),this.logger)}static propagateAttributesDown(e,t,r){var n,i;if(!r)return;const o=null!==(n=t[e])&&void 0!==n?n:{},s=null!==(i=r[e])&&void 0!==i?i:{};r[e]=()=>Object.assign(Object.assign({},container_1.Container.errorless(o)),container_1.Container.errorless(s))}static maybeAddReferenceAttributes(e){if(null==e?void 0:e.addResourceAttributesToAttributes){const t=e.additionalAttributes,r=e.additionalAttributes;e.additionalAttributes=()=>Object.assign(Object.assign({},container_1.Container.errorless(t)),container_1.Container.errorless(r))}}};builder$7.Builder=Builder$1;var log4jsWrapper={};Object.defineProperty(log4jsWrapper,"__esModule",{value:!0}),log4jsWrapper.Log4jsWrapper=void 0;class Log4jsWrapper{constructor(e){this.logger=e}get level(){return this.convert("level"in this.logger?this.logger.level:this.logger.publishLevel())}error(e,...t){this.logger.warn(e,...t)}warn(e,...t){this.logger.warn(e,...t)}info(e,...t){this.logger.info(e,...t)}debug(e,...t){this.logger.debug(e,...t)}verbose(e,...t){this.logger.trace(e,...t)}convert(e){if(void 0===e)return 60;switch("string"!=typeof e?e.levelStr.toLowerCase():e.toLowerCase()){case"off":return 0;case"error":return 30;case"warn":return 50;case"info":default:return 60;case"debug":return 70;case"trace":return 80}}}log4jsWrapper.Log4jsWrapper=Log4jsWrapper;var builder={},nullPerfProvider={};Object.defineProperty(nullPerfProvider,"__esModule",{value:!0}),nullPerfProvider.NullPerformanceProvider=void 0;class NullPerformanceProvider{getAppsCPU(){return Promise.resolve(void 0)}getAppsMemory(){return Promise.resolve(void 0)}getSystemCPU(){return Promise.resolve(void 0)}getSystemMemory(){return Promise.resolve(void 0)}}nullPerfProvider.NullPerformanceProvider=NullPerformanceProvider,Object.defineProperty(builder,"__esModule",{value:!0}),builder.MetricsDependencyBuilder=void 0;const nullPerfProvider_1=nullPerfProvider;class MetricsDependencyBuilder{constructor(){this.performanceProvider=new nullPerfProvider_1.NullPerformanceProvider,this.instanceFocusedHandler=()=>()=>{},this.instanceStartedHandler=()=>()=>{},this.instanceStoppedHandler=()=>()=>{},this.instanceReadyHandler=()=>()=>{},this.instanceErrorHandler=()=>()=>{},this.instanceCrashHandler=()=>()=>{},this.layoutRestoredHandler=()=>()=>{},this.workspaceLoadedHandler=()=>()=>{},this.workspaceRestoredHandler=()=>()=>{},this.workspaceSavedHandler=()=>()=>{},this.workspaceStartedHandler=()=>()=>{},this.workspaceStoppedHandler=()=>()=>{},this.workspaceSelectedHandler=()=>()=>{},this.platformStartedHandler=()=>()=>{},this.platformErrorHandler=()=>()=>{}}build(){return{performanceProvider:this.performanceProvider,instanceStartedHandler:this.instanceStartedHandler,instanceStoppedHandler:this.instanceStoppedHandler,instanceReadyHandler:this.instanceReadyHandler,instanceFocusedHandler:this.instanceFocusedHandler,instanceErrorHandler:this.instanceErrorHandler,instanceCrashHandler:this.instanceCrashHandler,layoutRestoredHandler:this.layoutRestoredHandler,workspaceLoadedHandler:this.workspaceLoadedHandler,workspaceSavedHandler:this.workspaceSavedHandler,workspaceStartedHandler:this.workspaceStartedHandler,workspaceStoppedHandler:this.workspaceStoppedHandler,workspaceSelectedHandler:this.workspaceSelectedHandler,platformStartedHandler:this.platformStartedHandler,platformErrorHandler:this.platformErrorHandler,workspaceRestoredHandler:this.workspaceRestoredHandler}}withInstanceStartedHandler(e){return this.instanceStartedHandler=e,this}withInstanceStoppedHandler(e){return this.instanceStoppedHandler=e,this}withInstanceReadyHandler(e){return this.instanceReadyHandler=e,this}withInstanceFocusedHandler(e){return this.instanceFocusedHandler=e,this}withInstanceErrorHandler(e){return this.instanceErrorHandler=e,this}withInstanceCrashHandler(e){return this.instanceCrashHandler=e,this}withLayoutRestoredHandler(e){return this.layoutRestoredHandler=e,this}withWorkspaceLoadedHandler(e){return this.workspaceLoadedHandler=e,this}withWorkspaceSavedHandler(e){return this.workspaceSavedHandler=e,this}withWorkspaceStartedHandler(e){return this.workspaceRestoredHandler=()=>()=>{},this.workspaceStartedHandler=e,this}withWorkspaceStoppedHandler(e){return this.workspaceStoppedHandler=e,this}withWorkspaceSelectedHandler(e){return this.workspaceSelectedHandler=e,this}withPlatformStartedHandler(e){return this.platformStartedHandler=e,this}withPlatformErrorHandler(e){return this.platformErrorHandler=e,this}withPerfProvider(e){return this.performanceProvider=e,this}withWorkspaceRestoredHandler(e){return this.workspaceRestoredHandler=e,this.workspaceStartedHandler=()=>()=>{},this}}builder.MetricsDependencyBuilder=MetricsDependencyBuilder;var types={};Object.defineProperty(types,"__esModule",{value:!0}),function(e){var t=commonjsGlobal$1&&commonjsGlobal$1.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=commonjsGlobal$1&&commonjsGlobal$1.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=commonjsGlobal$1&&commonjsGlobal$1.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)},i=commonjsGlobal$1&&commonjsGlobal$1.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&t(n,e,i);return r(n,e),n};Object.defineProperty(e,"__esModule",{value:!0}),e.OtelExporterTraceOtlpHttp=e.OtelExporterMetricsOtlpHttp=e.OtelMetricsSDK=e.OtelTraceBaseSDK=e.OtelAPI=e.isPlainObject=e.safeStringify=e.flattenOtelAtributes=e.Logs=e.OTEL_PI_KEY=e.withSpan=e.Traces=e.MetricsDependencyBuilder=e.OTLPMetricExporter=e.InMemoryMetricExporter=e.Container=e.Log4jsWrapper=e.ioInsightsSampler=e.Builder=void 0;var o=builder$7;Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return o.Builder}});var s=requireIoInsightsSampler();Object.defineProperty(e,"ioInsightsSampler",{enumerable:!0,get:function(){return s.ioInsightsSampler}});var a=log4jsWrapper;Object.defineProperty(e,"Log4jsWrapper",{enumerable:!0,get:function(){return a.Log4jsWrapper}});var c=container$1;Object.defineProperty(e,"Container",{enumerable:!0,get:function(){return c.Container}});var l=require$$4;Object.defineProperty(e,"InMemoryMetricExporter",{enumerable:!0,get:function(){return l.InMemoryMetricExporter}});var u=require$$5;Object.defineProperty(e,"OTLPMetricExporter",{enumerable:!0,get:function(){return u.OTLPMetricExporter}});var d=builder;Object.defineProperty(e,"MetricsDependencyBuilder",{enumerable:!0,get:function(){return d.MetricsDependencyBuilder}}),n(types,e);const h=i(requireTraces());e.Traces=h.default,Object.defineProperty(e,"withSpan",{enumerable:!0,get:function(){return h.withSpan}}),e.OTEL_PI_KEY="__interopIOTracePropagationInfo";var p=logs;Object.defineProperty(e,"Logs",{enumerable:!0,get:function(){return p.Logs}});var g=otelUtils;Object.defineProperty(e,"flattenOtelAtributes",{enumerable:!0,get:function(){return g.flattenOtelAtributes}});var m=safeStringify$1;Object.defineProperty(e,"safeStringify",{enumerable:!0,get:function(){return m.safeStringify}});var f=isPlainObject$6;Object.defineProperty(e,"isPlainObject",{enumerable:!0,get:function(){return f.isPlainObject}});const y=i(require$$13$1);e.OtelAPI=y;const $=i(require$$14$1);e.OtelTraceBaseSDK=$;const b=i(require$$4);e.OtelMetricsSDK=b;const v=i(require$$5);e.OtelExporterMetricsOtlpHttp=v;const w=i(require$$15);e.OtelExporterTraceOtlpHttp=w}(dist);var c$2=(e=>(e[e.off=0]="off",e[e.error=200]="error",e[e.warn=300]="warn",e[e.info=400]="info",e[e.debug=500]="debug",e[e.trace=600]="trace",e[e.all=Number.MAX_SAFE_INTEGER]="all",e))(c$2||{}),u$1=Object.create(null),g$5={},f$1="gateway";g$5[f$1]=600;var l$2=e=>{console[e.level](`${e.time.toISOString()} ${e.level.toUpperCase()} [${e.name}] - ${e.message}`,...e.data)};function E$2(e){let{name:t,level:r}=e;L$2(t),d$1(r,t)&&l$2(e)}function a$1(e,t,r,...n){this.enabledFor(t)&&l$2({time:new Date,level:t,name:e,message:r,data:n})}function d$1(e,t){let r=c$2[e];return g$5[t]>=r}function y$3(e){L$2(e);let t=function(r,n,...i){a$1.call(t,e,r,n,...i)};for(let r of Object.keys(c$2).filter(function(e){return isNaN(Number(e))}))t[r]=function(n,...i){a$1.call(t,e,r,n,...i)};return t.enabledFor=function(t){return d$1(t,e)},t.child=function(t){return v$3(`${e}.${t}`)},t}function L$2(e){if(!e.startsWith(f$1))throw new Error(`Logger name must start with ${f$1}`);if(void 0===g$5[e]){let t=Object.entries(g$5).sort(([e],[t])=>t.localeCompare(e)),[,r]=t.find(([t])=>e.startsWith(t));g$5[e]=r}}function v$3(e){let t=u$1[e];return void 0===t&&(t=y$3(e),u$1[e]=t),t}function b$2(e){function t(e,t){for(let r of Object.keys(g$5).filter(t=>t.startsWith(e)))g$5[r]=c$2[t];void 0===g$5[e]&&(g$5[e]=c$2[t])}let r=e.level;if("string"==typeof r)g$5[f$1]=c$2[r],t(f$1,r);else if("object"==typeof r){let e=Object.entries(r).sort(([e],[t])=>e.localeCompare(t));for(let[r,n]of e)t(r,n)}l$2=e.appender??l$2}var my=Object.freeze({__proto__:null,ROOT_LOGGER_NAME:f$1,configure:b$2,getLogger:v$3,logEvent:E$2}),NOTHING=Symbol.for("immer-nothing"),DRAFTABLE=Symbol.for("immer-draftable"),DRAFT_STATE=Symbol.for("immer-state");function die(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var O$1=Object,getPrototypeOf$1=O$1.getPrototypeOf,CONSTRUCTOR="constructor",PROTOTYPE="prototype",CONFIGURABLE="configurable",ENUMERABLE="enumerable",WRITABLE="writable",VALUE="value",isDraft=e=>!!e&&!!e[DRAFT_STATE];function isDraftable(e){return!!e&&(isPlainObject$2(e)||isArray$5(e)||!!e[DRAFTABLE]||!!e[CONSTRUCTOR]?.[DRAFTABLE]||isMap$4(e)||isSet$4(e))}var objectCtorString=O$1[PROTOTYPE][CONSTRUCTOR].toString(),cachedCtorStrings=new WeakMap;function isPlainObject$2(e){if(!e||!isObjectish(e))return!1;const t=getPrototypeOf$1(e);if(null===t||t===O$1[PROTOTYPE])return!0;const r=O$1.hasOwnProperty.call(t,CONSTRUCTOR)&&t[CONSTRUCTOR];if(r===Object)return!0;if(!isFunction$3(r))return!1;let n=cachedCtorStrings.get(r);return void 0===n&&(n=Function.toString.call(r),cachedCtorStrings.set(r,n)),n===objectCtorString}function each(e,t,r=!0){if(0===getArchtype(e)){(r?Reflect.ownKeys(e):O$1.keys(e)).forEach(r=>{t(r,e[r],e)})}else e.forEach((r,n)=>t(n,r,e))}function getArchtype(e){const t=e[DRAFT_STATE];return t?t.type_:isArray$5(e)?1:isMap$4(e)?2:isSet$4(e)?3:0}var has$1=(e,t,r=getArchtype(e))=>2===r?e.has(t):O$1[PROTOTYPE].hasOwnProperty.call(e,t),get$1=(e,t,r=getArchtype(e))=>2===r?e.get(t):e[t],set$1=(e,t,r,n=getArchtype(e))=>{2===n?e.set(t,r):3===n?e.add(r):e[t]=r};function is$3(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}var isArray$5=Array.isArray,isMap$4=e=>e instanceof Map,isSet$4=e=>e instanceof Set,isObjectish=e=>"object"==typeof e,isFunction$3=e=>"function"==typeof e,isBoolean$3=e=>"boolean"==typeof e,getProxyDraft=e=>isObjectish(e)?e?.[DRAFT_STATE]:null,latest=e=>e.copy_||e.base_,getValue=e=>{const t=getProxyDraft(e);return t?t.copy_??t.base_:e},getFinalValue=e=>e.modified_?e.copy_:e.base_;function shallowCopy(e,t){if(isMap$4(e))return new Map(e);if(isSet$4(e))return new Set(e);if(isArray$5(e))return Array[PROTOTYPE].slice.call(e);const r=isPlainObject$2(e);if(!0===t||"class_only"===t&&!r){const t=O$1.getOwnPropertyDescriptors(e);delete t[DRAFT_STATE];let r=Reflect.ownKeys(t);for(let n=0;n1&&O$1.defineProperties(e,{set:dontMutateMethodOverride,add:dontMutateMethodOverride,clear:dontMutateMethodOverride,delete:dontMutateMethodOverride}),O$1.freeze(e),t&&each(e,(e,t)=>{freeze(t,!0)},!1)),e}function dontMutateFrozenCollections(){die(2)}var dontMutateMethodOverride={[VALUE]:dontMutateFrozenCollections};function isFrozen(e){return null===e||!isObjectish(e)||O$1.isFrozen(e)}var PluginMapSet="MapSet",PluginPatches="Patches",plugins={};function getPlugin(e){const t=plugins[e];return t||die(0,e),t}var isPluginLoaded=e=>!!plugins[e],currentScope;function loadPlugin(e,t){plugins[e]||(plugins[e]=t)}var getCurrentScope=()=>currentScope,createScope=(e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:isPluginLoaded(PluginMapSet)?getPlugin(PluginMapSet):void 0});function usePatchesInScope(e,t){t&&(e.patchPlugin_=getPlugin(PluginPatches),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function revokeScope(e){leaveScope(e),e.drafts_.forEach(revokeDraft),e.drafts_=null}function leaveScope(e){e===currentScope&&(currentScope=e.parent_)}var enterScope=e=>currentScope=createScope(currentScope,e);function revokeDraft(e){const t=e[DRAFT_STATE];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function processResult(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];if(void 0!==e&&e!==r){r[DRAFT_STATE].modified_&&(revokeScope(t),die(4)),isDraftable(e)&&(e=finalize(t,e));const{patchPlugin_:n}=t;n&&n.generateReplacementPatches_(r[DRAFT_STATE].base_,e,t)}else e=finalize(t,r);return maybeFreeze(t,e,!0),revokeScope(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==NOTHING?e:void 0}function finalize(e,t){if(isFrozen(t))return t;const r=t[DRAFT_STATE];if(!r){return handleValue(t,e.handledSet_,e)}if(!isSameScope(r,e))return t;if(!r.modified_)return r.base_;if(!r.finalized_){const{callbacks_:t}=r;if(t)for(;t.length>0;){t.pop()(e)}generatePatchesAndFinalize(r,e)}return r.copy_}function maybeFreeze(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&freeze(t,r)}function markStateFinalized(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var isSameScope=(e,t)=>e.scope_===t,EMPTY_LOCATIONS_RESULT=[];function updateDraftInParent(e,t,r,n){const i=latest(e),o=e.type_;if(void 0!==n){if(get$1(i,n,o)===t)return void set$1(i,n,r,o)}if(!e.draftLocations_){const t=e.draftLocations_=new Map;each(i,(e,r)=>{if(isDraft(r)){const n=t.get(r)||[];n.push(e),t.set(r,n)}})}const s=e.draftLocations_.get(t)??EMPTY_LOCATIONS_RESULT;for(const e of s)set$1(i,e,r,o)}function registerChildFinalizationCallback(e,t,r){e.callbacks_.push(function(n){const i=t;if(!i||!isSameScope(i,n))return;n.mapSetPlugin_?.fixSetContents(i);const o=getFinalValue(i);updateDraftInParent(e,i.draft_??i,o,r),generatePatchesAndFinalize(i,n)})}function generatePatchesAndFinalize(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||(e.assigned_?.size??0)>0)){const{patchPlugin_:r}=t;if(r){const n=r.getPath(e);n&&r.generatePatches_(e,n,t)}markStateFinalized(e)}}function handleCrossReference(e,t,r){const{scope_:n}=e;if(isDraft(r)){const i=r[DRAFT_STATE];isSameScope(i,n)&&i.callbacks_.push(function(){prepareCopy(e);const n=getFinalValue(i);updateDraftInParent(e,r,n,t)})}else isDraftable(r)&&e.callbacks_.push(function(){const i=latest(e);get$1(i,t,e.type_)===r&&n.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&handleValue(get$1(e.copy_,t,e.type_),n.handledSet_,n)})}function handleValue(e,t,r){return!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1||isDraft(e)||t.has(e)||!isDraftable(e)||isFrozen(e)||(t.add(e),each(e,(n,i)=>{if(isDraft(i)){const t=i[DRAFT_STATE];if(isSameScope(t,r)){const r=getFinalValue(t);set$1(e,n,r,e.type_),markStateFinalized(t)}}else isDraftable(i)&&handleValue(i,t,r)})),e}function createProxyProxy(e,t){const r=isArray$5(e),n={type_:r?1:0,scope_:t?t.scope_:getCurrentScope(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let i=n,o=objectTraps;r&&(i=[n],o=arrayTraps);const{revoke:s,proxy:a}=Proxy.revocable(i,o);return n.draft_=a,n.revoke_=s,[a,n]}var objectTraps={get(e,t){if(t===DRAFT_STATE)return e;const r=latest(e);if(!has$1(r,t,e.type_))return readPropFromProto(e,r,t);const n=r[t];if(e.finalized_||!isDraftable(n))return n;if(n===peek(e.base_,t)){prepareCopy(e);const r=1===e.type_?+t:t,i=createProxy(e.scope_,n,e,r);return e.copy_[r]=i}return n},has:(e,t)=>t in latest(e),ownKeys:e=>Reflect.ownKeys(latest(e)),set(e,t,r){const n=getDescriptorFromProto(latest(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const n=peek(latest(e),t),i=n?.[DRAFT_STATE];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_.set(t,!1),!0;if(is$3(r,n)&&(void 0!==r||has$1(e.base_,t,e.type_)))return!0;prepareCopy(e),markChanged(e)}return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_.set(t,!0),handleCrossReference(e,t,r)),!0},deleteProperty:(e,t)=>(prepareCopy(e),void 0!==peek(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),markChanged(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=latest(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{[WRITABLE]:!0,[CONFIGURABLE]:1!==e.type_||"length"!==t,[ENUMERABLE]:n[ENUMERABLE],[VALUE]:r[t]}:n},defineProperty(){die(11)},getPrototypeOf:e=>getPrototypeOf$1(e.base_),setPrototypeOf(){die(12)}},arrayTraps={};function peek(e,t){const r=e[DRAFT_STATE];return(r?latest(r):e)[t]}function readPropFromProto(e,t,r){const n=getDescriptorFromProto(t,r);return n?VALUE in n?n[VALUE]:n.get?.call(e.draft_):void 0}function getDescriptorFromProto(e,t){if(!(t in e))return;let r=getPrototypeOf$1(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=getPrototypeOf$1(r)}}function markChanged(e){e.modified_||(e.modified_=!0,e.parent_&&markChanged(e.parent_))}function prepareCopy(e){e.copy_||(e.assigned_=new Map,e.copy_=shallowCopy(e.base_,e.scope_.immer_.useStrictShallowCopy_))}each(objectTraps,(e,t)=>{arrayTraps[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}),arrayTraps.deleteProperty=function(e,t){return arrayTraps.set.call(this,e,t,void 0)},arrayTraps.set=function(e,t,r){return objectTraps.set.call(this,e[0],t,r,e[0])};var Immer2=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,r)=>{if(isFunction$3(e)&&!isFunction$3(t)){const r=t;t=e;const n=this;return function(e=r,...i){return n.produce(e,e=>t.call(this,e,...i))}}let n;if(isFunction$3(t)||die(6),void 0===r||isFunction$3(r)||die(7),isDraftable(e)){const i=enterScope(this),o=createProxy(i,e,void 0);let s=!0;try{n=t(o),s=!1}finally{s?revokeScope(i):leaveScope(i)}return usePatchesInScope(i,r),processResult(n,i)}if(!e||!isObjectish(e)){if(n=t(e),void 0===n&&(n=e),n===NOTHING&&(n=void 0),this.autoFreeze_&&freeze(n,!0),r){const t=[],i=[];getPlugin(PluginPatches).generateReplacementPatches_(e,n,{patches_:t,inversePatches_:i}),r(t,i)}return n}die(1,e)},this.produceWithPatches=(e,t)=>{if(isFunction$3(e))return(t,...r)=>this.produceWithPatches(t,t=>e(t,...r));let r,n;const i=this.produce(e,t,(e,t)=>{r=e,n=t});return[i,r,n]},isBoolean$3(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),isBoolean$3(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),isBoolean$3(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){isDraftable(e)||die(8),isDraft(e)&&(e=current(e));const t=enterScope(this),r=createProxy(t,e,void 0);return r[DRAFT_STATE].isManual_=!0,leaveScope(t),r}finishDraft(e,t){const r=e&&e[DRAFT_STATE];r&&r.isManual_||die(9);const{scope_:n}=r;return usePatchesInScope(n,t),processResult(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));const n=getPlugin(PluginPatches).applyPatches_;return isDraft(e)?n(e,t):this.produce(e,e=>n(e,t))}};function createProxy(e,t,r,n){const[i,o]=isMap$4(t)?getPlugin(PluginMapSet).proxyMap_(t,r):isSet$4(t)?getPlugin(PluginMapSet).proxySet_(t,r):createProxyProxy(t,r);return(r?.scope_??getCurrentScope()).drafts_.push(i),o.callbacks_=r?.callbacks_??[],o.key_=n,r&&void 0!==n?registerChildFinalizationCallback(r,o,n):o.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(o);const{patchPlugin_:t}=e;o.modified_&&t&&t.generatePatches_(o,[],e)}),i}function current(e){return isDraft(e)||die(10,e),currentImpl(e)}function currentImpl(e){if(!isDraftable(e)||isFrozen(e))return e;const t=e[DRAFT_STATE];let r,n=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=shallowCopy(e,t.scope_.immer_.useStrictShallowCopy_),n=t.scope_.immer_.shouldUseStrictIteration()}else r=shallowCopy(e,!0);return each(r,(e,t)=>{set$1(r,e,currentImpl(t))},n),t&&(t.finalized_=!1),r}function enableMapSet(){class e extends Map{constructor(e,t){super(),this[DRAFT_STATE]={type_:2,parent_:t,scope_:t?t.scope_:getCurrentScope(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:e,draft_:this,isManual_:!1,revoked_:!1,callbacks_:[]}}get size(){return latest(this[DRAFT_STATE]).size}has(e){return latest(this[DRAFT_STATE]).has(e)}set(e,r){const n=this[DRAFT_STATE];return i(n),latest(n).has(e)&&latest(n).get(e)===r||(t(n),markChanged(n),n.assigned_.set(e,!0),n.copy_.set(e,r),n.assigned_.set(e,!0)),this}delete(e){if(!this.has(e))return!1;const r=this[DRAFT_STATE];return i(r),t(r),markChanged(r),r.base_.has(e)?r.assigned_.set(e,!1):r.assigned_.delete(e),r.copy_.delete(e),!0}clear(){const e=this[DRAFT_STATE];i(e),latest(e).size&&(t(e),markChanged(e),e.assigned_=new Map,each(e.base_,t=>{e.assigned_.set(t,!1)}),e.copy_.clear())}forEach(e,t){const r=this[DRAFT_STATE];latest(r).forEach((r,n,i)=>{e.call(t,this.get(n),n,this)})}get(e){const r=this[DRAFT_STATE];i(r);const n=latest(r).get(e);if(r.finalized_||!isDraftable(n))return n;if(n!==r.base_.get(e))return n;const o=createProxy(r.scope_,n,r,e);return t(r),r.copy_.set(e,o),o}keys(){return latest(this[DRAFT_STATE]).keys()}values(){const e=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{const t=e.next();if(t.done)return t;return{done:!1,value:this.get(t.value)}}}}entries(){const e=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const r=this.get(t.value);return{done:!1,value:[t.value,r]}}}}[Symbol.iterator](){return this.entries()}}function t(e){e.copy_||(e.assigned_=new Map,e.copy_=new Map(e.base_))}class r extends Set{constructor(e,t){super(),this[DRAFT_STATE]={type_:3,parent_:t,scope_:t?t.scope_:getCurrentScope(),modified_:!1,finalized_:!1,copy_:void 0,base_:e,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1,assigned_:void 0,callbacks_:[]}}get size(){return latest(this[DRAFT_STATE]).size}has(e){const t=this[DRAFT_STATE];return i(t),t.copy_?!!t.copy_.has(e)||!(!t.drafts_.has(e)||!t.copy_.has(t.drafts_.get(e))):t.base_.has(e)}add(e){const t=this[DRAFT_STATE];return i(t),this.has(e)||(n(t),markChanged(t),t.copy_.add(e)),this}delete(e){if(!this.has(e))return!1;const t=this[DRAFT_STATE];return i(t),n(t),markChanged(t),t.copy_.delete(e)||!!t.drafts_.has(e)&&t.copy_.delete(t.drafts_.get(e))}clear(){const e=this[DRAFT_STATE];i(e),latest(e).size&&(n(e),markChanged(e),e.copy_.clear())}values(){const e=this[DRAFT_STATE];return i(e),n(e),e.copy_.values()}entries(){const e=this[DRAFT_STATE];return i(e),n(e),e.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(e,t){const r=this.values();let n=r.next();for(;!n.done;)e.call(t,n.value,n.value,this),n=r.next()}}function n(e){e.copy_||(e.copy_=new Set,e.base_.forEach(t=>{if(isDraftable(t)){const r=createProxy(e.scope_,t,e,t);e.drafts_.set(t,r),e.copy_.add(r)}else e.copy_.add(t)}))}function i(e){e.revoked_&&die(3,JSON.stringify(latest(e)))}loadPlugin(PluginMapSet,{proxyMap_:function(t,r){const n=new e(t,r);return[n,n[DRAFT_STATE]]},proxySet_:function(e,t){const n=new r(e,t);return[n,n[DRAFT_STATE]]},fixSetContents:function(e){if(3===e.type_&&e.copy_){const t=new Set(e.copy_);e.copy_.clear(),t.forEach(t=>{e.copy_.add(getValue(t))})}}})}var immer=new Immer2,produce=immer.produce,castDraft=e=>e;const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(e=>[e.name,e]),errorConstructors=new Map(list);class NonError extends Error{name="NonError";constructor(e){super(NonError._prepareSuperMessage(e))}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=e=>{toJsonWasCalled.add(e);const t=e.toJSON();return toJsonWasCalled.delete(e),t},newError=e=>{const t=errorConstructors.get(e)??Error;return t===AggregateError?new t([]):new t},destroyCircular=({from:e,seen:t,to:r,forceEnumerable:n,maxDepth:i,depth:o,useToJSON:s,serialize:a})=>{if(r||(r=Array.isArray(e)?[]:isErrorLike(e)?newError(e.name):{}),t.push(e),o>=i)return r;if(s&&"function"==typeof e.toJSON&&!toJsonWasCalled.has(e))return toJSON(e);const c=e=>destroyCircular({from:e,seen:[...t],forceEnumerable:n,maxDepth:i,depth:o,useToJSON:s,serialize:a});for(const[n,i]of Object.entries(e))if(i&&i instanceof Uint8Array&&"Buffer"===i.constructor.name)r[n]="[object Buffer]";else if(null===i||"object"!=typeof i||"function"!=typeof i.pipe){if("function"!=typeof i)if(i&&"object"==typeof i)t.includes(e[n])?r[n]="[Circular]":(o++,r[n]=c(e[n]));else try{r[n]=i}catch{}}else r[n]="[object Stream]";if(r instanceof Error)for(const{property:t,enumerable:i}of errorProperties)void 0!==e[t]&&null!==e[t]&&Object.defineProperty(r,t,{value:isErrorLike(e[t])||Array.isArray(e[t])?c(e[t]):e[t],enumerable:!!n||i,configurable:!0,writable:!0});return r};function deserializeError(e,t={}){const{maxDepth:r=Number.POSITIVE_INFINITY}=t;return e instanceof Error?e:isMinimumViableSerializedError(e)?destroyCircular({from:e,seen:[],to:newError(e.name),maxDepth:r,depth:0,serialize:!1}):new NonError(e)}function isErrorLike(e){return Boolean(e)&&"object"==typeof e&&"string"==typeof e.name&&"string"==typeof e.message&&"string"==typeof e.stack}function isMinimumViableSerializedError(e){return Boolean(e)&&"object"==typeof e&&"string"==typeof e.message&&!Array.isArray(e)}var transit={exports:{}},goog=goog||{};goog.global=commonjsGlobal$1||self,goog.exportPath_=function(e,t,r,n){e=e.split("."),n=n||goog.global,e[0]in n||void 0===n.execScript||n.execScript("var "+e[0]);for(var i;e.length&&(i=e.shift());)if(e.length||void 0===t)n=n[i]&&n[i]!==Object.prototype[i]?n[i]:n[i]={};else if(!r&&goog.isObject(t)&&goog.isObject(n[i]))for(var o in t)t.hasOwnProperty(o)&&(n[i][o]=t[o]);else n[i]=t},goog.define=function(e,t){return t},goog.FEATURESET_YEAR=2012,goog.DEBUG=!0,goog.LOCALE="en",goog.TRUSTED_SITE=!0,goog.DISALLOW_TEST_ONLY_CODE=!goog.DEBUG,goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING=!1,goog.provide=function(e){if(goog.isInModuleLoader_())throw Error("goog.provide cannot be used within a module.");goog.constructNamespace_(e)},goog.constructNamespace_=function(e,t,r){goog.exportPath_(e,t,r)},goog.getScriptNonce=function(e){return e&&e!=goog.global?goog.getScriptNonce_(e.document):(null===goog.cspNonce_&&(goog.cspNonce_=goog.getScriptNonce_(goog.global.document)),goog.cspNonce_)},goog.NONCE_PATTERN_=/^[\w+/_-]+[=]{0,2}$/,goog.cspNonce_=null,goog.getScriptNonce_=function(e){return(e=e.querySelector&&e.querySelector("script[nonce]"))&&(e=e.nonce||e.getAttribute("nonce"))&&goog.NONCE_PATTERN_.test(e)?e:""},goog.VALID_MODULE_RE_=/^[a-zA-Z_$][a-zA-Z0-9._$]*$/,goog.module=function(e){if("string"!=typeof e||!e||-1==e.search(goog.VALID_MODULE_RE_))throw Error("Invalid module identifier");if(!goog.isInGoogModuleLoader_())throw Error("Module "+e+" has been loaded incorrectly. Note, modules cannot be loaded as normal scripts. They require some kind of pre-processing step. You're likely trying to load a module via a script tag or as a part of a concatenated bundle without rewriting the module. For more info see: https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.");if(goog.moduleLoaderState_.moduleName)throw Error("goog.module may only be called once per module.");goog.moduleLoaderState_.moduleName=e},goog.module.get=function(e){return goog.module.getInternal_(e)},goog.module.getInternal_=function(e){return null},goog.ModuleType={ES6:"es6",GOOG:"goog"},goog.moduleLoaderState_=null,goog.isInModuleLoader_=function(){return goog.isInGoogModuleLoader_()||goog.isInEs6ModuleLoader_()},goog.isInGoogModuleLoader_=function(){return!!goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.GOOG},goog.isInEs6ModuleLoader_=function(){if(goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.ES6)return!0;var e=goog.global.$jscomp;return!!e&&("function"==typeof e.getCurrentModulePath&&!!e.getCurrentModulePath())},goog.module.declareLegacyNamespace=function(){goog.moduleLoaderState_.declareLegacyNamespace=!0},goog.declareModuleId=function(e){if(goog.moduleLoaderState_)goog.moduleLoaderState_.moduleName=e;else{var t=goog.global.$jscomp;if(!t||"function"!=typeof t.getCurrentModulePath)throw Error('Module with namespace "'+e+'" has been loaded incorrectly.');t=t.require(t.getCurrentModulePath()),goog.loadedModules_[e]={exports:t,type:goog.ModuleType.ES6,moduleId:e}}},goog.setTestOnly=function(e){if(goog.DISALLOW_TEST_ONLY_CODE)throw e=e||"",Error("Importing test-only code into non-debug environment"+(e?": "+e:"."))},goog.forwardDeclare=function(e){},goog.getObjectByName=function(e,t){e=e.split("."),t=t||goog.global;for(var r=0;r>>0),goog.uidCounter_=0,goog.cloneObject=function(e){var t=goog.typeOf(e);if("object"==t||"array"==t){if("function"==typeof e.clone)return e.clone();for(var r in t="array"==t?[]:{},e)t[r]=goog.cloneObject(e[r]);return t}return e},goog.bindNative_=function(e,t,r){return e.call.apply(e.bind,arguments)},goog.bindJs_=function(e,t,r){if(!e)throw Error();if(2").replace(/'/g,"'").replace(/"/g,'"').replace(/&/g,"&")),t&&(e=e.replace(/\{\$([^}]+)}/g,function(e,r){return null!=t&&r in t?t[r]:e})),e},goog.getMsgWithFallback=function(e,t){return e},goog.exportSymbol=function(e,t,r){goog.exportPath_(e,t,!0,r)},goog.exportProperty=function(e,t,r){e[t]=r},goog.inherits=function(e,t){function r(){}r.prototype=t.prototype,e.superClass_=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.base=function(e,r,n){for(var i=Array(arguments.length-2),o=2;o>8-n%1*8)){if(255<(r=e.charCodeAt(n+=.75)))throw Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");t=t<<8|r}return o},com.cognitect.transit.util.atob=function(e){if("undefined"!=typeof atob)return atob(e);if(1==(e=String(e).replace(/=+$/,"")).length%4)throw Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,r,n=0,i=0,o="";r=e.charAt(i++);~r&&(t=n%4?64*t+r:r,n++%4)?o+=String.fromCharCode(255&t>>(-2*n&6)):0)r=com.cognitect.transit.util.chars.indexOf(r);return o},com.cognitect.transit.util.Uint8ToBase64=function(e){for(var t,r=0,n=e.length,i="";rcom.cognitect.transit.caching.MIN_SIZE_CACHEABLE&&(!!t||(t=e.charAt(0),e=e.charAt(1),t===com.cognitect.transit.delimiters.ESC&&(":"===e||"$"===e||"#"===e)))},com.cognitect.transit.caching.idxToCode=function(e){var t=Math.floor(e/com.cognitect.transit.caching.CACHE_CODE_DIGITS);return e=String.fromCharCode(e%com.cognitect.transit.caching.CACHE_CODE_DIGITS+com.cognitect.transit.caching.BASE_CHAR_IDX),0===t?com.cognitect.transit.delimiters.SUB+e:com.cognitect.transit.delimiters.SUB+String.fromCharCode(t+com.cognitect.transit.caching.BASE_CHAR_IDX)+e},com.cognitect.transit.caching.WriteCache=function(){this.cacheSize=this.gen=this.idx=0,this.cache={}},com.cognitect.transit.caching.WriteCache.prototype.write=function(e,t){return com.cognitect.transit.caching.isCacheable(e,t)?(this.cacheSize===com.cognitect.transit.caching.MAX_CACHE_SIZE?(this.clear(),this.gen=0,this.cache={}):this.idx===com.cognitect.transit.caching.MAX_CACHE_ENTRIES&&this.clear(),null==(t=this.cache[e])?(this.cache[e]=[com.cognitect.transit.caching.idxToCode(this.idx),this.gen],this.idx++,e):t[1]!=this.gen?(t[1]=this.gen,t[0]=com.cognitect.transit.caching.idxToCode(this.idx),this.idx++,e):t[0]):e},com.cognitect.transit.caching.WriteCache.prototype.clear=function(){this.idx=0,this.gen++},com.cognitect.transit.caching.writeCache=function(){return new com.cognitect.transit.caching.WriteCache},com.cognitect.transit.caching.isCacheCode=function(e){return e.charAt(0)===com.cognitect.transit.delimiters.SUB&&" "!==e.charAt(1)},com.cognitect.transit.caching.codeToIdx=function(e){return 2===e.length?e.charCodeAt(1)-com.cognitect.transit.caching.BASE_CHAR_IDX:(e.charCodeAt(1)-com.cognitect.transit.caching.BASE_CHAR_IDX)*com.cognitect.transit.caching.CACHE_CODE_DIGITS+(e=e.charCodeAt(2)-com.cognitect.transit.caching.BASE_CHAR_IDX)},com.cognitect.transit.caching.ReadCache=function(){this.idx=0,this.cache=[]},com.cognitect.transit.caching.ReadCache.prototype.write=function(e,t){return this.idx==com.cognitect.transit.caching.MAX_CACHE_ENTRIES&&(this.idx=0),this.cache[this.idx]=e,this.idx++,e},com.cognitect.transit.caching.ReadCache.prototype.read=function(e,t){return this.cache[com.cognitect.transit.caching.codeToIdx(e)]},com.cognitect.transit.caching.ReadCache.prototype.clear=function(){this.idx=0},com.cognitect.transit.caching.readCache=function(){return new com.cognitect.transit.caching.ReadCache},com.cognitect.transit.eq={},com.cognitect.transit.eq.hashCodeProperty="transit$hashCode$",com.cognitect.transit.eq.hashCodeCounter=1,com.cognitect.transit.eq.equals=function(e,t){if(null==e)return null==t;if(e===t)return!0;if("object"==typeof e){if(com.cognitect.transit.util.isArray(e)){if(com.cognitect.transit.util.isArray(t)&&e.length===t.length){for(var r=0;r>2)},com.cognitect.transit.eq.stringCodeCache={},com.cognitect.transit.eq.stringCodeCacheSize=0,com.cognitect.transit.eq.STR_CACHE_MAX=256,com.cognitect.transit.eq.hashString=function(e){var t=com.cognitect.transit.eq.stringCodeCache[e];if(null!=t)return t;for(var r=t=0;r=com.cognitect.transit.eq.STR_CACHE_MAX&&(com.cognitect.transit.eq.stringCodeCache={},com.cognitect.transit.eq.stringCodeCacheSize=1),com.cognitect.transit.eq.stringCodeCache[e]=t},com.cognitect.transit.eq.hashMapLike=function(e){var t=0;if(null!=e.forEach)e.forEach(function(e,r,n){t=(t+(com.cognitect.transit.eq.hashCode(r)^com.cognitect.transit.eq.hashCode(e)))%4503599627370496});else for(var r=com.cognitect.transit.util.objectKeys(e),n=0;n>21;return 0==e||-1==e&&!(0==this.low_&&-2097152==this.high_)}toString(e){if(2>(e=e||10)||36>2);var r=Math.pow(e,t),n=module$contents$goog$math$Long_Long.fromBits(r,r/module$contents$goog$math$Long_TWO_PWR_32_DBL_);r=this.div(n),n=Math.abs(this.subtract(r.multiply(n)).toNumber());var i=10==e?""+n:n.toString(e);return i.length>>0}getNumBitsAbs(){if(this.isNegative())return this.equals(module$contents$goog$math$Long_Long.getMinValue())?64:this.negate().getNumBitsAbs();for(var e=0!=this.high_?this.high_:this.low_,t=31;0this.high_}isOdd(){return!(1&~this.low_)}equals(e){return this.low_==e.low_&&this.high_==e.high_}notEquals(e){return!this.equals(e)}lessThan(e){return 0>this.compare(e)}lessThanOrEqual(e){return 0>=this.compare(e)}greaterThan(e){return 0e.getLowBitsUnsigned()?1:-1:this.high_>e.high_?1:-1}negate(){var e=1+~this.low_|0;return module$contents$goog$math$Long_Long.fromBits(e,~this.high_+!e|0)}add(e){var t=this.high_>>>16,r=65535&this.high_,n=this.low_>>>16,i=e.high_>>>16,o=65535&e.high_,s=e.low_>>>16;return n=(s=((e=(65535&this.low_)+(65535&e.low_))>>>16)+(n+s))>>>16,t=((n+=r+o)>>>16)+(t+i)&65535,module$contents$goog$math$Long_Long.fromBits((65535&s)<<16|65535&e,t<<16|65535&n)}subtract(e){return this.add(e.negate())}multiply(e){if(this.isZero())return this;if(e.isZero())return e;var t=this.high_>>>16,r=65535&this.high_,n=this.low_>>>16,i=65535&this.low_,o=e.high_>>>16,s=65535&e.high_,a=e.low_>>>16,c=i*(e=65535&e.low_),l=(c>>>16)+n*e,u=l>>>16;u+=(l=(65535&l)+i*a)>>>16;var d=(u+=r*e)>>>16;return d=(d+=(u=(65535&u)+n*a)>>>16)+((u=(65535&u)+i*s)>>>16)+(t*e+r*a+n*s+i*o)&65535,module$contents$goog$math$Long_Long.fromBits((65535&l)<<16|65535&c,d<<16|65535&u)}div(e){if(e.isZero())throw Error("division by zero");if(this.isNegative()){if(this.equals(module$contents$goog$math$Long_Long.getMinValue())){if(e.equals(module$contents$goog$math$Long_Long.getOne())||e.equals(module$contents$goog$math$Long_Long.getNegOne()))return module$contents$goog$math$Long_Long.getMinValue();if(e.equals(module$contents$goog$math$Long_Long.getMinValue()))return module$contents$goog$math$Long_Long.getOne();var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(module$contents$goog$math$Long_Long.getZero()))return e.isNegative()?module$contents$goog$math$Long_Long.getOne():module$contents$goog$math$Long_Long.getNegOne();var r=this.subtract(e.multiply(t));return t.add(r.div(e))}return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate()}if(this.isZero())return module$contents$goog$math$Long_Long.getZero();if(e.isNegative())return e.equals(module$contents$goog$math$Long_Long.getMinValue())?module$contents$goog$math$Long_Long.getZero():this.div(e.negate()).negate();var n=module$contents$goog$math$Long_Long.getZero();for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(t)/Math.LN2);i=48>=i?1:Math.pow(2,i-48);for(var o=module$contents$goog$math$Long_Long.fromNumber(t),s=o.multiply(e);s.isNegative()||s.greaterThan(r);)t-=i,s=(o=module$contents$goog$math$Long_Long.fromNumber(t)).multiply(e);o.isZero()&&(o=module$contents$goog$math$Long_Long.getOne()),n=n.add(o),r=r.subtract(s)}return n}modulo(e){return this.subtract(this.div(e).multiply(e))}not(){return module$contents$goog$math$Long_Long.fromBits(~this.low_,~this.high_)}and(e){return module$contents$goog$math$Long_Long.fromBits(this.low_&e.low_,this.high_&e.high_)}or(e){return module$contents$goog$math$Long_Long.fromBits(this.low_|e.low_,this.high_|e.high_)}xor(e){return module$contents$goog$math$Long_Long.fromBits(this.low_^e.low_,this.high_^e.high_)}shiftLeft(e){if(0==(e&=63))return this;var t=this.low_;return 32>e?module$contents$goog$math$Long_Long.fromBits(t<>>32-e):module$contents$goog$math$Long_Long.fromBits(0,t<e?module$contents$goog$math$Long_Long.fromBits(this.low_>>>e|t<<32-e,t>>e):module$contents$goog$math$Long_Long.fromBits(t>>e-32,0<=t?0:-1)}shiftRightUnsigned(e){if(0==(e&=63))return this;var t=this.high_;return 32>e?module$contents$goog$math$Long_Long.fromBits(this.low_>>>e|t<<32-e,t>>>e):32==e?module$contents$goog$math$Long_Long.fromBits(t,0):module$contents$goog$math$Long_Long.fromBits(t>>>e-32,0)}static fromInt(e){var t=0|e;return goog.asserts.assert(e===t,"value should be a 32-bit integer"),-128<=t&&128>t?module$contents$goog$math$Long_getCachedIntValue_(t):new module$contents$goog$math$Long_Long(t,0>t?-1:0)}static fromNumber(e){return 0=module$contents$goog$math$Long_TWO_PWR_63_DBL_?module$contents$goog$math$Long_Long.getMaxValue():new module$contents$goog$math$Long_Long(e,e/module$contents$goog$math$Long_TWO_PWR_32_DBL_):0>e?e<=-module$contents$goog$math$Long_TWO_PWR_63_DBL_?module$contents$goog$math$Long_Long.getMinValue():new module$contents$goog$math$Long_Long(-e,-e/module$contents$goog$math$Long_TWO_PWR_32_DBL_).negate():module$contents$goog$math$Long_Long.getZero()}static fromBits(e,t){return new module$contents$goog$math$Long_Long(e,t)}static fromString(e,t){if("-"==e.charAt(0))return module$contents$goog$math$Long_Long.fromString(e.substring(1),t).negate();var r=parseInt(e,t||10);if(r<=module$contents$goog$math$Long_MAX_SAFE_INTEGER_)return new module$contents$goog$math$Long_Long(r%module$contents$goog$math$Long_TWO_PWR_32_DBL_|0,r/module$contents$goog$math$Long_TWO_PWR_32_DBL_|0);if(0==e.length)throw Error("number format error: empty string");if(0<=e.indexOf("-"))throw Error('number format error: interior "-" character: '+e);if(2>(t=t||10)||36o?(o=module$contents$goog$math$Long_Long.fromNumber(Math.pow(t,o)),n=n.multiply(o).add(module$contents$goog$math$Long_Long.fromNumber(s))):n=(n=n.multiply(r)).add(module$contents$goog$math$Long_Long.fromNumber(s))}return n}static isStringInRange(e,t){if(2>(t=t||10)||36e?-1:0)})}const module$contents$goog$math$Long_MAX_VALUE_FOR_RADIX_=" 111111111111111111111111111111111111111111111111111111111111111 2021110011022210012102010021220101220221 13333333333333333333333333333333 1104332401304422434310311212 1540241003031030222122211 22341010611245052052300 777777777777777777777 67404283172107811827 9223372036854775807 1728002635214590697 41a792678515120367 10b269549075433c37 4340724c6c71dc7a7 160e2ad3246366807 7fffffffffffffff 33d3d8307b214008 16agh595df825fa7 ba643dci0ffeehh 5cbfjia3fh26ja7 2heiciiie82dh97 1adaibb21dckfa7 i6k448cf4192c2 acd772jnc9l0l7 64ie1focnn5g77 3igoecjbmca687 27c48l5b37oaop 1bk39f3ah3dmq7 q1se8f0m04isb hajppbc1fc207 bm03i95hia437 7vvvvvvvvvvvv 5hg4ck9jd4u37 3tdtk1v8j6tpp 2pijmikexrxp7 1y2p0ij32e8e7".split(" "),module$contents$goog$math$Long_MIN_VALUE_FOR_RADIX_=" -1000000000000000000000000000000000000000000000000000000000000000 -2021110011022210012102010021220101220222 -20000000000000000000000000000000 -1104332401304422434310311213 -1540241003031030222122212 -22341010611245052052301 -1000000000000000000000 -67404283172107811828 -9223372036854775808 -1728002635214590698 -41a792678515120368 -10b269549075433c38 -4340724c6c71dc7a8 -160e2ad3246366808 -8000000000000000 -33d3d8307b214009 -16agh595df825fa8 -ba643dci0ffeehi -5cbfjia3fh26ja8 -2heiciiie82dh98 -1adaibb21dckfa8 -i6k448cf4192c3 -acd772jnc9l0l8 -64ie1focnn5g78 -3igoecjbmca688 -27c48l5b37oaoq -1bk39f3ah3dmq8 -q1se8f0m04isc -hajppbc1fc208 -bm03i95hia438 -8000000000000 -5hg4ck9jd4u38 -3tdtk1v8j6tpq -2pijmikexrxp8 -1y2p0ij32e8e8".split(" "),module$contents$goog$math$Long_MAX_SAFE_INTEGER_=9007199254740991,module$contents$goog$math$Long_TWO_PWR_32_DBL_=4294967296,module$contents$goog$math$Long_TWO_PWR_63_DBL_=0x8000000000000000,module$contents$goog$math$Long_ZERO_=module$contents$goog$math$Long_Long.fromBits(0,0),module$contents$goog$math$Long_ONE_=module$contents$goog$math$Long_Long.fromBits(1,0),module$contents$goog$math$Long_NEG_ONE_=module$contents$goog$math$Long_Long.fromBits(-1,-1),module$contents$goog$math$Long_MAX_VALUE_=module$contents$goog$math$Long_Long.fromBits(4294967295,2147483647),module$contents$goog$math$Long_MIN_VALUE_=module$contents$goog$math$Long_Long.fromBits(0,2147483648),module$contents$goog$math$Long_TWO_PWR_24_=module$contents$goog$math$Long_Long.fromBits(16777216,0);com.cognitect.transit.types={},com.cognitect.transit.types.ITERATOR="undefined"!=typeof Symbol?Symbol.iterator:"@@iterator",com.cognitect.transit.types.TaggedValue=function(e,t){this.tag=e,this.rep=t,this.hashCode=-1},com.cognitect.transit.types.TaggedValue.prototype.toString=function(){return"[TaggedValue: "+this.tag+", "+this.rep+"]"},com.cognitect.transit.types.TaggedValue.prototype.equiv=function(e){return com.cognitect.transit.eq.equals(this,e)},com.cognitect.transit.types.TaggedValue.prototype.equiv=com.cognitect.transit.types.TaggedValue.prototype.equiv,com.cognitect.transit.types.TaggedValue.prototype.com$cognitect$transit$equals=function(e){return e instanceof com.cognitect.transit.types.TaggedValue&&(this.tag===e.tag&&com.cognitect.transit.eq.equals(this.rep,e.rep))},com.cognitect.transit.types.TaggedValue.prototype.com$cognitect$transit$hashCode=function(){return-1===this.hashCode&&(this.hashCode=com.cognitect.transit.eq.hashCombine(com.cognitect.transit.eq.hashCode(this.tag),com.cognitect.transit.eq.hashCode(this.rep))),this.hashCode},com.cognitect.transit.types.taggedValue=function(e,t){return new com.cognitect.transit.types.TaggedValue(e,t)},com.cognitect.transit.types.isTaggedValue=function(e){return e instanceof com.cognitect.transit.types.TaggedValue},com.cognitect.transit.types.nullValue=function(){return null},com.cognitect.transit.types.boolValue=function(e){return"t"===e},com.cognitect.transit.types.MAX_INT=module$contents$goog$math$Long_Long.fromString("9007199254740991"),com.cognitect.transit.types.MIN_INT=module$contents$goog$math$Long_Long.fromString("-9007199254740991"),com.cognitect.transit.types.intValue=function(e){return"number"==typeof e||e instanceof module$contents$goog$math$Long_Long||(e=module$contents$goog$math$Long_Long.fromString(e,10)).greaterThan(com.cognitect.transit.types.MAX_INT)||e.lessThan(com.cognitect.transit.types.MIN_INT)?e:e.toNumber()},module$contents$goog$math$Long_Long.prototype.equiv=function(e){return com.cognitect.transit.eq.equals(this,e)},module$contents$goog$math$Long_Long.prototype.equiv=module$contents$goog$math$Long_Long.prototype.equiv,module$contents$goog$math$Long_Long.prototype.com$cognitect$transit$equals=function(e){return e instanceof module$contents$goog$math$Long_Long&&this.equals(e)},module$contents$goog$math$Long_Long.prototype.com$cognitect$transit$hashCode=function(){return this.toInt()},com.cognitect.transit.types.isInteger=function(e){return e instanceof module$contents$goog$math$Long_Long||"number"==typeof e&&!isNaN(e)&&1/0!==e&&parseFloat(e)===parseInt(e,10)},com.cognitect.transit.types.floatValue=function(e){return parseFloat(e)},com.cognitect.transit.types.bigInteger=function(e){return com.cognitect.transit.types.taggedValue("n",e)},com.cognitect.transit.types.isBigInteger=function(e){return e instanceof com.cognitect.transit.types.TaggedValue&&"n"===e.tag},com.cognitect.transit.types.bigDecimalValue=function(e){return com.cognitect.transit.types.taggedValue("f",e)},com.cognitect.transit.types.isBigDecimal=function(e){return e instanceof com.cognitect.transit.types.TaggedValue&&"f"===e.tag},com.cognitect.transit.types.charValue=function(e){return e},com.cognitect.transit.types.Keyword=function(e){this._name=e,this.hashCode=-1},com.cognitect.transit.types.Keyword.prototype.toString=function(){return":"+this._name},com.cognitect.transit.types.Keyword.prototype.namespace=function(){var e=this._name.indexOf("/");return-1!=e?this._name.substring(0,e):null},com.cognitect.transit.types.Keyword.prototype.name=function(){var e=this._name.indexOf("/");return-1!=e?this._name.substring(e+1,this._name.length):this._name},com.cognitect.transit.types.Keyword.prototype.equiv=function(e){return com.cognitect.transit.eq.equals(this,e)},com.cognitect.transit.types.Keyword.prototype.equiv=com.cognitect.transit.types.Keyword.prototype.equiv,com.cognitect.transit.types.Keyword.prototype.com$cognitect$transit$equals=function(e){return e instanceof com.cognitect.transit.types.Keyword&&this._name==e._name},com.cognitect.transit.types.Keyword.prototype.com$cognitect$transit$hashCode=function(){return-1===this.hashCode&&(this.hashCode=com.cognitect.transit.eq.hashCode(this._name)),this.hashCode},com.cognitect.transit.types.keyword=function(e){return new com.cognitect.transit.types.Keyword(e)},com.cognitect.transit.types.isKeyword=function(e){return e instanceof com.cognitect.transit.types.Keyword},com.cognitect.transit.types.Symbol=function(e){this._name=e,this.hashCode=-1},com.cognitect.transit.types.Symbol.prototype.namespace=function(){var e=this._name.indexOf("/");return-1!=e?this._name.substring(0,e):null},com.cognitect.transit.types.Symbol.prototype.name=function(){var e=this._name.indexOf("/");return-1!=e?this._name.substring(e+1,this._name.length):this._name},com.cognitect.transit.types.Symbol.prototype.toString=function(){return this._name},com.cognitect.transit.types.Symbol.prototype.equiv=function(e){return com.cognitect.transit.eq.equals(this,e)},com.cognitect.transit.types.Symbol.prototype.equiv=com.cognitect.transit.types.Symbol.prototype.equiv,com.cognitect.transit.types.Symbol.prototype.com$cognitect$transit$equals=function(e){return e instanceof com.cognitect.transit.types.Symbol&&this._name==e._name},com.cognitect.transit.types.Symbol.prototype.com$cognitect$transit$hashCode=function(){return-1===this.hashCode&&(this.hashCode=com.cognitect.transit.eq.hashCode(this._name)),this.hashCode},com.cognitect.transit.types.symbol=function(e){return new com.cognitect.transit.types.Symbol(e)},com.cognitect.transit.types.isSymbol=function(e){return e instanceof com.cognitect.transit.types.Symbol},com.cognitect.transit.types.hexFor=function(e,t,r){var n="";r=r||t+1;for(var i=8*(7-t),o=module$contents$goog$math$Long_Long.fromInt(255).shiftLeft(i);tn;n+=2,r-=8)t|=parseInt(e.substring(n,n+2),16)<n;n+=2,r-=8)i|=parseInt(e.substring(n,n+2),16)<n;n+=2,r-=8)t|=parseInt(e.substring(n,n+2),16)<n;n+=2,r-=8)i|=parseInt(e.substring(n,n+2),16)< "+com.cognitect.transit.types.print(n),tcom.cognitect.transit.types.ARRAY_MAP_ACCESS_THRESHOLD&&(this.backingMap=com.cognitect.transit.types.map(this._entries,!1,!0),this._entries=[],!0))},com.cognitect.transit.types.TransitArrayMap.prototype.clear=function(){this.hashCode=-1,this.backingMap?this.backingMap.clear():this._entries=[],this.size=0},com.cognitect.transit.types.TransitArrayMap.prototype.clear=com.cognitect.transit.types.TransitArrayMap.prototype.clear,com.cognitect.transit.types.TransitArrayMap.prototype.keys=function(){return this.backingMap?this.backingMap.keys():new com.cognitect.transit.types.TransitArrayMapIterator(this._entries,com.cognitect.transit.types.KEYS)},com.cognitect.transit.types.TransitArrayMap.prototype.keys=com.cognitect.transit.types.TransitArrayMap.prototype.keys,com.cognitect.transit.types.TransitArrayMap.prototype.keySet=function(){if(this.backingMap)return this.backingMap.keySet();for(var e=[],t=0,r=0;rcom.cognitect.transit.types.ARRAY_MAP_THRESHOLD&&(this.backingMap=com.cognitect.transit.types.map(this._entries,!1,!0),this._entries=null)}},com.cognitect.transit.types.TransitArrayMap.prototype.set=com.cognitect.transit.types.TransitArrayMap.prototype.set,com.cognitect.transit.types.TransitArrayMap.prototype.delete=function(e){if(this.hashCode=-1,this.backingMap)return e=this.backingMap.delete(e),this.size=this.backingMap.size,e;for(var t=0;t=e.length&&this.arrayBuilder.fromArray){for(i=[],n=0;n{}},e={};function n(t){var r=e[t];if(void 0!==r)return r.exports;var i=e[t]={exports:{}};return t$1[t](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var s={};n.d(s,{MG:()=>$$2,fr:()=>Lt$1,sR:()=>Ae,Zo:()=>ke$1,iH:()=>Re$1,rt:()=>Pt,jB:()=>be$1,M8:()=>le,$t:()=>Ce,aq:()=>me$1,pG:()=>Ot$1,eP:()=>Te$1,KU:()=>xe,zW:()=>Ie,IX:()=>E$1,mY:()=>_$1,a7:()=>j$1,JG:()=>Ut$1,ay:()=>Xt$1,X2:()=>ee$1,WU:()=>de$2,Uw:()=>ge$1,gw:()=>pe$1,iX:()=>Fe,re:()=>se$1,Pg:()=>Be$1,tD:()=>ie$1,R$:()=>te$1,Dj:()=>Ft$1,m7:()=>U$2,NZ:()=>P$1,xo:()=>b$1,ou:()=>i,qC:()=>ze$1,mD:()=>d,Ay:()=>Ye$1});class i{constructor(){this.source=null,this.type=null,this.channel=null,this.start=null,this.stop=null,this.tokenIndex=null,this.line=null,this.column=null,this._text=null}getTokenSource(){return this.source[0]}getInputStream(){return this.source[1]}get text(){return this._text}set text(e){this._text=e}}function r(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r>>16)*l&65535)<<16)&4294967295,i=i<<15|i>>>17,i=(65535&i)*u+(((i>>>16)*u&65535)<<16)&4294967295,c^=i,c=c<<13|c>>>19,n=5*(65535&c)+((5*(c>>>16)&65535)<<16)&4294967295,c=27492+(65535&n)+((58964+(n>>>16)&65535)<<16);switch(i=0,s){case 3:i^=(255&r.charCodeAt(d+2))<<16;case 2:i^=(255&r.charCodeAt(d+1))<<8;case 1:i^=255&r.charCodeAt(d),i=(65535&i)*l+(((i>>>16)*l&65535)<<16)&4294967295,i=i<<15|i>>>17,i=(65535&i)*u+(((i>>>16)*u&65535)<<16)&4294967295,c^=i}return c^=r.length,c^=c>>>16,c=2246822507*(65535&c)+((2246822507*(c>>>16)&65535)<<16)&4294967295,c^=c>>>13,c=3266489909*(65535&c)+((3266489909*(c>>>16)&65535)<<16)&4294967295,c^=c>>>16,c>>>0}let l$1=class e{constructor(){this.count=0,this.hash=0}update(){for(let e=0;e>>17,e*=461845907,this.count=this.count+1;let r=this.hash^e;r=r<<13|r>>>19,r=5*r+3864292196,this.hash=r}}}finish(){let e=this.hash^4*this.count;return e^=e>>>16,e*=2246822507,e^=e>>>13,e*=3266489909,e^=e>>>16,e}static hashStuff(){const t=new e;return t.update.apply(t,arguments),t.finish()}};function h$2(e){return e?"string"==typeof e?a(e):e.hashCode():-1}function c$1(e,t){return e&&e.equals?e.equals(t):e===t}function u(e){return null===e?"null":e}function d(e){return Array.isArray(e)?"["+e.map(u).join(", ")+"]":"null"}let g$4=class{constructor(e,t){this.buckets=new Array(16),this.threshold=Math.floor(12),this.itemCount=0,this.hashFunction=e||h$2,this.equalsFunction=t||c$1}get(e){if(null==e)return e;const t=this._getBucket(e);if(!t)return null;for(const r of t)if(this.equalsFunction(r,e))return r;return null}add(e){return this.getOrAdd(e)===e}getOrAdd(e){this._expand();const t=this._getSlot(e);let r=this.buckets[t];if(!r)return r=[e],this.buckets[t]=r,this.itemCount++,e;for(const t of r)if(this.equalsFunction(t,e))return t;return r.push(e),this.itemCount++,e}has(e){return null!=this.get(e)}values(){return this.buckets.filter(e=>null!=e).flat(1)}toString(){return d(this.values())}get length(){return this.itemCount}_getSlot(e){return this.hashFunction(e)&this.buckets.length-1}_getBucket(e){return this.buckets[this._getSlot(e)]}_expand(){if(this.itemCount<=this.threshold)return;const e=this.buckets,t=2*this.buckets.length;this.buckets=new Array(t),this.threshold=Math.floor(.75*t);for(const t of e)if(t)for(const e of t){const t=this._getSlot(e);let r=this.buckets[t];r||(r=[],this.buckets[t]=r),r.push(e)}}};class p{hashCode(){const e=new l$1;return this.updateHashCode(e),e.finish()}evaluate(e,t){}evalPrecedence(e,t){return this}static andContext(e,t){if(null===e||e===p.NONE)return t;if(null===t||t===p.NONE)return e;const r=new f(e,t);return 1===r.opnds.length?r.opnds[0]:r}static orContext(e,t){if(null===e)return t;if(null===t)return e;if(e===p.NONE||t===p.NONE)return p.NONE;const r=new x$2(e,t);return 1===r.opnds.length?r.opnds[0]:r}}class f extends p{constructor(e,t){super();const r=new g$4;e instanceof f?e.opnds.map(function(e){r.add(e)}):r.add(e),t instanceof f?t.opnds.map(function(e){r.add(e)}):r.add(t);const n=T$2(r);if(n.length>0){let e=null;n.map(function(t){(null===e||t.precedencee.toString());return(e.length>3?e.slice(3):e).join("&&")}}let x$2=class e extends p{constructor(t,r){super();const n=new g$4;t instanceof e?t.opnds.map(function(e){n.add(e)}):n.add(t),r instanceof e?r.opnds.map(function(e){n.add(e)}):n.add(r);const i=T$2(n);if(i.length>0){const e=i.sort(function(e,t){return e.compareTo(t)}),t=e[e.length-1];n.add(t)}this.opnds=Array.from(n.values())}equals(t){return this===t||t instanceof e&&r(this.opnds,t.opnds)}updateHashCode(e){e.update(this.opnds,"OR")}evaluate(e,t){for(let r=0;re.toString());return(e.length>3?e.slice(3):e).join("||")}};function T$2(e){const t=[];return e.values().map(function(e){e instanceof p.PrecedencePredicate&&t.push(e)}),t}function S$2(e,t){if(null===e){const e={state:null,alt:null,context:null,semanticContext:null};return t&&(e.reachesIntoOuterContext=0),e}{const r={};return r.state=e.state||null,r.alt=void 0===e.alt?null:e.alt,r.context=e.context||null,r.semanticContext=e.semanticContext||null,t&&(r.reachesIntoOuterContext=e.reachesIntoOuterContext||0,r.precedenceFilterSuppressed=e.precedenceFilterSuppressed||!1),r}}let m$1=class e{constructor(e,t){this.checkContext(e,t),e=S$2(e),t=S$2(t,!0),this.state=null!==e.state?e.state:t.state,this.alt=null!==e.alt?e.alt:t.alt,this.context=null!==e.context?e.context:t.context,this.semanticContext=null!==e.semanticContext?e.semanticContext:null!==t.semanticContext?t.semanticContext:p.NONE,this.reachesIntoOuterContext=t.reachesIntoOuterContext,this.precedenceFilterSuppressed=t.precedenceFilterSuppressed}checkContext(e,t){null!==e.context&&void 0!==e.context||null!==t&&null!==t.context&&void 0!==t.context||(this.context=null)}hashCode(){const e=new l$1;return this.updateHashCode(e),e.finish()}updateHashCode(e){e.update(this.state.stateNumber,this.alt,this.context,this.semanticContext)}equals(t){return this===t||t instanceof e&&this.state.stateNumber===t.state.stateNumber&&this.alt===t.alt&&(null===this.context?null===t.context:this.context.equals(t.context))&&this.semanticContext.equals(t.semanticContext)&&this.precedenceFilterSuppressed===t.precedenceFilterSuppressed}hashCodeForConfigSet(){const e=new l$1;return e.update(this.state.stateNumber,this.alt,this.semanticContext),e.finish()}equalsForConfigSet(t){return this===t||t instanceof e&&this.state.stateNumber===t.state.stateNumber&&this.alt===t.alt&&this.semanticContext.equals(t.semanticContext)}toString(){return"("+this.state+","+this.alt+(null!==this.context?",["+this.context.toString()+"]":"")+(this.semanticContext!==p.NONE?","+this.semanticContext.toString():"")+(this.reachesIntoOuterContext>0?",up="+this.reachesIntoOuterContext:"")+")"}},E$1=class e{constructor(e,t){this.start=e,this.stop=t}clone(){return new e(this.start,this.stop)}contains(e){return e>=this.start&&ethis.addInterval(e),this),this}reduce(e){if(e=r.stop?(this.intervals.splice(e+1,1),this.reduce(e)):t.stop>=r.start&&(this.intervals[e]=new E$1(t.start,r.stop),this.intervals.splice(e+1,1))}}complement(t,r){const n=new e;return n.addInterval(new E$1(t,r+1)),null!==this.intervals&&this.intervals.forEach(e=>n.removeRange(e)),n}contains(e){if(null===this.intervals)return!1;for(let t=0;tr.start&&e.stop=r.stop?(this.intervals.splice(t,1),t-=1):e.start"):e.push("'"+String.fromCharCode(r.start)+"'"):e.push("'"+String.fromCharCode(r.start)+"'..'"+String.fromCharCode(r.stop-1)+"'")}return e.length>1?"{"+e.join(", ")+"}":e[0]}toIndexString(){const e=[];for(let t=0;t"):e.push(r.start.toString()):e.push(r.start.toString()+".."+(r.stop-1).toString())}return e.length>1?"{"+e.join(", ")+"}":e[0]}toTokenString(e,t){const r=[];for(let n=0;n1?"{"+r.join(", ")+"}":r[0]}elementName(e,t,r){return r===i.EOF?"":r===i.EPSILON?"":e[r]||t[r]}get length(){return this.intervals.map(e=>e.length).reduce((e,t)=>e+t)}},C$1=class e{constructor(){this.atn=null,this.stateNumber=e.INVALID_STATE_NUMBER,this.stateType=null,this.ruleIndex=0,this.epsilonOnlyTransitions=!1,this.transitions=[],this.nextTokenWithinRule=null}toString(){return this.stateNumber}equals(t){return t instanceof e&&this.stateNumber===t.stateNumber}isNonGreedyExitState(){return!1}addTransition(e,t){void 0===t&&(t=-1),0===this.transitions.length?this.epsilonOnlyTransitions=e.isEpsilon:this.epsilonOnlyTransitions!==e.isEpsilon&&(this.epsilonOnlyTransitions=!1),-1===t?this.transitions.push(e):this.transitions.splice(t,1,e)}};C$1.INVALID_TYPE=0,C$1.BASIC=1,C$1.RULE_START=2,C$1.BLOCK_START=3,C$1.PLUS_BLOCK_START=4,C$1.STAR_BLOCK_START=5,C$1.TOKEN_START=6,C$1.RULE_STOP=7,C$1.BLOCK_END=8,C$1.STAR_LOOP_BACK=9,C$1.STAR_LOOP_ENTRY=10,C$1.PLUS_LOOP_BACK=11,C$1.LOOP_END=12,C$1.serializationNames=["INVALID","BASIC","RULE_START","BLOCK_START","PLUS_BLOCK_START","STAR_BLOCK_START","TOKEN_START","RULE_STOP","BLOCK_END","STAR_LOOP_BACK","STAR_LOOP_ENTRY","PLUS_LOOP_BACK","LOOP_END"],C$1.INVALID_STATE_NUMBER=-1;let A$2=class extends C$1{constructor(){return super(),this.stateType=C$1.RULE_STOP,this}},N$1=class{constructor(e){if(null==e)throw"target cannot be null.";this.target=e,this.isEpsilon=!1,this.label=null}};N$1.EPSILON=1,N$1.RANGE=2,N$1.RULE=3,N$1.PREDICATE=4,N$1.ATOM=5,N$1.ACTION=6,N$1.SET=7,N$1.NOT_SET=8,N$1.WILDCARD=9,N$1.PRECEDENCE=10,N$1.serializationNames=["INVALID","EPSILON","RANGE","RULE","PREDICATE","ATOM","ACTION","SET","NOT_SET","WILDCARD","PRECEDENCE"],N$1.serializationTypes={EpsilonTransition:N$1.EPSILON,RangeTransition:N$1.RANGE,RuleTransition:N$1.RULE,PredicateTransition:N$1.PREDICATE,AtomTransition:N$1.ATOM,ActionTransition:N$1.ACTION,SetTransition:N$1.SET,NotSetTransition:N$1.NOT_SET,WildcardTransition:N$1.WILDCARD,PrecedencePredicateTransition:N$1.PRECEDENCE};let k$1=class extends N$1{constructor(e,t,r,n){super(e),this.ruleIndex=t,this.precedence=r,this.followState=n,this.serializationType=N$1.RULE,this.isEpsilon=!0}matches(e,t,r){return!1}},I$2=class extends N$1{constructor(e,t){super(e),this.serializationType=N$1.SET,null!=t?this.label=t:(this.label=new _$1,this.label.addOne(i.INVALID_TYPE))}matches(e,t,r){return this.label.contains(e)}toString(){return this.label.toString()}},y$2=class extends I$2{constructor(e,t){super(e,t),this.serializationType=N$1.NOT_SET}matches(e,t,r){return e>=t&&e<=r&&!super.matches(e,t,r)}toString(){return"~"+super.toString()}},L$1=class extends N$1{constructor(e){super(e),this.serializationType=N$1.WILDCARD}matches(e,t,r){return e>=t&&e<=r}toString(){return"."}};class O extends N$1{constructor(e){super(e)}}let R$2=class{},w$2=class extends R$2{},v$2=class extends w$2{},P$1=class extends v$2{get ruleContext(){throw new Error("missing interface implementation")}},b$1=class extends v$2{},D$1=class extends b$1{};const F$1={toStringTree:function(e,t,r){t=t||null,null!==(r=r||null)&&(t=r.ruleNames);let n=F$1.getNodeText(e,t);n=function(e){return e.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r")}(n);const i=e.getChildCount();if(0===i)return n;let o="("+n+" ";i>0&&(n=F$1.toStringTree(e.getChild(0),t),o=o.concat(n));for(let r=1;r=0&&t0&&(e+=", "),this.returnStates[t]!==B$2.EMPTY_RETURN_STATE?(e+=this.returnStates[t],null!==this.parents[t]?e=e+" "+this.parents[t]:e+="null"):e+="$";return e+"]"}}get length(){return this.returnStates.length}},V$2=class e extends B$2{constructor(e,t){let r=0;const n=new l$1;null!==e?n.update(e,t):n.update(1),r=n.finish(),super(r),this.parentCtx=e,this.returnState=t}getParent(e){return this.parentCtx}getReturnState(e){return this.returnState}equals(t){return this===t||t instanceof e&&this.hashCode()===t.hashCode()&&this.returnState===t.returnState&&(null==this.parentCtx?null==t.parentCtx:this.parentCtx.equals(t.parentCtx))}toString(){const e=null===this.parentCtx?"":this.parentCtx.toString();return 0===e.length?this.returnState===B$2.EMPTY_RETURN_STATE?"$":""+this.returnState:this.returnState+" "+e}get length(){return 1}static create(t,r){return r===B$2.EMPTY_RETURN_STATE&&null===t?B$2.EMPTY:new e(t,r)}},q$2=class extends V$2{constructor(){super(null,B$2.EMPTY_RETURN_STATE)}isEmpty(){return!0}getParent(e){return null}getReturnState(e){return this.returnState}equals(e){return this===e}toString(){return"$"}};B$2.EMPTY=new q$2;let H$1=class{constructor(e,t){this.buckets=new Array(16),this.threshold=Math.floor(12),this.itemCount=0,this.hashFunction=e||h$2,this.equalsFunction=t||c$1}set(e,t){this._expand();const r=this._getSlot(e);let n=this.buckets[r];if(!n)return n=[[e,t]],this.buckets[r]=n,this.itemCount++,t;const i=n.find(t=>this.equalsFunction(t[0],e),this);if(i){const e=i[1];return i[1]=t,e}return n.push([e,t]),this.itemCount++,t}containsKey(e){const t=this._getBucket(e);return!!t&&!!t.find(t=>this.equalsFunction(t[0],e),this)}get(e){const t=this._getBucket(e);if(!t)return null;const r=t.find(t=>this.equalsFunction(t[0],e),this);return r?r[1]:null}entries(){return this.buckets.filter(e=>null!=e).flat(1)}getKeys(){return this.entries().map(e=>e[0])}getValues(){return this.entries().map(e=>e[1])}toString(){return"["+this.entries().map(e=>"{"+e[0]+":"+e[1]+"}").join(", ")+"]"}get length(){return this.itemCount}_getSlot(e){return this.hashFunction(e)&this.buckets.length-1}_getBucket(e){return this.buckets[this._getSlot(e)]}_expand(){if(this.itemCount<=this.threshold)return;const e=this.buckets,t=2*this.buckets.length;this.buckets=new Array(t),this.threshold=Math.floor(.75*t);for(const t of e)if(t)for(const e of t){const t=this._getSlot(e[0]);let r=this.buckets[t];r||(r=[],this.buckets[t]=r),r.push(e)}}};function K$2(e,t){if(null==t&&(t=U$2.EMPTY),null===t.parentCtx||t===U$2.EMPTY)return B$2.EMPTY;const r=K$2(e,t.parentCtx),n=e.states[t.invokingState].transitions[0];return V$2.create(r,n.followState.stateNumber)}function Y$1(e,t,r){if(e.isEmpty())return e;let n=r.get(e)||null;if(null!==n)return n;if(n=t.get(e),null!==n)return r.set(e,n),n;let i=!1,o=[];for(let n=0;nt.returnState&&(i[0]=t.returnState,i[1]=e.returnState);const o=new z$4([r,r],i);return null!==n&&n.set(e,t,o),o}const i=[e.returnState,t.returnState];let o=[e.parentCtx,t.parentCtx];e.returnState>t.returnState&&(i[0]=t.returnState,i[1]=e.returnState,o=[t.parentCtx,e.parentCtx]);const s=new z$4(o,i);return null!==n&&n.set(e,t,s),s}}(e,t,r,n);if(r){if(e instanceof q$2)return e;if(t instanceof q$2)return t}return e instanceof V$2&&(e=new z$4([e.getParent()],[e.returnState])),t instanceof V$2&&(t=new z$4([t.getParent()],[t.returnState])),function(e,t,r,n){if(null!==n){let r=n.get(e,t);if(null!==r)return B$2.trace_atn_sim&&console.log("mergeArrays a="+e+",b="+t+" -> previous"),r;if(r=n.get(t,e),null!==r)return B$2.trace_atn_sim&&console.log("mergeArrays a="+e+",b="+t+" -> previous"),r}let i=0,o=0,s=0,a=new Array(e.returnStates.length+t.returnStates.length).fill(0),c=new Array(e.returnStates.length+t.returnStates.length).fill(null);for(;i a"),e):l.equals(t)?(null!==n&&n.set(e,t,t),B$2.trace_atn_sim&&console.log("mergeArrays a="+e+",b="+t+" -> b"),t):(function(e){const t=new H$1;for(let r=0;r "+l),l)}(e,t,r,n)}let W$2=class e{constructor(){this.data=new Uint32Array(1)}set(t){e._checkIndex(t),this._resize(t),this.data[t>>>5]|=1<>>5;return!(r>=this.data.length||!(this.data[r]&1<>>5;r>=1;return r+32*e}}return 0}hashCode(){return l$1.hashStuff(this.values())}equals(t){return t instanceof e&&r(this.data,t.data)}toString(){return"{"+this.values().join(", ")+"}"}get length(){return this.data.map(t=>e._bitCount(t)).reduce((e,t)=>e+t,0)}_resize(e){const t=e+32>>>5;if(t<=this.data.length)return;const r=new Uint32Array(t);r.set(this.data),r.fill(0,this.data.length),this.data=r}static _checkIndex(e){if(e<0)throw new RangeError("index cannot be negative")}static _bitCount(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,e+=e>>8,0+(e+=e>>16)&63}},j$1=class e{constructor(e){this.atn=e}getDecisionLookahead(t){if(null===t)return null;const r=t.transitions.length,n=[];for(let i=0;i=this.states.length)throw"Invalid state number.";const r=this.states[e];let n=this.nextTokens(r);if(!n.contains(i.EPSILON))return n;const o=new _$1;for(o.addSet(n),o.removeOne(i.EPSILON);null!==t&&t.invokingState>=0&&n.contains(i.EPSILON);){const e=this.states[t.invokingState].transitions[0];n=this.nextTokens(e.followState),o.addSet(n),o.removeOne(i.EPSILON),t=t.parentCtx}return n.contains(i.EPSILON)&&o.addOne(i.EOF),o}};$$2.INVALID_ALT_NUMBER=0;let X$2=class extends C$1{constructor(){super(),this.stateType=C$1.BASIC}},J$2=class extends C$1{constructor(){return super(),this.decision=-1,this.nonGreedy=!1,this}},Z$2=class extends J$2{constructor(){return super(),this.endState=null,this}},Q$2=class extends C$1{constructor(){return super(),this.stateType=C$1.BLOCK_END,this.startState=null,this}},tt$1=class extends C$1{constructor(){return super(),this.stateType=C$1.LOOP_END,this.loopBackState=null,this}},et$1=class extends C$1{constructor(){return super(),this.stateType=C$1.RULE_START,this.stopState=null,this.isPrecedenceRule=!1,this}},nt$1=class extends J$2{constructor(){return super(),this.stateType=C$1.TOKEN_START,this}},st$1=class extends J$2{constructor(){return super(),this.stateType=C$1.PLUS_LOOP_BACK,this}},it$2=class extends C$1{constructor(){return super(),this.stateType=C$1.STAR_LOOP_BACK,this}},rt$1=class extends J$2{constructor(){return super(),this.stateType=C$1.STAR_LOOP_ENTRY,this.loopBackState=null,this.isPrecedenceDecision=null,this}},ot$1=class extends Z$2{constructor(){return super(),this.stateType=C$1.PLUS_BLOCK_START,this.loopBackState=null,this}};class at extends Z$2{constructor(){return super(),this.stateType=C$1.STAR_BLOCK_START,this}}let lt$1=class extends Z$2{constructor(){return super(),this.stateType=C$1.BLOCK_START,this}},ht$1=class extends N$1{constructor(e,t){super(e),this.label_=t,this.label=this.makeLabel(),this.serializationType=N$1.ATOM}makeLabel(){const e=new _$1;return e.addOne(this.label_),e}matches(e,t,r){return this.label_===e}toString(){return this.label_}};class ct extends N$1{constructor(e,t,r){super(e),this.serializationType=N$1.RANGE,this.start=t,this.stop=r,this.label=this.makeLabel()}makeLabel(){const e=new _$1;return e.addRange(this.start,this.stop),e}matches(e,t,r){return e>=this.start&&e<=this.stop}toString(){return"'"+String.fromCharCode(this.start)+"'..'"+String.fromCharCode(this.stop)+"'"}}let ut$1=class extends N$1{constructor(e,t,r,n){super(e),this.serializationType=N$1.ACTION,this.ruleIndex=t,this.actionIndex=void 0===r?-1:r,this.isCtxDependent=void 0!==n&&n,this.isEpsilon=!0}matches(e,t,r){return!1}toString(){return"action_"+this.ruleIndex+":"+this.actionIndex}},dt$1=class extends N$1{constructor(e,t){super(e),this.serializationType=N$1.EPSILON,this.isEpsilon=!0,this.outermostPrecedenceReturn=t}matches(e,t,r){return!1}toString(){return"epsilon"}},gt$1=class e extends p{constructor(e,t,r){super(),this.ruleIndex=void 0===e?-1:e,this.predIndex=void 0===t?-1:t,this.isCtxDependent=void 0!==r&&r}evaluate(e,t){const r=this.isCtxDependent?t:null;return e.sempred(r,this.ruleIndex,this.predIndex)}updateHashCode(e){e.update(this.ruleIndex,this.predIndex,this.isCtxDependent)}equals(t){return this===t||t instanceof e&&this.ruleIndex===t.ruleIndex&&this.predIndex===t.predIndex&&this.isCtxDependent===t.isCtxDependent}toString(){return"{"+this.ruleIndex+":"+this.predIndex+"}?"}};p.NONE=new gt$1;let pt$2=class extends O{constructor(e,t,r,n){super(e),this.serializationType=N$1.PREDICATE,this.ruleIndex=t,this.predIndex=r,this.isCtxDependent=n,this.isEpsilon=!0}matches(e,t,r){return!1}getPredicate(){return new gt$1(this.ruleIndex,this.predIndex,this.isCtxDependent)}toString(){return"pred_"+this.ruleIndex+":"+this.predIndex}},ft$1=class e extends p{constructor(e){super(),this.precedence=void 0===e?0:e}evaluate(e,t){return e.precpred(t,this.precedence)}evalPrecedence(e,t){return e.precpred(t,this.precedence)?p.NONE:null}compareTo(e){return this.precedence-e.precedence}updateHashCode(e){e.update(this.precedence)}equals(t){return this===t||t instanceof e&&this.precedence===t.precedence}toString(){return"{"+this.precedence+">=prec}?"}};p.PrecedencePredicate=ft$1;let xt$1=class extends O{constructor(e,t){super(e),this.serializationType=N$1.PRECEDENCE,this.precedence=t,this.isEpsilon=!0}matches(e,t,r){return!1}getPredicate(){return new ft$1(this.precedence)}toString(){return this.precedence+" >= _p"}},Tt$1=class{constructor(e){void 0===e&&(e=null),this.readOnly=!1,this.verifyATN=null===e||e.verifyATN,this.generateRuleBypassTransitions=null!==e&&e.generateRuleBypassTransitions}};Tt$1.defaultOptions=new Tt$1,Tt$1.defaultOptions.readOnly=!0;let St$1=class{constructor(e){this.actionType=e,this.isPositionDependent=!1}hashCode(){const e=new l$1;return this.updateHashCode(e),e.finish()}updateHashCode(e){e.update(this.actionType)}equals(e){return this===e}},mt$1=class extends St$1{constructor(){super(6)}execute(e){e.skip()}toString(){return"skip"}};mt$1.INSTANCE=new mt$1;let Et$1=class e extends St$1{constructor(e){super(0),this.channel=e}execute(e){e._channel=this.channel}updateHashCode(e){e.update(this.actionType,this.channel)}equals(t){return this===t||t instanceof e&&this.channel===t.channel}toString(){return"channel("+this.channel+")"}},_t$1=class e extends St$1{constructor(e,t){super(1),this.ruleIndex=e,this.actionIndex=t,this.isPositionDependent=!0}execute(e){e.action(null,this.ruleIndex,this.actionIndex)}updateHashCode(e){e.update(this.actionType,this.ruleIndex,this.actionIndex)}equals(t){return this===t||t instanceof e&&this.ruleIndex===t.ruleIndex&&this.actionIndex===t.actionIndex}},Ct$1=class extends St$1{constructor(){super(3)}execute(e){e.more()}toString(){return"more"}};Ct$1.INSTANCE=new Ct$1;let At$1=class e extends St$1{constructor(e){super(7),this.type=e}execute(e){e.type=this.type}updateHashCode(e){e.update(this.actionType,this.type)}equals(t){return this===t||t instanceof e&&this.type===t.type}toString(){return"type("+this.type+")"}},Nt$1=class e extends St$1{constructor(e){super(5),this.mode=e}execute(e){e.pushMode(this.mode)}updateHashCode(e){e.update(this.actionType,this.mode)}equals(t){return this===t||t instanceof e&&this.mode===t.mode}toString(){return"pushMode("+this.mode+")"}},kt$1=class extends St$1{constructor(){super(4)}execute(e){e.popMode()}toString(){return"popMode"}};kt$1.INSTANCE=new kt$1;let It$1=class e extends St$1{constructor(e){super(2),this.mode=e}execute(e){e.setMode(this.mode)}updateHashCode(e){e.update(this.actionType,this.mode)}equals(t){return this===t||t instanceof e&&this.mode===t.mode}toString(){return"mode("+this.mode+")"}};function yt$1(e,t){const r=[];return r[e-1]=t,r.map(function(e){return t})}let Lt$1=class{constructor(e){null==e&&(e=Tt$1.defaultOptions),this.deserializationOptions=e,this.stateFactories=null,this.actionFactories=null}deserialize(e){const t=this.reset(e);this.checkVersion(t),t&&this.skipUUID();const r=this.readATN();this.readStates(r,t),this.readRules(r,t),this.readModes(r);const n=[];return this.readSets(r,n,this.readInt.bind(this)),t&&this.readSets(r,n,this.readInt32.bind(this)),this.readEdges(r,n),this.readDecisions(r),this.readLexerActions(r,t),this.markPrecedenceDecisions(r),this.verifyATN(r),this.deserializationOptions.generateRuleBypassTransitions&&1===r.grammarType&&(this.generateRuleBypassTransitions(r),this.verifyATN(r)),r}reset(e){if(3===(e.charCodeAt?e.charCodeAt(0):e[0])){const t=function(e){const t=e.charCodeAt(0);return t>1?t-2:t+65534},r=e.split("").map(t);return r[0]=e.charCodeAt(0),this.data=r,this.pos=0,!0}return this.data=e,this.pos=0,!1}skipUUID(){let e=0;for(;e++<8;)this.readInt()}checkVersion(e){const t=this.readInt();if(!e&&4!==t)throw"Could not deserialize ATN with version "+t+" (expected 4)."}readATN(){const e=this.readInt(),t=this.readInt();return new $$2(e,t)}readStates(e,t){let r,n,i;const o=[],s=[],a=this.readInt();for(let r=0;r0;)i.addTransition(c.transitions[l-1]),c.transitions=c.transitions.slice(-1);e.ruleToStartState[t].addTransition(new dt$1(i)),o.addTransition(new dt$1(a));const u=new X$2;e.addState(u),u.addTransition(new ht$1(o,e.ruleToTokenType[t])),i.addTransition(new dt$1(u))}stateIsEndStateFor(e,t){if(e.ruleIndex!==t)return null;if(!(e instanceof rt$1))return null;const r=e.transitions[e.transitions.length-1].target;return r instanceof tt$1&&r.epsilonOnlyTransitions&&r.transitions[0].target instanceof A$2?e:null}markPrecedenceDecisions(e){for(let t=0;t=0):this.checkCondition(r.transitions.length<=1||r instanceof A$2)}}checkCondition(e,t){if(!e)throw null==t&&(t="IllegalState"),t}readInt(){return this.data[this.pos++]}readInt32(){return this.readInt()|this.readInt()<<16}edgeFactory(e,t,r,n,o,s,a,c){const l=e.states[n];switch(t){case N$1.EPSILON:return new dt$1(l);case N$1.RANGE:return new ct(l,0!==a?i.EOF:o,s);case N$1.RULE:return new k$1(e.states[o],s,a,l);case N$1.PREDICATE:return new pt$2(l,o,s,0!==a);case N$1.PRECEDENCE:return new xt$1(l,o);case N$1.ATOM:return new ht$1(l,0!==a?i.EOF:o);case N$1.ACTION:return new ut$1(l,o,s,0!==a);case N$1.SET:return new I$2(l,c[o]);case N$1.NOT_SET:return new y$2(l,c[o]);case N$1.WILDCARD:return new L$1(l);default:throw"The specified transition type: "+t+" is not valid."}}stateFactory(e,t){if(null===this.stateFactories){const e=[];e[C$1.INVALID_TYPE]=null,e[C$1.BASIC]=()=>new X$2,e[C$1.RULE_START]=()=>new et$1,e[C$1.BLOCK_START]=()=>new lt$1,e[C$1.PLUS_BLOCK_START]=()=>new ot$1,e[C$1.STAR_BLOCK_START]=()=>new at,e[C$1.TOKEN_START]=()=>new nt$1,e[C$1.RULE_STOP]=()=>new A$2,e[C$1.BLOCK_END]=()=>new Q$2,e[C$1.STAR_LOOP_BACK]=()=>new it$2,e[C$1.STAR_LOOP_ENTRY]=()=>new rt$1,e[C$1.PLUS_LOOP_BACK]=()=>new st$1,e[C$1.LOOP_END]=()=>new tt$1,this.stateFactories=e}if(e>this.stateFactories.length||null===this.stateFactories[e])throw"The specified state type "+e+" is not valid.";{const r=this.stateFactories[e]();if(null!==r)return r.ruleIndex=t,r}}lexerActionFactory(e,t,r){if(null===this.actionFactories){const e=[];e[0]=(e,t)=>new Et$1(e),e[1]=(e,t)=>new _t$1(e,t),e[2]=(e,t)=>new It$1(e),e[3]=(e,t)=>Ct$1.INSTANCE,e[4]=(e,t)=>kt$1.INSTANCE,e[5]=(e,t)=>new Nt$1(e),e[6]=(e,t)=>mt$1.INSTANCE,e[7]=(e,t)=>new At$1(e),this.actionFactories=e}if(e>this.actionFactories.length||null===this.actionFactories[e])throw"The specified lexer action type "+e+" is not valid.";return this.actionFactories[e](t,r)}},Ot$1=class{syntaxError(e,t,r,n,i,o){}reportAmbiguity(e,t,r,n,i,o,s){}reportAttemptingFullContext(e,t,r,n,i,o){}reportContextSensitivity(e,t,r,n,i,o){}},Rt$1=class extends Ot$1{constructor(){super()}syntaxError(e,t,r,n,i,o){console.error("line "+r+":"+n+" "+i)}};Rt$1.INSTANCE=new Rt$1;let wt$1=class extends Ot$1{constructor(e){if(super(),null===e)throw"delegates";return this.delegates=e,this}syntaxError(e,t,r,n,i,o){this.delegates.map(s=>s.syntaxError(e,t,r,n,i,o))}reportAmbiguity(e,t,r,n,i,o,s){this.delegates.map(a=>a.reportAmbiguity(e,t,r,n,i,o,s))}reportAttemptingFullContext(e,t,r,n,i,o){this.delegates.map(s=>s.reportAttemptingFullContext(e,t,r,n,i,o))}reportContextSensitivity(e,t,r,n,i,o){this.delegates.map(s=>s.reportContextSensitivity(e,t,r,n,i,o))}},vt$1=class{constructor(){this._listeners=[Rt$1.INSTANCE],this._interp=null,this._stateNumber=-1}checkVersion(e){const t="4.13.2";t!==e&&console.log("ANTLR runtime and generated code versions disagree: "+t+"!="+e)}addErrorListener(e){this._listeners.push(e)}removeErrorListeners(){this._listeners=[]}getLiteralNames(){return Object.getPrototypeOf(this).constructor.literalNames||[]}getSymbolicNames(){return Object.getPrototypeOf(this).constructor.symbolicNames||[]}getTokenNames(){if(!this.tokenNames){const e=this.getLiteralNames(),t=this.getSymbolicNames(),r=e.length>t.length?e.length:t.length;this.tokenNames=[];for(let n=0;n";let t=e.text;return null===t&&(t=e.type===i.EOF?"":"<"+e.type+">"),t=t.replace("\n","\\n").replace("\r","\\r").replace("\t","\\t"),"'"+t+"'"}getErrorListenerDispatch(){return console.warn("Calling deprecated method in Recognizer class: getErrorListenerDispatch()"),this.getErrorListener()}getErrorListener(){return new wt$1(this._listeners)}sempred(e,t,r){return!0}precpred(e,t){return!0}get atn(){return this._interp.atn}get state(){return this._stateNumber}set state(e){this._stateNumber=e}};vt$1.tokenTypeMapCache={},vt$1.ruleIndexMapCache={};class Pt extends i{constructor(e,t,r,n,o){super(),this.source=void 0!==e?e:Pt.EMPTY_SOURCE,this.type=void 0!==t?t:null,this.channel=void 0!==r?r:i.DEFAULT_CHANNEL,this.start=void 0!==n?n:-1,this.stop=void 0!==o?o:-1,this.tokenIndex=-1,null!==this.source[0]?(this.line=e[0].line,this.column=e[0].column):this.column=-1}clone(){const e=new Pt(this.source,this.type,this.channel,this.start,this.stop);return e.tokenIndex=this.tokenIndex,e.line=this.line,e.column=this.column,e.text=this.text,e}cloneWithType(e){const t=new Pt(this.source,e,this.channel,this.start,this.stop);return t.tokenIndex=this.tokenIndex,t.line=this.line,t.column=this.column,e===i.EOF&&(t.text=""),t}toString(){let e=this.text;return e=null!==e?e.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"):"","[@"+this.tokenIndex+","+this.start+":"+this.stop+"='"+e+"',<"+this.type+">"+(this.channel>0?",channel="+this.channel:"")+","+this.line+":"+this.column+"]"}get text(){if(null!==this._text)return this._text;const e=this.getInputStream();if(null===e)return null;const t=e.size;return this.start"}set text(e){this._text=e}}Pt.EMPTY_SOURCE=[null,null];class bt{}class Dt extends bt{constructor(e){super(),this.copyText=void 0!==e&&e}create(e,t,r,n,i,o,s,a){const c=new Pt(e,t,n,i,o);return c.line=s,c.column=a,null!==r?c.text=r:this.copyText&&null!==e[1]&&(c.text=e[1].getText(i,o)),c}createThin(e,t){const r=new Pt(null,e);return r.text=t,r}}Dt.DEFAULT=new Dt;let Ft$1=class e extends Error{constructor(t){super(t.message),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.message=t.message,this.recognizer=t.recognizer,this.input=t.input,this.ctx=t.ctx,this.offendingToken=null,this.offendingState=-1,null!==this.recognizer&&(this.offendingState=this.recognizer.state)}getExpectedTokens(){return null!==this.recognizer?this.recognizer.atn.getExpectedTokens(this.offendingState,this.ctx):null}toString(){return this.message}},Mt$1=class extends Ft$1{constructor(e,t,r,n){super({message:"",recognizer:e,input:t,ctx:null}),this.startIndex=r,this.deadEndConfigs=n}toString(){let e="";return this.startIndex>=0&&this.startIndex":"\n"===e?"\\n":"\t"===e?"\\t":"\r"===e?"\\r":e}getCharErrorDisplay(e){return"'"+this.getErrorDisplayForChar(e)+"'"}recover(e){this._input.LA(1)!==i.EOF&&(e instanceof Mt$1?this._interp.consume(this._input):this._input.consume())}get inputStream(){return this._input}set inputStream(e){this._input=null,this._tokenFactorySourcePair=[this,this._input],this.reset(),this._input=e,this._tokenFactorySourcePair=[this,this._input]}get sourceName(){return this._input.sourceName}get type(){return this._type}set type(e){this._type=e}get line(){return this._interp.line}set line(e){this._interp.line=e}get column(){return this._interp.column}set column(e){this._interp.column=e}get text(){return null!==this._text?this._text:this._interp.getText(this._input)}set text(e){this._text=e}};function Bt$1(e){return e.hashCodeForConfigSet()}function zt$1(e,t){return e===t||null!==e&&null!==t&&e.equalsForConfigSet(t)}Ut$1.DEFAULT_MODE=0,Ut$1.MORE=-2,Ut$1.SKIP=-3,Ut$1.DEFAULT_TOKEN_CHANNEL=i.DEFAULT_CHANNEL,Ut$1.HIDDEN=i.HIDDEN_CHANNEL,Ut$1.MIN_CHAR_VALUE=0,Ut$1.MAX_CHAR_VALUE=1114111;class Vt{constructor(e){this.configLookup=new g$4(Bt$1,zt$1),this.fullCtx=void 0===e||e,this.readOnly=!1,this.configs=[],this.uniqueAlt=0,this.conflictingAlts=null,this.hasSemanticContext=!1,this.dipsIntoOuterContext=!1,this.cachedHashCode=-1}add(e,t){if(void 0===t&&(t=null),this.readOnly)throw"This set is readonly";e.semanticContext!==p.NONE&&(this.hasSemanticContext=!0),e.reachesIntoOuterContext>0&&(this.dipsIntoOuterContext=!0);const r=this.configLookup.getOrAdd(e);if(r===e)return this.cachedHashCode=-1,this.configs.push(e),!0;const n=!this.fullCtx,i=G$1(r.context,e.context,n,t);return r.reachesIntoOuterContext=Math.max(r.reachesIntoOuterContext,e.reachesIntoOuterContext),e.precedenceFilterSuppressed&&(r.precedenceFilterSuppressed=!0),r.context=i,!0}getStates(){const e=new g$4;for(let t=0;te.MAX_DFA_EDGE)return null;let n=t.edges[r-e.MIN_DFA_EDGE];return void 0===n&&(n=null),e.debug&&null!==n&&console.log("reuse state "+t.stateNumber+" edge to "+n.stateNumber),n}computeTargetState(e,t,r){const n=new Kt$1;return this.getReachableConfigSet(e,t.configs,n,r),0===n.items.length?(n.hasSemanticContext||this.addDFAEdge(t,r,Ht$1.ERROR),Ht$1.ERROR):this.addDFAEdge(t,r,null,n)}failOrAccept(e,t,r,n){if(null!==this.prevAccept.dfaState){const r=e.dfaState.lexerActionExecutor;return this.accept(t,r,this.startIndex,e.index,e.line,e.column),e.dfaState.prediction}if(n===i.EOF&&t.index===this.startIndex)return i.EOF;throw new Mt$1(this.recog,t,this.startIndex,r)}getReachableConfigSet(t,r,n,o){let s=$$2.INVALID_ALT_NUMBER;for(let a=0;ae.MAX_DFA_EDGE||(e.debug&&console.log("EDGE "+t+" -> "+n+" upon "+r),null===t.edges&&(t.edges=[]),t.edges[r-e.MIN_DFA_EDGE]=n),n}addDFAState(e){const t=new qt$1(null,e);let r=null;for(let t=0;te.startsWith("k-")).map(e=>this.data[e],this)}};const Qt$1={SLL:0,LL:1,LL_EXACT_AMBIG_DETECTION:2,hasSLLConflictTerminatingPrediction:function(e,t){if(Qt$1.allConfigsInRuleStopStates(t))return!0;if(e===Qt$1.SLL&&t.hasSemanticContext){const e=new Vt;for(let r=0;r1)return!0;return!1},allSubsetsEqual:function(e){let t=null;for(let r=0;r "+s),0===s.items.length?null:s}removeAllConfigsNotInRuleStopState(e,t){if(te$1.allConfigsInRuleStopStates(e))return e;const r=new Vt(e.fullCtx);for(let n=0;n0&&(o=this.getAltThatFinishedDecisionEntryRule(i),o!==$$2.INVALID_ALT_NUMBER)?o:$$2.INVALID_ALT_NUMBER}getAltThatFinishedDecisionEntryRule(e){const t=[];for(let r=0;r0||n.state instanceof A$2&&n.context.hasEmptyPath())&&t.indexOf(n.alt)<0&&t.push(n.alt)}return 0===t.length?$$2.INVALID_ALT_NUMBER:Math.min.apply(null,t)}splitAccordingToSemanticValidity(e,t){const r=new Vt(e.fullCtx),n=new Vt(e.fullCtx);for(let i=0;i=0&&(n+=1)}this.closureCheckingStopState(d,t,r,u,i,n,s)}}}canDropLoopEntryEdgeInLeftRecursiveRule(e){const t=e.state;if(t.stateType!==C$1.STAR_LOOP_ENTRY)return!1;if(t.stateType!==C$1.STAR_LOOP_ENTRY||!t.isPrecedenceDecision||e.context.isEmpty()||e.context.hasEmptyPath())return!1;const r=e.context.length;for(let n=0;n=0?this.parser.ruleNames[e]:""}getEpsilonTarget(e,t,r,n,o,s){switch(t.serializationType){case N$1.RULE:return this.ruleTransition(e,t);case N$1.PRECEDENCE:return this.precedenceTransition(e,t,r,n,o);case N$1.PREDICATE:return this.predTransition(e,t,r,n,o);case N$1.ACTION:return this.actionTransition(e,t);case N$1.EPSILON:return new m$1({state:t.target},e);case N$1.ATOM:case N$1.RANGE:case N$1.SET:return s&&t.matches(i.EOF,0,1)?new m$1({state:t.target},e):null;default:return null}}actionTransition(e,t){if(this.debug){const e=-1===t.actionIndex?65535:t.actionIndex;console.log("ACTION edge "+t.ruleIndex+":"+e)}return new m$1({state:t.target},e)}precedenceTransition(e,t,r,n,i){this.debug&&(console.log("PRED (collectPredicates="+r+") "+t.precedence+">=_p, ctx dependent=true"),null!==this.parser&&console.log("context surrounding pred is "+d(this.parser.getRuleInvocationStack())));let o=null;if(r&&n)if(i){const r=this._input.index;this._input.seek(this._startIndex);const n=t.getPredicate().evaluate(this.parser,this._outerContext);this._input.seek(r),n&&(o=new m$1({state:t.target},e))}else{const r=p.andContext(e.semanticContext,t.getPredicate());o=new m$1({state:t.target,semanticContext:r},e)}else o=new m$1({state:t.target},e);return this.debug&&console.log("config from pred transition="+o),o}predTransition(e,t,r,n,i){this.debug&&(console.log("PRED (collectPredicates="+r+") "+t.ruleIndex+":"+t.predIndex+", ctx dependent="+t.isCtxDependent),null!==this.parser&&console.log("context surrounding pred is "+d(this.parser.getRuleInvocationStack())));let o=null;if(r&&(t.isCtxDependent&&n||!t.isCtxDependent))if(i){const r=this._input.index;this._input.seek(this._startIndex);const n=t.getPredicate().evaluate(this.parser,this._outerContext);this._input.seek(r),n&&(o=new m$1({state:t.target},e))}else{const r=p.andContext(e.semanticContext,t.getPredicate());o=new m$1({state:t.target,semanticContext:r},e)}else o=new m$1({state:t.target},e);return this.debug&&console.log("config from pred transition="+o),o}ruleTransition(e,t){this.debug&&console.log("CALL rule "+this.getRuleName(t.target.ruleIndex)+", ctx="+e.context);const r=t.followState,n=V$2.create(e.context,r.stateNumber);return new m$1({state:t.target,context:n},e)}getConflictingAlts(e){const t=te$1.getConflictingAltSubsets(e);return te$1.getAlts(t)}getConflictingAltsOrUniqueAlt(e){let t=null;return e.uniqueAlt!==$$2.INVALID_ALT_NUMBER?(t=new W$2,t.set(e.uniqueAlt)):t=e.conflictingAlts,t}getTokenName(e){if(e===i.EOF)return"EOF";if(null!==this.parser&&null!==this.parser.literalNames){if(!(e>=this.parser.literalNames.length&&e>=this.parser.symbolicNames.length))return(this.parser.literalNames[e]||this.parser.symbolicNames[e])+"<"+e+">";console.log(e+" ttype out of range: "+this.parser.literalNames),console.log(""+this.parser.getInputStream().getTokens())}return""+e}getLookaheadName(e){return this.getTokenName(e.LA(1))}dumpDeadEndConfigs(e){console.log("dead end configs: ");const t=e.getDeadEndConfigs();for(let e=0;e0){const e=r.state.transitions[0];e instanceof ht$1?n="Atom "+this.getTokenName(e.label):e instanceof I$2&&(n=(e instanceof y$2?"~":"")+"Set "+e.set)}console.error(r.toString(this.parser,!0)+":"+n)}}noViableAlt(e,t,r,n){return new ee$1(this.parser,e,e.get(n),e.LT(1),r,t)}getUniqueAlt(e){let t=$$2.INVALID_ALT_NUMBER;for(let r=0;r "+n+" upon "+this.getTokenName(r)),null===n)return null;if(n=this.addDFAState(e,n),null===t||r<-1||r>this.atn.maxTokenType)return n;if(null===t.edges&&(t.edges=[]),t.edges[r+1]=n,this.debug){const t=null===this.parser?null:this.parser.literalNames,r=null===this.parser?null:this.parser.symbolicNames;console.log("DFA=\n"+e.toString(t,r))}return n}addDFAState(e,t){if(t===Ht$1.ERROR)return t;const r=e.states.get(t);return null!==r?(this.trace_atn_sim&&console.log("addDFAState "+t+" exists"),r):(t.stateNumber=e.states.length,t.configs.readOnly||(t.configs.optimizeConfigs(this),t.configs.setReadonly(!0)),this.trace_atn_sim&&console.log("addDFAState new "+t),e.states.add(t),this.debug&&console.log("adding new DFA state: "+t),t)}reportAttemptingFullContext(e,t,r,n,i){if(this.debug||this.retry_debug){const t=new E$1(n,i+1);console.log("reportAttemptingFullContext decision="+e.decision+":"+r+", input="+this.parser.getTokenStream().getText(t))}null!==this.parser&&this.parser.getErrorListener().reportAttemptingFullContext(this.parser,e,n,i,t,r)}reportContextSensitivity(e,t,r,n,i){if(this.debug||this.retry_debug){const t=new E$1(n,i+1);console.log("reportContextSensitivity decision="+e.decision+":"+r+", input="+this.parser.getTokenStream().getText(t))}null!==this.parser&&this.parser.getErrorListener().reportContextSensitivity(this.parser,e,n,i,t,r)}reportAmbiguity(e,t,r,n,i,o,s){if(this.debug||this.retry_debug){const e=new E$1(r,n+1);console.log("reportAmbiguity "+o+":"+s+", input="+this.parser.getTokenStream().getText(e))}null!==this.parser&&this.parser.getErrorListener().reportAmbiguity(this.parser,e,r,n,i,o,s)}},ie$1=class{constructor(){this.cache=new H$1}add(e){if(e===B$2.EMPTY)return B$2.EMPTY;const t=this.cache.get(e)||null;return null!==t?t:(this.cache.set(e,e),e)}get(e){return this.cache.get(e)||null}get length(){return this.cache.length}};const re$1={ATN:$$2,ATNDeserializer:Lt$1,LexerATNSimulator:Xt$1,ParserATNSimulator:se$1,PredictionMode:te$1,PredictionContextCache:ie$1};let oe$1=class{constructor(e,t,r){this.dfa=e,this.literalNames=t||[],this.symbolicNames=r||[]}toString(){if(null===this.dfa.s0)return null;let e="";const t=this.dfa.sortedStates();for(let r=0;r"),e=e.concat(this.getStateString(t)),e=e.concat("\n"))}}}return 0===e.length?null:e}getEdgeLabel(e){return 0===e?"EOF":null!==this.literalNames||null!==this.symbolicNames?this.literalNames[e-1]||this.symbolicNames[e-1]:String.fromCharCode(e-1)}getStateString(e){const t=(e.isAcceptState?":":"")+"s"+e.stateNumber+(e.requiresFullContext?"^":"");return e.isAcceptState?null!==e.predicates?t+"=>"+d(e.predicates):t+"=>"+e.prediction.toString():t}},ae$1=class extends oe$1{constructor(e){super(e,null)}getEdgeLabel(e){return"'"+String.fromCharCode(e)+"'"}};class le{constructor(e,t){if(void 0===t&&(t=0),this.atnStartState=e,this.decision=t,this._states=new g$4,this.s0=null,this.precedenceDfa=!1,e instanceof rt$1&&e.isPrecedenceDecision){this.precedenceDfa=!0;const e=new qt$1(null,new Vt);e.edges=[],e.isAcceptState=!1,e.requiresFullContext=!1,this.s0=e}}getPrecedenceStartState(e){if(!this.precedenceDfa)throw"Only precedence DFAs may contain a precedence start state.";return e<0||e>=this.s0.edges.length?null:this.s0.edges[e]||null}setPrecedenceStartState(e,t){if(!this.precedenceDfa)throw"Only precedence DFAs may contain a precedence start state.";e<0||(this.s0.edges[e]=t)}setPrecedenceDfa(e){if(this.precedenceDfa!==e){if(this._states=new g$4,e){const e=new qt$1(null,new Vt);e.edges=[],e.isAcceptState=!1,e.requiresFullContext=!1,this.s0=e}else this.s0=null;this.precedenceDfa=e}}sortedStates(){return this._states.values().sort(function(e,t){return e.stateNumber-t.stateNumber})}toString(e,t){return e=e||null,t=t||null,null===this.s0?"":new oe$1(this,e,t).toString()}toLexerString(){return null===this.s0?"":new ae$1(this).toString()}get states(){return this._states}}const he$2={DFA:le,DFASerializer:oe$1,LexerDFASerializer:ae$1,PredPrediction:Jt$1},ce={PredictionContext:B$2},ue$1={Interval:E$1,IntervalSet:_$1};let de$2=class{visitTerminal(e){}visitErrorNode(e){}enterEveryRule(e){}exitEveryRule(e){}},ge$1=class{visit(e){return Array.isArray(e)?e.map(function(e){return e.accept(this)},this):e.accept(this)}visitChildren(e){return e.children?this.visit(e.children):null}visitTerminal(e){}visitErrorNode(e){}},pe$1=class{walk(e,t){if(t instanceof D$1||void 0!==t.isErrorNode&&t.isErrorNode())e.visitErrorNode(t);else if(t instanceof b$1)e.visitTerminal(t);else{this.enterRule(e,t);for(let r=0;r=i.length)return""+r;const o=i[n]||null;return null===o||0===o.length?""+r:`${r} (${o})`}getConflictingAlts(e,t){if(null!==e)return e;const r=new W$2;for(let e=0;e=0&&e.consume(),this.lastErrorIndex=e._input.index,null===this.lastErrorStates&&(this.lastErrorStates=[]),this.lastErrorStates.push(e.state);const r=this.getErrorRecoverySet(e);this.consumeUntil(e,r)}sync(e){if(this.inErrorRecoveryMode(e))return;const t=e._interp.atn.states[e.state],r=e.getTokenStream().LA(1),n=e.atn.nextTokens(t);if(n.contains(r))return this.nextTokensContext=null,void(this.nextTokenState=C$1.INVALID_STATE_NUMBER);if(n.contains(i.EPSILON))null===this.nextTokensContext&&(this.nextTokensContext=e._ctx,this.nextTokensState=e._stateNumber);else switch(t.stateType){case C$1.BLOCK_START:case C$1.STAR_BLOCK_START:case C$1.PLUS_BLOCK_START:case C$1.STAR_LOOP_ENTRY:if(null!==this.singleTokenDeletion(e))return;throw new xe(e);case C$1.PLUS_LOOP_BACK:case C$1.STAR_LOOP_BACK:{this.reportUnwantedToken(e);const t=new _$1;t.addSet(e.getExpectedTokens());const r=t.addSet(this.getErrorRecoverySet(e));this.consumeUntil(e,r)}}}reportNoViableAlternative(e,t){const r=e.getTokenStream();let n;n=null!==r?t.startToken.type===i.EOF?"":r.getText(new E$1(t.startToken.tokenIndex,t.offendingToken.tokenIndex)):"";const o="no viable alternative at input "+this.escapeWSAndQuote(n);e.notifyErrorListeners(o,t.offendingToken,t)}reportInputMismatch(e,t){const r="mismatched input "+this.getTokenErrorDisplay(t.offendingToken)+" expecting "+t.getExpectedTokens().toString(e.literalNames,e.symbolicNames);e.notifyErrorListeners(r,t.offendingToken,t)}reportFailedPredicate(e,t){const r="rule "+e.ruleNames[e._ctx.ruleIndex]+" "+t.message;e.notifyErrorListeners(r,t.offendingToken,t)}reportUnwantedToken(e){if(this.inErrorRecoveryMode(e))return;this.beginErrorCondition(e);const t=e.getCurrentToken(),r="extraneous input "+this.getTokenErrorDisplay(t)+" expecting "+this.getExpectedTokens(e).toString(e.literalNames,e.symbolicNames);e.notifyErrorListeners(r,t,null)}reportMissingToken(e){if(this.inErrorRecoveryMode(e))return;this.beginErrorCondition(e);const t=e.getCurrentToken(),r="missing "+this.getExpectedTokens(e).toString(e.literalNames,e.symbolicNames)+" at "+this.getTokenErrorDisplay(t);e.notifyErrorListeners(r,t,null)}recoverInline(e){const t=this.singleTokenDeletion(e);if(null!==t)return e.consume(),t;if(this.singleTokenInsertion(e))return this.getMissingSymbol(e);throw new xe(e)}singleTokenInsertion(e){const t=e.getTokenStream().LA(1),r=e._interp.atn,n=r.states[e.state].transitions[0].target;return!!r.nextTokens(n,e._ctx).contains(t)&&(this.reportMissingToken(e),!0)}singleTokenDeletion(e){const t=e.getTokenStream().LA(2);if(this.getExpectedTokens(e).contains(t)){this.reportUnwantedToken(e),e.consume();const t=e.getCurrentToken();return this.reportMatch(e),t}return null}getMissingSymbol(e){const t=e.getCurrentToken(),r=this.getExpectedTokens(e).first();let n;n=r===i.EOF?"":"";let o=t;const s=e.getTokenStream().LT(-1);return o.type===i.EOF&&null!==s&&(o=s),e.getTokenFactory().create(o.source,r,n,i.DEFAULT_CHANNEL,-1,-1,o.line,o.column)}getExpectedTokens(e){return e.getExpectedTokens()}getTokenErrorDisplay(e){if(null===e)return"";let t=e.text;return null===t&&(t=e.type===i.EOF?"":"<"+e.type+">"),this.escapeWSAndQuote(t)}escapeWSAndQuote(e){return"'"+(e=(e=(e=e.replace(/\n/g,"\\n")).replace(/\r/g,"\\r")).replace(/\t/g,"\\t"))+"'"}getErrorRecoverySet(e){const t=e._interp.atn;let r=e._ctx;const n=new _$1;for(;null!==r&&r.invokingState>=0;){const e=t.states[r.invokingState].transitions[0],i=t.nextTokens(e.followState);n.addSet(i),r=r.parentCtx}return n.removeOne(i.EPSILON),n}consumeUntil(e,t){let r=e.getTokenStream().LA(1);for(;r!==i.EOF&&!t.contains(r);)e.consume(),r=e.getTokenStream().LA(1)}}class Ae extends Ce{constructor(){super()}recover(e,t){let r=e._ctx;for(;null!==r;)r.exception=t,r=r.parentCtx;throw new Ee$1(t)}recoverInline(e){this.recover(e,new xe(e))}sync(e){}}const Ne$1={RecognitionException:Ft$1,NoViableAltException:ee$1,LexerNoViableAltException:Mt$1,InputMismatchException:xe,FailedPredicateException:Te$1,DiagnosticErrorListener:me$1,BailErrorStrategy:Ae,DefaultErrorStrategy:Ce,ErrorListener:Ot$1};let ke$1=class{constructor(e,t){if(this.name="",this.strdata=e,this.decodeToUnicodeCodePoints=t||!1,this._index=0,this.data=[],this.decodeToUnicodeCodePoints)for(let e=0;e=this._size)throw"cannot consume EOF";this._index+=1}LA(e){if(0===e)return 0;e<0&&(e+=1);const t=this._index+e-1;return t<0||t>=this._size?i.EOF:this.data[t]}LT(e){return this.LA(e)}mark(){return-1}release(e){}seek(e){e<=this._index?this._index=e:this._index=Math.min(e,this._size)}getText(e,t){if(t>=this._size&&(t=this._size-1),e>=this._size)return"";if(this.decodeToUnicodeCodePoints){let r="";for(let n=e;n<=t;n++)r+=String.fromCodePoint(this.data[n]);return r}return this.strdata.slice(e,t+1)}toString(){return this.strdata}get index(){return this._index}get size(){return this._size}};class Ie extends ke$1{constructor(e,t){super(e,t)}}n(763);class Oe extends Ie{static fromPath(e,t,r){throw new Error("FileStream is only available when running in Node!")}constructor(e,t,r){throw new Error("FileStream is only available when running in Node!")}}const Re$1={fromString:function(e){return new ke$1(e,!0)},fromBlob:function(e,t,r,n){const i=new window.FileReader;i.onload=function(e){const t=new ke$1(e.target.result,!0);r(t)},i.onerror=n,i.readAsText(e,t)},fromBuffer:function(e,t){return new ke$1(e.toString(t),!0)},fromPath:function(e,t,r){Oe.fromPath(e,t,r)},fromPathSync:function(e,t){return new Oe(e,t)}},we={arrayToString:d,stringToCharArray:function(e){let t=new Uint16Array(e.length);for(let r=0;r=0&&(this.fetchedEOF?this.index0)||this.fetch(t)>=t}fetch(e){if(this.fetchedEOF)return 0;for(let t=0;t=this.tokens.length&&(t=this.tokens.length-1);for(let o=e;o=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[t]}adjustSeekIndex(e){return e}lazyInit(){-1===this.index&&this.setup()}setup(){this.sync(0),this.index=this.adjustSeekIndex(0)}setTokenSource(e){this.tokenSource=e,this.tokens=[],this.index=-1,this.fetchedEOF=!1}nextTokenOnChannel(e,t){if(this.sync(e),e>=this.tokens.length)return-1;let r=this.tokens[e];for(;r.channel!==t;){if(r.type===i.EOF)return-1;e+=1,this.sync(e),r=this.tokens[e]}return e}previousTokenOnChannel(e,t){for(;e>=0&&this.tokens[e].channel!==t;)e-=1;return e}getHiddenTokensToRight(e,t){if(void 0===t&&(t=-1),this.lazyInit(),e<0||e>=this.tokens.length)throw e+" not in 0.."+this.tokens.length-1;const r=this.nextTokenOnChannel(e+1,Ut$1.DEFAULT_TOKEN_CHANNEL),n=e+1,i=-1===r?this.tokens.length-1:r;return this.filterForChannel(n,i,t)}getHiddenTokensToLeft(e,t){if(void 0===t&&(t=-1),this.lazyInit(),e<0||e>=this.tokens.length)throw e+" not in 0.."+this.tokens.length-1;const r=this.previousTokenOnChannel(e-1,Ut$1.DEFAULT_TOKEN_CHANNEL);if(r===e-1)return null;const n=r+1,i=e-1;return this.filterForChannel(n,i,t)}filterForChannel(e,t,r){const n=[];for(let i=e;i=this.tokens.length&&(r=this.tokens.length-1);let n="";for(let e=t;e=0&&this._parseListeners.splice(t,1),0===this._parseListeners.length&&(this._parseListeners=null)}}removeParseListeners(){this._parseListeners=null}triggerEnterRuleEvent(){if(null!==this._parseListeners){const e=this._ctx;this._parseListeners.forEach(function(t){t.enterEveryRule(e),e.enterRule(t)})}}triggerExitRuleEvent(){if(null!==this._parseListeners){const e=this._ctx;this._parseListeners.slice(0).reverse().forEach(function(t){e.exitRule(t),t.exitEveryRule(e)})}}getTokenFactory(){return this._input.tokenSource._factory}setTokenFactory(e){this._input.tokenSource._factory=e}getATNWithBypassAlts(){const e=this.getSerializedATN();if(null===e)throw"The current parser does not support an ATN with bypass alternatives.";let t=this.bypassAltsAtnCache[e];if(null===t){const r=new Tt$1;r.generateRuleBypassTransitions=!0,t=new Lt$1(r).deserialize(e),this.bypassAltsAtnCache[e]=t}return t}getInputStream(){return this.getTokenStream()}setInputStream(e){this.setTokenStream(e)}getTokenStream(){return this._input}setTokenStream(e){this._input=null,this.reset(),this._input=e}get syntaxErrorsCount(){return this._syntaxErrors}getCurrentToken(){return this._input.LT(1)}notifyErrorListeners(e,t,r){r=r||null,null===(t=t||null)&&(t=this.getCurrentToken()),this._syntaxErrors+=1;const n=t.line,i=t.column;this.getErrorListener().syntaxError(this,t,n,i,e,r)}consume(){const e=this.getCurrentToken();e.type!==i.EOF&&this.getInputStream().consume();const t=null!==this._parseListeners&&this._parseListeners.length>0;if(this.buildParseTrees||t){let r;r=this._errHandler.inErrorRecoveryMode(this)?this._ctx.addErrorNode(e):this._ctx.addTokenNode(e),r.invokingState=this.state,t&&this._parseListeners.forEach(function(e){r instanceof D$1||void 0!==r.isErrorNode&&r.isErrorNode()?e.visitErrorNode(r):r instanceof b$1&&e.visitTerminal(r)})}return e}addContextToParseTree(){null!==this._ctx.parentCtx&&this._ctx.parentCtx.addChild(this._ctx)}enterRule(e,t,r){this.state=t,this._ctx=e,this._ctx.start=this._input.LT(1),this.buildParseTrees&&this.addContextToParseTree(),this.triggerEnterRuleEvent()}exitRule(){this._ctx.stop=this._input.LT(-1),this.triggerExitRuleEvent(),this.state=this._ctx.invokingState,this._ctx=this._ctx.parentCtx}enterOuterAlt(e,t){e.setAltNumber(t),this.buildParseTrees&&this._ctx!==e&&null!==this._ctx.parentCtx&&(this._ctx.parentCtx.removeLastChild(),this._ctx.parentCtx.addChild(e)),this._ctx=e}getPrecedence(){return 0===this._precedenceStack.length?-1:this._precedenceStack[this._precedenceStack.length-1]}enterRecursionRule(e,t,r,n){this.state=t,this._precedenceStack.push(n),this._ctx=e,this._ctx.start=this._input.LT(1),this.triggerEnterRuleEvent()}pushNewRecursionContext(e,t,r){const n=this._ctx;n.parentCtx=e,n.invokingState=t,n.stop=this._input.LT(-1),this._ctx=e,this._ctx.start=n.start,this.buildParseTrees&&this._ctx.addChild(n),this.triggerEnterRuleEvent()}unrollRecursionContexts(e){this._precedenceStack.pop(),this._ctx.stop=this._input.LT(-1);const t=this._ctx,r=this.getParseListeners();if(null!==r&&r.length>0)for(;this._ctx!==e;)this.triggerExitRuleEvent(),this._ctx=this._ctx.parentCtx;else this._ctx=e;t.parentCtx=e,this.buildParseTrees&&null!==e&&e.addChild(t)}getInvokingContext(e){let t=this._ctx;for(;null!==t;){if(t.ruleIndex===e)return t;t=t.parentCtx}return null}precpred(e,t){return t>=this._precedenceStack[this._precedenceStack.length-1]}inContext(e){return!1}isExpectedToken(e){const t=this._interp.atn;let r=this._ctx;const n=t.states[this.state];let o=t.nextTokens(n);if(o.contains(e))return!0;if(!o.contains(i.EPSILON))return!1;for(;null!==r&&r.invokingState>=0&&o.contains(i.EPSILON);){const n=t.states[r.invokingState].transitions[0];if(o=t.nextTokens(n.followState),o.contains(e))return!0;r=r.parentCtx}return!(!o.contains(i.EPSILON)||e!==i.EOF)}getExpectedTokens(){return this._interp.atn.getExpectedTokens(this.state,this._ctx)}getExpectedTokensWithinCurrentRule(){const e=this._interp.atn,t=e.states[this.state];return e.nextTokens(t)}getRuleIndex(e){const t=this.getRuleIndexMap()[e];return null!==t?t:-1}getRuleInvocationStack(e){null===(e=e||null)&&(e=this._ctx);const t=[];for(;null!==e;){const r=e.ruleIndex;r<0?t.push("n/a"):t.push(this.ruleNames[r]),e=e.parentCtx}return t}getDFAStrings(){return this._interp.decisionToDFA.toString()}dumpDFA(){let e=!1;for(let t=0;t0&&(e&&console.log(),this.printer.println("Decision "+r.decision+":"),this.printer.print(r.toString(this.literalNames,this.symbolicNames)),e=!0)}}getSourceName(){return this._input.getSourceName()}setTrace(e){e?(null!==this._tracer&&this.removeParseListener(this._tracer),this._tracer=new De$1(this),this.addParseListener(this._tracer)):(this.removeParseListener(this._tracer),this._tracer=null)}}Fe.bypassAltsAtnCache={};let Me$1=class extends b$1{constructor(e){super(),this.parentCtx=null,this.symbol=e}getChild(e){return null}getSymbol(){return this.symbol}getParent(){return this.parentCtx}getPayload(){return this.symbol}getSourceInterval(){if(null===this.symbol)return E$1.INVALID_INTERVAL;const e=this.symbol.tokenIndex;return new E$1(e,e)}getChildCount(){return 0}accept(e){return e.visitTerminal(this)}getText(){return this.symbol.text}toString(){return this.symbol.type===i.EOF?"":this.symbol.text}},Ue$1=class extends Me$1{constructor(e){super(e)}isErrorNode(){return!0}accept(e){return e.visitErrorNode(this)}},Be$1=class extends U$2{constructor(e,t){super(e,t),this.children=null,this.start=null,this.stop=null,this.exception=null}copyFrom(e){this.parentCtx=e.parentCtx,this.invokingState=e.invokingState,this.children=null,this.start=e.start,this.stop=e.stop,e.children&&(this.children=[],e.children.map(function(e){e instanceof Ue$1&&(this.children.push(e),e.parentCtx=this)},this))}enterRule(e){}exitRule(e){}addChild(e){return null===this.children&&(this.children=[]),this.children.push(e),e}removeLastChild(){null!==this.children&&this.children.pop()}addTokenNode(e){const t=new Me$1(e);return this.addChild(t),t.parentCtx=this,t}addErrorNode(e){const t=new Ue$1(e);return this.addChild(t),t.parentCtx=this,t}getChild(e,t){if(t=t||null,null===this.children||e<0||e>=this.children.length)return null;if(null===t)return this.children[e];for(let r=0;r=this.children.length)return null;for(let r=0;r2&&void 0!==arguments[2]?arguments[2]:e.DEFAULT_PROGRAM_NAME;n="number"==typeof t?t:t.tokenIndex;let o=this.getProgram(i),s=new He$1(this.tokens,n,o.length,r);o.push(s)}insertBefore(t,r){let n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.DEFAULT_PROGRAM_NAME;n="number"==typeof t?t:t.tokenIndex;const o=this.getProgram(i),s=new qe$1(this.tokens,n,o.length,r);o.push(s)}replaceSingle(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.DEFAULT_PROGRAM_NAME;this.replace(t,t,r,n)}replace(t,r,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.DEFAULT_PROGRAM_NAME;if("number"!=typeof t&&(t=t.tokenIndex),"number"!=typeof r&&(r=r.tokenIndex),t>r||t<0||r<0||r>=this.tokens.size)throw new RangeError(`replace: range invalid: ${t}..${r}(size=${this.tokens.size})`);let o=this.getProgram(i),s=new Ke$1(this.tokens,t,r,o.length,n);o.push(s)}delete(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.DEFAULT_PROGRAM_NAME;void 0===r&&(r=t),this.replace(t,r,null,n)}getProgram(e){let t=this.programs.get(e);return null==t&&(t=this.initializeProgram(e)),t}initializeProgram(e){const t=[];return this.programs.set(e,t),t}getText(t){let r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.DEFAULT_PROGRAM_NAME;r=t instanceof E$1?t:new E$1(0,this.tokens.size-1),"string"==typeof t&&(n=t);const o=this.programs.get(n);let s=r.start,a=r.stop;if(a>this.tokens.size-1&&(a=this.tokens.size-1),s<0&&(s=0),null==o||0===o.length)return this.tokens.getText(new E$1(s,a));let c=[],l=this.reduceToSingleOperationPerIndex(o),u=s;for(;u<=a&&u=this.tokens.size-1&&c.push(e.text.toString());return c.join("")}reduceToSingleOperationPerIndex(e){for(let t=0;tn.index&&t.index<=n.lastIndex&&(e[t.instructionIndex]=void 0);let o=this.getKindOfOps(e,Ke$1,t);for(let t of o){if(t.index>=n.index&&t.lastIndex<=n.lastIndex){e[t.instructionIndex]=void 0;continue}let r=t.lastIndexn.lastIndex;if(null!=t.text||null!=n.text||r){if(!r)throw new Error(`replace op boundaries of ${n} overlap with previous ${t}`)}else e[t.instructionIndex]=void 0,n.index=Math.min(t.index,n.index),n.lastIndex=Math.max(t.lastIndex,n.lastIndex)}}for(let t=0;t=r.index&&n.index<=r.lastIndex)throw new Error(`insert op ${n} within boundaries of previous ${r}`)}else r.text=this.catOpText(n.text,r.text),e[t]=void 0}let t=new Map;for(let r of e)if(null!=r){if(null!=t.get(r.index))throw new Error("should only be one op per index");t.set(r.index,r)}return t}catOpText(e,t){let r="",n="";return null!=e&&(r=e.toString()),null!=t&&(n=t.toString()),r+n}getKindOfOps(e,t,r){return e.slice(0,r).filter(e=>e&&e instanceof t)}};class Ve{constructor(e,t,r,n){this.tokens=e,this.instructionIndex=r,this.index=t,this.text=void 0===n?"":n}toString(){let e=this.constructor.name;const t=e.indexOf("$");return e=e.substring(t+1,e.length),"<"+e+"@"+this.tokens.get(this.index)+':"'+this.text+'">'}}let qe$1=class extends Ve{constructor(e,t,r,n){super(e,t,r,n)}execute(e){return this.text&&e.push(this.text.toString()),this.tokens.get(this.index).type!==i.EOF&&e.push(String(this.tokens.get(this.index).text)),this.index+1}},He$1=class extends qe$1{constructor(e,t,r,n){super(e,t+1,r,n)}},Ke$1=class extends Ve{constructor(e,t,r,n,i){super(e,t,n,i),this.lastIndex=r}execute(e){return this.text&&e.push(this.text.toString()),this.lastIndex+1}toString(){return null==this.text?"":"'}};const Ye$1={atn:re$1,dfa:he$2,context:ce,misc:ue$1,tree:fe$1,error:Ne$1,Token:i,CommonToken:Pt,CharStreams:Re$1,CharStream:ke$1,InputStream:Ie,CommonTokenStream:be$1,Lexer:Ut$1,Parser:Fe,ParserRuleContext:Be$1,Interval:E$1,IntervalSet:_$1,LL1Analyzer:j$1,Utils:we,TokenStreamRewriter:ze$1};var Ge$1=s.MG,We$1=s.fr;s.sR,s.Zo;var Xe$1=s.iH;s.rt;var Ze$1=s.jB,Qe$1=s.M8;s.$t,s.aq,s.pG;var sn$1=s.eP;s.KU,s.zW,s.IX,s.mY,s.a7;var cn$1=s.JG,un$1=s.ay;s.X2,s.WU;var pn$1=s.Uw;s.gw;var xn$1=s.iX,Tn$1=s.re,Sn$1=s.Pg,mn$1=s.tD;s.R$;var _n$1=s.Dj;s.m7,s.NZ,s.xo;var kn$1=s.ou;s.qC,s.mD,s.Ay;var navigator$1={userAgent:!1},window$1={},CryptoJS=CryptoJS||function(e,t){var r={},n=r.lib={},i=n.Base=function(){function e(){}return{extend:function(t){e.prototype=this;var r=new e;return t&&r.mixIn(t),r.hasOwnProperty("init")||(r.init=function(){r.$super.init.apply(this,arguments)}),r.init.prototype=r,r.$super=this,r},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||a).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=s<<24-(n+o)%4*8}else for(o=0;o>>2]=r[o>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r=[],n=0;n>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new o.init(r,t/2)}},c=s.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new o.init(r,t)}},l=s.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},u=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,n=r.words,i=r.sigBytes,s=this.blockSize,a=i/(4*s),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*s,l=e.min(4*c,i);if(c){for(var u=0;u>>2]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:c,padding:u}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var r=t.createEncryptor;else r=t.createDecryptor,this._minBufferSize=1;this._mode=r.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var d=t.CipherParams=r.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(o)},parse:function(e){var t=(e=o.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var r=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return d.create({ciphertext:e,salt:r})}},t.SerializableCipher=r.extend({cfg:r.extend({format:c}),encrypt:function(e,t,r,n){n=this.cfg.extend(n);var i=e.createEncryptor(r,n);return t=i.finalize(t),i=i.cfg,d.create({ciphertext:t,key:r,iv:i.iv,algorithm:e,mode:i.mode,padding:i.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,r,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(r,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,r,i){return i||(i=n.random(8)),e=s.create({keySize:t+r}).compute(e,i),r=n.create(e.words.slice(t),4*r),e.sigBytes=4*t,d.create({key:e,iv:r,salt:i})}},g=t.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:p}),encrypt:function(e,t,r,n){return r=(n=this.cfg.extend(n)).kdf.execute(r,e.keySize,e.ivSize),n.iv=r.iv,(e=h.encrypt.call(this,e,t,r.key,n)).mixIn(r),e},decrypt:function(e,t,r,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),r=n.kdf.execute(r,e.keySize,e.ivSize,t.salt),n.iv=r.iv,h.decrypt.call(this,e,t,r.key,n)}})}(),function(){for(var e=CryptoJS,t=e.lib.BlockCipher,r=e.algo,n=[],i=[],o=[],s=[],a=[],c=[],l=[],u=[],d=[],h=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var m=0,f=0;for(g=0;256>g;g++){var y=(y=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&y^99;n[m]=y,i[y]=m;var $=p[m],b=p[$],v=p[b],w=257*p[y]^16843008*y;o[m]=w<<24|w>>>8,s[m]=w<<16|w>>>16,a[m]=w<<8|w>>>24,c[m]=w,w=16843009*v^65537*b^257*$^16843008*m,l[y]=w<<24|w>>>8,u[y]=w<<16|w>>>16,d[y]=w<<8|w>>>24,h[y]=w,m?(m=$^p[p[p[v^$]]],f^=p[p[f]]):m=f=1}var S=[0,1,2,4,8,16,32,64,128,27,54];r=r.AES=t.extend({_doReset:function(){for(var e=(r=this._key).words,t=r.sigBytes/4,r=4*((this._nRounds=t+6)+1),i=this._keySchedule=[],o=0;o>>24]<<24|n[s>>>16&255]<<16|n[s>>>8&255]<<8|n[255&s]):(s=n[(s=s<<8|s>>>24)>>>24]<<24|n[s>>>16&255]<<16|n[s>>>8&255]<<8|n[255&s],s^=S[o/t|0]<<24),i[o]=i[o-t]^s}for(e=this._invKeySchedule=[],t=0;tt||4>=o?s:l[n[s>>>24]]^u[n[s>>>16&255]]^d[n[s>>>8&255]]^h[n[255&s]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,o,s,a,c,n)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,l,u,d,h,i),r=e[t+1],e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,n,i,o,s,a){for(var c=this._nRounds,l=e[t]^r[0],u=e[t+1]^r[1],d=e[t+2]^r[2],h=e[t+3]^r[3],p=4,g=1;g>>24]^i[u>>>16&255]^o[d>>>8&255]^s[255&h]^r[p++],f=n[u>>>24]^i[d>>>16&255]^o[h>>>8&255]^s[255&l]^r[p++],y=n[d>>>24]^i[h>>>16&255]^o[l>>>8&255]^s[255&u]^r[p++];h=n[h>>>24]^i[l>>>16&255]^o[u>>>8&255]^s[255&d]^r[p++],l=m,u=f,d=y}m=(a[l>>>24]<<24|a[u>>>16&255]<<16|a[d>>>8&255]<<8|a[255&h])^r[p++],f=(a[u>>>24]<<24|a[d>>>16&255]<<16|a[h>>>8&255]<<8|a[255&l])^r[p++],y=(a[d>>>24]<<24|a[h>>>16&255]<<16|a[l>>>8&255]<<8|a[255&u])^r[p++],h=(a[h>>>24]<<24|a[l>>>16&255]<<16|a[u>>>8&255]<<8|a[255&d])^r[p++],e[t]=m,e[t+1]=f,e[t+2]=y,e[t+3]=h},keySize:8});e.AES=t._createHelper(r)}(),function(){function e(e,t){var r=(this._lBlock>>>e^this._rBlock)&t;this._rBlock^=r,this._lBlock^=r<>>e^this._lBlock)&t;this._lBlock^=r,this._rBlock^=r<r;r++){var n=s[r]-1;t[r]=e[n>>>5]>>>31-n%32&1}for(e=this._subKeys=[],n=0;16>n;n++){var i=e[n]=[],o=c[n];for(r=0;24>r;r++)i[r/6|0]|=t[(a[r]-1+o)%28]<<31-r%6,i[4+(r/6|0)]|=t[28+(a[r+24]-1+o)%28]<<31-r%6;for(i[0]=i[0]<<1|i[0]>>>31,r=1;7>r;r++)i[r]>>>=4*(r-1)+3;i[7]=i[7]<<5|i[7]>>>27}for(t=this._invSubKeys=[],r=0;16>r;r++)t[r]=e[15-r]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._subKeys)},decryptBlock:function(e,t){this._doCryptBlock(e,t,this._invSubKeys)},_doCryptBlock:function(r,n,i){this._lBlock=r[n],this._rBlock=r[n+1],e.call(this,4,252645135),e.call(this,16,65535),t.call(this,2,858993459),t.call(this,8,16711935),e.call(this,1,1431655765);for(var o=0;16>o;o++){for(var s=i[o],a=this._lBlock,c=this._rBlock,d=0,h=0;8>h;h++)d|=l[h][((c^s[h])&u[h])>>>0];this._lBlock=c,this._rBlock=a^d}i=this._lBlock,this._lBlock=this._rBlock,this._rBlock=i,e.call(this,1,1431655765),t.call(this,8,16711935),t.call(this,2,858993459),e.call(this,16,65535),e.call(this,4,252645135),r[n]=this._lBlock,r[n+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});r.DES=i._createHelper(d),o=o.TripleDES=i.extend({_doReset:function(){var e=this._key.words;this._des1=d.createEncryptor(n.create(e.slice(0,2))),this._des2=d.createEncryptor(n.create(e.slice(2,4))),this._des3=d.createEncryptor(n.create(e.slice(4,6)))},encryptBlock:function(e,t){this._des1.encryptBlock(e,t),this._des2.decryptBlock(e,t),this._des3.encryptBlock(e,t)},decryptBlock:function(e,t){this._des3.decryptBlock(e,t),this._des2.encryptBlock(e,t),this._des1.decryptBlock(e,t)},keySize:6,ivSize:2,blockSize:2}),r.TripleDES=i._createHelper(o)}(),function(){var e=CryptoJS,t=e.lib.WordArray;e.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,n=this._map;e.clamp(),e=[];for(var i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,s=0;4>s&&i+.75*s>>6*(3-s)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var r=e.length,n=this._map;(i=n.charAt(64))&&(-1!=(i=e.indexOf(i))&&(r=i));for(var i=[],o=0,s=0;s>>6-s%4*2;i[o>>>2]|=(a|c)<<24-o%4*8,o++}return t.create(i,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){function t(e,t,r,n,i,o,s){return((e=e+(t&r|~t&n)+i+s)<>>32-o)+t}function r(e,t,r,n,i,o,s){return((e=e+(t&n|r&~n)+i+s)<>>32-o)+t}function n(e,t,r,n,i,o,s){return((e=e+(t^r^n)+i+s)<>>32-o)+t}function i(e,t,r,n,i,o,s){return((e=e+(r^(t|~n))+i+s)<>>32-o)+t}for(var o=CryptoJS,s=(c=o.lib).WordArray,a=c.Hasher,c=o.algo,l=[],u=0;64>u;u++)l[u]=4294967296*e.abs(e.sin(u+1))|0;c=c.MD5=a.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,o){for(var s=0;16>s;s++){var a=e[c=o+s];e[c]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}s=this._hash.words;var c=e[o+0],u=(a=e[o+1],e[o+2]),d=e[o+3],h=e[o+4],p=e[o+5],g=e[o+6],m=e[o+7],f=e[o+8],y=e[o+9],$=e[o+10],b=e[o+11],v=e[o+12],w=e[o+13],S=e[o+14],_=e[o+15],E=t(E=s[0],T=s[1],I=s[2],C=s[3],c,7,l[0]),C=t(C,E,T,I,a,12,l[1]),I=t(I,C,E,T,u,17,l[2]),T=t(T,I,C,E,d,22,l[3]);E=t(E,T,I,C,h,7,l[4]),C=t(C,E,T,I,p,12,l[5]),I=t(I,C,E,T,g,17,l[6]),T=t(T,I,C,E,m,22,l[7]),E=t(E,T,I,C,f,7,l[8]),C=t(C,E,T,I,y,12,l[9]),I=t(I,C,E,T,$,17,l[10]),T=t(T,I,C,E,b,22,l[11]),E=t(E,T,I,C,v,7,l[12]),C=t(C,E,T,I,w,12,l[13]),I=t(I,C,E,T,S,17,l[14]),E=r(E,T=t(T,I,C,E,_,22,l[15]),I,C,a,5,l[16]),C=r(C,E,T,I,g,9,l[17]),I=r(I,C,E,T,b,14,l[18]),T=r(T,I,C,E,c,20,l[19]),E=r(E,T,I,C,p,5,l[20]),C=r(C,E,T,I,$,9,l[21]),I=r(I,C,E,T,_,14,l[22]),T=r(T,I,C,E,h,20,l[23]),E=r(E,T,I,C,y,5,l[24]),C=r(C,E,T,I,S,9,l[25]),I=r(I,C,E,T,d,14,l[26]),T=r(T,I,C,E,f,20,l[27]),E=r(E,T,I,C,w,5,l[28]),C=r(C,E,T,I,u,9,l[29]),I=r(I,C,E,T,m,14,l[30]),E=n(E,T=r(T,I,C,E,v,20,l[31]),I,C,p,4,l[32]),C=n(C,E,T,I,f,11,l[33]),I=n(I,C,E,T,b,16,l[34]),T=n(T,I,C,E,S,23,l[35]),E=n(E,T,I,C,a,4,l[36]),C=n(C,E,T,I,h,11,l[37]),I=n(I,C,E,T,m,16,l[38]),T=n(T,I,C,E,$,23,l[39]),E=n(E,T,I,C,w,4,l[40]),C=n(C,E,T,I,c,11,l[41]),I=n(I,C,E,T,d,16,l[42]),T=n(T,I,C,E,g,23,l[43]),E=n(E,T,I,C,y,4,l[44]),C=n(C,E,T,I,v,11,l[45]),I=n(I,C,E,T,_,16,l[46]),E=i(E,T=n(T,I,C,E,u,23,l[47]),I,C,c,6,l[48]),C=i(C,E,T,I,m,10,l[49]),I=i(I,C,E,T,S,15,l[50]),T=i(T,I,C,E,p,21,l[51]),E=i(E,T,I,C,v,6,l[52]),C=i(C,E,T,I,d,10,l[53]),I=i(I,C,E,T,$,15,l[54]),T=i(T,I,C,E,a,21,l[55]),E=i(E,T,I,C,f,6,l[56]),C=i(C,E,T,I,_,10,l[57]),I=i(I,C,E,T,g,15,l[58]),T=i(T,I,C,E,w,21,l[59]),E=i(E,T,I,C,h,6,l[60]),C=i(C,E,T,I,b,10,l[61]),I=i(I,C,E,T,u,15,l[62]),T=i(T,I,C,E,y,21,l[63]);s[0]=s[0]+E|0,s[1]=s[1]+T|0,s[2]=s[2]+I|0,s[3]=s[3]+C|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;r[i>>>5]|=128<<24-i%32;var o=e.floor(n/4294967296);for(r[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(i+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(r.length+1),this._process(),r=(t=this._hash).words,n=0;4>n;n++)i=r[n],r[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),o.MD5=a._createHelper(c),o.HmacMD5=a._createHmacHelper(c)}(Math),function(){var e=CryptoJS,t=(i=e.lib).WordArray,r=i.Hasher,n=[],i=e.algo.SHA1=r.extend({_doReset:function(){this._hash=new t.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],o=r[1],s=r[2],a=r[3],c=r[4],l=0;80>l;l++){if(16>l)n[l]=0|e[t+l];else{var u=n[l-3]^n[l-8]^n[l-14]^n[l-16];n[l]=u<<1|u>>>31}u=(i<<5|i>>>27)+c+n[l],u=20>l?u+(1518500249+(o&s|~o&a)):40>l?u+(1859775393+(o^s^a)):60>l?u+((o&s|o&a|s&a)-1894007588):u+((o^s^a)-899497514),c=a,a=s,s=o<<30|o>>>2,o=i,i=u}r[0]=r[0]+i|0,r[1]=r[1]+o|0,r[2]=r[2]+s|0,r[3]=r[3]+a|0,r[4]=r[4]+c|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=Math.floor(r/4294967296),t[15+(n+64>>>9<<4)]=r,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(i),e.HmacSHA1=r._createHmacHelper(i)}(),function(e){for(var t=CryptoJS,r=(i=t.lib).WordArray,n=i.Hasher,i=t.algo,o=[],s=[],a=function(e){return 4294967296*(e-(0|e))|0},c=2,l=0;64>l;){var u;e:{u=c;for(var d=e.sqrt(u),h=2;h<=d;h++)if(!(u%h)){u=!1;break e}u=!0}u&&(8>l&&(o[l]=a(e.pow(c,.5))),s[l]=a(e.pow(c,1/3)),l++),c++}var p=[];i=i.SHA256=n.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],a=r[3],c=r[4],l=r[5],u=r[6],d=r[7],h=0;64>h;h++){if(16>h)p[h]=0|e[t+h];else{var g=p[h-15],m=p[h-2];p[h]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[h-7]+((m<<15|m>>>17)^(m<<13|m>>>19)^m>>>10)+p[h-16]}g=d+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&l^~c&u)+s[h]+p[h],m=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&i^n&o^i&o),d=u,u=l,l=c,c=a+g|0,a=o,o=i,i=n,n=g+m|0}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+a|0,r[4]=r[4]+c|0,r[5]=r[5]+l|0,r[6]=r[6]+u|0,r[7]=r[7]+d|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;return r[i>>>5]|=128<<24-i%32,r[14+(i+64>>>9<<4)]=e.floor(n/4294967296),r[15+(i+64>>>9<<4)]=n,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(i),t.HmacSHA256=n._createHmacHelper(i)}(Math),function(){var e=CryptoJS,t=e.lib.WordArray,r=(n=e.algo).SHA256,n=n.SHA224=r.extend({_doReset:function(){this._hash=new t.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var e=r._doFinalize.call(this);return e.sigBytes-=4,e}});e.SHA224=r._createHelper(n),e.HmacSHA224=r._createHmacHelper(n)}(),function(){function e(){return n.create.apply(n,arguments)}for(var t=CryptoJS,r=t.lib.Hasher,n=(o=t.x64).Word,i=o.WordArray,o=t.algo,s=[e(1116352408,3609767458),e(1899447441,602891725),e(3049323471,3964484399),e(3921009573,2173295548),e(961987163,4081628472),e(1508970993,3053834265),e(2453635748,2937671579),e(2870763221,3664609560),e(3624381080,2734883394),e(310598401,1164996542),e(607225278,1323610764),e(1426881987,3590304994),e(1925078388,4068182383),e(2162078206,991336113),e(2614888103,633803317),e(3248222580,3479774868),e(3835390401,2666613458),e(4022224774,944711139),e(264347078,2341262773),e(604807628,2007800933),e(770255983,1495990901),e(1249150122,1856431235),e(1555081692,3175218132),e(1996064986,2198950837),e(2554220882,3999719339),e(2821834349,766784016),e(2952996808,2566594879),e(3210313671,3203337956),e(3336571891,1034457026),e(3584528711,2466948901),e(113926993,3758326383),e(338241895,168717936),e(666307205,1188179964),e(773529912,1546045734),e(1294757372,1522805485),e(1396182291,2643833823),e(1695183700,2343527390),e(1986661051,1014477480),e(2177026350,1206759142),e(2456956037,344077627),e(2730485921,1290863460),e(2820302411,3158454273),e(3259730800,3505952657),e(3345764771,106217008),e(3516065817,3606008344),e(3600352804,1432725776),e(4094571909,1467031594),e(275423344,851169720),e(430227734,3100823752),e(506948616,1363258195),e(659060556,3750685593),e(883997877,3785050280),e(958139571,3318307427),e(1322822218,3812723403),e(1537002063,2003034995),e(1747873779,3602036899),e(1955562222,1575990012),e(2024104815,1125592928),e(2227730452,2716904306),e(2361852424,442776044),e(2428436474,593698344),e(2756734187,3733110249),e(3204031479,2999351573),e(3329325298,3815920427),e(3391569614,3928383900),e(3515267271,566280711),e(3940187606,3454069534),e(4118630271,4000239992),e(116418474,1914138554),e(174292421,2731055270),e(289380356,3203993006),e(460393269,320620315),e(685471733,587496836),e(852142971,1086792851),e(1017036298,365543100),e(1126000580,2618297676),e(1288033470,3409855158),e(1501505948,4234509866),e(1607167915,987167468),e(1816402316,1246189591)],a=[],c=0;80>c;c++)a[c]=e();o=o.SHA512=r.extend({_doReset:function(){this._hash=new i.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var r=(d=this._hash.words)[0],n=d[1],i=d[2],o=d[3],c=d[4],l=d[5],u=d[6],d=d[7],h=r.high,p=r.low,g=n.high,m=n.low,f=i.high,y=i.low,$=o.high,b=o.low,v=c.high,w=c.low,S=l.high,_=l.low,E=u.high,C=u.low,I=d.high,T=d.low,A=h,D=p,x=g,R=m,O=f,N=y,P=$,k=b,M=v,L=w,F=S,j=_,U=E,B=C,H=I,q=T,z=0;80>z;z++){var W=a[z];if(16>z)var G=W.high=0|e[t+2*z],J=W.low=0|e[t+2*z+1];else{G=((J=(G=a[z-15]).high)>>>1|(K=G.low)<<31)^(J>>>8|K<<24)^J>>>7;var K=(K>>>1|J<<31)^(K>>>8|J<<24)^(K>>>7|J<<25),V=((J=(V=a[z-2]).high)>>>19|(Z=V.low)<<13)^(J<<3|Z>>>29)^J>>>6,Z=(Z>>>19|J<<13)^(Z<<3|J>>>29)^(Z>>>6|J<<26),X=(J=a[z-7]).high,Y=(Q=a[z-16]).high,Q=Q.low;G=(G=(G=G+X+((J=K+J.low)>>>0>>0?1:0))+V+((J=J+Z)>>>0>>0?1:0))+Y+((J=J+Q)>>>0>>0?1:0);W.high=G,W.low=J}X=M&F^~M&U,Q=L&j^~L&B,W=A&x^A&O^x&O;var ee=D&R^D&N^R&N,te=(K=(A>>>28|D<<4)^(A<<30|D>>>2)^(A<<25|D>>>7),V=(D>>>28|A<<4)^(D<<30|A>>>2)^(D<<25|A>>>7),(Z=s[z]).high),re=Z.low;Y=H+((M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9))+((Z=q+((L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9)))>>>0>>0?1:0),H=U,q=B,U=F,B=j,F=M,j=L,M=P+(Y=(Y=(Y=Y+X+((Z=Z+Q)>>>0>>0?1:0))+te+((Z=Z+re)>>>0>>0?1:0))+G+((Z=Z+J)>>>0>>0?1:0))+((L=k+Z|0)>>>0>>0?1:0)|0,P=O,k=N,O=x,N=R,x=A,R=D,A=Y+(W=K+W+((J=V+ee)>>>0>>0?1:0))+((D=Z+J|0)>>>0>>0?1:0)|0}p=r.low=p+D,r.high=h+A+(p>>>0>>0?1:0),m=n.low=m+R,n.high=g+x+(m>>>0>>0?1:0),y=i.low=y+N,i.high=f+O+(y>>>0>>0?1:0),b=o.low=b+k,o.high=$+P+(b>>>0>>0?1:0),w=c.low=w+L,c.high=v+M+(w>>>0>>0?1:0),_=l.low=_+j,l.high=S+F+(_>>>0>>0?1:0),C=u.low=C+B,u.high=E+U+(C>>>0>>0?1:0),T=d.low=T+q,d.high=I+H+(T>>>0>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(r/4294967296),t[31+(n+128>>>10<<5)]=r,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32}),t.SHA512=r._createHelper(o),t.HmacSHA512=r._createHmacHelper(o)}(),function(){var e=CryptoJS,t=(i=e.x64).Word,r=i.WordArray,n=(i=e.algo).SHA512,i=i.SHA384=n.extend({_doReset:function(){this._hash=new r.init([new t.init(3418070365,3238371032),new t.init(1654270250,914150663),new t.init(2438529370,812702999),new t.init(355462360,4144912697),new t.init(1731405415,4290775857),new t.init(2394180231,1750603025),new t.init(3675008525,1694076839),new t.init(1203062813,3204075428)])},_doFinalize:function(){var e=n._doFinalize.call(this);return e.sigBytes-=16,e}});e.SHA384=n._createHelper(i),e.HmacSHA384=n._createHmacHelper(i)}(),function(){var e=CryptoJS,t=(n=e.lib).WordArray,r=n.Hasher,n=e.algo,i=t.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=t.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),s=t.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),a=t.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),c=t.create([0,1518500249,1859775393,2400959708,2840853838]),l=t.create([1352829926,1548603684,1836072691,2053994217,0]);n=n.RIPEMD160=r.extend({_doReset:function(){this._hash=t.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=0;16>r;r++){var n=e[v=t+r];e[v]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8)}var u,d,h,p,g,m,f,y,$,b,v=this._hash.words,w=(n=c.words,l.words),S=i.words,_=o.words,E=s.words,C=a.words;m=u=v[0],f=d=v[1],y=h=v[2],$=p=v[3],b=g=v[4];var I;for(r=0;80>r;r+=1)I=u+e[t+S[r]]|0,I=16>r?I+((d^h^p)+n[0]):32>r?I+((d&h|~d&p)+n[1]):48>r?I+(((d|~h)^p)+n[2]):64>r?I+((d&p|h&~p)+n[3]):I+((d^(h|~p))+n[4]),I=(I=(I|=0)<>>32-E[r])+g|0,u=g,g=p,p=h<<10|h>>>22,h=d,d=I,I=m+e[t+_[r]]|0,I=16>r?I+((f^(y|~$))+w[0]):32>r?I+((f&$|y&~$)+w[1]):48>r?I+(((f|~y)^$)+w[2]):64>r?I+((f&y|~f&$)+w[3]):I+((f^y^$)+w[4]),I=(I=(I|=0)<>>32-C[r])+b|0,m=b,b=$,$=y<<10|y>>>22,y=f,f=I;I=v[1]+h+$|0,v[1]=v[2]+p+b|0,v[2]=v[3]+g+m|0,v[3]=v[4]+u+f|0,v[4]=v[0]+d+y|0,v[0]=I},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;for(t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),e.sigBytes=4*(t.length+1),this._process(),t=(e=this._hash).words,r=0;5>r;r++)n=t[r],t[r]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8);return e},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.RIPEMD160=r._createHelper(n),e.HmacRIPEMD160=r._createHmacHelper(n)}(),function(){var e=CryptoJS,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,r){e=this._hasher=new e.init,"string"==typeof r&&(r=t.parse(r));var n=e.blockSize,i=4*n;r.sigBytes>i&&(r=e.finalize(r)),r.clamp();for(var o=this._oKey=r.clone(),s=this._iKey=r.clone(),a=o.words,c=s.words,l=0;l>6)+b64map.charAt(63&r);for(t+1==e.length?(r=parseInt(e.substring(t,t+1),16),n+=b64map.charAt(r<<2)):t+2==e.length&&(r=parseInt(e.substring(t,t+2),16),n+=b64map.charAt(r>>2)+b64map.charAt((3&r)<<4));(3&n.length)>0;)n+=b64pad;return n}function b64tohex(e){var t,r,n,i="",o=0;for(t=0;t>2),r=3&n,o=1):1==o?(i+=int2char(r<<2|n>>4),r=15&n,o=2):2==o?(i+=int2char(r),i+=int2char(n>>2),r=3&n,o=3):(i+=int2char(r<<2|n>>4),i+=int2char(15&n),o=0));return 1==o&&(i+=int2char(r<<2)),i} -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */function BigInteger(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function nbi(){return new BigInteger(null)}function am1(e,t,r,n,i,o){for(;--o>=0;){var s=t*this[e++]+r[n]+i;i=Math.floor(s/67108864),r[n++]=67108863&s}return i}function am2(e,t,r,n,i,o){for(var s=32767&t,a=t>>15;--o>=0;){var c=32767&this[e],l=this[e++]>>15,u=a*c+l*s;i=((c=s*c+((32767&u)<<15)+r[n]+(1073741823&i))>>>30)+(u>>>15)+a*l+(i>>>30),r[n++]=1073741823&c}return i}function am3(e,t,r,n,i,o){for(var s=16383&t,a=t>>14;--o>=0;){var c=16383&this[e],l=this[e++]>>14,u=a*c+l*s;i=((c=s*c+((16383&u)<<14)+r[n]+i)>>28)+(u>>14)+a*l,r[n++]=268435455&c}return i}"Microsoft Internet Explorer"==navigator$1.appName?(BigInteger.prototype.am=am2,dbits=30):"Netscape"!=navigator$1.appName?(BigInteger.prototype.am=am1,dbits=26):(BigInteger.prototype.am=am3,dbits=28),BigInteger.prototype.DB=dbits,BigInteger.prototype.DM=(1<=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s}function bnpFromInt(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0}function nbv(e){var t=nbi();return t.fromInt(e),t}function bnpFromString(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,o=0;--n>=0;){var s=8==r?255&e[n]:intAt(e,n);s<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==o?this[this.t++]=s:o+r>this.DB?(this[this.t-1]|=(s&(1<>this.DB-o):this[this.t-1]|=s<=this.DB&&(o-=this.DB))}8==r&&128&e[0]&&(this.s=-1,o>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==e;)--this.t}function bnToString(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,o=int2char(r));s>=0;)a>(a+=this.DB-t)):(r=this[s]>>(a-=t)&n,a<=0&&(a+=this.DB,--s)),r>0&&(i=!0),i&&(o+=int2char(r));return i?o:"0"}function bnNegate(){var e=nbi();return BigInteger.ZERO.subTo(this,e),e}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0}function nbits(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function bnBitLength(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s}function bnpDRShiftTo(e,t){for(var r=e;r=0;--r)t[r+s+1]=this[r]>>i|a,a=(this[r]&o)<=0;--r)t[r]=0;t[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()}function bnpRShiftTo(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,o=(1<>n;for(var s=r+1;s>n;n>0&&(t[this.t-r-1]|=(this.s&o)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t[r++]=this.DV+n:n>0&&(t[r++]=n),t.t=r,t.clamp()}function bnpMultiplyTo(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t[i]=0;for(i=0;i=0;)e[r]=0;for(r=0;r=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()}function bnpDivRemTo(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(c,o),i.lShiftTo(c,r)):(n.copyTo(o),i.copyTo(r));var l=o.t,u=o[l-1];if(0!=u){var d=u*(1<1?o[l-2]>>this.F2:0),h=this.FV/d,p=(1<=0&&(r[r.t++]=1,r.subTo(y,r)),BigInteger.ONE.dlShiftTo(l,y),y.subTo(o,o);o.t=0;){var $=r[--m]==u?this.DM:Math.floor(r[m]*h+(r[m-1]+g)*p);if((r[m]+=o.am(0,$,r,f,0,l))<$)for(o.dlShiftTo(f,y),r.subTo(y,r);r[m]<--$;)r.subTo(y,r)}null!=t&&(r.drShiftTo(l,t),s!=a&&BigInteger.ZERO.subTo(t,t)),r.t=l,r.clamp(),c>0&&r.rShiftTo(c,r),s<0&&BigInteger.ZERO.subTo(r,r)}}}function bnMod(e){var t=nbi();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(BigInteger.ZERO)>0&&e.subTo(t,t),t}function Classic(e){this.m=e}function cConvert(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function cRevert(e){return e}function cReduce(e){e.divRemTo(this.m,null,e)}function cMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function cSqrTo(e,t){e.squareTo(t),this.reduce(t)}function bnpInvDigit(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t}function Montgomery(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(t,t),t}function montRevert(e){var t=nbi();return e.copyTo(t),this.reduce(t),t}function montReduce(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,n,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function montSqrTo(e,t){e.squareTo(t),this.reduce(t)}function montMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function bnpIsEven(){return 0==(this.t>0?1&this[0]:this.s)}function bnpExp(e,t){if(e>4294967295||e<1)return BigInteger.ONE;var r=nbi(),n=nbi(),i=t.convert(this),o=nbits(e)-1;for(i.copyTo(r);--o>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var s=r;r=n,n=s}return t.revert(r)}function bnModPowInt(e,t){var r;return r=e<256||t.isEven()?new Classic(t):new Montgomery(t),this.exp(e,r)} -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -function bnClone(){var e=nbi();return this.copyTo(e),e}function bnIntValue(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<>24}function bnShortValue(){return 0==this.t?this.s:this[0]<<16>>16}function bnpChunkSize(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function bnSigNum(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1}function bnpToRadix(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=nbv(r),i=nbi(),o=nbi(),s="";for(this.divRemTo(n,i,o);i.signum()>0;)s=(r+o.intValue()).toString(e).substr(1)+s,i.divRemTo(n,i,o);return o.intValue().toString(e)+s}function bnpFromRadix(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,o=0,s=0,a=0;a=r&&(this.dMultiply(n),this.dAddOffset(s,0),o=0,s=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(s,0)),i&&BigInteger.ZERO.subTo(this,this)}function bnpFromNumber(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(BigInteger.ONE.shiftLeft(e-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(BigInteger.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this[e]&(1<>(n+=this.DB-8)):(r=this[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),128&r&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t}function bnEquals(e){return 0==this.compareTo(e)}function bnMin(e){return this.compareTo(e)<0?this:e}function bnMax(e){return this.compareTo(e)>0?this:e}function bnpBitwiseTo(e,t,r){var n,i,o=Math.min(e.t,this.t);for(n=0;n>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function bnGetLowestSetBit(){for(var e=0;e=this.t?0!=this.s:!!(this[t]&1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t[r++]=n:n<-1&&(t[r++]=this.DV+n),t.t=r,t.clamp()}function bnAdd(e){var t=nbi();return this.addTo(e,t),t}function bnSubtract(e){var t=nbi();return this.subTo(e,t),t}function bnMultiply(e){var t=nbi();return this.multiplyTo(e,t),t}function bnSquare(){var e=nbi();return this.squareTo(e),e}function bnDivide(e){var t=nbi();return this.divRemTo(e,t,null),t}function bnRemainder(e){var t=nbi();return this.divRemTo(e,null,t),t}function bnDivideAndRemainder(e){var t=nbi(),r=nbi();return this.divRemTo(e,t,r),new Array(t,r)}function bnpDMultiply(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function bnpDAddOffset(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}}function NullExp(){}function nNop(e){return e}function nMulTo(e,t,r){e.multiplyTo(t,r)}function nSqrTo(e,t){e.squareTo(t)}function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i=0;)r[n]=0;for(n=Math.max(t-this.t,0);n2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=nbi();return e.copyTo(t),this.reduce(t),t}function barrettRevert(e){return e}function barrettReduce(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function barrettSqrTo(e,t){e.squareTo(t),this.reduce(t)}function barrettMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function bnModPow(e,t){var r,n,i=e.bitLength(),o=nbv(1);if(i<=0)return o;r=i<18?1:i<48?3:i<144?4:i<768?5:6,n=i<8?new Classic(t):t.isEven()?new Barrett(t):new Montgomery(t);var s=new Array,a=3,c=r-1,l=(1<1){var u=nbi();for(n.sqrTo(s[1],u);a<=l;)s[a]=nbi(),n.mulTo(u,s[a-2],s[a]),a+=2}var d,h,p=e.t-1,g=!0,m=nbi();for(i=nbits(e[p])-1;p>=0;){for(i>=c?d=e[p]>>i-c&l:(d=(e[p]&(1<0&&(d|=e[p-1]>>this.DB+i-c)),a=r;!(1&d);)d>>=1,--a;if((i-=a)<0&&(i+=this.DB,--p),g)s[d].copyTo(o),g=!1;else{for(;a>1;)n.sqrTo(o,m),n.sqrTo(m,o),a-=2;a>0?n.sqrTo(o,m):(h=o,o=m,m=h),n.mulTo(m,s[d],o)}for(;p>=0&&!(e[p]&1<0&&(t.rShiftTo(o,t),r.rShiftTo(o,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return o>0&&r.lShiftTo(o,r),r}function bnpModInt(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this[n])%e;return r}function bnModInverse(e){var t=e.isEven();if(this.isEven()&&t||0==e.signum())return BigInteger.ZERO;for(var r=e.clone(),n=this.clone(),i=nbv(1),o=nbv(0),s=nbv(0),a=nbv(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),t?(i.isEven()&&o.isEven()||(i.addTo(this,i),o.subTo(e,o)),i.rShiftTo(1,i)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),t?(s.isEven()&&a.isEven()||(s.addTo(this,s),a.subTo(e,a)),s.rShiftTo(1,s)):a.isEven()||a.subTo(e,a),a.rShiftTo(1,a);r.compareTo(n)>=0?(r.subTo(n,r),t&&i.subTo(s,i),o.subTo(a,o)):(n.subTo(r,n),t&&s.subTo(i,s),a.subTo(o,a))}return 0!=n.compareTo(BigInteger.ONE)?BigInteger.ZERO:a.compareTo(e)>=0?a.subtract(e):a.signum()<0?(a.addTo(e,a),a.signum()<0?a.add(e):a):a}Classic.prototype.convert=cConvert,Classic.prototype.revert=cRevert,Classic.prototype.reduce=cReduce,Classic.prototype.mulTo=cMulTo,Classic.prototype.sqrTo=cSqrTo,Montgomery.prototype.convert=montConvert,Montgomery.prototype.revert=montRevert,Montgomery.prototype.reduce=montReduce,Montgomery.prototype.mulTo=montMulTo,Montgomery.prototype.sqrTo=montSqrTo,BigInteger.prototype.copyTo=bnpCopyTo,BigInteger.prototype.fromInt=bnpFromInt,BigInteger.prototype.fromString=bnpFromString,BigInteger.prototype.clamp=bnpClamp,BigInteger.prototype.dlShiftTo=bnpDLShiftTo,BigInteger.prototype.drShiftTo=bnpDRShiftTo,BigInteger.prototype.lShiftTo=bnpLShiftTo,BigInteger.prototype.rShiftTo=bnpRShiftTo,BigInteger.prototype.subTo=bnpSubTo,BigInteger.prototype.multiplyTo=bnpMultiplyTo,BigInteger.prototype.squareTo=bnpSquareTo,BigInteger.prototype.divRemTo=bnpDivRemTo,BigInteger.prototype.invDigit=bnpInvDigit,BigInteger.prototype.isEven=bnpIsEven,BigInteger.prototype.exp=bnpExp,BigInteger.prototype.toString=bnToString,BigInteger.prototype.negate=bnNegate,BigInteger.prototype.abs=bnAbs,BigInteger.prototype.compareTo=bnCompareTo,BigInteger.prototype.bitLength=bnBitLength,BigInteger.prototype.mod=bnMod,BigInteger.prototype.modPowInt=bnModPowInt,BigInteger.ZERO=nbv(0),BigInteger.ONE=nbv(1),NullExp.prototype.convert=nNop,NullExp.prototype.revert=nNop,NullExp.prototype.mulTo=nMulTo,NullExp.prototype.sqrTo=nSqrTo,Barrett.prototype.convert=barrettConvert,Barrett.prototype.revert=barrettRevert,Barrett.prototype.reduce=barrettReduce,Barrett.prototype.mulTo=barrettMulTo,Barrett.prototype.sqrTo=barrettSqrTo;var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(e){var t,r=this.abs();if(1==r.t&&r[0]<=lowprimes[lowprimes.length-1]){for(t=0;t>1)>lowprimes.length&&(e=lowprimes.length);for(var i=nbi(),o=0;o>8&255,rng_pool[rng_pptr++]^=e>>16&255,rng_pool[rng_pptr++]^=e>>24&255,rng_pptr>=rng_psize&&(rng_pptr-=rng_psize)}function rng_seed_time(){rng_seed_int((new Date).getTime())}if(null==rng_pool){var t;if(rng_pool=new Array,rng_pptr=0,void 0!==window$1&&(void 0!==window$1.crypto||void 0!==window$1.msCrypto)){var crypto$1=window$1.crypto||window$1.msCrypto;if(crypto$1.getRandomValues){var ua$2=new Uint8Array(32);for(crypto$1.getRandomValues(ua$2),t=0;t<32;++t)rng_pool[rng_pptr++]=ua$2[t]}else if("Netscape"==navigator$1.appName&&navigator$1.appVersion<"5"){var z$3=window$1.crypto.random(32);for(t=0;t>>8,rng_pool[rng_pptr++]=255&t;rng_pptr=0,rng_seed_time()}function rng_get_byte(){if(null==rng_state){for(rng_seed_time(),(rng_state=prng_newstate()).init(rng_pool),rng_pptr=0;rng_pptr0&&t.length>0))throw"Invalid RSA public key";this.n=parseBigInt(e,16),this.e=parseInt(t,16)}}function RSADoPublic(e){return e.modPowInt(this.e,this.n)}function RSASetPrivate(e,t,r){if(this.isPrivate=!0,"string"!=typeof e)this.n=e,this.e=t,this.d=r;else{if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA private key";this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(r,16)}}function RSASetPrivateEx(e,t,r,n,i,o,s,a){if(this.isPrivate=!0,this.isPublic=!1,null==e)throw"RSASetPrivateEx N == null";if(null==t)throw"RSASetPrivateEx E == null";if(0==e.length)throw"RSASetPrivateEx N.length == 0";if(0==t.length)throw"RSASetPrivateEx E.length == 0";if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA private key in RSASetPrivateEx";this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(r,16),this.p=parseBigInt(n,16),this.q=parseBigInt(i,16),this.dmp1=parseBigInt(o,16),this.dmq1=parseBigInt(s,16),this.coeff=parseBigInt(a,16)}function RSAGenerate(e,t){var r=new SecureRandom,n=e>>1;this.e=parseInt(t,16);for(var i=new BigInteger(t,16),o=e/2-100,s=BigInteger.ONE.shiftLeft(o);;){for(;this.p=new BigInteger(e-n,1,r),0!=this.p.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.p.isProbablePrime(10););for(;this.q=new BigInteger(n,1,r),0!=this.q.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var a=this.p;this.p=this.q,this.q=a}var c=this.q.subtract(this.p).abs();if(!(c.bitLength()0;--t){o=o.twice();var u=n.testBit(t);u!=r.testBit(t)&&(o=o.add(u?this:i))}for(t=a.bitLength()-2;t>0;--t){c=c.twice();var d=a.testBit(t);d!=s.testBit(t)&&(c=c.add(d?c:l))}return o}function pointFpMultiplyTwo(e,t,r){var n;n=e.bitLength()>r.bitLength()?e.bitLength()-1:r.bitLength()-1;for(var i=this.curve.getInfinity(),o=this.add(t);n>=0;)i=i.twice(),e.testBit(n)?i=r.testBit(n)?i.add(o):i.add(this):r.testBit(n)&&(i=i.add(t)),--n;return i}function ECCurveFp(e,t,r){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(r),this.infinity=new ECPointFp(this,null,null)}function curveFpGetQ(){return this.q}function curveFpGetA(){return this.a}function curveFpGetB(){return this.b}function curveFpEquals(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)}function curveFpGetInfinity(){return this.infinity}function curveFpFromBigInteger(e){return new ECFieldElementFp(this.q,e)}function curveFpDecodePointHex(e){switch(parseInt(e.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:var t=e.substr(0,2);e.substr(2);var r=this.fromBigInteger(new BigInteger(a,16)),n=this.getA(),i=this.getB(),o=r.square().add(n).multiply(r).add(i).sqrt();return"03"==t&&(o=o.negate()),new ECPointFp(this,r,o);case 4:case 6:case 7:var s=(e.length-2)/2,a=e.substr(2,s),c=e.substr(s+2,s);return new ECPointFp(this,this.fromBigInteger(new BigInteger(a,16)),this.fromBigInteger(new BigInteger(c,16)));default:return null}}SecureRandom.prototype.nextBytes=rng_get_bytes,RSAKey.prototype.doPublic=RSADoPublic,RSAKey.prototype.setPublic=RSASetPublic,RSAKey.prototype.type="RSA",RSAKey.prototype.doPrivate=RSADoPrivate,RSAKey.prototype.setPrivate=RSASetPrivate,RSAKey.prototype.setPrivateEx=RSASetPrivateEx,RSAKey.prototype.generate=RSAGenerate,ECFieldElementFp.prototype.equals=feFpEquals,ECFieldElementFp.prototype.toBigInteger=feFpToBigInteger,ECFieldElementFp.prototype.negate=feFpNegate,ECFieldElementFp.prototype.add=feFpAdd,ECFieldElementFp.prototype.subtract=feFpSubtract,ECFieldElementFp.prototype.multiply=feFpMultiply,ECFieldElementFp.prototype.square=feFpSquare,ECFieldElementFp.prototype.divide=feFpDivide,ECFieldElementFp.prototype.sqrt=function(){return new ECFieldElementFp(this.q,this.x.sqrt().mod(this.q))},ECPointFp.prototype.getX=pointFpGetX,ECPointFp.prototype.getY=pointFpGetY,ECPointFp.prototype.equals=pointFpEquals,ECPointFp.prototype.isInfinity=pointFpIsInfinity,ECPointFp.prototype.negate=pointFpNegate,ECPointFp.prototype.add=pointFpAdd,ECPointFp.prototype.twice=pointFpTwice,ECPointFp.prototype.multiply=pointFpMultiply,ECPointFp.prototype.multiplyTwo=pointFpMultiplyTwo,ECCurveFp.prototype.getQ=curveFpGetQ,ECCurveFp.prototype.getA=curveFpGetA,ECCurveFp.prototype.getB=curveFpGetB,ECCurveFp.prototype.equals=curveFpEquals,ECCurveFp.prototype.getInfinity=curveFpGetInfinity,ECCurveFp.prototype.fromBigInteger=curveFpFromBigInteger,ECCurveFp.prototype.decodePointHex=curveFpDecodePointHex, -/*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib - */ -ECFieldElementFp.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},ECPointFp.prototype.getEncoded=function(e){var t=function(e,t){var r=e.toByteArrayUnsigned();if(tr.length;)r.unshift(0);return r},r=this.getX().toBigInteger(),n=this.getY().toBigInteger(),i=t(r,32);return e?n.isEven()?i.unshift(2):i.unshift(3):(i.unshift(4),i=i.concat(t(n,32))),i},ECPointFp.decodeFrom=function(e,t){t[0];var r=t.length-1,n=t.slice(1,1+r/2),i=t.slice(1+r/2,1+r);n.unshift(0),i.unshift(0);var o=new BigInteger(n),s=new BigInteger(i);return new ECPointFp(e,e.fromBigInteger(o),e.fromBigInteger(s))},ECPointFp.decodeFromHex=function(e,t){t.substr(0,2);var r=t.length-2,n=t.substr(2,r/2),i=t.substr(2+r/2,r/2),o=new BigInteger(n,16),s=new BigInteger(i,16);return new ECPointFp(e,e.fromBigInteger(o),e.fromBigInteger(s))},ECPointFp.prototype.add2D=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;if(this.x.equals(e.x))return this.y.equals(e.y)?this.twice():this.curve.getInfinity();var t=e.x.subtract(this.x),r=e.y.subtract(this.y).divide(t),n=r.square().subtract(this.x).subtract(e.x),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new ECPointFp(this.curve,n,i)},ECPointFp.prototype.twice2D=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=this.curve.fromBigInteger(BigInteger.valueOf(2)),t=this.curve.fromBigInteger(BigInteger.valueOf(3)),r=this.x.square().multiply(t).add(this.curve.a).divide(this.y.multiply(e)),n=r.square().subtract(this.x.multiply(e)),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new ECPointFp(this.curve,n,i)},ECPointFp.prototype.multiply2D=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new BigInteger("3")),i=this.negate(),o=this;for(t=n.bitLength()-2;t>0;--t){o=o.twice();var s=n.testBit(t);s!=r.testBit(t)&&(o=o.add2D(s?this:i))}return o},ECPointFp.prototype.isOnCurve=function(){var e=this.getX().toBigInteger(),t=this.getY().toBigInteger(),r=this.curve.getA().toBigInteger(),n=this.curve.getB().toBigInteger(),i=this.curve.getQ(),o=t.multiply(t).mod(i),s=e.multiply(e).multiply(e).add(r.multiply(e)).add(n).mod(i);return o.equals(s)},ECPointFp.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},ECPointFp.prototype.validate=function(){var e=this.curve.getQ();if(this.isInfinity())throw new Error("Point is at infinity.");var t=this.getX().toBigInteger(),r=this.getY().toBigInteger();if(t.compareTo(BigInteger.ONE)<0||t.compareTo(e.subtract(BigInteger.ONE))>0)throw new Error("x coordinate out of bounds");if(r.compareTo(BigInteger.ONE)<0||r.compareTo(e.subtract(BigInteger.ONE))>0)throw new Error("y coordinate out of bounds");if(!this.isOnCurve())throw new Error("Point is not on the curve.");if(this.multiply(e).isInfinity())throw new Error("Point is not a scalar multiple of G.");return!0}; -/*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval - */ -var jsonParse=function(){var e=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)|(?:"(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))*"))',"g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),r={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function n(e,t,n){return t?r[t]:String.fromCharCode(parseInt(n,16))}var i=new String(""),o=Object.hasOwnProperty;return function(r,s){var a,c,l=r.match(e),u=l[0],d=!1;"{"===u?a={}:"["===u?a=[]:(a=[],d=!0);for(var h=[a],p=1-d,g=l.length;p=0;)delete r[n[c]]}return s.call(e,t,r)};a=f({"":a},"")}return a}}();void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(e){var t=e.toString(16);return t.length%2==1&&(t="0"+t),t},this.bigIntToMinTwosComplementsHex=function(e){return twoscompl(e)},this.getPEMStringFromHex=function(e,t){return hextopem(e,t)},this.newObject=function(e){var t=KJUR.asn1,r=t.ASN1Object,n=t.DERBoolean,i=t.DERInteger,o=t.DERBitString,s=t.DEROctetString,a=t.DERNull,c=t.DERObjectIdentifier,l=t.DEREnumerated,u=t.DERUTF8String,d=t.DERNumericString,h=t.DERPrintableString,p=t.DERTeletexString,g=t.DERIA5String,m=t.DERUTCTime,f=t.DERGeneralizedTime,y=t.DERVisibleString,$=t.DERBMPString,b=t.DERSequence,v=t.DERSet,w=t.DERTaggedObject,S=t.ASN1Util.newObject;if(e instanceof t.ASN1Object)return e;var _=Object.keys(e);if(1!=_.length)throw new Error("key of param shall be only one.");var E=_[0];if(-1==":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+E+":"))throw new Error("undefined key: "+E);if("bool"==E)return new n(e[E]);if("int"==E)return new i(e[E]);if("bitstr"==E)return new o(e[E]);if("octstr"==E)return new s(e[E]);if("null"==E)return new a(e[E]);if("oid"==E)return new c(e[E]);if("enum"==E)return new l(e[E]);if("utf8str"==E)return new u(e[E]);if("numstr"==E)return new d(e[E]);if("prnstr"==E)return new h(e[E]);if("telstr"==E)return new p(e[E]);if("ia5str"==E)return new g(e[E]);if("utctime"==E)return new m(e[E]);if("gentime"==E)return new f(e[E]);if("visstr"==E)return new y(e[E]);if("bmpstr"==E)return new $(e[E]);if("asn1"==E)return new r(e[E]);if("seq"==E){for(var C=e[E],I=[],T=0;T15)throw new Error("ASN.1 length too long to represent by 8x: n = "+e.toString(16));return(128+r).toString(16)+t},this.tohex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getEncodedHex=function(){return this.tohex()},this.getValueHex=function(){return this.tohex(),this.hV},this.getFreshValueHex=function(){return""},this.setByParam=function(e){this.params=e},null!=e&&null!=e.tlv&&(this.hTLV=e.tlv,this.isModified=!1)},KJUR.asn1.DERAbstractString=function(e){KJUR.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=utf8tohex(this.s).toLowerCase()},this.setStringHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?this.setString(e):void 0!==e.str?this.setString(e.str):void 0!==e.hex&&this.setStringHex(e.hex))},extendClass(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractTime=function(e){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(e){var t=e.getTime()+6e4*e.getTimezoneOffset();return new Date(t)},this.formatDate=function(e,t,r){var n=this.zeroPadding,i=this.localDateToUTC(e),o=String(i.getFullYear());"utc"==t&&(o=o.substr(2,2));var s=o+n(String(i.getMonth()+1),2)+n(String(i.getDate()),2)+n(String(i.getHours()),2)+n(String(i.getMinutes()),2)+n(String(i.getSeconds()),2);if(!0===r){var a=i.getMilliseconds();if(0!=a){var c=n(String(a),3);s=s+"."+(c=c.replace(/[0]+$/,""))}}return s+"Z"},this.zeroPadding=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},this.setByParam=function(e){this.hV=null,this.hTLV=null,this.params=e},this.getString=function(){},this.setString=function(e){this.hTLV=null,this.isModified=!0,null==this.params&&(this.params={}),this.params.str=e},this.setByDate=function(e){this.hTLV=null,this.isModified=!0,null==this.params&&(this.params={}),this.params.date=e},this.setByDateValue=function(e,t,r,n,i,o){var s=new Date(Date.UTC(e,t-1,r,n,i,o,0));this.setByDate(s)},this.getFreshValueHex=function(){return this.hV}},extendClass(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractStructured=function(e){KJUR.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array=e},this.appendASN1Object=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array.push(e)},this.asn1Array=new Array,void 0!==e&&void 0!==e.array&&(this.asn1Array=e.array)},extendClass(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object),KJUR.asn1.DERBoolean=function(e){KJUR.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},extendClass(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object),KJUR.asn1.DERInteger=function(e){KJUR.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.params=null;var t=twoscompl;this.setByBigInteger=function(e){this.isModified=!0,this.params={bigint:e}},this.setByInteger=function(e){this.isModified=!0,this.params=e},this.setValueHex=function(e){this.isModified=!0,this.params={hex:e}},this.getFreshValueHex=function(){var e=this.params,r=null;if(null==e)throw new Error("value not set");if("object"==typeof e&&null!=e.hex)return this.hV=e.hex,this.hV;if("number"==typeof e)r=new BigInteger(String(e),10);else if(null!=e.int)r=new BigInteger(String(e.int),10);else{if(null==e.bigint)throw new Error("wrong parameter");r=e.bigint}return this.hV=t(r),this.hV},null!=e&&(this.params=e)},extendClass(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object),KJUR.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.tohex()}KJUR.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(e){this.hTLV=null,this.isModified=!0,this.hV=e},this.setUnusedBitsAndHexValue=function(e,t){if(e<0||7>6).toString(16)+n.toString(16))}n=128|(15&t)<<2|(192&r)>>6;var i=128|63&r;return hextoutf8((224|(240&t)>>4).toString(16)+n.toString(16)+i.toString(16))});return t.join("")}function encodeURIComponentAll(e){for(var t=encodeURIComponent(e),r="",n=0;n"7"?"00"+e:e}function oidtohex(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=parseInt(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var o="",s=0;s0&&(l=l+"."+a.join(".")),l}catch(e){return null}}function inttohex(e){return twoscompl(new BigInteger(String(e),10))}function twoscompl(e){var t=e.toString(16);if("-"!=t.substr(0,1))return t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t),t;var r=t.substr(1).length;r%2==1?r+=1:t.match(/^[0-7]/)||(r+=2);for(var n="",i=0;i=n)break}return s},ASN1HEX.getNthChildIdx=function(e,t,r){return ASN1HEX.getChildIdx(e,t)[r]},ASN1HEX.getIdxbyList=function(e,t,r,n){var i,o,s=ASN1HEX;return 0==r.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(i=r.shift())>=(o=s.getChildIdx(e,t)).length?-1:s.getIdxbyList(e,o[i],r,n)},ASN1HEX.getIdxbyListEx=function(e,t,r,n){var i,o,s=ASN1HEX;if(0==r.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;i=r.shift(),o=s.getChildIdx(e,t);for(var a=0,c=0;c=e.length?null:i.getTLV(e,o)},ASN1HEX.getTLVbyListEx=function(e,t,r,n){var i=ASN1HEX,o=i.getIdxbyListEx(e,t,r,n);return-1==o?null:i.getTLV(e,o)},ASN1HEX.getVbyList=function(e,t,r,n,i){var o,s,a=ASN1HEX;return-1==(o=a.getIdxbyList(e,t,r,n))||o>=e.length?null:(s=a.getV(e,o),!0===i&&(s=s.substr(2)),s)},ASN1HEX.getVbyListEx=function(e,t,r,n,i){var o,s,a=ASN1HEX;return-1==(o=a.getIdxbyListEx(e,t,r,n))?null:(s=a.getV(e,o),"03"==e.substr(o,2)&&!1!==i&&(s=s.substr(2)),s)},ASN1HEX.getInt=function(e,t,r){null==r&&(r=-1);try{var n=e.substr(t,2);if("02"!=n&&"03"!=n)return r;var i=ASN1HEX.getV(e,t);return"02"==n?parseInt(i,16):bitstrtoint(i)}catch(e){return r}},ASN1HEX.getOID=function(e,t,r){null==r&&(r=null);try{return"06"!=e.substr(t,2)?r:hextooid(ASN1HEX.getV(e,t))}catch(e){return r}},ASN1HEX.getOIDName=function(e,t,r){null==r&&(r=null);try{var n=ASN1HEX.getOID(e,t,r);if(n==r)return r;var i=KJUR.asn1.x509.OID.oid2name(n);return""==i?n:i}catch(e){return r}},ASN1HEX.getString=function(e,t,r){null==r&&(r=null);try{return hextorstr(ASN1HEX.getV(e,t))}catch(e){return r}},ASN1HEX.hextooidstr=function(e){var t=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},r=[],n=e.substr(0,2),i=parseInt(n,16);r[0]=new String(Math.floor(i/40)),r[1]=new String(i%40);for(var o=e.substr(2),s=[],a=0;a0&&(u=u+"."+c.join(".")),u},ASN1HEX.dump=function(e,t,r,n){var i=ASN1HEX,o=i.getV,s=i.dump,a=i.getChildIdx,c=e;e instanceof KJUR.asn1.ASN1Object&&(c=e.tohex());var l=function(e,t){return e.length<=2*t?e:e.substr(0,t)+"..(total "+e.length/2+"bytes).."+e.substr(e.length-t,t)};void 0===t&&(t={ommit_long_octet:32}),void 0===r&&(r=0),void 0===n&&(n="");var u,d=t.ommit_long_octet;if("01"==(u=c.substr(r,2)))return"00"==(h=o(c,r))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==u)return n+"INTEGER "+l(h=o(c,r),d)+"\n";if("03"==u){var h=o(c,r);if(i.isASN1HEX(h.substr(2))){var p=n+"BITSTRING, encapsulates\n";return p+=s(h.substr(2),t,0,n+" ")}return n+"BITSTRING "+l(h,d)+"\n"}if("04"==u){h=o(c,r);if(i.isASN1HEX(h)){p=n+"OCTETSTRING, encapsulates\n";return p+=s(h,t,0,n+" ")}return n+"OCTETSTRING "+l(h,d)+"\n"}if("05"==u)return n+"NULL\n";if("06"==u){var g=o(c,r),m=KJUR.asn1.ASN1Util.oidHexToInt(g),f=KJUR.asn1.x509.OID.oid2name(m),y=m.replace(/\./g," ");return""!=f?n+"ObjectIdentifier "+f+" ("+y+")\n":n+"ObjectIdentifier ("+y+")\n"}if("0a"==u)return n+"ENUMERATED "+parseInt(o(c,r))+"\n";if("0c"==u)return n+"UTF8String '"+hextoutf8(o(c,r))+"'\n";if("13"==u)return n+"PrintableString '"+hextoutf8(o(c,r))+"'\n";if("14"==u)return n+"TeletexString '"+hextoutf8(o(c,r))+"'\n";if("16"==u)return n+"IA5String '"+hextoutf8(o(c,r))+"'\n";if("17"==u)return n+"UTCTime "+hextoutf8(o(c,r))+"\n";if("18"==u)return n+"GeneralizedTime "+hextoutf8(o(c,r))+"\n";if("1a"==u)return n+"VisualString '"+hextoutf8(o(c,r))+"'\n";if("1e"==u)return n+"BMPString '"+ucs2hextoutf8(o(c,r))+"'\n";if("30"==u){if("3000"==c.substr(r,4))return n+"SEQUENCE {}\n";p=n+"SEQUENCE\n";var $=t;if((2==(w=a(c,r)).length||3==w.length)&&"06"==c.substr(w[0],2)&&"04"==c.substr(w[w.length-1],2)){f=i.oidname(o(c,w[0]));var b=JSON.parse(JSON.stringify(t));b.x509ExtName=f,$=b}for(var v=0;v4?{enum:{hex:f}}:{enum:parseInt(f,16)};if("30"==g||"31"==g)return m[p[g]]=function(e){for(var t=[],n=s(e,0),i=0;i31)&&(128==(192&r)&&(31&r)==n))}catch(e){return!1}},ASN1HEX.isASN1HEX=function(e){var t=ASN1HEX;if(e.length%2==1)return!1;var r=t.getVblen(e,0),n=e.substr(0,2),i=t.getL(e,0);return e.length-n.length-i.length==2*r},ASN1HEX.checkStrictDER=function(e,t,r,n,i){var o=ASN1HEX;if(void 0===r){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!KJUR.lang.String.isHex(e))throw new Error("not hex string");r=e.length,i=(n=e.length/2)<128?1:Math.ceil(n.toString(16))+1}if(o.getL(e,t).length>2*i)throw new Error("L of TLV too long: idx="+t);var s=o.getVblen(e,t);if(s>n)throw new Error("value of L too long than hex: idx="+t);var a=o.getTLV(e,t),c=a.length-2-o.getL(e,t).length;if(c!==2*s)throw new Error("V string length and L's value not the same:"+c+"/"+2*s);if(0===t&&e.length!=a.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+a.length);var l=e.substr(t,2);if("02"===l){var u=o.getVidx(e,t);if("00"==e.substr(u,2)&&e.charCodeAt(u+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(l,16)){for(var d=o.getVblen(e,t),h=0,p=o.getChildIdx(e,t),g=0;g0&&e.push(new n({tag:"a3",obj:new l(t.ext)})),new KJUR.asn1.DERSequence({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.TBSCertificate,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Extensions=function(e){KJUR.asn1.x509.Extensions.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERSequence,n=t.x509;this.aParam=[],this.setByParam=function(e){this.aParam=e},this.tohex=function(){for(var e=[],t=0;t-1&&e.push(new n({int:this.pathLen}));var t=new i({array:e});return this.asn1ExtnValue=t,this.asn1ExtnValue.tohex()},this.oid="2.5.29.19",this.cA=!1,this.pathLen=-1,void 0!==e&&(void 0!==e.cA&&(this.cA=e.cA),void 0!==e.pathLen&&(this.pathLen=e.pathLen))},extendClass(KJUR.asn1.x509.BasicConstraints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.CRLDistributionPoints=function(e){KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.x509;this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.setByDPArray=function(e){for(var n=[],i=0;i0&&e.push(new r({array:t}))}return new r({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyInformation,KJUR.asn1.ASN1Object),KJUR.asn1.x509.PolicyQualifierInfo=function(e){KJUR.asn1.x509.PolicyQualifierInfo.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERSequence,n=t.DERIA5String,i=t.DERObjectIdentifier,o=t.x509.UserNotice;this.params=null,this.tohex=function(){return void 0!==this.params.cps?new r({array:[new i({oid:"1.3.6.1.5.5.7.2.1"}),new n({str:this.params.cps})]}).tohex():null!=this.params.unotice?new r({array:[new i({oid:"1.3.6.1.5.5.7.2.2"}),new o(this.params.unotice)]}).tohex():void 0},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyQualifierInfo,KJUR.asn1.ASN1Object),KJUR.asn1.x509.UserNotice=function(e){KJUR.asn1.x509.UserNotice.superclass.constructor.call(this,e);var t=KJUR.asn1.DERSequence;KJUR.asn1.DERInteger;var r=KJUR.asn1.x509.DisplayText,n=KJUR.asn1.x509.NoticeReference;this.params=null,this.tohex=function(){var e=[];return void 0!==this.params.noticeref&&e.push(new n(this.params.noticeref)),void 0!==this.params.exptext&&e.push(new r(this.params.exptext)),new t({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.UserNotice,KJUR.asn1.ASN1Object),KJUR.asn1.x509.NoticeReference=function(e){KJUR.asn1.x509.NoticeReference.superclass.constructor.call(this,e);var t=KJUR.asn1.DERSequence,r=KJUR.asn1.DERInteger,n=KJUR.asn1.x509.DisplayText;this.params=null,this.tohex=function(){var e=[];if(void 0!==this.params.org&&e.push(new n(this.params.org)),void 0!==this.params.noticenum){for(var i=[],o=this.params.noticenum,s=0;s0)for(var e=0;e0;i++){var o=t.shift();if(!0===r){var s=(n.pop()+","+o).replace(/\\,/g,",");n.push(s),r=!1}else n.push(o);"\\"===o.substr(-1,1)&&(r=!0)}return n=n.map(function(e){return e.replace("/","\\/")}),n.reverse(),"/"+n.join("/")},KJUR.asn1.x509.X500Name.ldapToOneline=function(e){return KJUR.asn1.x509.X500Name.ldapToCompat(e)},KJUR.asn1.x509.RDN=function(e){KJUR.asn1.x509.RDN.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=KJUR.asn1.x509.AttributeTypeAndValue;this.setByParam=function(e){void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.str&&this.addByMultiValuedString(e.str),void 0!==e.array&&(this.paramArray=e.array)},this.addByString=function(e){this.asn1Array.push(new KJUR.asn1.x509.AttributeTypeAndValue({str:e,rule:this.sRule}))},this.addByMultiValuedString=function(e){for(var t=KJUR.asn1.x509.RDN.parseString(e),r=0;r0)for(var e=0;e0;i++){var o=t.shift();if(!0===r){var s=(n.pop()+"+"+o).replace(/\\\+/g,"+");n.push(s),r=!1}else n.push(o);"\\"===o.substr(-1,1)&&(r=!0)}var a=!1,c=[];for(i=0;n.length>0;i++){o=n.shift();if(!0===a){var l=c.pop();if(o.match(/"$/)){s=(l+"+"+o).replace(/^([^=]+)="(.*)"$/,"$1=$2");c.push(s),a=!1}else c.push(l+"+"+o)}else c.push(o);o.match(/^[^=]+="/)&&(a=!0)}return c},KJUR.asn1.x509.AttributeTypeAndValue=function(e){KJUR.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this),this.sRule="utf8",this.sType=null,this.sValue=null,this.dsType=null;var t=KJUR,r=t.asn1,n=r.DERSequence,i=r.DERUTF8String,o=r.DERPrintableString,s=r.DERTeletexString,a=r.DERIA5String,c=r.DERVisibleString,l=r.DERBMPString,u=t.lang.String.isMail,d=t.lang.String.isPrintable;this.setByParam=function(e){if(void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.ds&&(this.dsType=e.ds),void 0===e.value&&void 0!==e.str){var t=e.str.match(/^([^=]+)=(.+)$/);if(!t)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.sType=t[1],this.sValue=t[2]}else this.sType=e.type,this.sValue=e.value},this.setByString=function(e,t){void 0!==t&&(this.sRule=t);var r=e.match(/^([^=]+)=(.+)$/);if(!r)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.setByAttrTypeAndValueStr(r[1],r[2])},this._getDsType=function(){var e=this.sType,t=this.sValue,r=this.sRule;return"prn"===r?"CN"==e&&u(t)?"ia5":d(t)?"prn":"utf8":"utf8"===r?"CN"==e&&u(t)?"ia5":"C"==e?"prn":"utf8":"utf8"},this.setByAttrTypeAndValueStr=function(e,t,r){void 0!==r&&(this.sRule=r),this.sType=e,this.sValue=t},this.getValueObj=function(e,t){if("utf8"==e)return new i({str:t});if("prn"==e)return new o({str:t});if("tel"==e)return new s({str:t});if("ia5"==e)return new a({str:t});if("vis"==e)return new c({str:t});if("bmp"==e)return new l({str:t});throw new Error("unsupported directory string type: type="+e+" value="+t)},this.tohex=function(){null==this.dsType&&(this.dsType=this._getDsType());var e=KJUR.asn1.x509.OID.atype2obj(this.sType),t=this.getValueObj(this.dsType,this.sValue),r=new n({array:[e,t]});return this.TLV=r.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.AttributeTypeAndValue,KJUR.asn1.ASN1Object),KJUR.asn1.x509.SubjectPublicKeyInfo=function(e){KJUR.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);var t=KJUR,r=t.asn1,n=r.DERInteger,i=r.DERBitString,o=r.DERObjectIdentifier,s=r.DERSequence,a=r.ASN1Util.newObject,c=r.x509.AlgorithmIdentifier,l=t.crypto;l.ECDSA,l.DSA,this.getASN1Object=function(){if(null==this.asn1AlgId||null==this.asn1SubjPKey)throw"algId and/or subjPubKey not set";return new s({array:[this.asn1AlgId,this.asn1SubjPKey]})},this.tohex=function(){var e=this.getASN1Object();return this.hTLV=e.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},this.setPubKey=function(e){try{if(e instanceof RSAKey){var t=a({seq:[{int:{bigint:e.n}},{int:{int:e.e}}]}).tohex();this.asn1AlgId=new c({name:"rsaEncryption"}),this.asn1SubjPKey=new i({hex:"00"+t})}}catch(e){}try{if(e instanceof KJUR.crypto.ECDSA){var r=new o({name:e.curveName});this.asn1AlgId=new c({name:"ecPublicKey",asn1params:r}),this.asn1SubjPKey=new i({hex:"00"+e.pubKeyHex})}}catch(e){}try{if(e instanceof KJUR.crypto.DSA){r=new a({seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]});this.asn1AlgId=new c({name:"dsa",asn1params:r});var s=new n({bigint:e.y});this.asn1SubjPKey=new i({hex:"00"+s.tohex()})}}catch(e){}},void 0!==e&&this.setPubKey(e)},extendClass(KJUR.asn1.x509.SubjectPublicKeyInfo,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Time=function(e){KJUR.asn1.x509.Time.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERUTCTime,n=t.DERGeneralizedTime;this.params=null,this.type=null,this.setTimeParams=function(e){this.timeParams=e},this.setByParam=function(e){this.params=e},this.getType=function(e){return e.match(/^[0-9]{12}Z$/)?"utc":e.match(/^[0-9]{14}Z$/)?"gen":e.match(/^[0-9]{12}\.[0-9]+Z$/)?"utc":e.match(/^[0-9]{14}\.[0-9]+Z$/)?"gen":null},this.tohex=function(){var e=this.params,t=null;if("string"==typeof e&&(e={str:e}),null==e||!e.str||null!=e.type&&null!=e.type||(e.type=this.getType(e.str)),null!=e&&e.str?("utc"==e.type&&(t=new r(e.str)),"gen"==e.type&&(t=new n(e.str))):t="gen"==this.type?new n:new r,null==t)throw new Error("wrong setting for Time");return this.TLV=t.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},KJUR.asn1.x509.Time_bak=function(e){KJUR.asn1.x509.Time_bak.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERUTCTime,n=t.DERGeneralizedTime;this.setTimeParams=function(e){this.timeParams=e},this.tohex=function(){var e=null;return e=null!=this.timeParams?"utc"==this.type?new r(this.timeParams):new n(this.timeParams):"utc"==this.type?new r:new n,this.TLV=e.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},this.type="utc",void 0!==e&&(void 0!==e.type?this.type=e.type:void 0!==e.str&&(e.str.match(/^[0-9]{12}Z$/)&&(this.type="utc"),e.str.match(/^[0-9]{14}Z$/)&&(this.type="gen")),this.timeParams=e)},extendClass(KJUR.asn1.x509.Time,KJUR.asn1.ASN1Object),KJUR.asn1.x509.AlgorithmIdentifier=function(e){KJUR.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this),this.nameAlg=null,this.asn1Alg=null,this.asn1Params=null,this.paramEmpty=!1;var t=KJUR.asn1,r=t.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV;if(this.tohex=function(){if(null===this.nameAlg&&null===this.asn1Alg)throw new Error("algorithm not specified");if(null!==this.nameAlg){var e=null;for(var n in r)n===this.nameAlg&&(e=r[n]);if(null!==e)return this.hTLV=e,this.hTLV}null!==this.nameAlg&&null===this.asn1Alg&&(this.asn1Alg=t.x509.OID.name2obj(this.nameAlg));var i=[this.asn1Alg];null!==this.asn1Params&&i.push(this.asn1Params);var o=new t.DERSequence({array:i});return this.hTLV=o.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(void 0!==e.name&&(this.nameAlg=e.name),void 0!==e.asn1params&&(this.asn1Params=e.asn1params),void 0!==e.paramempty&&(this.paramEmpty=e.paramempty)),null===this.asn1Params&&!1===this.paramEmpty&&null!==this.nameAlg){void 0!==this.nameAlg.name&&(this.nameAlg=this.nameAlg.name);var n=this.nameAlg.toLowerCase();"withdsa"!==n.substr(-7,7)&&"withecdsa"!==n.substr(-9,9)&&(this.asn1Params=new t.DERNull)}},extendClass(KJUR.asn1.x509.AlgorithmIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV={SHAwithRSAandMGF1:"300d06092a864886f70d01010a3000",SHA256withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040201a11a301806092a864886f70d010108300b0609608648016503040201a203020120",SHA384withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040202a11a301806092a864886f70d010108300b0609608648016503040202a203020130",SHA512withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040203a11a301806092a864886f70d010108300b0609608648016503040203a203020140"},KJUR.asn1.x509.GeneralName=function(e){KJUR.asn1.x509.GeneralName.superclass.constructor.call(this);var t=KJUR.asn1,r=t.x509,n=r.X500Name,i=r.OtherName,o=t.DERIA5String;t.DERPrintableString;var s=t.DEROctetString,a=t.DERTaggedObject,c=t.ASN1Object,l=Error;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e,t,r=this.params,u=!1;if(void 0!==r.other)e="a0",t=new i(r.other);else if(void 0!==r.rfc822)e="81",t=new o({str:r.rfc822});else if(void 0!==r.dns)e="82",t=new o({str:r.dns});else if(void 0!==r.dn)e="a4",u=!0,t="string"==typeof r.dn?new n({str:r.dn}):r.dn instanceof KJUR.asn1.x509.X500Name?r.dn:new n(r.dn);else if(void 0!==r.ldapdn)e="a4",u=!0,t=new n({ldapstr:r.ldapdn});else if(void 0!==r.certissuer||void 0!==r.certsubj){var d,h;e="a4",u=!0;var p=null;if(void 0!==r.certsubj?(d=!1,h=r.certsubj):(d=!0,h=r.certissuer),h.match(/^[0-9A-Fa-f]+$/),-1!=h.indexOf("-----BEGIN ")&&(p=pemtohex(h)),null==p)throw new Error("certsubj/certissuer not cert");var g,m=new X509;m.hex=p,g=d?m.getIssuerHex():m.getSubjectHex(),(t=new c).hTLV=g}else if(void 0!==r.uri)e="86",t=new o({str:r.uri});else{if(void 0===r.ip)throw new l("improper params");var f;e="87";var y=r.ip;try{if(y.match(/^[0-9a-f]+$/)){var $=y.length;if(8!=$&&16!=$&&32!=$&&64!=$)throw"err";f=y}else f=iptohex(y)}catch(e){throw new l("malformed IP address: "+r.ip+":"+e.message)}t=new s({hex:f})}return new a({tag:e,explicit:u,obj:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.GeneralName,KJUR.asn1.ASN1Object),KJUR.asn1.x509.GeneralNames=function(e){KJUR.asn1.x509.GeneralNames.superclass.constructor.call(this);var t=KJUR.asn1;this.setByParamArray=function(e){for(var r=0;r0){for(var r=o(e.valhex,t[0]),n=u(r,0),i=[],s=0;s1){var l=o(e.valhex,t[1]);e.polhex=l}delete e.valhex},this.setSignaturePolicyIdentifier=function(e){var r=u(e.valhex,0);if(r.length>0){var s=n.getOID(e.valhex,r[0]);e.oid=s}if(r.length>1){var a=new t,c=u(e.valhex,r[1]),l=o(e.valhex,c[0]),d=a.getAlgorithmIdentifierName(l);e.alg=d;var h=i(e.valhex,c[1]);e.hash=h}delete e.valhex},this.setSigningCertificateV2=function(e){var t=u(e.valhex,0);if(t.length>0){for(var r=o(e.valhex,t[0]),n=u(r,0),i=[],s=0;s1){var l=o(e.valhex,t[1]);e.polhex=l}delete e.valhex},this.getESSCertID=function(e){var t={},r=u(e,0);if(r.length>0){var n=i(e,r[0]);t.hash=n}if(r.length>1){var s=o(e,r[1]),a=this.getIssuerSerial(s);null!=a.serial&&(t.serial=a.serial),null!=a.issuer&&(t.issuer=a.issuer)}return t},this.getESSCertIDv2=function(t){var n={},s=u(t,0);if(s.length<1||3a+1){var d=o(t,s[a+1]),h=this.getIssuerSerial(d);n.issuer=h.issuer,n.serial=h.serial}return n},this.getIssuerSerial=function(e){var t={},n=u(e,0),s=o(e,n[0]),a=r.getGeneralNames(s)[0].dn;t.issuer=a;var c=i(e,n[1]);return t.serial={hex:c},t},this.getCertificateSet=function(e){for(var t=u(e,0),r=[],n=0;n=0;s--)i+=n[s];return i}if("string"==typeof e&&null!=o[e])return namearraytobinstr([e],o);if("object"==typeof e&&null!=e.length)return namearraytobinstr(e,o);throw new t("wrong params")},this.tohex=function(){this.params;var e=this.getBinValue();return new n({bin:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.PKIFailureInfo,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.AbstractTSAAdapter=function(e){this.getTSTHex=function(e,t){throw"not implemented yet"}},KJUR.asn1.tsp.SimpleTSAAdapter=function(e){var t=KJUR,r=t.asn1.tsp,n=t.crypto.Util.hashHex;r.SimpleTSAAdapter.superclass.constructor.call(this),this.params=null,this.serial=0,this.getTSTHex=function(e,t){var i=n(e,t);this.params.econtent.content.messageImprint={alg:t,hash:i},this.params.econtent.content.serial={int:this.serial++};var o=Math.floor(1e9*Math.random());return this.params.econtent.content.nonce={int:o},new r.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.tsp.SimpleTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter),KJUR.asn1.tsp.FixedTSAAdapter=function(e){var t=KJUR,r=t.asn1.tsp,n=t.crypto.Util.hashHex;r.FixedTSAAdapter.superclass.constructor.call(this),this.params=null,this.getTSTHex=function(e,t){var i=n(e,t);return this.params.econtent.content.messageImprint={alg:t,hash:i},new r.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.tsp.FixedTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter),KJUR.asn1.tsp.TSPUtil=new function(){},KJUR.asn1.tsp.TSPUtil.newTimeStampToken=function(e){return new KJUR.asn1.tsp.TimeStampToken(e)},KJUR.asn1.tsp.TSPUtil.parseTimeStampReq=function(e){return(new KJUR.asn1.tsp.TSPParser).getTimeStampReq(e)},KJUR.asn1.tsp.TSPUtil.parseMessageImprint=function(e){return(new KJUR.asn1.tsp.TSPParser).getMessageImprint(e)},KJUR.asn1.tsp.TSPParser=function(){var e=new X509,t=ASN1HEX,r=t.getV,n=t.getTLV,i=t.getIdxbyList;t.getTLVbyListEx;var o=t.getChildIdx,s=["granted","grantedWithMods","rejection","waiting","revocationWarning","revocationNotification"],a={0:"badAlg",2:"badRequest",5:"badDataFormat",14:"timeNotAvailable",15:"unacceptedPolicy",16:"unacceptedExtension",17:"addInfoNotAvailable",25:"systemFailure"};this.getResponse=function(e){var t=o(e,0);if(1==t.length)return this.getPKIStatusInfo(n(e,t[0]));if(t.length>1){var r=this.getPKIStatusInfo(n(e,t[0])),i=n(e,t[1]),s=this.getToken(i);return s.statusinfo=r,s}},this.getToken=function(e){var t=(new KJUR.asn1.cms.CMSParser).getCMSSignedData(e);return this.setTSTInfo(t),t},this.setTSTInfo=function(e){var t=e.econtent;if("tstinfo"==t.type){var r=t.content.hex,n=this.getTSTInfo(r);t.content=n}},this.getTSTInfo=function(t){var i={},s=o(t,0),a=r(t,s[1]);i.policy=hextooid(a);var c=n(t,s[2]);i.messageImprint=this.getMessageImprint(c);var l=r(t,s[3]);i.serial={hex:l};var u=r(t,s[4]);i.genTime={str:hextoutf8(u)};var d=0;if(s.length>5&&"30"==t.substr(s[5],2)){var h=n(t,s[5]);i.accuracy=this.getAccuracy(h),d++}s.length>5+d&&"01"==t.substr(s[5+d],2)&&("ff"==r(t,s[5+d])&&(i.ordering=!0),d++);if(s.length>5+d&&"02"==t.substr(s[5+d],2)){var p=r(t,s[5+d]);i.nonce={hex:p},d++}if(s.length>5+d&&"a0"==t.substr(s[5+d],2)){var g=n(t,s[5+d]);g="30"+g.substr(2),pGeneralNames=e.getGeneralNames(g);var m=pGeneralNames[0].dn;i.tsa=m,d++}if(s.length>5+d&&"a1"==t.substr(s[5+d],2)){var f=n(t,s[5+d]);f="30"+f.substr(2);var y=e.getExtParamArray(f);i.ext=y,d++}return i},this.getAccuracy=function(e){for(var t={},n=o(e,0),i=0;i1&&"30"==e.substr(i[1],2)){var u=n(e,i[1]);t.statusstr=this.getPKIFreeText(u),a++}if(i.length>a&&"03"==e.substr(i[1+a],2)){var d=n(e,i[1+a]);t.failinfo=this.getPKIFailureInfo(d)}return t},this.getPKIFreeText=function(e){for(var r=[],n=o(e,0),i=0;i=t?e:new Array(t-e.length+1).join(r)+e};function bitstrtoint(e){if(e.length%2!=0)return-1;if(null==(e=e.toLowerCase()).match(/^[0-9a-f]+$/))return-1;try{var t=e.substr(0,2);if("00"==t)return parseInt(e.substr(2),16);var r=parseInt(t,16);if(r>7)return-1;var n=e.substr(2),i=parseInt(n,16).toString(2);"0"==i&&(i="00000000"),i=i.slice(0,0-r);var o=parseInt(i,2);return NaN==o?-1:o}catch(e){return-1}}function bitstrtobinstr(e){if("string"!=typeof e)return null;if(e.length%2!=0)return null;if(!e.match(/^[0-9a-f]+$/))return null;try{var t=parseInt(e.substr(0,2),16);if(t<0||7=0;n--)o+=i[n];return o}function aryval(e,t,r){if("object"==typeof e){t=String(t).split(".");for(var n=0;ni)throw"key is too short for SigAlg: keylen="+r+","+t;for(var o="0001",s="00"+n,a="",c=i-4-s.length,l=0;l=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(o)>=0)return!1;var a=n.modInverse(o),c=e.multiply(a).mod(o),l=t.multiply(a).mod(o);return s.multiply(c).add(i.multiply(l)).getX().toBigInteger().mod(o).equals(t)},this.serializeSig=function(e,t){var r=e.toByteArraySigned(),n=t.toByteArraySigned(),i=[];return i.push(2),i.push(r.length),(i=i.concat(r)).push(2),i.push(n.length),(i=i.concat(n)).unshift(i.length),i.unshift(48),i},this.parseSig=function(e){var t;if(48!=e[0])throw new Error("Signature not a valid DERSequence");if(2!=e[t=2])throw new Error("First element in signature must be a DERInteger");var n=e.slice(t+2,t+2+e[t+1]);if(2!=e[t+=2+e[t+1]])throw new Error("Second element in signature must be a DERInteger");var i=e.slice(t+2,t+2+e[t+1]);return t+=2+e[t+1],{r:r.fromByteArrayUnsigned(n),s:r.fromByteArrayUnsigned(i)}},this.parseSigCompact=function(e){if(65!==e.length)throw"Signature has the wrong length";var t=e[0]-27;if(t<0||t>7)throw"Invalid signature type";var n=this.ecparams.n;return{r:r.fromByteArrayUnsigned(e.slice(1,33)).mod(n),s:r.fromByteArrayUnsigned(e.slice(33,65)).mod(n),i:t}},this.readPKCS5PrvKeyHex=function(e){if(!1===l(e))throw new Error("not ASN.1 hex string");var t,r,n;try{t=c(e,0,["[0]",0],"06"),r=c(e,0,[1],"04");try{n=c(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=s(t),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(r),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n,i;try{c(e,0,[1,0],"06"),r=c(e,0,[1,1],"06"),n=c(e,0,[2,0,1],"04");try{i=c(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=s(r),void 0===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n;try{c(e,0,[0,0],"06"),r=c(e,0,[0,1],"06"),n=c(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=s(r),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,r){if(!1===l(e))throw new t("not ASN.1 hex string");var n,i;try{n=c(e,0,[0,5,0,1],"06"),i=c(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=s(n),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i)},void 0!==e&&void 0!==e.curve&&(this.curveName=e.curve),void 0===this.curveName&&(this.curveName="secp256r1"),this.setNamedCurve(this.curveName),void 0!==e&&(void 0!==e.prv&&this.setPrivateKeyHex(e.prv),void 0!==e.pub&&this.setPublicKeyHex(e.pub))},KJUR.crypto.ECDSA.parseSigHex=function(e){var t=KJUR.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new BigInteger(t.r,16),s:new BigInteger(t.s,16)}},KJUR.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV;if(t.checkStrictDER(e,0),"30"!=e.substr(0,2))throw new Error("signature is not a ASN.1 sequence");var i=r(e,0);if(2!=i.length)throw new Error("signature shall have two elements");var o=i[0],s=i[1];if("02"!=e.substr(o,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(s,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,o),s:n(e,s)}},KJUR.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=KJUR.crypto.ECDSA.parseSigHexInHexRS(e),r=t.r,n=t.s;if(r.length>=130&&r.length<=134){if(r.length%2!=0)throw Error("unknown ECDSA sig r length error");if(n.length%2!=0)throw Error("unknown ECDSA sig s length error");"00"==r.substr(0,2)&&(r=r.substr(2)),"00"==n.substr(0,2)&&(n=n.substr(2));var i=Math.max(r.length,n.length);return(r=("000000"+r).slice(-i))+(n=("000000"+n).slice(-i))}if("00"==r.substr(0,2)&&r.length%32==2&&(r=r.substr(2)),"00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),r.length%32==30&&(r="00"+r),n.length%32==30&&(n="00"+n),r.length%32!=0)throw Error("unknown ECDSA sig r length error");if(n.length%32!=0)throw Error("unknown ECDSA sig s length error");return r+n},KJUR.crypto.ECDSA.concatSigToASN1Sig=function(e){if(e.length%4!=0)throw Error("unknown ECDSA concatinated r-s sig length error");var t=e.substr(0,e.length/2),r=e.substr(e.length/2);return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(t,r)},KJUR.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var r=new BigInteger(e,16),n=new BigInteger(t,16);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(r,n)},KJUR.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var r=KJUR.asn1,n=new r.DERInteger({bigint:e}),i=new r.DERInteger({bigint:t});return new r.DERSequence({array:[n,i]}).tohex()},KJUR.crypto.ECDSA.getName=function(e){return"2b8104001f"===e?"secp192k1":"2a8648ce3d030107"===e?"secp256r1":"2b8104000a"===e?"secp256k1":"2b81040021"===e?"secp224r1":"2b81040022"===e?"secp384r1":"2b81040023"===e?"secp521r1":-1!=="|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(e)?"secp256r1":-1!=="|secp256k1|".indexOf(e)?"secp256k1":-1!=="|secp224r1|NIST P-224|P-224|".indexOf(e)?"secp224r1":-1!=="|secp384r1|NIST P-384|P-384|".indexOf(e)?"secp384r1":-1!=="|secp521r1|NIST P-521|P-521|".indexOf(e)?"secp521r1":null},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.crypto.ECParameterDB=new function(){var e={},t={};function r(e){return new BigInteger(e,16)}this.getByName=function(r){var n=r;if(void 0!==t[n]&&(n=t[r]),void 0!==e[n])return e[n];throw"unregistered EC curve name: "+n},this.regist=function(n,i,o,s,a,c,l,u,d,h,p,g){e[n]={};var m=r(o),f=r(s),y=r(a),$=r(c),b=r(l),v=new ECCurveFp(m,f,y),w=v.decodePointHex("04"+u+d);e[n].name=n,e[n].keylen=i,e[n].keycharlen=2*Math.ceil(i/8),e[n].curve=v,e[n].G=w,e[n].n=$,e[n].h=b,e[n].oid=p,e[n].info=g;for(var S=0;S1?new BigInteger(n,16):null,l=new BigInteger(i,16),this.setPrivate(o,s,a,c,l)},this.setPublic=function(e,t,r,n){this.isPublic=!0,this.p=e,this.q=t,this.g=r,this.y=n,this.x=null},this.setPublicHex=function(e,t,r,n){var i,o,s,a;i=new BigInteger(e,16),o=new BigInteger(t,16),s=new BigInteger(r,16),a=new BigInteger(n,16),this.setPublic(i,o,s,a)},this.signWithMessageHash=function(e){var t=this.p,r=this.q,n=this.g;this.y;var i=this.x,o=KJUR.crypto.Util.getRandomBigIntegerMinToMax(BigInteger.ONE.add(BigInteger.ONE),r.subtract(BigInteger.ONE)),s=new BigInteger(e.substr(0,r.bitLength()/4),16),a=n.modPow(o,t).mod(r),c=o.modInverse(r).multiply(s.add(i.multiply(a))).mod(r);return KJUR.asn1.ASN1Util.jsonToASN1HEX({seq:[{int:{bigint:a}},{int:{bigint:c}}]})},this.verifyWithMessageHash=function(e,t){var r=this.p,n=this.q,i=this.g,o=this.y,s=this.parseASN1Signature(t),a=s[0],c=s[1],l=new BigInteger(e.substr(0,n.bitLength()/4),16);if(BigInteger.ZERO.compareTo(a)>0||a.compareTo(n)>0)throw"invalid DSA signature";if(BigInteger.ZERO.compareTo(c)>=0||c.compareTo(n)>0)throw"invalid DSA signature";var u=c.modInverse(n),d=l.multiply(u).mod(n),h=a.multiply(u).mod(n);return 0==i.modPow(d,r).multiply(o.modPow(h,r)).mod(r).mod(n).compareTo(a)},this.parseASN1Signature=function(e){try{return[new n(t(e,0,[0],"02"),16),new n(t(e,0,[1],"02"),16)]}catch(e){throw new Error("malformed ASN.1 DSA signature")}},this.readPKCS5PrvKeyHex=function(e){var n,i,o,s,a;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1],"02"),i=t(e,0,[2],"02"),o=t(e,0,[3],"02"),s=t(e,0,[4],"02"),a=t(e,0,[5],"02")}catch(e){throw new Error("malformed PKCS#1/5 plain DSA private key")}this.setPrivateHex(n,i,o,s,a)},this.readPKCS8PrvKeyHex=function(e){var n,i,o,s;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1,1,0],"02"),i=t(e,0,[1,1,1],"02"),o=t(e,0,[1,1,2],"02"),s=t(e,0,[2,0],"02")}catch(e){throw new Error("malformed PKCS#8 plain DSA private key")}this.setPrivateHex(n,i,o,null,s)},this.readPKCS8PubKeyHex=function(e){var n,i,o,s;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[0,1,0],"02"),i=t(e,0,[0,1,1],"02"),o=t(e,0,[0,1,2],"02"),s=t(e,0,[1,0],"02")}catch(e){throw new Error("malformed PKCS#8 DSA public key")}this.setPublicHex(n,i,o,s)},this.readCertPubKeyHex=function(e,n){var i,o,s,a;if(!1===r(e))throw new Error("not ASN.1 hex string");try{i=t(e,0,[0,5,0,1,0],"02"),o=t(e,0,[0,5,0,1,1],"02"),s=t(e,0,[0,5,0,1,2],"02"),a=t(e,0,[0,5,1,0],"02")}catch(e){throw new Error("malformed X.509 certificate DSA public key")}this.setPublicHex(i,o,s,a)}};var KEYUTIL=function(){var e=function(e,r,n){return t(CryptoJS.AES,e,r,n)},t=function(e,t,r,n){var i=CryptoJS.enc.Hex.parse(t),o=CryptoJS.enc.Hex.parse(r),s=CryptoJS.enc.Hex.parse(n),a={};a.key=o,a.iv=s,a.ciphertext=i;var c=e.decrypt(a,o,{iv:s});return CryptoJS.enc.Hex.stringify(c)},r=function(e,t,r){return n(CryptoJS.AES,e,t,r)},n=function(e,t,r,n){var i=CryptoJS.enc.Hex.parse(t),o=CryptoJS.enc.Hex.parse(r),s=CryptoJS.enc.Hex.parse(n),a=e.encrypt(i,o,{iv:s}),c=CryptoJS.enc.Hex.parse(a.toString());return CryptoJS.enc.Base64.stringify(c)},i={"AES-256-CBC":{proc:e,eproc:r,keylen:32,ivlen:16},"AES-192-CBC":{proc:e,eproc:r,keylen:24,ivlen:16},"AES-128-CBC":{proc:e,eproc:r,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:function(e,r,n){return t(CryptoJS.TripleDES,e,r,n)},eproc:function(e,t,r){return n(CryptoJS.TripleDES,e,t,r)},keylen:24,ivlen:8},"DES-CBC":{proc:function(e,r,n){return t(CryptoJS.DES,e,r,n)},eproc:function(e,t,r){return n(CryptoJS.DES,e,t,r)},keylen:8,ivlen:8}},o=function(e){var t={},r=e.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));r&&(t.cipher=r[1],t.ivsalt=r[2]);var n=e.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));n&&(t.type=n[1]);var i=-1,o=0;-1!=e.indexOf("\r\n\r\n")&&(i=e.indexOf("\r\n\r\n"),o=2),-1!=e.indexOf("\n\n")&&(i=e.indexOf("\n\n"),o=1);var s=e.indexOf("-----END");if(-1!=i&&-1!=s){var a=e.substring(i+2*o,s-o);a=a.replace(/\s+/g,""),t.data=a}return t},s=function(e,t,r){for(var n=r.substring(0,16),o=CryptoJS.enc.Hex.parse(n),s=CryptoJS.enc.Utf8.parse(t),a=i[e].keylen+i[e].ivlen,c="",l=null;;){var u=CryptoJS.algo.MD5.create();if(null!=l&&u.update(l),u.update(s),u.update(o),l=u.finalize(),(c+=CryptoJS.enc.Hex.stringify(l)).length>=2*a)break}var d={};return d.keyhex=c.substr(0,2*i[e].keylen),d.ivhex=c.substr(2*i[e].keylen,2*i[e].ivlen),d},a=function(e,t,r,n){var o=CryptoJS.enc.Base64.parse(e),s=CryptoJS.enc.Hex.stringify(o);return(0,i[t].proc)(s,r,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return o(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,r){return s(e,t,r)},decryptKeyB64:function(e,t,r,n){return a(e,t,r,n)},getDecryptedKeyHex:function(e,t){var r=o(e),n=r.cipher,i=r.ivsalt,c=r.data,l=s(n,t,i).keyhex;return a(c,n,l,i)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,r,n,o){var a="";if(void 0!==n&&null!=n||(n="AES-256-CBC"),void 0===i[n])throw new Error("KEYUTIL unsupported algorithm: "+n);if(void 0===o||null==o){var c=function(e){var t=CryptoJS.lib.WordArray.random(e);return CryptoJS.enc.Hex.stringify(t)}(i[n].ivlen);o=c.toUpperCase()}var l=function(e,t,r,n){return(0,i[t].eproc)(e,r,n)}(t,n,s(n,r,o).keyhex,o);a="-----BEGIN "+e+" PRIVATE KEY-----\r\n";return a+="Proc-Type: 4,ENCRYPTED\r\n",a+="DEK-Info: "+n+","+o+"\r\n",a+="\r\n",a+=l.replace(/(.{64})/g,"$1\r\n"),a+="\r\n-----END "+e+" PRIVATE KEY-----\r\n"},getEncryptedPKCS8PEM:function(e,t,r){return hextopem(this.getEncryptedPKCS8Hex(e,t,r),"ENCRYPTED PRIVATE KEY")},getEncryptedPKCS8Hex:function(e,t,r){var n;(n=null==r||null==r?{}:JSON.parse(JSON.stringify(r))).plain=e,this.initPBES2Param(n),this.encryptPBES2Param(n,t);var i=this.generatePBES2ASN1Param(n);return KJUR.asn1.ASN1Util.newObject(i).tohex()},initPBES2Param:function(e){var t;(null==aryval(e,"encalg")&&(e.encalg="aes256-CBC"),null==aryval(e,"iter")&&(e.iter=2048),null==aryval(e,"prf")&&(e.prf="hmacWithSHA256"),null==aryval(e,"salt")&&(e.salt=CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(8))),null==aryval(e,"enciv"))&&("des-EDE3-CBC"==e.encalg&&(t=8),"aes128-CBC"==e.encalg&&(t=16),"aes256-CBC"==e.encalg&&(t=16),e.enciv=CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(t)))},encryptPBES2Param:function(e,t){var r=KEYUTIL.getDKFromPBES2Param(e,t);try{var n=KJUR.crypto.Cipher.encrypt(e.plain,r,e.encalg,{iv:e.enciv})}catch(t){throw new Error("encrypt error: "+e.plain+" "+r+" "+e.encalg+" "+e.enciv)}e.enc=n},generatePBES2ASN1Param:function(e){var t={seq:[{seq:[{oid:"pkcs5PBES2"},{seq:[{seq:[{oid:"pkcs5PBKDF2"},{seq:[{octstr:{hex:e.salt}},{int:{hex:inttohex(e.iter)}}]}]},{seq:[{oid:e.encalg},{octstr:{hex:e.enciv}}]}]}]},{octstr:{hex:e.enc}}]};return"hmacWithSHA1"!=e.prf&&t.seq[0].seq[1].seq[0].seq[1].seq.push({seq:[{oid:e.prf},{null:""}]}),t},parseHexOfEncryptedPKCS8:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={},o=r(e,0);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+o.length);i.ciphertext=n(e,o[1]);var s=r(e,o[0]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+s.length);if("2a864886f70d01050d"!=n(e,s[0]))throw new Error("this only supports pkcs5PBES2");var a=r(e,s[1]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+a.length);var c=r(e,a[1]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+c.length);if("2a864886f70d0307"!=n(e,c[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=n(e,c[1]);var l=r(e,a[0]);if(2!=l.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+l.length);if("2a864886f70d01050c"!=n(e,l[0]))throw new Error("this only supports pkcs5PBKDF2");var u=r(e,l[1]);if(u.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+u.length);i.pbkdf2Salt=n(e,u[0]);var d=n(e,u[1]);try{i.pbkdf2Iter=parseInt(d,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+d)}return i},getPBKDF2KeyHexFromParam:function(e,t){var r=CryptoJS.enc.Hex.parse(e.pbkdf2Salt),n=e.pbkdf2Iter,i=CryptoJS.PBKDF2(t,r,{keySize:6,iterations:n});return CryptoJS.enc.Hex.stringify(i)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(e,t){var r=pemtohex(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(r),i=KEYUTIL.getPBKDF2KeyHexFromParam(n,t),o={};o.ciphertext=CryptoJS.enc.Hex.parse(n.ciphertext);var s=CryptoJS.enc.Hex.parse(i),a=CryptoJS.enc.Hex.parse(n.encryptionSchemeIV),c=CryptoJS.TripleDES.decrypt(o,s,{iv:a});return CryptoJS.enc.Hex.stringify(c)},parsePBES2:function(e){var t=ASN1HEX.parse(e);if("pkcs5PBES2"!=aryval(t,"seq.0.seq.0.oid")||"pkcs5PBKDF2"!=aryval(t,"seq.0.seq.1.seq.0.seq.0.oid"))throw new Error("not pkcs5PBES2 and pkcs5PBKDF2 used");var r=aryval(t,"seq.0.seq.1.seq.0.seq.1.seq");if(null==r)throw new Error("PBKDF2 parameter not found");var n=aryval(r,"0.octstr.hex"),i=aryval(r,"1.int.hex"),o=aryval(r,"2.seq.0.oid","hmacWithSHA1"),s=-1;try{s=parseInt(i,16)}catch(e){throw new Error("iter not proper value")}var a=aryval(t,"seq.0.seq.1.seq.1.seq.0.oid"),c=aryval(t,"seq.0.seq.1.seq.1.seq.1.octstr.hex"),l=aryval(t,"seq.1.octstr.hex");if(null==a||null==c||null==l)throw new Error("encalg, enciv or enc is undefined");return{salt:n,iter:s,prf:o,encalg:a,enciv:c,enc:l}},getDKFromPBES2Param:function(e,t){var r={hmacWithSHA1:CryptoJS.algo.SHA1,hmacWithSHA224:CryptoJS.algo.SHA224,hmacWithSHA256:CryptoJS.algo.SHA256,hmacWithSHA384:CryptoJS.algo.SHA384,hmacWithSHA512:CryptoJS.algo.SHA512}[e.prf];if(null==r)throw new Error("unsupported prf");var n={"des-EDE3-CBC":6,"aes128-CBC":4,"aes256-CBC":8}[e.encalg];if(null==n)throw new Error("unsupported encalg");var i=CryptoJS.enc.Hex.parse(e.salt),o=e.iter;try{var s=CryptoJS.PBKDF2(t,i,{keySize:n,iterations:o,hasher:r});return CryptoJS.enc.Hex.stringify(s)}catch(r){throw new Error("PBKDF2 error: "+r+" "+JSON.stringify(e)+" "+t)}},getPlainHexFromEncryptedPKCS8PEM:function(e,t){if(-1==e.indexOf("BEGIN ENCRYPTED PRIVATE KEY"))throw new Error("not Encrypted PKCS#8 PEM string");var r,n=pemtohex(e);try{r=KEYUTIL.parsePBES2(n)}catch(e){throw new Error("malformed PBES2 format: "+e.message)}var i=KEYUTIL.getDKFromPBES2Param(r,t);return KJUR.crypto.Cipher.decrypt(r.enc,i,r.encalg,{iv:r.enciv})},getKeyFromEncryptedPKCS8PEM:function(e,t){var r=this.getPlainHexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(r)},parsePlainPrivatePKCS8Hex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={algparam:null};if("30"!=e.substr(0,2))throw new Error("malformed plain PKCS8 private key(code:001)");var o=r(e,0);if(o.length<3)throw new Error("malformed plain PKCS8 private key(code:002)");if("30"!=e.substr(o[1],2))throw new Error("malformed PKCS8 private key(code:003)");var s=r(e,o[1]);if(2!=s.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(s[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(i.algoid=n(e,s[0]),"06"==e.substr(s[1],2)&&(i.algparam=n(e,s[1])),"04"!=e.substr(o[2],2))throw new Error("malformed PKCS8 private key(code:006)");return i.keyidx=t.getVidx(e,o[2]),i},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=pemtohex(e,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(t)},getKeyFromPlainPrivatePKCS8Hex:function(e){var t,r=this.parsePlainPrivatePKCS8Hex(e);if("2a864886f70d010101"==r.algoid)t=new RSAKey;else if("2a8648ce380401"==r.algoid)t=new KJUR.crypto.DSA;else{if("2a8648ce3d0201"!=r.algoid)throw new Error("unsupported private key algorithm");t=new KJUR.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,r=ASN1HEX.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===r)t=new RSAKey;else if("2a8648ce380401"===r)t=new KJUR.crypto.DSA;else{if("2a8648ce3d0201"!==r)throw new Error("unsupported PKCS#8 public key hex");t=new KJUR.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var o=r(e,0);if(2!=o.length)throw new Error("malformed RSA key(code:002)");if("02"!=e.substr(o[0],2))throw new Error("malformed RSA key(code:003)");if(i.n=n(e,o[0]),"02"!=e.substr(o[1],2))throw new Error("malformed RSA key(code:004)");return i.e=n(e,o[1]),i},parsePublicPKCS8Hex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={algparam:null},o=r(e,0);if(2!=o.length)throw new Error("outer DERSequence shall have 2 elements: "+o.length);var s=o[0];if("30"!=e.substr(s,2))throw new Error("malformed PKCS8 public key(code:001)");var a=r(e,s);if(2!=a.length)throw new Error("malformed PKCS8 public key(code:002)");if("06"!=e.substr(a[0],2))throw new Error("malformed PKCS8 public key(code:003)");if(i.algoid=n(e,a[0]),"06"==e.substr(a[1],2)?i.algparam=n(e,a[1]):"30"==e.substr(a[1],2)&&(i.algparam={},i.algparam.p=t.getVbyList(e,a[1],[0],"02"),i.algparam.q=t.getVbyList(e,a[1],[1],"02"),i.algparam.g=t.getVbyList(e,a[1],[2],"02")),"03"!=e.substr(o[1],2))throw new Error("malformed PKCS8 public key(code:004)");return i.key=n(e,o[1]).substr(2),i}}}();function _zeroPaddingOfSignature(e,t){for(var r="",n=t/4-e.length,i=0;i>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function _rsasign_getAlgNameAndHashFromHexDisgestInfo(e){for(var t in KJUR.crypto.Util.DIGESTINFOHEAD){var r=KJUR.crypto.Util.DIGESTINFOHEAD[t],n=r.length;if(e.substring(0,n)==r)return[t,e.substring(n)]}return[]}function X509(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV;t.dump;var i,o=t.parse,s=t.getTLV,a=t.getVbyList,c=t.getVbyListEx,l=t.getTLVbyList,u=t.getTLVbyListEx,d=t.getIdxbyList,h=t.getIdxbyListEx,p=t.getVidx,g=t.getInt,m=t.oidname,f=t.hextooidstr,y=pemtohex,$=Error;try{i=KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV}catch(e){}this.HEX2STAG={"0c":"utf8",13:"prn",16:"ia5","1a":"vis","1e":"bmp"},this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){if(null===this.hex||0!==this.version)return this.version;var e=l(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=l(e,0,[0]),r=g(t,0);if(r<0||20?t:void 0}catch(e){return}},this._asn1ToNoticeRef=function(e){try{for(var t={},r=aryval(e,"seq"),n=0;n0?t:void 0}catch(e){return}},this._asn1ToNoticeNum=function(e){try{for(var t=aryval(e,"seq"),r=[],n=0;n1){var a=s(e,o[1]),c=this.getGeneralName(a);null!=c.uri&&(i.uri=c.uri)}if(o.length>2){var l=s(e,o[2]);"0101ff"==l&&(i.reqauth=!0),"010100"==l&&(i.reqauth=!1)}return i},this.getExtSubjectDirectoryAttributes=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectDirectoryAttributes");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var n={extname:"subjectDirectoryAttributes"};t&&(n.critical=!0);try{for(var i=o(e),a=[],c=0;c0&&(t.ext=this.getExtParamArray()),t.sighex=this.getSignatureValueHex(),1==e.tbshex&&(t.tbshex=l(this.hex,0,[0])),1==e.nodnarray&&(delete t.issuer.array,delete t.subject.array),t},this.getExtParamArray=function(e){null==e&&(-1!=h(this.hex,0,[0,"[3]"])&&(e=u(this.hex,0,[0,"[3]",0],"30")));for(var t=[],n=r(e,0),i=0;i2&&"04"===m.substr(g[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(T=new s).readPKCS5PrvKeyHex(m)}return T}if("pkcs8prv"===r)return T=u.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===r)return u._getKeyFromPublicPKCS8Hex(e);if("x509pub"===r)return X509.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return X509.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var y=pemtohex(e,"PUBLIC KEY");return u._getKeyFromPublicPKCS8Hex(y)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var $=l(e,"RSA PRIVATE KEY");return u.getKey($,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var b=i(x=l(e,"DSA PRIVATE KEY"),0,[1],"02"),v=i(x,0,[2],"02"),w=i(x,0,[3],"02"),S=i(x,0,[4],"02"),_=i(x,0,[5],"02");return(T=new a).setPrivate(new BigInteger(b,16),new BigInteger(v,16),new BigInteger(w,16),new BigInteger(S,16),new BigInteger(_,16)),T}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){$=l(e,"EC PRIVATE KEY");return u.getKey($,null,"pkcs5prv")}if(-1!=e.indexOf("-END PRIVATE KEY-"))return u.getKeyFromPlainPrivatePKCS8PEM(e);if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var E=u.getDecryptedKeyHex(e,t),C=new RSAKey;return C.readPKCS5PrvKeyHex(E),C}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var I,T=i(x=u.getDecryptedKeyHex(e,t),0,[1],"04"),A=i(x,0,[2,0],"06"),D=i(x,0,[3,0],"03").substr(2);if(void 0===KJUR.crypto.OID.oidhex2name[A])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+A);return(I=new s({curve:KJUR.crypto.OID.oidhex2name[A]})).setPublicKeyHex(D),I.setPrivateKeyHex(T),I.isPublic=!1,I}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var x;b=i(x=u.getDecryptedKeyHex(e,t),0,[1],"02"),v=i(x,0,[2],"02"),w=i(x,0,[3],"02"),S=i(x,0,[4],"02"),_=i(x,0,[5],"02");return(T=new a).setPrivate(new BigInteger(b,16),new BigInteger(v,16),new BigInteger(w,16),new BigInteger(S,16),new BigInteger(_,16)),T}if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return u.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},KEYUTIL.generateKeypair=function(e,t){if("RSA"==e){var r=t;(s=new RSAKey).generate(r,"10001"),s.isPrivate=!0,s.isPublic=!0;var n=new RSAKey,i=s.n.toString(16),o=s.e.toString(16);return n.setPublic(i,o),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}if("EC"==e){var s,a,c=t,l=new KJUR.crypto.ECDSA({curve:c}).generateKeyPairHex();return(s=new KJUR.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),s.setPrivateKeyHex(l.ecprvhex),s.isPrivate=!0,s.isPublic=!1,(n=new KJUR.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}throw new Error("unknown algorithm: "+e)},KEYUTIL.getPEM=function(e,t,r,n,i,o){var s=KJUR,a=s.asn1,c=a.DERObjectIdentifier,l=a.DERInteger,u=a.ASN1Util.newObject,d=a.x509.SubjectPublicKeyInfo,h=s.crypto,p=h.DSA,g=h.ECDSA,m=RSAKey;function f(e){return u({seq:[{int:0},{int:{bigint:e.n}},{int:e.e},{int:{bigint:e.d}},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.dmp1}},{int:{bigint:e.dmq1}},{int:{bigint:e.coeff}}]})}function y(e){return u({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a0",!0,{oid:{name:e.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]})}function $(e){return u({seq:[{int:0},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}},{int:{bigint:e.y}},{int:{bigint:e.x}}]})}if((void 0!==m&&e instanceof m||void 0!==p&&e instanceof p||void 0!==g&&e instanceof g)&&1==e.isPublic&&(void 0===t||"PKCS8PUB"==t))return hextopem(S=new d(e).tohex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==m&&e instanceof m&&(void 0===r||null==r)&&1==e.isPrivate)return hextopem(S=f(e).tohex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===r||null==r)&&1==e.isPrivate){var b=new c({name:e.curveName}).tohex(),v=y(e).tohex(),w="";return w+=hextopem(b,"EC PARAMETERS"),w+=hextopem(v,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===r||null==r)&&1==e.isPrivate)return hextopem(S=$(e).tohex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==m&&e instanceof m&&void 0!==r&&null!=r&&1==e.isPrivate){var S=f(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",S,r,n,o)}if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==r&&null!=r&&1==e.isPrivate){S=y(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",S,r,n,o)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==r&&null!=r&&1==e.isPrivate){S=$(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",S,r,n,o)}var _=function(e,t){if("string"==typeof t)return KEYUTIL.getEncryptedPKCS8PEM(e,t);if("object"==typeof t&&null!=aryval(t,"passcode")){var r=JSON.parse(JSON.stringify(t)),n=r.passcode;return delete r.passcode,KEYUTIL.getEncryptedPKCS8PEM(e,n,r)}};if("PKCS8PRV"==t&&null!=m&&e instanceof m&&1==e.isPrivate){var E=f(e).tohex();S=u({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:E}}]}).tohex();return void 0===r||null==r?hextopem(S,"PRIVATE KEY"):_(S,r)}if("PKCS8PRV"==t&&void 0!==g&&e instanceof g&&1==e.isPrivate){var C={seq:[{int:1},{octstr:{hex:e.prvKeyHex}}]};"string"==typeof e.pubKeyHex&&C.seq.push({tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]});E=new u(C).tohex(),S=u({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:E}}]}).tohex();return void 0===r||null==r?hextopem(S,"PRIVATE KEY"):_(S,r)}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate){E=new l({bigint:e.x}).tohex(),S=u({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:E}}]}).tohex();return void 0===r||null==r?hextopem(S,"PRIVATE KEY"):_(S,r)}throw new Error("unsupported object nor format")},KEYUTIL.getKeyFromCSRPEM=function(e){var t=pemtohex(e,"CERTIFICATE REQUEST");return KEYUTIL.getKeyFromCSRHex(t)},KEYUTIL.getKeyFromCSRHex=function(e){var t=KEYUTIL.parseCSRHex(e);return KEYUTIL.getKey(t.p8pubkeyhex,null,"pkcs8pub")},KEYUTIL.parseCSRHex=function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getTLV,i={},o=e;if("30"!=o.substr(0,2))throw new Error("malformed CSR(code:001)");var s=r(o,0);if(s.length<1)throw new Error("malformed CSR(code:002)");if("30"!=o.substr(s[0],2))throw new Error("malformed CSR(code:003)");var a=r(o,s[0]);if(a.length<3)throw new Error("malformed CSR(code:004)");return i.p8pubkeyhex=n(o,a[2]),i},KEYUTIL.getKeyID=function(e){var t=KEYUTIL,r=ASN1HEX;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=pemtohex(t.getPEM(e)),i=r.getIdxbyList(n,0,[1]),o=r.getV(n,i).substring(2);return KJUR.crypto.Util.hashHex(o,"sha1")},KEYUTIL.getJWK=function(e,t,r,n,i){var o,s,a={},c=KJUR.crypto.Util.hashHex;if("string"==typeof e)o=KEYUTIL.getKey(e),-1!=e.indexOf("CERTIFICATE")&&(s=pemtohex(e));else{if("object"!=typeof e)throw new Error("unsupported keyinfo type");e instanceof X509?(o=e.getPublicKey(),s=e.hex):o=e}if(o instanceof RSAKey&&o.isPrivate)a.kty="RSA",a.n=hextob64u(o.n.toString(16)),a.e=hextob64u(o.e.toString(16)),a.d=hextob64u(o.d.toString(16)),a.p=hextob64u(o.p.toString(16)),a.q=hextob64u(o.q.toString(16)),a.dp=hextob64u(o.dmp1.toString(16)),a.dq=hextob64u(o.dmq1.toString(16)),a.qi=hextob64u(o.coeff.toString(16));else if(o instanceof RSAKey&&o.isPublic)a.kty="RSA",a.n=hextob64u(o.n.toString(16)),a.e=hextob64u(o.e.toString(16));else if(o instanceof KJUR.crypto.ECDSA&&o.isPrivate){if("P-256"!==(u=o.getShortNISTPCurveName())&&"P-384"!==u&&"P-521"!==u)throw new Error("unsupported curve name for JWT: "+u);var l=o.getPublicKeyXYHex();a.kty="EC",a.crv=u,a.x=hextob64u(l.x),a.y=hextob64u(l.y),a.d=hextob64u(o.prvKeyHex)}else if(o instanceof KJUR.crypto.ECDSA&&o.isPublic){var u;if("P-256"!==(u=o.getShortNISTPCurveName())&&"P-384"!==u&&"P-521"!==u)throw new Error("unsupported curve name for JWT: "+u);l=o.getPublicKeyXYHex();a.kty="EC",a.crv=u,a.x=hextob64u(l.x),a.y=hextob64u(l.y)}if(null==a.kty)throw new Error("unsupported keyinfo");return o.isPrivate||1==t||(a.kid=KJUR.jws.JWS.getJWKthumbprint(a)),null!=s&&1!=r&&(a.x5c=[hex2b64(s)]),null!=s&&1!=n&&(a.x5t=b64tob64u(hex2b64(c(s,"sha1")))),null!=s&&1!=i&&(a["x5t#S256"]=b64tob64u(hex2b64(c(s,"sha256")))),a},KEYUTIL.getJWKFromKey=function(e){return KEYUTIL.getJWK(e,!0,!0,!0,!0)},RSAKey.getPosArrayOfChildrenFromHex=function(e){return ASN1HEX.getChildIdx(e,0)},RSAKey.getHexValueArrayOfChildrenFromHex=function(e){var t,r=ASN1HEX.getV,n=r(e,(t=RSAKey.getPosArrayOfChildrenFromHex(e))[0]),i=r(e,t[1]),o=r(e,t[2]),s=r(e,t[3]),a=r(e,t[4]),c=r(e,t[5]),l=r(e,t[6]),u=r(e,t[7]),d=r(e,t[8]);return(t=new Array).push(n,i,o,s,a,c,l,u,d),t},RSAKey.prototype.readPrivateKeyFromPEMString=function(e){var t=pemtohex(e),r=RSAKey.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8])},RSAKey.prototype.readPKCS5PrvKeyHex=function(e){var t=RSAKey.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},RSAKey.prototype.readPKCS8PrvKeyHex=function(e){var t,r,n,i,o,s,a,c,l=ASN1HEX,u=l.getVbyListEx;if(!1===l.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=u(e,0,[2,0,1],"02"),r=u(e,0,[2,0,2],"02"),n=u(e,0,[2,0,3],"02"),i=u(e,0,[2,0,4],"02"),o=u(e,0,[2,0,5],"02"),s=u(e,0,[2,0,6],"02"),a=u(e,0,[2,0,7],"02"),c=u(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,r,n,i,o,s,a,c)},RSAKey.prototype.readPKCS5PubKeyHex=function(e){var t=ASN1HEX,r=t.getV;if(!1===t.isASN1HEX(e))throw new Error("keyHex is not ASN.1 hex string");var n=t.getChildIdx(e,0);if(2!==n.length||"02"!==e.substr(n[0],2)||"02"!==e.substr(n[1],2))throw new Error("wrong hex for PKCS#5 public key");var i=r(e,n[0]),o=r(e,n[1]);this.setPublic(i,o)},RSAKey.prototype.readPKCS8PubKeyHex=function(e){var t=ASN1HEX;if(!1===t.isASN1HEX(e))throw new Error("not ASN.1 hex string");if("06092a864886f70d010101"!==t.getTLVbyListEx(e,0,[0,0]))throw new Error("not PKCS8 RSA public key");var r=t.getTLVbyListEx(e,0,[1,0]);this.readPKCS5PubKeyHex(r)},RSAKey.prototype.readCertPubKeyHex=function(e,t){var r,n;(r=new X509).readCertHex(e),n=r.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)},RSAKey.prototype.sign=function(e,t){var r=function(e){return KJUR.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(r,t)},RSAKey.prototype.signWithMessageHash=function(e,t){var r=parseBigInt(KJUR.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return _zeroPaddingOfSignature(this.doPrivate(r).toString(16),this.n.bitLength())},RSAKey.prototype.signPSS=function(e,t,r){var n=function(e){return KJUR.crypto.Util.hashHex(e,t)}(rstrtohex(e));return void 0===r&&(r=-1),this.signWithMessageHashPSS(n,t,r)},RSAKey.prototype.signWithMessageHashPSS=function(e,t,r){var n,i=hextorstr(e),o=i.length,s=this.n.bitLength()-1,a=Math.ceil(s/8),c=function(e){return KJUR.crypto.Util.hashHex(e,t)};if(-1===r||void 0===r)r=o;else if(-2===r)r=a-o-2;else if(r<-2)throw new Error("invalid salt length");if(a0&&(l=new Array(r),(new SecureRandom).nextBytes(l),l=String.fromCharCode.apply(String,l));var u=hextorstr(c(rstrtohex("\0\0\0\0\0\0\0\0"+i+l))),d=[];for(n=0;n>8*a-s&255;for(g[0]&=~m,n=0;nn)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var o=_rsasign_getAlgNameAndHashFromHexDisgestInfo(i.replace(/^1f+00/,""));if(0==o.length)return!1;var s=o[0],a=o[1],c=function(e){return KJUR.crypto.Util.hashString(e,s)}(e);return a==c},RSAKey.prototype.verifyWithMessageHash=function(e,t){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var r=parseBigInt(t,16);if(r.bitLength()>this.n.bitLength())return 0;var n=_rsasign_getAlgNameAndHashFromHexDisgestInfo(this.doPublic(r).toString(16).replace(/^1f+00/,""));return 0!=n.length&&(n[0],n[1]==e)},RSAKey.prototype.verifyPSS=function(e,t,r,n){var i=function(e){return KJUR.crypto.Util.hashHex(e,r)}(rstrtohex(e));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(i,t,r,n)},RSAKey.prototype.verifyWithMessageHashPSS=function(e,t,r,n){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var i,o=new BigInteger(t,16),s=function(e){return KJUR.crypto.Util.hashHex(e,r)},a=hextorstr(e),c=a.length,l=this.n.bitLength()-1,u=Math.ceil(l/8);if(-1===n||void 0===n)n=c;else if(-2===n)n=u-c-2;else if(n<-2)throw new Error("invalid salt length");if(u>8*u-l&255;if(0!==(h.charCodeAt(0)&g))throw new Error("bits beyond keysize not zero");var m=pss_mgf1_str(p,h.length,s),f=[];for(i=0;i0)&&-1==(":"+r.join(":")+":").indexOf(":"+m+":"))throw"algorithm '"+m+"' not accepted in the list";if("none"!=m&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=KEYUTIL.getKey(t)),!("RS"!=f&&"PS"!=f||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==f&&!(t instanceof c))throw"key shall be a ECDSA obj for ES* algs";var y=null;if(void 0===o.jwsalg2sigalg[g.alg])throw"unsupported alg name: "+m;if("none"==(y=o.jwsalg2sigalg[m]))throw"not supported";if("Hmac"==y.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var $=new l({alg:y,pass:t});return $.updateString(h),p==$.doFinal()}if(-1!=y.indexOf("withECDSA")){var b,v=null;try{v=c.concatSigToASN1Sig(p)}catch(e){return!1}return(b=new u({alg:y})).init(t),b.updateString(h),b.verify(v)}return(b=new u({alg:y})).init(t),b.updateString(h),b.verify(p)},KJUR.jws.JWS.parse=function(e){var t,r,n,i=e.split("."),o={};if(2!=i.length&&3!=i.length)throw"malformed sJWS: wrong number of '.' splitted elements";return t=i[0],r=i[1],3==i.length&&(n=i[2]),o.headerObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(t)),o.payloadObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(r)),o.headerPP=JSON.stringify(o.headerObj,null," "),null==o.payloadObj?o.payloadPP=b64utoutf8(r):o.payloadPP=JSON.stringify(o.payloadObj,null," "),void 0!==n&&(o.sigHex=b64utohex(n)),o},KJUR.jws.JWS.verifyJWT=function(e,t,r){var n=KJUR.jws,i=n.JWS,o=i.readSafeJSONString,s=i.inArray,a=i.includedArray;if(!isBase64URLDot(e))return!1;var c=e.split(".");if(3!=c.length)return!1;var l=c[0],u=c[1];b64utohex(c[2]);var d=o(b64utoutf8(l)),h=o(b64utoutf8(u));if(void 0===d.alg)return!1;if(void 0===r.alg)throw"acceptField.alg shall be specified";if(!s(d.alg,r.alg))return!1;if(void 0!==h.iss&&"object"==typeof r.iss&&!s(h.iss,r.iss))return!1;if(void 0!==h.sub&&"object"==typeof r.sub&&!s(h.sub,r.sub))return!1;if(void 0!==h.aud&&"object"==typeof r.aud)if("string"==typeof h.aud){if(!s(h.aud,r.aud))return!1}else if("object"==typeof h.aud&&!a(h.aud,r.aud))return!1;var p=n.IntDate.getNow();return void 0!==r.verifyAt&&"number"==typeof r.verifyAt&&(p=r.verifyAt),void 0!==r.gracePeriod&&"number"==typeof r.gracePeriod||(r.gracePeriod=0),!(void 0!==h.exp&&"number"==typeof h.exp&&h.exp+r.gracePeriodi&&this.aHeader.pop(),this.aSignature.length>i&&this.aSignature.pop(),"addSignature failed: "+e}},this.verifyAll=function(e){if(this.aHeader.length!==e.length||this.aSignature.length!==e.length)return!1;for(var t=0;t0))throw"malformed header";if(this.aHeader=e.headers,"string"!=typeof e.payload)throw"malformed signatures";if(this.sPayload=e.payload,!(e.signatures.length>0))throw"malformed signatures";this.aSignature=e.signatures}catch(e){throw"malformed JWS-JS JSON object: "+e}},this.getJSON=function(){return{headers:this.aHeader,payload:this.sPayload,signatures:this.aSignature}},this.isEmpty=function(){return 0==this.aHeader.length?1:0}};var RSAKey_1=RSAKey;KJUR.crypto.ECDSA,KJUR.crypto.DSA,KJUR.crypto.Signature,KJUR.crypto.MessageDigest,KJUR.crypto.Mac;var KEYUTIL_1=KEYUTIL,b64utoutf8_1=b64utoutf8,KJUR_1=KJUR;async function g$3(e,t,r){let n=await(r?.fetch??globalThis.fetch??fetch)(e.href,{signal:AbortSignal.timeout(t),headers:r?.headers});if(200!==n.status)throw new Error(`Failed to fetch ${e.href}: ${n.statusText}`);try{return await n.json()}catch{throw new Error("Failed to parse response")}}KJUR.crypto,KJUR.asn1,KJUR.jws,KJUR.lang;var x$1="/.well-known/openid-configuration",v$1="/.well-known/oauth-authorization-server";function W$1(e){if(!e.issuer)throw new Error("'issuer' not found is authorization server metadata")}async function $$1(e){let t=e.URL??globalThis.URL??URL,r=new t(e.issuerBaseUri);if(r.pathname.includes("/.well-known/")){let t=await g$3(r,e.timeout,e);return W$1(t),t}let n=[];r.pathname.endsWith("/")?n.push(`${r.pathname}${x$1.substring(1)}`):n.push(`${r.pathname}${x$1}`),r.pathname.endsWith("/")?n.push(`${v$1}`):n.push(`${v$1}${r.pathname}`);for(let i of n)try{let n=new t(i,r),o=await g$3(n,e.timeout,e);return W$1(o),o}catch{}throw new Error("Failed to fetch authorization server metadata")}var V$1=e=>{let t,r=0;return()=>{let n=Date.now();return(!t||n>r+e.cacheMaxAge)&&(r=n,t=$$1(e).catch(e=>{throw t=void 0,e})),t}},c=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}},h$1=class extends c{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},y$1=class extends c{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},l=class extends c{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},w$1=class extends c{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="No matching key found in the JSON Web Key Set",t){super(e,t)}},m=class extends c{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}};function q$1(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new h$1('Unsupported "alg" value for a JSON Web Key Set')}}function z$2(e){return!!e&&"object"==typeof e&&Array.isArray(e.keys)}var R$1=class{#e;#t=new WeakMap;constructor(e){if(!z$2(e))throw new l("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:r,kid:n}={...e,...t?.header},i=q$1(r),o=this.#e.keys.filter(e=>{let t=e.kty===i;return t&&"string"==typeof n&&(t=e.kid===n),t&&"string"==typeof e.alg&&(t=e.alg===r),t&&"string"==typeof e.use&&(t="sig"===e.use),t}),{0:s,length:a}=o;if(0===a)throw new w$1;if(1!==a)throw new Error("Multiple matching keys found");return B$1(this.#t,s,r)}};async function B$1(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){let e=KEYUTIL_1.getKey(t);if(!(e instanceof RSAKey_1))throw new Error("RSA key expected!");n[r]=e}return n[r]}function I$1(e){let t=new R$1(e),r=async(e,r)=>await t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}async function Q$1(e,t,r,n){let i=await(n?.fetch??globalThis.fetch??fetch)(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(e=>{throw"TimeoutError"===e.name?new m:e});if(200!==i.status)throw new c(`Expected 200 OK from JSON Web Key Set response, got ${i.status} ${i.statusText}`);try{return await i.json()}catch(e){throw new c(`Failed to parse the JSON Web Key Set response as JSON: ${e instanceof Error?e.message:String(e)}`)}}var S$1=class{#e;#t;#r;#n;#i;#o;#s;#a;constructor(e,t){this.#e=t.fetch,this.#t=new(t.URL??globalThis.URL??URL)(e.href),this.#s=new(t.Headers??globalThis.Headers??Headers)(t.headers),this.#r="number"==typeof t.timeout?t.timeout:5e3,this.#n="number"==typeof t.cacheMaxAge?t.cacheMaxAge:6e5}fresh(){return"number"==typeof this.#i&&Date.now(){this.#a=I$1(e),this.#i=Date.now(),this.#o=void 0}).catch(e=>{throw this.#o=void 0,e}),await this.#o}};function U$1(e,t){let r=new S$1(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(r.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}var T$1=e=>{let t,r,n=e.URL??URL;return i=>((void 0===t||r!==i)&&(r=i,t=U$1(new n(i),e)),t)};function K$1(e){return"string"==typeof e?[e]:Array.isArray(e)?e:void 0}function H(e,t,r){let{headerObj:n,payloadObj:i}=KJUR_1.jws.JWS.parse(e),o={alg:r?.algorithms??[n.alg],aud:K$1(r?.audience),iss:K$1(r?.issuer),sub:K$1(r?.subject),gracePeriod:r?.clockTolerance};if("function"==typeof t)return t(n).then(t=>KJUR_1.jws.JWS.verifyJWT(e,t,o)).then(e=>{if(!e)throw new y$1;return{payload:i,protectedHeader:n}});if(KJUR_1.jws.JWS.verifyJWT(e,t,o))return{payload:i,protectedHeader:n};throw new y$1}var A$1=(e,t,r)=>{for(let[n,i]of Object.entries(r))if(!1!==i){let r="alg"===n||"typ"===n?t[n]:e[n];if(!("string"==typeof i&&r===i||"function"==typeof i&&i(r,e,t)))throw new Error(`Unexpected '${n}' value: ${JSON.stringify(r)}`)}},M$1=(e,t,r,n,i,o,s)=>({alg:e=>"string"==typeof e&&"none"!==e.toLowerCase()&&(void 0===o||o.includes(e))&&(void 0===s||e===s),typ:e=>!i||"string"==typeof e&&"at+jwt"===e.toLowerCase().replace(/^application\//,""),iss:t=>"string"==typeof t&&t===e,aud:e=>(t="string"==typeof t?[t]:t,"string"==typeof e?t.includes(e):!!Array.isArray(e)&&t.some(Set.prototype.has.bind(new Set(e)))),exp:e=>{let t=Math.floor(Date.now()/1e3);return"number"==typeof e&&e>=t-r},iat:e=>{if(void 0===n)return void 0===e&&!i||"number"==typeof e;let t=Math.floor(Date.now()/1e3);return"number"==typeof e&&et-r-n},sub:e=>void 0===e&&!i||"string"==typeof e,jti:e=>void 0===e&&!i||"string"==typeof e}),J$1=class extends Error{},X$1=({issuerBaseUri:e="",jwksUri:t="",issuer:r="",audience:n="",tokenSigningAlg:i,timeout:o=5e3,cacheMaxAge:s=6e5,clockTolerance:a=5,maxTokenAge:c,strict:l=!1,validators:u,fetch:d,URL:h})=>{let p,g;if(!(e||r&&t))throw new Error("Either 'issuerBaseUri' or both 'issuer' and 'jwksUri' must be provided");if(!n)throw new Error("An 'audience' is required to validate the 'aud' claim");let m=V$1({issuerBaseUri:e,timeout:o,cacheMaxAge:s,fetch:d,URL:h}),f=T$1({timeout:o,cacheMaxAge:s,fetch:d,URL:h});return async o=>{try{if(e){let{jwks_uri:e,issuer:n,id_token_signing_alg_values_supported:i}=await m();t=t||e,r=r||n,p=i}g??={...M$1(r,n,a,c,l,p,i),...u};let{payload:s,protectedHeader:d}=await H(o,f(t),{clockTolerance:a});return A$1(s,d,g),{payload:s,header:d,token:o}}catch(e){throw new J$1(`${e instanceof Error?e.message:String(e)}`)}}},Z$1=X$1,Nc=Object.defineProperty,ge=(e,t)=>()=>(e&&(t=e(e=0)),t),Ht=(e,t)=>{for(var r in t)Nc(e,r,{get:t[r],enumerable:!0})},jr={};function qc(e){return"string"==typeof e}function We(e,t){return qc(e)?e===t:"string"==typeof t&&e.test(t)}function Jr(e,t){for(let r of e)if(We(r,t))return!0;return!1}function Lt(e){if("string"==typeof e){let t=Ec.exec(e)?.groups;if(t??=$c.exec(e)?.groups,t?.pattern)return new RegExp(t.pattern,t.flags??"")}return e}Ht(jr,{regexify:()=>Lt,valueMatches:()=>We,valuesMatch:()=>Jr});var $c,Ec,Ft=ge(()=>{$c=/^#(\(\?(?[im]*)\))?(?.*)$/,Ec=/^\/(?(?:[^/\\]|\\.)+)\/(?[gimsuyd]*)$/});function R(e){return v$3(e)}var L=ge(()=>{});function Zi(e,t){return t.reduce((t,r)=>r===e?t:t.concat(r),[])}function nn(e,t){return e[t]?e:produce(e,e=>{e[t]={}})}function $e(e){return e instanceof Set?Array.from(e).map($e):e instanceof Array?e.map($e):e instanceof Map?$e(Object.fromEntries(e)):e instanceof Object?Object.keys(e).reduce((t,r)=>(t[r]=$e(e[r]),t),{}):e}function dd(e){let t=new Map;return function(r,n){let i=t.get(this)+(Array.isArray(this)?`[${r}]`:`.${r}`);return n===Object(n)&&t.set(n,i),n instanceof RegExp&&(n=`#${n.source}`),e.call(this,r,n,i.replace(/undefined\.\.?/,""))}}function rt(...e){return dd((t,r,n)=>-1!==e.indexOf(n)?"******":r)}function nt(e){return JSON.stringify(e,Object.keys(e).sort(ud))}function pe(e){return!!e}var ud,me=ge(()=>{ud=(e,t)=>e.localeCompare(t)});function am(e,t){for(let[r,n]of Object.entries(e)){if(!We(n,t[r]))return!1}return!0}function Ea(e,t){return Jr(e,t)}function Nt(e,t,r){let n=r?.publishers?.reduce((r,n)=>{if(am(n.identity,e)){let e=n.metrics.block??n.metrics.blacklist??[];if(e.length>0&&Ea(e,t))return!1;{let e=n.metrics.allow??n.metrics.whitelist??[];return r||Ea(e,t)}}return r},void 0);if(void 0!==n)return n;let i=r?.non_matched??"allow";return"allow"===i||"whitelist"===i}var ci=ge(()=>{Ft()});function bm(e){if(e&&Object.keys(e).length>0)return e}function Fa(e){return"object"==typeof e?{value:Object.entries(e).reduce((e,[t,r])=>(e[t]=Fa(r),e),{})}:{value:e}}function Rm(e){return{timestamp:e.timestamp??Date.now(),value:Fa(e.value)}}function xm(e,t){return Array.from(e).reduce((e,r)=>{let n=t(r),i=e.get(n)??[];return 0===i.length&&e.set(n,i),i.push(r),e},new Map)}function*Sr(e,t){La.enabledFor("trace")&&La.debug(`conflating ${JSON.stringify(t)}`);let r,n=xm(t,e=>nt(e.identity));for(let[,e]of n){for(let t of e)if(t.status){let{identity:e,status:n,metadata:i}=t;r&&(yield r),yield{identity:e,status:n,metrics:void 0,metadata:bm(i)},r=void 0}else{let{metric:e,identity:n,datapoint:i}=t,o=e?.name;r||(r={identity:n}),r.metrics=r.metrics??{},r.metrics[o]=r.metrics[o]??{definition:{...e},datapoints:[]},delete r.metrics[o].definition.name,r.metrics[o].datapoints.push(Rm(i))}r&&(yield r)}}var La,pi=ge(()=>{L(),me(),La=R("gateway.metrics.common")});async function wm(e,t,r){return Object.entries(t??{}).forEach(([t,r])=>e.searchParams.append(t,r)),new Worker(e,r)}function Wa({url:e,parameters:t,options:r}){return wm(e,t,r)}var Ja=ge(()=>{});async function Im(e,t){try{let e=await import(t);if("function"==typeof e)return await e();if("function"==typeof e.default)return await e.default()}catch(t){e.error("failed to load preload",t)}}async function Tm(e,t,r){e.debug(`loading publisher from ${t}`);let n=await import(t);return"object"==typeof n.default&&(n=n.default),await n.create(r,e.child(`publisher.${n.name??t}`))}var vr,ja$1=ge(()=>{vr=class{#e;#t;#o;constructor(e){this.#e=e}async#r(e){let t,{publishFn:r,cfg:n}=e;if(n?.preload){let e=await Im(this.#e,n.preload);if("object"==typeof e)for(let t in e)n[t]=e[t]}t="function"==typeof r?r:await Tm(this.#e,r,n);let i=await t("start");this.#t=t,this.#o=i}async#s(){let e=await(this.#t?.("stop"));"function"==typeof e&&await e(this.#o)}async#i(e){if(!this.#t)throw new Error("worker not started");await this.#t(e)}async execute(e,t){switch(e){case"start":await this.#r(t);break;case"stop":await this.#s();break;case"update":await this.#i(t)}}}});function mi(e,t,r){let n={identity:e,status:{...t,"updated-at":t.updated,"expires-at":t.expires}};return r&&(n.metadata=r),n}async function Ir(e,t,r){Y.info(`creating publisher with configuration\n${JSON.stringify(e,rt("authentication.password"))}`);try{let n=e?.worker;if(void 0===n)return await Mm(r,e??{},t);{let i=e?Object.fromEntries(Object.entries(e).filter(([e])=>"worker"!==e)):{};return await Pm(r,i,t,n)}}catch(e){throw Y.error("Failed to create basic publisher",e),e}}async function Mm(e,t,r){let n=new fi$1(t),i=e=>{for(let t of r([e]))n.next(t)};return await n.start(e),i.close=async()=>{await n.stop()},i.on=e=>{n.on(e)},i}async function Pm(e,t,r,n){let i=new gi(await Wa(n),t);await i.start(e);let o=e=>{for(let t of r([e]))i.next(t)};return o.close=async()=>{await i.stop()},o.on=e=>{i.on(e)},o}function Tr(e,t){return new yi(e,t)}var Y,li,yi,wr,fi$1,gi,hi=ge(()=>{Ja(),me(),ci(),ja$1(),Y=v$3("gateway.metrics.publisher"),li=class{constructor(e,t,r,n,i){this.publisher=e,this.filters=t,this.repoId=r,this.heartbeatInterval=n,this.metadata=i}running=!0;latestStatus={initial:!0,stopped:!1,status:{state:0,updated:Date.now(),description:"Running"}};heartbeatCleanup;metrics=new Map;start(){Y.info(`starting repository for ${JSON.stringify(this.repoId)} with heartbeat interval ${this.heartbeatInterval}ms`);let e=Date.now();if(this.latestStatus.stopped&&(this.latestStatus.status.state=0,this.latestStatus.status.description="Running",this.latestStatus.status.updated=e,this.latestStatus.initial=!0,this.latestStatus.stopped=!1),this.heartbeatInterval>=0){let t={...this.latestStatus.status,timestamp:e,expires:e+3*this.heartbeatInterval},r=mi(this.repoId,t,this.metadata);this.publisher(r)}this.running=!0,this.heartbeatInterval>0&&(this.heartbeatCleanup=setInterval(()=>{if(!this.running)return;let e=Date.now(),t={...this.latestStatus.status,timestamp:e,expires:e+3*this.heartbeatInterval},r=mi(this.repoId,t,this.metadata);this.publisher(r)},this.heartbeatInterval))}stop(){Y.info(`stopping repository for ${JSON.stringify(this.repoId)}`),this.running=!1,this.heartbeatCleanup&&clearInterval(this.heartbeatCleanup);let e=Date.now();this.latestStatus.stopped=!0,this.status({state:-1,timestamp:e,updated:e,expires:e,description:"Repository Stopped"})}add(e){for(let t of e){let e=t.name;this.metrics.has(e)||void 0!==this.filters&&!Nt(this.repoId,e,this.filters)||this.metrics.set(e,t)}}publish(e){if(this.running&&e.length>0)for(let t of e){let e=this.metrics.get(t.name);if(e){let r={identity:this.repoId,metric:e,datapoint:{...t}};delete r.datapoint.name,this.publisher(r)}}}status(e){let t={...this.latestStatus};Object.assign(t.status,e),t.timestamp=e.timestamp,t.expires=e.expires;let r=t.status.state!==this.latestStatus.status.state;if((this.latestStatus.initial||r)&&(t.status.updated=e.timestamp),t.initial=!1,Object.assign(this.latestStatus,t),this.running||t.stopped){let t=mi(this.repoId,e,this.metadata);this.publisher(t)}}},yi=class{constructor(e,t){this.config=e,this.publisher=t}repository(e,t){let r=t?.metadata,n=this.config?.heartbeats??0;return new li(this.publisher,this.config?.filters,e,n,r)}async shutdown(){await this.publisher.close()}on(e){this.publisher.on(e)}},wr=class{#e;#t;#o;#r;#s;#i;constructor(e){let{buffer_size:t}=e;this.#e=e,this.#t=t??1e3,this.#o=new Map,this.#r=new Map,this.#s=[],this.#i=0}async start(e){try{await this.enqueue("start",{cfg:this.#e,publishFn:e})[1],Y.info(`publisher [${e}] started`)}catch(t){throw Y.error(`error starting publisher [${e}]: ${t}`),t}}next(e){let[t,r]=this.enqueue("update",e);r.catch(e=>{Y.warn(`update [${t}] error`,e)}).finally(()=>{this.#r.delete(t)})}async stop(e=!1,t=1e3){Y.info(`stopping publisher worker rejectProcessing: ${e}, timeout: ${t}, promises: ${this.#r.size}`);let r=e=>{this.#o.forEach(({resolver:t})=>{t.reject(new Error(`reject on stop: ${e}`))})};e&&r("now");let n=Promise.allSettled(this.#r),i=this.enqueue("stop",void 0)[1];await new Promise((e,i)=>{let o=setTimeout(()=>{r("timeout"),i(new Error("timeout"))},t);n.then(t=>{clearTimeout(o);for(let e of t)"rejected"===e.status&&Y.error(`Pending future failed with ${e.reason} on stop`);e()})}),await i,this.#r.size>0&&Y.error(`uncleared promises: ${this.#r.size}`),Y.info("publisher worker stopped")}enqueue(e,t){this.#o.size>=this.#t&&Y.warn(`processing queue is full. dropping cmd: ${JSON.stringify(e)}`);let r=++this.#i;return[r,new Promise((n,i)=>{this.#o.set(r,{resolver:{resolve:n,reject:i}}),this.processRequest(r,e,t)})]}processResult(e,t,r){let n=this.#o.get(e);if(n){let{resolver:i}=n;try{r?i.reject(r):i.resolve(t)}finally{this.#o.delete(e)}}else Y.error(`unknown message id: ${e}`)}emit(e){this.#s.forEach(t=>t(e))}on(e){this.#s.push(e)}},fi$1=class extends wr{#e;constructor(e){super(e),this.#e=new vr(Y)}processRequest(e,t,r){this.#e.execute(t,r).then(()=>{this.processResult(e,"ok")}).catch(t=>{this.processResult(e,"error",t instanceof Error?t:new Error(String(t)))})}},gi=class extends wr{worker;constructor(e,t){super(t),this.worker=e}processRequest(e,t,r){let n={id:e,cmd:t,arg:r};this.worker.postMessage(n)}async stop(e=!1,t=1e3){try{return await super.stop(e,t)}finally{this.worker.terminate()}}async start(e){await new Promise(e=>{this.worker.onerror=e=>{Y.error(`error from worker: ${e.message}`)},this.worker.onmessageerror=e=>{Y.error(`error receiving message: ${e.data}`)},this.worker.onmessage=t=>{if(t.data.ready)e();else if(t.data.id){let{id:e,result:r,error:n}=t.data;super.processResult(e,r,null==n?void 0:deserializeError(n))}else if(t.data.log){let{level:e,time:r,name:n,message:i,data:o}=t.data.log;E$2({level:e,time:new Date(r),name:n,message:i,data:o.map(e=>deserializeError(e))})}else t.data.event&&super.emit(t.data.event)}});try{await super.start(e),Y.info(`publisher worker [${e}] started`)}catch(t){throw Y.error(`error starting publisher worker [${e}]: ${t}`),this.worker.terminate(),t}}}}),za={};async function Va(e){let t=e?.conflation?.["max-datapoints-repo"]??50;return await Ir(e,e=>Sr(t,e),e?.publishFn??"@interopio/gateway/metrics/publisher/rest")}async function Dm(e){return Tr(e,await Va(e))}Ht(za,{restPublisher:()=>Va,restRepositoryFactory:()=>Dm});var Qa=ge(()=>{hi(),pi()}),Oc={};Ht(Oc,{Encoding:()=>Xe,Factory:()=>qi,Filtering:()=>jr,Logging:()=>my});var Xe={};Ht(Xe,{direct:()=>Wr,json:()=>Gr,transit:()=>Fr});var Ur=class{map;reverse=new Map;constructor(e){if(e)for(let[t,r]of e)this.reverse.set(r,t);else e=this.reverse;this.map=e}get(e){return this.map.get(e)}rev(e){return this.reverse.get(e)}};function $i(e,t){let r=e.indexOf("/");if(-1===r)return Ce$1.keyword(e);let n=e.substring(0,r),i=t?.get(n)??n;return Ce$1.keyword(i+e.substring(r))}function Ei(e,t){let r=e.name(),n=e.namespace();return null===n?r:(t.rev(n)??n)+"/"+r}function Hi(e,t,r,n=""){if(e instanceof Array)return e.map(e=>e);if(e instanceof Object){let i=Ce$1.map();for(let o in e){let s=r?.get(n),a=null===s?o:$i(o,t),c=e[o],l=`${n}/${o}`,u=r?.get(l);if(void 0===u||"string"!=typeof c||"*"!==u&&!u?.has(c)){null===s&&!r?.has(l)&&r?.set(l,null);let e=Hi(c,t,r,l);i.set(a,e)}else i.set(a,$i(c,t))}return i}return e}function Hr(e,t){if(Ce$1.isKeyword(e))return Ei(e,t);if(Ce$1.isMap(e)){let r={};for(let[n,i]of e){r[Ce$1.isKeyword(n)?Ei(n,t):n]=Hr(i,t)}return r}if(Ce$1.isList(e)||e instanceof Array){let r=[];for(let n of e)r.push(Hr(n,t));return r}return e}function Fr(e){let t=e?.verbose?"json-verbose":"json",r=new Ur(e?.namespaces);return{encode:n=>{let i=Hi(n,r,e?.keywordize);return Ce$1.writer(t).write(i)},decode:e=>{let n;try{n=Ce$1.reader(t).read(e)}catch(t){throw new Error(`"${e}" is not valid TRANSIT`,{cause:t})}return Hr(n,r)}}}function Gr(){return{encode:JSON.stringify,decode:JSON.parse}}function Ui(e){return e}function Lr(e){return e instanceof Array||Array.isArray(e)?e.map(Lr):e?.constructor===Object?Object.keys(e).reduce((t,r)=>(t[r]=Lr(e[r]),t),{}):void 0===e?null:e}function Wr(e){return{encode:Ui,decode:e?.cljs?Lr:Ui}}Ft(),L();var Se="global",se="context",Ne=`${Se}.errors.failure`;function x(e,t){return{receiver:e,body:t}}function G(e,t){return{...x({type:"cluster"},t),source:e}}function K(e,t,r){return{...x(t,r),source:e}}function Uc(e,t,r,n,i){let o={type:"error",request_id:t,reason_uri:n.uri,reason:n.message};return e&&(o.domain=e),r&&(o.peer_id=r),i&&(o.context=i),o}function h(e,t,r,n,i,o){return x(t,Uc(e,r,n,i,o))}function Hc(e,t,r){return{type:"success",request_id:t,domain:e,peer_id:r}}function I(e,t,r,n){return x(t,Hc(e,r,n))}function T(e){let t=e.type;return t&&"local"===t}function W(e){return!T(e)}function Lc(e,t,r,n){return{domain:e,type:"token",request_id:t,peer_id:r,token:n}}function Gi(e,t,r,n,i){return x(t,Lc(e,r,n,i))}function Fc(e,t,r,n,i){return{domain:e,type:"peer-added",peer_id:t,new_peer_id:r,identity:n,meta:i}}function qe(e,t,r,n,i,o){return x(t,Fc(e,r,n,i,o))}function Gc(e,t,r,n){return{domain:e,type:"peer-removed",peer_id:t,removed_id:r,reason_uri:n.uri,reason:n.message}}function Je(e,t,r,n,i){return x(t,Gc(e,r,n,i))}L();var ve=class extends Error{data;cause;constructor(e,t,r){super(e),this.name="ExceptionInfo",this.data=t,this.cause=r}};function V(e,t,r){return new ve(e,t,r)}function je(e){if(e instanceof ve)return e.data}function Be(e){if(e instanceof Error)return e.message}function S(e,t){return{uri:e,message:t}}function J(e,t){let r=je(e);return{uri:r?.uri??t,message:r?.message??Be(e)??""}}function k(e,t){throw new ve(t,{uri:e,message:t})}function Q(e){return{uri:e.reason_uri,message:e.reason}}var M=class e extends xn$1{static OR=1;static AND=2;static EQ=3;static NEQ=4;static MATCH=5;static LPAREN=6;static RPAREN=7;static DOLLAR=8;static POUND=9;static STR=10;static WORD=11;static NUMBER=12;static WS=13;static EOF=kn$1.EOF;static RULE_parse=0;static RULE_expr=1;static RULE_andOr=2;static RULE_eqNeq=3;static RULE_term=4;static RULE_ident=5;static RULE_ownIdent=6;static RULE_str=7;static RULE_word=8;static RULE_number=9;static literalNames=[null,"'||'","'&&'","'=='","'!='","'?'","'('","')'","'$'","'#'"];static symbolicNames=[null,"OR","AND","EQ","NEQ","MATCH","LPAREN","RPAREN","DOLLAR","POUND","STR","WORD","NUMBER","WS"];static ruleNames=["parse","expr","andOr","eqNeq","term","ident","ownIdent","str","word","number"];get grammarFileName(){return"Restrictions.g4"}get literalNames(){return e.literalNames}get symbolicNames(){return e.symbolicNames}get ruleNames(){return e.ruleNames}get serializedATN(){return e._serializedATN}createFailedPredicateException(e,t){return new sn$1(this,e,t)}constructor(t){super(t),this._interp=new Tn$1(this,e._ATN,e.DecisionsToDFA,new mn$1)}parse(){let t=new Br(this,this._ctx,this.state);this.enterRule(t,0,e.RULE_parse);try{this.enterOuterAlt(t,1),this.state=20,this.expr(),this.state=21,this.match(e.EOF)}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}expr(){let t=new Gt(this,this._ctx,this.state);this.enterRule(t,2,e.RULE_expr);try{this.enterOuterAlt(t,1),this.state=23,this.andOr(0)}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}andOr(t){void 0===t&&(t=0);let r=this._ctx,n=this.state,i=new fe(this,this._ctx,n),o=i;this.enterRecursionRule(i,4,e.RULE_andOr,t);try{let t;for(this.enterOuterAlt(i,1),i=new Kr(this,i),this._ctx=i,o=i,this.state=26,this.eqNeq(0),this._ctx.stop=this._input.LT(-1),this.state=36,this._errHandler.sync(this),t=this._interp.adaptivePredict(this._input,1,this._ctx);2!==t&&t!==Ge$1.INVALID_ALT_NUMBER;){if(1===t)switch(null!=this._parseListeners&&this.triggerExitRuleEvent(),o=i,this.state=34,this._errHandler.sync(this),this._interp.adaptivePredict(this._input,0,this._ctx)){case 1:if(i=new zr(this,new fe(this,r,n)),this.pushNewRecursionContext(i,4,e.RULE_andOr),this.state=28,!this.precpred(this._ctx,2))throw this.createFailedPredicateException("this.precpred(this._ctx, 2)");this.state=29,this.match(e.AND),this.state=30,this.eqNeq(0);break;case 2:if(i=new Vr(this,new fe(this,r,n)),this.pushNewRecursionContext(i,4,e.RULE_andOr),this.state=31,!this.precpred(this._ctx,1))throw this.createFailedPredicateException("this.precpred(this._ctx, 1)");this.state=32,this.match(e.OR),this.state=33,this.eqNeq(0)}this.state=38,this._errHandler.sync(this),t=this._interp.adaptivePredict(this._input,1,this._ctx)}}catch(e){if(!(e instanceof _n$1))throw e;i.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.unrollRecursionContexts(r)}return i}eqNeq(t){void 0===t&&(t=0);let r=this._ctx,n=this.state,i=new Z(this,this._ctx,n),o=i;this.enterRecursionRule(i,6,e.RULE_eqNeq,t);try{let t;for(this.enterOuterAlt(i,1),i=new Xr(this,i),this._ctx=i,o=i,this.state=40,this.term(),this._ctx.stop=this._input.LT(-1),this.state=53,this._errHandler.sync(this),t=this._interp.adaptivePredict(this._input,3,this._ctx);2!==t&&t!==Ge$1.INVALID_ALT_NUMBER;){if(1===t)switch(null!=this._parseListeners&&this.triggerExitRuleEvent(),o=i,this.state=51,this._errHandler.sync(this),this._interp.adaptivePredict(this._input,2,this._ctx)){case 1:if(i=new Zr(this,new Z(this,r,n)),this.pushNewRecursionContext(i,6,e.RULE_eqNeq),this.state=42,!this.precpred(this._ctx,3))throw this.createFailedPredicateException("this.precpred(this._ctx, 3)");this.state=43,this.match(e.EQ),this.state=44,this.term();break;case 2:if(i=new Yr(this,new Z(this,r,n)),this.pushNewRecursionContext(i,6,e.RULE_eqNeq),this.state=45,!this.precpred(this._ctx,2))throw this.createFailedPredicateException("this.precpred(this._ctx, 2)");this.state=46,this.match(e.NEQ),this.state=47,this.term();break;case 3:if(i=new Qr(this,new Z(this,r,n)),this.pushNewRecursionContext(i,6,e.RULE_eqNeq),this.state=48,!this.precpred(this._ctx,1))throw this.createFailedPredicateException("this.precpred(this._ctx, 1)");this.state=49,this.match(e.MATCH),this.state=50,this.term()}this.state=55,this._errHandler.sync(this),t=this._interp.adaptivePredict(this._input,3,this._ctx)}}catch(e){if(!(e instanceof _n$1))throw e;i.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.unrollRecursionContexts(r)}return i}term(){let t=new Ke(this,this._ctx,this.state);this.enterRule(t,8,e.RULE_term);try{switch(this.enterOuterAlt(t,1),this.state=64,this._errHandler.sync(this),this._interp.adaptivePredict(this._input,4,this._ctx)){case 1:this.state=56,this.ident();break;case 2:this.state=57,this.ownIdent();break;case 3:this.state=58,this.number_();break;case 4:this.state=59,this.str();break;case 5:this.state=60,this.match(e.LPAREN),this.state=61,this.andOr(0),this.state=62,this.match(e.RPAREN)}}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}ident(){let t=new Wt(this,this._ctx,this.state);this.enterRule(t,10,e.RULE_ident);try{this.enterOuterAlt(t,1),this.state=66,this.match(e.DOLLAR),this.state=67,this.word()}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}ownIdent(){let t=new Jt(this,this._ctx,this.state);this.enterRule(t,12,e.RULE_ownIdent);try{this.enterOuterAlt(t,1),this.state=69,this.match(e.POUND),this.state=70,this.word()}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}str(){let t,r=new jt(this,this._ctx,this.state);this.enterRule(r,14,e.RULE_str);try{for(this.enterOuterAlt(r,1),this.state=75,this._errHandler.sync(this),t=this._input.LA(1);13===t;)this.state=72,this.match(e.WS),this.state=77,this._errHandler.sync(this),t=this._input.LA(1);this.state=78,this.match(e.STR)}catch(e){if(!(e instanceof _n$1))throw e;r.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return r}word(){let t=new Rt(this,this._ctx,this.state);this.enterRule(t,16,e.RULE_word);try{this.enterOuterAlt(t,1),this.state=80,this.match(e.WORD)}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}number_(){let t,r=new Bt(this,this._ctx,this.state);this.enterRule(r,18,e.RULE_number);try{for(this.enterOuterAlt(r,1),this.state=85,this._errHandler.sync(this),t=this._input.LA(1);13===t;)this.state=82,this.match(e.WS),this.state=87,this._errHandler.sync(this),t=this._input.LA(1);this.state=88,this.match(e.NUMBER)}catch(e){if(!(e instanceof _n$1))throw e;r.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return r}sempred(e,t,r){switch(t){case 2:return this.andOr_sempred(e,r);case 3:return this.eqNeq_sempred(e,r)}return!0}andOr_sempred(e,t){switch(t){case 0:return this.precpred(this._ctx,2);case 1:return this.precpred(this._ctx,1)}return!0}eqNeq_sempred(e,t){switch(t){case 2:return this.precpred(this._ctx,3);case 3:return this.precpred(this._ctx,2);case 4:return this.precpred(this._ctx,1)}return!0}static _serializedATN=[4,1,13,91,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,1,0,1,0,1,0,1,1,1,1,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,5,2,35,8,2,10,2,12,2,38,9,2,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,5,3,52,8,3,10,3,12,3,55,9,3,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,3,4,65,8,4,1,5,1,5,1,5,1,6,1,6,1,6,1,7,5,7,74,8,7,10,7,12,7,77,9,7,1,7,1,7,1,8,1,8,1,9,5,9,84,8,9,10,9,12,9,87,9,9,1,9,1,9,1,9,0,2,4,6,10,0,2,4,6,8,10,12,14,16,18,0,0,91,0,20,1,0,0,0,2,23,1,0,0,0,4,25,1,0,0,0,6,39,1,0,0,0,8,64,1,0,0,0,10,66,1,0,0,0,12,69,1,0,0,0,14,75,1,0,0,0,16,80,1,0,0,0,18,85,1,0,0,0,20,21,3,2,1,0,21,22,5,0,0,1,22,1,1,0,0,0,23,24,3,4,2,0,24,3,1,0,0,0,25,26,6,2,-1,0,26,27,3,6,3,0,27,36,1,0,0,0,28,29,10,2,0,0,29,30,5,2,0,0,30,35,3,6,3,0,31,32,10,1,0,0,32,33,5,1,0,0,33,35,3,6,3,0,34,28,1,0,0,0,34,31,1,0,0,0,35,38,1,0,0,0,36,34,1,0,0,0,36,37,1,0,0,0,37,5,1,0,0,0,38,36,1,0,0,0,39,40,6,3,-1,0,40,41,3,8,4,0,41,53,1,0,0,0,42,43,10,3,0,0,43,44,5,3,0,0,44,52,3,8,4,0,45,46,10,2,0,0,46,47,5,4,0,0,47,52,3,8,4,0,48,49,10,1,0,0,49,50,5,5,0,0,50,52,3,8,4,0,51,42,1,0,0,0,51,45,1,0,0,0,51,48,1,0,0,0,52,55,1,0,0,0,53,51,1,0,0,0,53,54,1,0,0,0,54,7,1,0,0,0,55,53,1,0,0,0,56,65,3,10,5,0,57,65,3,12,6,0,58,65,3,18,9,0,59,65,3,14,7,0,60,61,5,6,0,0,61,62,3,4,2,0,62,63,5,7,0,0,63,65,1,0,0,0,64,56,1,0,0,0,64,57,1,0,0,0,64,58,1,0,0,0,64,59,1,0,0,0,64,60,1,0,0,0,65,9,1,0,0,0,66,67,5,8,0,0,67,68,3,16,8,0,68,11,1,0,0,0,69,70,5,9,0,0,70,71,3,16,8,0,71,13,1,0,0,0,72,74,5,13,0,0,73,72,1,0,0,0,74,77,1,0,0,0,75,73,1,0,0,0,75,76,1,0,0,0,76,78,1,0,0,0,77,75,1,0,0,0,78,79,5,10,0,0,79,15,1,0,0,0,80,81,5,11,0,0,81,17,1,0,0,0,82,84,5,13,0,0,83,82,1,0,0,0,84,87,1,0,0,0,85,83,1,0,0,0,85,86,1,0,0,0,86,88,1,0,0,0,87,85,1,0,0,0,88,89,5,12,0,0,89,19,1,0,0,0,7,34,36,51,53,64,75,85];static __ATN;static get _ATN(){return e.__ATN||(e.__ATN=(new We$1).deserialize(e._serializedATN)),e.__ATN}static DecisionsToDFA=e._ATN.decisionToState.map((e,t)=>new Qe$1(e,t))},Br=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}expr(){return this.getTypedRuleContext(Gt,0)}EOF(){return this.getToken(M.EOF,0)}get ruleIndex(){return M.RULE_parse}enterRule(e){e.enterParse&&e.enterParse(this)}exitRule(e){e.exitParse&&e.exitParse(this)}accept(e){return e.visitParse?e.visitParse(this):e.visitChildren(this)}},Gt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}andOr(){return this.getTypedRuleContext(fe,0)}get ruleIndex(){return M.RULE_expr}enterRule(e){e.enterExpr&&e.enterExpr(this)}exitRule(e){e.exitExpr&&e.exitExpr(this)}accept(e){return e.visitExpr?e.visitExpr(this):e.visitChildren(this)}},fe=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}get ruleIndex(){return M.RULE_andOr}copyFrom(e){super.copyFrom(e)}},Kr=class extends fe{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}eqNeq(){return this.getTypedRuleContext(Z,0)}enterRule(e){e.enterAndOrEqNeq&&e.enterAndOrEqNeq(this)}exitRule(e){e.exitAndOrEqNeq&&e.exitAndOrEqNeq(this)}accept(e){return e.visitAndOrEqNeq?e.visitAndOrEqNeq(this):e.visitChildren(this)}},Vr=class extends fe{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}andOr(){return this.getTypedRuleContext(fe,0)}OR(){return this.getToken(M.OR,0)}eqNeq(){return this.getTypedRuleContext(Z,0)}enterRule(e){e.enterOr&&e.enterOr(this)}exitRule(e){e.exitOr&&e.exitOr(this)}accept(e){return e.visitOr?e.visitOr(this):e.visitChildren(this)}},zr=class extends fe{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}andOr(){return this.getTypedRuleContext(fe,0)}AND(){return this.getToken(M.AND,0)}eqNeq(){return this.getTypedRuleContext(Z,0)}enterRule(e){e.enterAnd&&e.enterAnd(this)}exitRule(e){e.exitAnd&&e.exitAnd(this)}accept(e){return e.visitAnd?e.visitAnd(this):e.visitChildren(this)}},Z=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}get ruleIndex(){return M.RULE_eqNeq}copyFrom(e){super.copyFrom(e)}},Qr=class extends Z{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}eqNeq(){return this.getTypedRuleContext(Z,0)}MATCH(){return this.getToken(M.MATCH,0)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterMatch&&e.enterMatch(this)}exitRule(e){e.exitMatch&&e.exitMatch(this)}accept(e){return e.visitMatch?e.visitMatch(this):e.visitChildren(this)}},Yr=class extends Z{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}eqNeq(){return this.getTypedRuleContext(Z,0)}NEQ(){return this.getToken(M.NEQ,0)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterNeq&&e.enterNeq(this)}exitRule(e){e.exitNeq&&e.exitNeq(this)}accept(e){return e.visitNeq?e.visitNeq(this):e.visitChildren(this)}},Zr=class extends Z{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}eqNeq(){return this.getTypedRuleContext(Z,0)}EQ(){return this.getToken(M.EQ,0)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterEq&&e.enterEq(this)}exitRule(e){e.exitEq&&e.exitEq(this)}accept(e){return e.visitEq?e.visitEq(this):e.visitChildren(this)}},Xr=class extends Z{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterEqNeqTerm&&e.enterEqNeqTerm(this)}exitRule(e){e.exitEqNeqTerm&&e.exitEqNeqTerm(this)}accept(e){return e.visitEqNeqTerm?e.visitEqNeqTerm(this):e.visitChildren(this)}},Ke=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}ident(){return this.getTypedRuleContext(Wt,0)}ownIdent(){return this.getTypedRuleContext(Jt,0)}number_(){return this.getTypedRuleContext(Bt,0)}str(){return this.getTypedRuleContext(jt,0)}LPAREN(){return this.getToken(M.LPAREN,0)}andOr(){return this.getTypedRuleContext(fe,0)}RPAREN(){return this.getToken(M.RPAREN,0)}get ruleIndex(){return M.RULE_term}enterRule(e){e.enterTerm&&e.enterTerm(this)}exitRule(e){e.exitTerm&&e.exitTerm(this)}accept(e){return e.visitTerm?e.visitTerm(this):e.visitChildren(this)}},Wt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}DOLLAR(){return this.getToken(M.DOLLAR,0)}word(){return this.getTypedRuleContext(Rt,0)}get ruleIndex(){return M.RULE_ident}enterRule(e){e.enterIdent&&e.enterIdent(this)}exitRule(e){e.exitIdent&&e.exitIdent(this)}accept(e){return e.visitIdent?e.visitIdent(this):e.visitChildren(this)}},Jt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}POUND(){return this.getToken(M.POUND,0)}word(){return this.getTypedRuleContext(Rt,0)}get ruleIndex(){return M.RULE_ownIdent}enterRule(e){e.enterOwnIdent&&e.enterOwnIdent(this)}exitRule(e){e.exitOwnIdent&&e.exitOwnIdent(this)}accept(e){return e.visitOwnIdent?e.visitOwnIdent(this):e.visitChildren(this)}},jt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}STR(){return this.getToken(M.STR,0)}WS_list(){return this.getTokens(M.WS)}WS(e){return this.getToken(M.WS,e)}get ruleIndex(){return M.RULE_str}enterRule(e){e.enterStr&&e.enterStr(this)}exitRule(e){e.exitStr&&e.exitStr(this)}accept(e){return e.visitStr?e.visitStr(this):e.visitChildren(this)}},Rt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}WORD(){return this.getToken(M.WORD,0)}get ruleIndex(){return M.RULE_word}enterRule(e){e.enterWord&&e.enterWord(this)}exitRule(e){e.exitWord&&e.exitWord(this)}accept(e){return e.visitWord?e.visitWord(this):e.visitChildren(this)}},Bt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}NUMBER(){return this.getToken(M.NUMBER,0)}WS_list(){return this.getTokens(M.WS)}WS(e){return this.getToken(M.WS,e)}get ruleIndex(){return M.RULE_number}enterRule(e){e.enterNumber&&e.enterNumber(this)}exitRule(e){e.exitNumber&&e.exitNumber(this)}accept(e){return e.visitNumber?e.visitNumber(this):e.visitChildren(this)}},xt=class e extends cn$1{static OR=1;static AND=2;static EQ=3;static NEQ=4;static MATCH=5;static LPAREN=6;static RPAREN=7;static DOLLAR=8;static POUND=9;static STR=10;static WORD=11;static NUMBER=12;static WS=13;static EOF=kn$1.EOF;static channelNames=["DEFAULT_TOKEN_CHANNEL","HIDDEN"];static literalNames=[null,"'||'","'&&'","'=='","'!='","'?'","'('","')'","'$'","'#'"];static symbolicNames=[null,"OR","AND","EQ","NEQ","MATCH","LPAREN","RPAREN","DOLLAR","POUND","STR","WORD","NUMBER","WS"];static modeNames=["DEFAULT_MODE"];static ruleNames=["OR","AND","EQ","NEQ","MATCH","LPAREN","RPAREN","DOLLAR","POUND","STR","WORD","NUMBER","WS"];constructor(t){super(t),this._interp=new un$1(this,e._ATN,e.DecisionsToDFA,new mn$1)}get grammarFileName(){return"Restrictions.g4"}get literalNames(){return e.literalNames}get symbolicNames(){return e.symbolicNames}get ruleNames(){return e.ruleNames}get serializedATN(){return e._serializedATN}get channelNames(){return e.channelNames}get modeNames(){return e.modeNames}static _serializedATN=[4,0,13,86,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,1,0,1,0,1,0,1,1,1,1,1,1,1,2,1,2,1,2,1,3,1,3,1,3,1,4,1,4,1,5,1,5,1,6,1,6,1,7,1,7,1,8,1,8,1,9,1,9,4,9,52,8,9,11,9,12,9,53,1,9,1,9,1,10,4,10,59,8,10,11,10,12,10,60,1,11,3,11,64,8,11,1,11,5,11,67,8,11,10,11,12,11,70,9,11,1,11,3,11,73,8,11,1,11,4,11,76,8,11,11,11,12,11,77,1,12,4,12,81,8,12,11,12,12,12,82,1,12,1,12,0,0,13,1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,1,0,5,1,0,39,39,4,0,45,45,65,90,95,95,97,122,2,0,43,43,45,45,1,0,48,57,2,0,9,9,32,32,92,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,1,27,1,0,0,0,3,30,1,0,0,0,5,33,1,0,0,0,7,36,1,0,0,0,9,39,1,0,0,0,11,41,1,0,0,0,13,43,1,0,0,0,15,45,1,0,0,0,17,47,1,0,0,0,19,49,1,0,0,0,21,58,1,0,0,0,23,63,1,0,0,0,25,80,1,0,0,0,27,28,5,124,0,0,28,29,5,124,0,0,29,2,1,0,0,0,30,31,5,38,0,0,31,32,5,38,0,0,32,4,1,0,0,0,33,34,5,61,0,0,34,35,5,61,0,0,35,6,1,0,0,0,36,37,5,33,0,0,37,38,5,61,0,0,38,8,1,0,0,0,39,40,5,63,0,0,40,10,1,0,0,0,41,42,5,40,0,0,42,12,1,0,0,0,43,44,5,41,0,0,44,14,1,0,0,0,45,46,5,36,0,0,46,16,1,0,0,0,47,48,5,35,0,0,48,18,1,0,0,0,49,51,7,0,0,0,50,52,8,0,0,0,51,50,1,0,0,0,52,53,1,0,0,0,53,51,1,0,0,0,53,54,1,0,0,0,54,55,1,0,0,0,55,56,7,0,0,0,56,20,1,0,0,0,57,59,7,1,0,0,58,57,1,0,0,0,59,60,1,0,0,0,60,58,1,0,0,0,60,61,1,0,0,0,61,22,1,0,0,0,62,64,7,2,0,0,63,62,1,0,0,0,63,64,1,0,0,0,64,68,1,0,0,0,65,67,7,3,0,0,66,65,1,0,0,0,67,70,1,0,0,0,68,66,1,0,0,0,68,69,1,0,0,0,69,72,1,0,0,0,70,68,1,0,0,0,71,73,9,0,0,0,72,71,1,0,0,0,72,73,1,0,0,0,73,75,1,0,0,0,74,76,7,3,0,0,75,74,1,0,0,0,76,77,1,0,0,0,77,75,1,0,0,0,77,78,1,0,0,0,78,24,1,0,0,0,79,81,7,4,0,0,80,79,1,0,0,0,81,82,1,0,0,0,82,80,1,0,0,0,82,83,1,0,0,0,83,84,1,0,0,0,84,85,6,12,0,0,85,26,1,0,0,0,8,0,53,60,63,68,72,77,82,1,6,0,0];static __ATN;static get _ATN(){return e.__ATN||(e.__ATN=(new We$1).deserialize(e._serializedATN)),e.__ATN}static DecisionsToDFA=e._ATN.decisionToState.map((e,t)=>new Qe$1(e,t))},St=class extends pn$1{visitParse;visitExpr;visitAndOrEqNeq;visitOr;visitAnd;visitMatch;visitNeq;visitEq;visitEqNeqTerm;visitTerm;visitIdent;visitOwnIdent;visitStr;visitWord;visitNumber},N=new St,et=e=>{let t=N.visitChildren(e);return 1==t.length?t[0]:t};N.visitParse=e=>e.expr().accept(N),N.visitExpr=e=>["expr",et(e)],N.visitAndOrEqNeq=et,N.visitEqNeqTerm=et,N.visitTerm=e=>3===e.getChildCount()?N.visit(e.getChild(1)):et(e),N.visitEq=e=>["eq",et(e.eqNeq()),e.term().accept(N)],N.visitNeq=e=>["neq",et(e.eqNeq()),e.term().accept(N)],N.visitMatch=e=>["match",N.visitChildren(e.eqNeq())[0],e.term().accept(N)],N.visitAnd=e=>{let t=N.visitChildren(e.andOr()),r=N.visitChildren(e.eqNeq());return["and",t[0],r[0]]},N.visitIdent=e=>["ident",e.word().accept(N)],N.visitOwnIdent=e=>["own-ident",e.word().accept(N)],N.visitWord=e=>["word",e.WORD().symbol.text],N.visitNumber=e=>["number",e.NUMBER().symbol.text],N.visitStr=e=>["str",e.STR().symbol.text.slice(1,-1)];var ji=N;function Bi(e){let t=Xe$1.fromString(e),r=new xt(t),n=new Ze$1(r);return new M(n).parse().accept(ji)}function en$1(e,t){if(Array.isArray(t)){let[r,...n]=t,i=e[r];if(i){let t=n.map(t=>en$1(e,t));return i.apply(e,t)}let o=n.map(t=>en$1(e,t));return[r].concat(o)}return t}function Ki(e,t,r){return!((e?.length??0)>0)||en$1({and:(e,t)=>e&&t,or:(e,t)=>e||t,eq:(e,t)=>e===t,neq:(e,t)=>e!==t,match:(e,t)=>t&&e?new RegExp(t).test(e):e,str:e=>e,number:e=>JSON.parse(e),expr:e=>e,"own-ident":([e,r])=>t[r],ident:([e,t])=>r[t]},e)}function X(e){return"string"==typeof e?"cluster"===e||"local"===e?e:Bi(e):e}function ee(e,t,r){let[n,i]=t,[o,s]=r;switch(e){case"local":return n?"local"===n.type?"local"===o?.type:"peer"!==n.type||"peer"===o?.type&&o?.node===n?.node:void 0===o||"local"===o.type;case"cluster":return!0;default:return"cluster"===o?.type||!!Ki(e,i,s)}}if(void 0===globalThis.crypto)throw new Error("Crypto API is not available. If Running Node 18, try --experimental-global-webcrypto.");function Me(e=globalThis.crypto){return e.randomUUID().replaceAll("-","")}function A(e){return e?e.nodeId:Me()}function Pe(e){let t=e.currentId??1,r=`r-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function Vi(e){let t=e.currentId??1,r=`i-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function Kt(e){let t=e.currentId??1,r=`c-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function zi(e){let t=e.currentId??1,r=`a-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function Qi(e){let t=e.currentId??1,r=`p-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function zt(e,t){return{ids:{nodeId:e,currentId:1},signatureKey:t??Me()}}function he$1(e,t,r,n){return produce(e,e=>{e.peers[t][r]=n?{restrictions:n}:{},e.domains=e.domains||{},e.domains[r]=e.domains[r]||new Set,e.domains[r].add(t)})}function te(e,t,r){return produce(e,e=>{e.peers&&delete e.peers[t][r],e.domains&&e.domains[r]&&e.domains[r].delete(t)})}function de$1(e,t,r){return!!e.domains?.[r]?.has(t)}function Yi(e,t){return!!e[t]}function rn(e,t,r){return t?produce(e,e=>{e.gatewayRequests=e.gatewayRequests||{},e.gatewayRequests[t]=r}):e}function tt(e,t){return produce({state:e},e=>{e.state.gatewayRequests&&(e.removed=e.state.gatewayRequests[t],delete e.state.gatewayRequests[t],0===Object.keys(e.state.gatewayRequests).length&&delete e.state.gatewayRequests)})}function vt(e,t){return e.registeredDomains?.[t]?.domain}function ue(e,...t){return t.reduce(([e,t],r)=>{let[n,i]=r(e);return[n,t.concat(i)]},[e,[]])}function eo$1(e,t){switch(t.type){case"node":return t.node===e.node;case"peer":return t.node===e.node&&t.peer===e.peer;case"local":return t.receive===e.receive;default:return!1}}function Te(e,t,r){return ne(e,r).filter(e=>eo$1(e.source,t))}function to(e,t){return pd(e).filter(e=>eo$1(e.source,t))}function B(e,t,r){let n=g$2(e,t);if(n?.[r])return n}function g$2(e,t){return t?e.peers?.[t]:void 0}function _(e,t){if(t){let r=g$2(e,t);if(r)return r;throw V(`Unable to find peer ${t}`,{})}throw V("Peer id is missing",{})}function b(e,t,r){if(t){let n=B(e,t,r);if(n)return n;throw V(`Unable to find peer ${t} in domain ${r}`,{})}throw V("Peer id is missing",{})}function q(e){return"local"===e?.source.type}function re(e,t,r){return ee(t?.[e]?.restrictions,[t?.source,t?.identity],[{type:"cluster"},r])}function ro(e,t){let r=nt(t);return e.identities?.get(r)}function pd(e){return Object.values(e.peers||{})}function ne(e,t){return Array.from(e.domains?.[t]??[],r=>B(e,r,t)).filter(pe)}function sn(e,t,r,n,i,o){let s=g$2(e,r);if(s)return[e,s];let a=produce({id:r,identity:n,source:t},e=>{o&&(e.options=o),i&&(e.creationRequest=i)});return[produce(e,e=>{if(e.users=e.users||{},n.user){e.users.byName=e.users.byName||new Map;let t=e.users.byName.get(n.user);t?t.add(r):e.users.byName.set(n.user,new Set([r]))}else e.users.noUser=e.users.noUser||new Set,e.users.noUser.add(r);e.identities=e.identities||new Map,e.identities.set(nt(n),r),e.peers=e.peers||{},e.peers[r]=castDraft(a),o?.service&&(e.services=e.services||new Set,e.services.add(r))}),a]}function no$1(e,t){let r=t.identity,n=t.id,i=r.user;return produce(e,e=>{if(e.identities&&e.identities.delete(nt(r)),e.users)if(i){let t=e.users.byName?.get(i);t&&(t.delete(n),0==t.size&&e.users.byName?.delete(i)),e.users.byName&&0===e.users.byName.size&&delete e.users.byName}else e.users.noUser?.delete(n),0===e.users.noUser?.size&&delete e.users.noUser;e.peers&&delete e.peers[n],e.services=e.services||new Set,e.services&&e.services.delete(n)})}function C(e,t,r){return produce(e,e=>{e.peers=e.peers||castDraft({}),e.peers[t]=castDraft(r)})}function Ee(e,t,r){return produce(e,e=>{e.peers[t]=produce(e.peers[t],r)})}function Qt(e,t){let[r,n,i,o]=e,[s,a,c,l]=t;if(i||c)return ee(i,[r,n],[s,a])&&ee(c,[s,a],[r,n]);{let e=a?.user,t=n?.user;return l||o||e===t}}function it$1(e,t,r){return r.id!==t.id&&Qt([t.source,t.identity,t[e]?.restrictions,t.options?.service],[r.source,r.identity,r[e]?.restrictions,r.options?.service])}function Xi(e,t,r,n=!1){return ne(e,t).concat(Array.from(e.services??[],t=>g$2(e,t)).filter(pe)).filter(e=>n&&r.id===e.id||it$1(t,r,e))}function ie(e,t,r,n){if(r.options?.service)return Xi(e,t,r,n);{let i=r.identity.user;return i?Array.from(e.users?.byName?.get(i)??[]).concat(Array.from(e.services??[])).map(t=>g$2(e,t)).filter(pe).filter(e=>Yi(e,t)&&it$1(t,r,e)||!0===n&&e.id===r.id):Xi(e,t,r,n)}}function md(e,t,r,n,i){let o=i.identity,s=i.id,a=n.id,c=q(n);return produce(t,t=>{c&&t.push(qe(e,r,a,s,o,{local:c})),q(i)&&t.push(qe(e,i.source,s,a,n.identity,{local:c}))})}function Yt(e,t,r,n,i){return ie(r,t,i).reduce((t,r)=>md(e,t,n,i,r),[])}function Zt(e,t,r,n,i,o){let s=n.id;return[te(r,s,t),ie(r,t,n).filter(q).reduce((t,r)=>(t=t.concat(Je(e,r.source,r.id,s,i)),!o&&q(n)&&(t=t.concat(Je(e,n.source,s,r.id,i))),t),[])]}function ld(e,t){if(e===t)return!0;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(let n of r)if(e[n]!==t[n])return!1;return!0}function yd(e,t,r){let{peer_id:n}=r,i=g$2(e,n);if(i&&!ld(t,i.source))throw V(`The original source ${JSON.stringify(i.source)} of peer ${n} doesnt match the current source ${JSON.stringify(t)}`,{message:"Bad Source"})}enableMapSet(),me();var ot=R("gateway.node");function fd(e,t){let r=Object.values(t.registeredDomains).filter(e=>e.info.uri!==Se).map(e=>e.domain);return t.registeredDomains[Se]&&r.push(t.registeredDomains[Se].domain),r.reduce(([t,r],n)=>{ot.enabledFor("debug")&&ot.debug(`About to remove source from domain ${JSON.stringify(n.info())}`);let i=n.handleMessage(t,e);if(i){ot.enabledFor("debug")&&ot.debug(`removed source from domain ${JSON.stringify(n.info())}`);let[e,t]=i;return[e,r.concat(t)]}return[t,r]},[t,[]])}function ze(e,t,r){if("commands/source-removed"===t.body.type)return fd(t,e);{let{body:n}=t,{registeredDomains:i}=e,o=n.domain??Se,s=i[o]?.domain;if(s)return ot.enabledFor("debug")&&ot.debug(`Handling message with domain ${JSON.stringify(s.info())} message: \n ${JSON.stringify(t,null,"\t")}`),yd(e,r,n),s.handleMessage(e,t);{let i=n;return[e,[h(i.domain,r,i.request_id,i.peer_id,S(Ne,`Unable to find domain for message ${JSON.stringify(t)}`))]]}}}function Xt(e){return e.reduce((e,t)=>{let r=t.info(),n={};return n[r.uri]={domain:t,info:r},Object.assign(e,n)},{})}L(),me();var an=class{constructor(e){this.handler=e}close(){}message(e){this.handler(e)}addSource(e){}removeSource(e){let t={origin:"local",source:e,body:{type:"commands/source-removed"}};return this.handler(t)}},De=R("gateway.node.local");function gd(e,t){let{source:r,body:n,origin:i}=t;try{return n.dump?(De.info(`state dump:\n${JSON.stringify($e(e),null,"\t")}`),[e,[]]):"cluster"===i?[e,[]]:ze(e,t,r)}catch(i){De.error(`Error handling message ${JSON.stringify(t)}`,i);let o=n;return[e,[h(void 0,r,o.request_id,o.peer_id,J(i,Ne))]]}}function hd(e){return"receive"in e&&e.receive}function bd(e){switch(e.receiver.type){case"cluster":case"node":case"peer":return;case"local":{let{receiver:t,body:r}=e;De.enabledFor("debug")&&De.debug(`Sending message ${JSON.stringify(r,null,"\t")} to ${JSON.stringify(t)}`),hd(t)&&t.receive(r);break}default:De.error(`Unable to process response ${JSON.stringify(e)}`)}}function Rd(e,t){try{De.enabledFor("trace")&&De.debug(`domain handler processing message ${JSON.stringify(t)}`);let[r,n]=gd(e,t);if(n)for(let e of n)bd(e);return r??e}catch(r){return De.error(`error handling message ${JSON.stringify(t)}`,r),e}}function io(e,t){let r,n=e=>{try{r=Rd(r,e)}catch(t){throw De.error(`Error processing internal message ${JSON.stringify(e)}`,t),t}},i=Xt(e);return r=e.reduce((e,t)=>t.init(e),{...zt(t?.nodeId??A(),t?.signingKey),registeredDomains:i,handler:n}),new an(n)}var D=Se,cn=Ne,oo=`${D}.errors.unhandled_message`,dn=`${D}.errors.already_seen`,un=`${D}.errors.invalid_domain`,pn=`${D}.errors.authentication.failure`,mn=`${D}.errors.invalid_peer`;function so(e,t,r,n,i,o){let s={domain:D,type:"welcome",request_id:t,peer_id:r,available_domains:n,resolved_identity:i};return o&&(s.options=o),x(e,s)}function ao(e,t,r,n,i){return x(t,{domain:e,type:"authentication-request",request_id:r,authentication:i})}function st(e,t,r,n,i,o){let s={domain:D,type:"join",request_id:e,peer_id:t,destination:n,identity:i};return r&&(s.restrictions=r),o&&(s.options=o),s}function co(e){return x(e,{type:"ping"})}L();var ln={application:{required:!0},instance:{required:!1},region:{required:!1},environment:{required:!1},machine:{required:!1},user:{required:!1}};function Sd(e){return Object.keys(ln).find(t=>ln[t]&&ln[t].required&&void 0===e[t])}function uo(e){let t=Sd(e);if(t)throw new ve(`Identity ${JSON.stringify(e)} is missing required key: ${t}`,{})}function po(e,t){let r=e;return r&&-1!==r.indexOf(":")&&(r=r.substring(0,r.indexOf(":"))),r&&r.indexOf("127.0.0.1")>=0?t:r??t}function wt(e,t){return KJUR_1.jws.JWS.sign(null,{alg:"HS256",typ:"JWT"},e,t)}function er(e,t,r){let n;if(!KJUR_1.jws.JWS.verifyJWT(e,t,{alg:["HS256"],verifyAt:r?.now}))throw new Error("invalid jwt token");return n=KJUR_1.jws.JWS.parse(e),n.payloadObj}function fn$1(e,t,r,n){return wt({type:"gw-request","impersonate-peer":t,"gw-request":r},e.signatureKey)}function mo(e,t,r){return wt({type:"authentication",user:t.user},e.signatureKey)}function lo(e,t,r){void 0===r&&(r=r??Date.now());let n={};return r&&(n.now=Math.floor(r/1e3)),er(t,e,n)}function w(e,t){return{type:"peer",peer:t,node:e}}function _e(e){return{type:"node",node:e}}function gn(e){return Object.values(e.contexts||{})}L(),L();var vd=R("gateway.action"),yo$1="info";function $(e,t){let r=vd.child(e);if(r.enabledFor(yo$1)){let e=t();r[yo$1](e)}}function It(e){return`${e}.errors.not_authorized`}function fo(e){return`${e}.errors.bad_lifetime`}function go(e){return`${e}.errors.invalid_context`}function ho(e){return`${e}.errors.unhandled_message`}function hn(e){return S(`${e}.destroyed`,"Context destroyed explicitly")}function bo(e){return S(`${e}.peer-left`,"Context destroyed because its owner/last peer left")}function Ue(e){return`${e}.errors.failure`}function Ro(e,t,r,n,i,o){return x(t,{domain:e,type:"subscribed-context",request_id:r,peer_id:n,context_id:i,data:o})}function bn(e,t,r,n,i,o){return x(t,{domain:e,type:"context-added",peer_id:r,creator_id:n,context_id:i,name:o})}function Rn(e,t,r,n,i){return x(t,{domain:e,type:"context-destroyed",peer_id:r,context_id:n,reason_uri:i.uri,reason:i.message})}function xo(e,t,r,n,i){return x(t,{domain:e,type:"context-created",request_id:r,peer_id:n,context_id:i})}function So(e,t,r,n,i,o){return x(t,{domain:e,type:"context-updated",peer_id:r,updater_id:n,context_id:i,delta:o})}function wo(e){return Object.values(e.contexts||{})}function tr$1(e,t){return produce(e,e=>{e.contexts=e.contexts||{},e.contexts[t.id]=castDraft(t)})}function rr(e,t){return produce(e,e=>{e.contexts&&(delete e.contexts[t],0===Object.values(e.contexts).length&&delete e.contexts)})}function Qe(e,t,r){let n,i=r.identity.user,o=r.options?.service,s=Object.values(e.contexts||{});return n=s.find(e=>t===e.name&&e.identity.user===i),n||(n=s.find(e=>t===e.name&&(o||e.options?.service))),n}function He(e,t){if(t)return e.contexts?.[t]}function Tt(e,t,r){let n=t.contexts?.[r];if(n)return n;throw V(`Unable to find context with id ${r}`,{uri:go(e)})}function dt(e,t,r){return t&&r?t.members.has(r)?e:produce(e,e=>{e.contexts=e.contexts||{},e.contexts[t.id]=castDraft(produce(t,e=>{e.members=e.members||new Set,e.members.add(r)}))}):e}function nr(e,t,r){return produce([e,t],([e,n])=>{n.members.delete(r),r===n.owner&&delete n.owner,e.contexts=e.contexts||{},e.contexts[t.id]=n})}function Io(e,t,r){if(!t)return r;if(1===t.length)e[t[0]]=r;else{let n=e[t[0]];(void 0===n||Array.isArray(n)||"number"==typeof n||"boolean"==typeof n)&&(n={}),e[t[0]]=Io(n,t.slice(1),r)}return e}function Id(e,t){return{...e,...t}}function Td(e,t){let[r,n]=t;switch(r){case"removed":n.forEach(t=>{delete e?.[t]});break;case"added":e=Object.entries(n).reduce((e,[t,r])=>(e[t]=r,e),e??{});break;case"updated":e=Object.entries(n).reduce((e,[t,r])=>(Array.isArray(r)&&Array.isArray(e[t])?e[t]=r:r instanceof Object&&e[t]instanceof Object?e[t]=Id(e[t],r):e[t]=r,e),e??{});break;case"reset":n&&(e=n);break;case"commands":e=n.reduce((e,t)=>{switch(t.type){case"set":return Io(e??{},vo(t.path),t.value);case"remove":{let r=vo(t.path);if(!r)return{};{let t=e;for(let n=0;n{e.contexts[t].data=Object.entries(r).reduce((e,[t,r])=>Td(e,[t,r]),e.contexts[t].data),e.contexts[t].version=n})}function vo(e){if(e)return e.split(".")}function ir(e,t,r,n,i,o,s,a,c){let l=e.identity,u=e.options,d={id:a,data:r??{},identity:l,lifetime:n,read_permissions:i,write_permissions:o,permissions:s,members:new Set,version:c,name:t,creator:e.id};return u&&(castDraft(d).options=u),void 0===d.permissions&&delete castDraft(d).permissions,void 0===d.read_permissions&&delete castDraft(d).read_permissions,void 0===d.write_permissions&&delete castDraft(d).write_permissions,d}function Ao(e){let t=e.version?.updates||0;return t++,{updates:t,timestamp:Date.now()}}function or(){return{updates:0,timestamp:Date.now()}}function Le(e){return ee(e.permissions?.read,[{type:e.local?"local":"cluster"},e.identity],[{type:"cluster"},void 0])}function Co(e,t){let r=e.version,n=t.version;return r.updates>n.updates||r.updates===n.updates&&r.timestamp>=n.timestamp}function sr(e,t,r=!1){let n=e.lifetime;return t.id===e.creator||("activity"===n?e.members.has(t.id):t.id===e.creator||t.id===e.owner||(r?!!e.permissions?.write&&ee(e.permissions?.write,[void 0,e.identity],[t.source,t.identity]):ee(e.permissions?.write,[void 0,e.identity],[t.source,t.identity])))}function Mo(e,t,r){"activity"===t.lifetime&&k(It(e),"Activity contexts cannot be explicitly destroyed");let n="ownership"===t.lifetime;n&&t.owner===r.id||!n&&sr(t,r)||k(It(e),"Not authorized to destroy context")}function ar$1(e,t){return t.id===e.creator||t.id===e.owner||ee(e.permissions?.read,[void 0,e.identity],[t.source,t.identity])||sr(e,t,!0)}function Md(e,t){return q(e)&&"activity"!==t.lifetime&&ar$1(t,e)}function cr(e,t,r){ar$1(t,r)||k(It(e),"Not authorized to read context")}function Pd(e){if(!e.local&&!ee(e.permissions?.write,[void 0,e.identity],[{type:"cluster"},void 0]))throw new Error(`cannot create remote context '${e.name}' locally`)}function Dd(e,t,r,n){let{peer_id:i,name:o}=n;try{let r=_(t,i),n=Qe(t,o,r);return n?vn(e,t,r,n):(z$1.enabledFor("debug")&&z$1.debug(`unable to find remote context ${o}`),[t,[]])}catch(e){return z$1.enabledFor("debug")&&z$1.debug(`error processing remote context unsubscribe ${JSON.stringify(n)}`,e),[t,[]]}}function _d(e,t,r,n){let{request_id:i,peer_id:o,context_id:s}=n;try{let a=_(t,o),c=Tt(e,t,s),[l,u]=vn(e,t,a,c),d=u.concat([I(e,r,i,o)]);if(Le(c)){let e={...n,type:"unsubscribe-context",name:c.name};d=d.concat([G(w(A(l.ids),o),e)])}return[l,d]}catch(n){return[t,[h(e,r,i,o,J(n,Ue(e)))]]}}function dr(e,t,r,n){return W(r)?Dd(e,t,r,n):_d(e,t,r,n)}function Po(e,t,r){let{source:n,id:i}=r;return gn(t).filter(e=>Md(r,e)).map(t=>{let{creator:r,id:o,name:s}=t;return bn(e,n,i,r,o,s)})}function At(e){return e.options?.["context-compatibility-mode?"]?Se:se}function xn(e,t,r,n,i,o){let s=t.id,a=To(e,s,n,i);return $(se,()=>`[${t.name}#${t.id}] updated by [${r.identity.application}#${r.id}] (request: ${o})`),[a,Array.from(t.members).filter(e=>e!==r.id).map(e=>g$2(a,e)).filter(pe).filter(e=>q(e)).map(e=>So(At(e),e.source,e.id,r.id,s,n))]}function Od(e,t,r){let{request_id:n,peer_id:i,name:o,delta:s,version:a}=r;try{let e=_(t,i),c=Qe(t,o,e);return c?sr(c,e)&&Co(r,c)?xn(t,c,e,s,a,n):[t,[]]:(z$1.enabledFor("debug")&&z$1.debug(`unable to find remote context ${o}`),[t,[]])}catch(e){return z$1.enabledFor("debug")&&z$1.debug(`error processing remote context update ${JSON.stringify(r)}`,e),[t,[]]}}function kd(e,t,r,n){let{request_id:i,peer_id:o,context_id:s,delta:a}=n;try{let c=_(t,o),l=Tt(e,t,s),u=Ao(l);sr(l,c)||k(It(e),"Not authorized to update context");let d={...n,type:"update-context",version:u,name:l.name,delta:a};return ue(t,e=>xn(e,l,c,a,u,i),t=>[t,[I(e,r,i,o)]],e=>[e,Le(l)?[G(w(A(e.ids),o),d)]:[]])}catch(n){return[t,[h(e,r,i,o,J(n,Ue(e)))]]}}function ut(e,t,r,n){return W(r)?Od(e,t,n):kd(e,t,r,n)}function Do(e,t,r,n){let{name:i,data:o,peer_id:s}=r,a=r.lifetime??n.defaultLifetime,c=!n.isLocal||t.options?.respect_context_lifetime||"retained"!==a&&void 0!==a?a:n.defaultLifetime??"retained",l=r.permissions?.read??n?.defaultPermissions?.("read",i,t.identity),u=r.permissions?.write??n?.defaultPermissions?.("write",i,t.identity),d=l||u?{read:l,write:u}:void 0,[h,p]=Kt(e.ids),g=r.version??or(),m=produce(ir(t,i,o,c,r.read_permissions,r.write_permissions,d,p,g),e=>{e.members=new Set([s]),e.local=n.isLocal,e.lifetime=c,"ownership"===c&&(e.owner=s)});return Pd(m),[tr$1({...e,ids:h},m),m]}function _o(e,t,r,n,i,o){return $(se,()=>`[${i.name}#${i.id}] subscribed by [${o.identity.application}#${o.id}] (request: ${n})`),[dt(t,i,o.id),[Ro(e,r,n,o.id,i.id,i.data)]]}function Nd(e,t,r,n){let{peer_id:i,name:o,request_id:s}=n;try{let r=_(t,i),n=Qe(t,o,r);return n?(cr(e,n,r),$(se,()=>`[${n.name}#${n.id}] subscribed by [${r.identity.application}#${r.id}] (request: ${s})`),[dt(t,n,i),[]]):(z$1.enabledFor("debug")&&z$1.debug(`unable to find remote context ${o}`),[t,[]])}catch(e){return z$1.enabledFor("debug")&&z$1.debug(`error processing remote context subscribe ${JSON.stringify(n)}`,e),[t,[]]}}function qd(e,t,r,n){let{request_id:i,peer_id:o,context_id:s}=n;try{let a=_(t,o),c=Tt(e,t,s);cr(e,c,a);let[l,u]=_o(e,t,r,i,c,a);if(Le(c)){let e={...n,type:"subscribe-context",name:c.name};return[l,u.concat([G(w(A(l.ids),o),e)])]}return[l,u]}catch(n){return[t,[h(e,r,i,o,J(n,Ue(e)))]]}}function ur$1(e,t,r,n){return W(r)?Nd(e,t,r,n):qd(e,t,r,n)}function Oo(e,t,r){let n=t.name,i=t.id,o=r.id;return ie(e,"context-domain",r,!0).filter(e=>q(e)).filter(e=>ar$1(t,e)).map(e=>bn(At(e),e.source,e.id,o,i,n))}function $d(e,t,r){let n=e.id;return t.filter(e=>q(e)).filter(t=>ar$1(e,t)).map(e=>Rn(At(e),e.source,e.id,n,r))}function ko$1(e,t){let r=X(t.read_permissions),n=X(t.write_permissions),i=r||n?{read:r,write:n}:void 0,o=t.lifetime;return o||k(fo(e),`Bad lifetime value ${o}`),{...t,domain:e,lifetime:o,permissions:i}}function Ed(e,t,r,n){let{request_id:i,peer_id:o,name:s}=r;try{let a=b(t,o,"context-domain"),c=Qe(t,s,a);if(c)return cr(e,c,a),Co(r,c)?xn(t,c,a,{reset:r.data},r.version,i):[t,[]];{let o=ko$1(e,r),[s,c]=Do(t,a,o,{isLocal:!1,defaultPermissions:(e,t,r)=>n?.defaultContextRestrictions?.apply(r,[t])});return $(se,()=>`[${c.name}#${c.id}] created for ${c.identity.user??""} by [${c.identity.application}#${c.creator}] (request: ${i}, permissions: ${JSON.stringify(c.permissions)})`),[s,Oo(s,c,a)]}}catch{return z$1.enabledFor("debug")&&z$1.debug(`error processing remote context create ${JSON.stringify(r)}`),[t,[]]}}me();var z$1=R("gateway.contexts");function Ud(e,t,r,n,i){let{request_id:o,peer_id:s,name:a}=n;try{let c=b(t,s,"context-domain"),l=Qe(t,a,c);if(l)return cr(e,l,c),_o(e,t,r,o,l,c);{let a=ko$1(e,n),[l,u]=Do(t,c,a,{isLocal:!0,defaultLifetime:i?.retainedOverride,defaultPermissions:(e,t,r)=>i?.defaultContextRestrictions?.apply(r,[t])});$(se,()=>`[${u.name}#${u.id}] created for ${u.identity.user??""} by [${u.identity.application}#${u.creator}] (request: ${o}, permissions: ${JSON.stringify(u.permissions)})`);let d=Oo(l,u,c);if(d.push(xo(e,r,o,s,u.id)),Le(u)){let e={...n,type:"create-context",version:u.version,lifetime:u.lifetime};d.push(G(w(A(t.ids),s),e))}return[l,d]}}catch(i){return z$1.error(`error creating context from request ${JSON.stringify(n)}`,i),[t,[h(e,r,o,s,J(i,Ue(e)))]]}}function pr(e,t,r,n,i){return W(r)?Ed(e,t,n,i):Ud(e,t,r,n,i)}function Hd(e){switch(e.lifetime){case"ownership":return!e.owner;case"ref-counted":return 0===e.members.size;default:return!1}}function Sn(e,t,r,n){$(se,()=>`[${r.name}#${r.id}] destroyed (reason: ${JSON.stringify(n)})`);let i=r.id,o=r.members;return[rr(t,i),$d(r,ne(t,"context-domain").filter(e=>!o.has(e.id)),n).reduce((e,t)=>e.concat(t),Array.from(o).map(e=>g$2(t,e)).filter(pe).filter(e=>q(e)).map(t=>Rn(e,t.source,t.id,i,n)))]}function Ld(e,t,r,n){let{peer_id:i,name:o}=n;try{let r=_(t,i),n=Qe(t,o,r);return n?(Mo(e,n,r),Sn(e,t,n,hn(e))):(z$1.enabledFor("debug")&&z$1.debug(`unable to find remote context ${o}`),[t,[]])}catch(e){return z$1.enabledFor("debug")&&z$1.debug(`error processing remote destroy ${JSON.stringify(n)}`,e),[t,[]]}}function Fd(e,t,r,n){let{request_id:i,peer_id:o,context_id:s}=n;try{let a=_(t,o),c=Tt(e,t,s);Mo(e,c,a);let l={...n,type:"destroy-context",name:c.name};return ue(t,t=>Sn(e,t,c,hn(e)),t=>[t,[I(e,r,i,o)]],e=>[e,Le(c)?[G(w(A(t.ids),o),l)]:[]])}catch(n){return[t,[h(e,r,i,o,J(n,Ue(e)))]]}}function mr(e,t,r,n){return W(r)?Ld(e,t,r,n):Fd(e,t,r,n)}function Gd(e,t,r){return gn(t).reduce(([t,n],i)=>{let[o,s]=vn(e,t,r,i);return[o,n.concat(s)]},[t,[]])}function vn(e,t,r,n){if(n.members.has(r.id)){let[i,o]=nr(t,n,r.id);return $(se,()=>`[${n.name}#${n.id}] unsubscribed by [${r.identity.application}#${r.id}]`),Hd(o)?Sn(e,i,o,bo(e)):[i,[]]}return[t,[]]}function lr(e,t,r,n,i){let[o,s]=Zt(e,"context-domain",t,r,n,i);$(se,()=>`[${r.identity.application}#${r.id}] removed from context domain (reason: ${JSON.stringify(n)}, source removed: ${i})`);let[a,c]=Gd(e,o,r);return[a,c.concat(s.filter(e=>wn(a,e)))]}function wn(e,t){let r=g$2(e,t.body.peer_id);return!!r&&!r.options?.["context-compatibility-mode?"]}function Jd(e,t,r,n,i){let{request_id:o,identity:s,authentication:a,options:c}=r,l=a?.provider??n.default,u=n.available[l];if(u){let r={requestId:o,remoteIdentity:s,authentication:a,signatureKey:e.signatureKey,clientAuth:t.auth};return u.authenticate(r).then(e=>{let t=e.type;return"success"===e.type?t="internal/authenticated":"continue"===e.type&&(t="internal/authentication-request"),{...e,type:t}}).catch(e=>(ye.debug("authentication request rejected",e),{message:Be(e),...je(e),type:"internal/authentication-failed"})).then(e=>{let r={...e,request_id:o,identity:s};"internal/authenticated"===r.type&&(r.options=c),i({origin:"local",source:t,body:r})}),[e,[]]}return[e,[h(D,t,o,void 0,S(pn,`Requested authentication provider ${l} is not available`))]]}function jd(e,t,r){let{peer_id:n,identity:i,options:o}=r,s=vt(e,r.destination);return s?([e]=sn(e,t,n,i,null,o),ye.enabledFor("info")&&ye.info(`added remote peer ${n} on ${JSON.stringify(t)} with ${JSON.stringify(i)}`),s.handleMessage(e,{origin:"cluster",source:t,body:{...r,type:"domain/join"}})):[e,[]]}function No(e,t,r){let{peer_id:n,request_id:i,destination:o}=r,s=g$2(e,n);if(s?.identity){let a=vt(e,o);if(a){let n={...r,type:"domain/join",identity:s.identity};return a.handleMessage(e,{origin:"local",source:t,body:n})}return[e,[h(D,t,i,n,S(un,`Unable to join missing domain ${o}`))]]}return[e,[h(D,t,i,n,S(mn,`Unable to find peer with id ${n}`))]]}function Bd(e,t,r){return W(t)?jd(e,t,r):No(e,t,r)}function Kd(e,t,r){return No(e,t,r)}function Vd(e,t,r){let{peer_id:n,destination:i}=r;if(g$2(e,n)){let n=vt(e,i);if(n)return n.handleMessage(e,{origin:"local",source:t,body:{...r,type:"domain/leave"}})}return[e,[]]}function zd(e,t,r){let{peer_id:n,request_id:i,destination:o}=r;if(g$2(e,n)){let s=vt(e,o);return s?s.handleMessage(e,{origin:"local",source:t,body:{...r,type:"domain/leave"}}):[e,[h(D,t,i,n,S(un,`Unable to join missing domain ${o}`))]]}return[e,[h(D,t,i,n,S(mn,`Unable to find peer with id ${n}`))]]}function Qd(e,t,r){return W(t)?Vd(e,t,r):zd(e,t,r)}var ye=R("gateway.domains.global");function Yd(e,t,r){ye.enabledFor("debug")&&ye.debug(`removing source ${JSON.stringify(t)} from global domain`);let n=e.ids.nodeId,[i,o]=to(e,t).reduce(([e,i],o)=>(e=no$1(e,o),T(t)&&(ye.enabledFor("info")&&ye.info(`removed peer ${o.id} was on endpoint ${t.endpoint}`),i=i.concat(G(w(n,o.id),r))),[e,i]),[e,[]]);return ye.enabledFor("debug")&&ye.debug(`removed source ${JSON.stringify(t)} from global domain`),[i,o]}function Zd(e,t){return Object.keys(e).filter(t=>"?"===e[t]).reduce((e,r)=>{let n={};return n[r]=t,Object.assign(e,n)},e)}function Xd(e,t){let r=t?.user;return r?{...e,user:r}:e}function eu(e,t,r){let{request_id:n,message:i}=r;return[e,[h(D,t,n,void 0,S(pn,i))]]}function tu(e,t,r){let{request_id:n,authentication:i}=r;return[e,[ao(D,t,n,void 0,i)]]}function ru$1(e,t,r,n){let i=ro(e,r);if(i){let o=g$2(e,i);throw new ve(`peer for ${JSON.stringify(r)} already accepted on source ${JSON.stringify(o?.source)} with id ${i}, ignoring request (with id?: ${n}) on source ${JSON.stringify(t)}`,{uri:dn,message:"Hello already received once",existing:o})}}function nu(e,t,r,n){let{request_id:i,identity:o,user:s,login:a,impersonatePeer:c,gwRequest:l,accessToken:u}=r;l?.id&&(e=tt(e,l.id).state);let d={machine:po(t.host,"127.0.0.1"),...o};if(s&&(d={...d,user:s}),a&&(d={...d,login:a}),c&&(d=Xd(d,c)),!d.instance){let[t,r]=Vi(e.ids);d={...d,instance:r},e={...e,ids:t}}let p={...r.options};"context_compatibility_mode"in p||(p.context_compatibility_mode=n?.contextCompatibility??!0),p["context-compatibility-mode?"]=p.context_compatibility_mode,delete p.context_compatibility_mode;try{ru$1(e,t,d,i),uo(d);let r,[o,s]=Qi(e.ids);d=Zd(d,s),[e,r]=sn({...e,ids:o},t,s,d,l,p),ye.enabledFor("info")&&ye.info(`added local peer ${r.id} on endpoint ${t.endpoint} with ${JSON.stringify(d)}`);let a={};u&&(a.access_token=u),n?.welcomeInfo&&(a.info=n?.welcomeInfo);let c=Object.values(e.registeredDomains??{}).map(e=>e.info),h=so(t,i,r.id,c,d,0===Object.keys(a).length?void 0:a);return ue(e,e=>[e,[h]],e=>p["context-compatibility-mode?"]?Kd(e,t,{request_id:i,peer_id:r.id,identity:d,options:p,destination:se,domain:D}):[e,[]])}catch(r){let n=[],o=je(r);if(ye.warn("authenticated peer not welcomed",r),o?.uri===dn){let e=o.existing;e&&n.push(co(e.source))}return T(t)&&n.push(h(D,t,i,void 0,J(r,cn))),[e,n]}}function iu(e,t,r){return ut(D,e,t,r)}function ou(e,t,r,n){return pr(D,e,t,r,n)}function su(e,t,r){return mr(D,e,t,r)}function au(e,t,r){return ur$1(D,e,t,r)}function cu(e,t,r){return dr(D,e,t,r)}function du(e,t,r,n,i){switch(r.type){case"hello":return Jd(e,t,r,n,e.handler);case"join":return Bd(e,t,r);case"leave":return Qd(e,t,r);case"internal/authenticated":return nu(e,t,r,i);case"internal/authentication-failed":return eu(e,t,r);case"internal/authentication-request":return tu(e,t,r);case"create-context":return ou(e,t,r,i);case"update-context":return iu(e,t,r);case"subscribe-context":return au(e,t,r);case"unsubscribe-context":return cu(e,t,r);case"destroy-context":return su(e,t,r);case"ping":return[e,[]];case"commands/source-removed":return Yd(e,t,r);case"create-token":{let{request_id:n,peer_id:i}=r,o=_(e,i);if(o.identity.user)return[e,[Gi(D,t,n,i,mo(e,{user:o.identity.user}))]];throw V("Cannot create token for peer without user",{})}default:{let n=`Unhandled message ${JSON.stringify(r)}`;return ye.error(n),[e,[h(D,t,r.request_id??-1,r.peer_id,S(oo,n))]]}}}function uu(e,t,r,n){let{source:i,body:o}=t;try{return du(e,i,o,r,n)}catch(t){return[e,[h(D,i,o.request_id??-1,o.peer_id,J(t,cn))]]}}var In=class{constructor(e,t){this.authenticators=e,this.options=t}info(){return{uri:D,description:"",version:2}}init(e){return e}destroy(e){return e}handleMessage(e,t){return uu(e,t,this.authenticators,this.options)}stateToMessages(e,t){return[]}};function qo(e,t){return new In(e,t??{contextCompatibility:!0})}function $o(e,t){let{login:r,secret:n}=e,i=t??r;return i&&(n||""===n)?Promise.resolve({type:"success",user:i,login:r}):Promise.reject(V("Missing login/secret",{type:"failure",message:"Missing login/secret"}))}function Eo(e){if(pu(e))return e.token}function pu(e){return"gateway-token"===e?.method}function Uo(e){return"gateway-client"===e?.method}L();var Ct=class{#e=[];#t;#o=!1;#r=!1;constructor(e=-1){this.#t=e}put(e){return new Promise((t,r)=>{this.#o&&r(new Error("cannot enqueue promise serializer is closed"));let n={action:e,resolve:t,reject:r};this.#t<0||this.#e.lengthnew Promise((t,r)=>{let{authentication:n}=e;Ho.enabledFor("debug")&&Ho.debug(`processing authentication ${JSON.stringify(n,rt("secret","token","providerContext"))}`),this.#o(t,r,e)})),new Promise((e,r)=>{t=setTimeout(()=>{r(new Error("timeout"))},this.#e)})]).finally(()=>clearTimeout(t))}}},Lo={timeout:5e3,max_pending_requests:2e4};function pt$1(e,t){return new Tn(e.timeout??Lo.timeout,e.max_pending_requests??Lo.max_pending_requests,(e,r,n)=>{t.auth(n).then(t=>e(t)).catch(e=>r(e))})}L();var Cn=R("gateway.auth.basic");async function yu({authentication:e},t,r,n,i){switch(e?.method){case"secret":{let o=e.login,s=i?await i(o):o;if(n&&!await n(s,e.secret))throw V("Invalid login/secret",{type:"failure",message:"Invalid login/secret"});let a=await $o(e,s),c=wt({user:a.user,exp:Math.floor((Date.now()+r)/1e3)},t);return{...a,accessToken:c}}case"access-token":try{let r=e.token,n=er(r,t).user;return{type:"success",login:n,user:n,accessToken:r}}catch(e){throw V(`Invalid or expired token:${Be(e)}`,{type:"failure",message:"Invalid or expired token: "+Be(e)},e)}default:{let t=`Unknown authentication method '${e?.method}'`;throw Cn.debug(t),V(t,{type:"failure",message:t})}}}var Mn=class{#e;#t;#o;#r;constructor(e,t,r,n){this.#e=e,this.#t=t,this.#o=r,this.#r=n}auth(e){return yu(e,this.#e,this.#t,this.#o,this.#r)}};function Fo(e){let t=1e3*(e.ttl??6e4),r=e.secretVerifier,n=e.usernameResolver;return Cn.enabledFor("debug")&&Cn.debug(`creating basic authenticator: ttl: ${t}, secret verifier: ${void 0!==r}, username resolver: ${void 0!==n}`),pt$1(e,new Mn(Me(),t,r,n))}var Pn=class{#e;constructor(e,t){this.#e=Z$1({issuerBaseUri:e.issuerBaseURL,audience:e.audience?[e.audience]:[],clockTolerance:3600,timeout:5e3,cacheMaxAge:6e4,...t})}async auth(e){let{method:t,token:r}=e.authentication;if("access-token"!==t)throw new Error("unsupported authentication method");if(!r)throw new Error("missing access token");try{let{payload:e}=await this.#e(r);return{type:"success",user:e.sub}}catch(e){throw new Error("invalid token",{cause:e})}}};function Go(e,t){return pt$1(e,new Pn(e,t))}var Dn=class{authFn;constructor(e){this.authFn=e}async auth(e){return await this.authFn(e)}};function Wo(e,t){return pt$1(e,new Dn(t))}var _n=class{#e;constructor(e){this.#e=e}subscriber(){return(e,t,r)=>{switch(e.type){case"member-added":this.#e?.onMemberAdded?.(t,e.node);break;case"member-removed":this.#e?.onMemberRemoved?.(t,e.node);break;case"message-received":this.#e?.onMessage?.(t,e.message)}}}},On=class{#e;constructor(e){this.#e=e}close(){}register(e,t,r){let n=new _n(r);return this.#e.subscribe(e,n.subscriber())}unregister(e){this.#e.unsubscribe(e)}publish(e,t){let r={type:"publish-message",message:t};this.#e.execute(e,r)}addUsers(e,t){this.#e.execute(e,{type:"add-users",added:t})}removeUsers(e,t){this.#e.execute(e,{type:"remove-users",removed:t})}};function Jo(e){return new On(e)}L();var y="agm",jo=`${y}.errors.failure`,Bo=`${y}.errors.unhandled_message`,Ko=`${y}.errors.unregistration.failure`,mt=`${y}.errors.invocation.failure`,Vo=`${y}.errors.subscription.failure`,Mt=`${y}.errors.subscription.invalid_subscription`,kn=S(`${y}.peer-removed`,"Peer has been removed"),zo=S(`${y}.method-removed`,"Method has been removed"),Qo=S(Mt,"Trying to drop a subscription that wasnt established. Did you mean to return an error instead?");function Ru(e,t,r,n){return{domain:y,type:"methods-added",peer_id:e,source_type:n,server_id:t,methods:r}}function Nn(e,t,r,n,i){return x(e,Ru(t,r,n,i))}function Yo(e,t,r){return{domain:y,type:"register",request_id:e,peer_id:t,methods:r}}function xu(e,t,r){return{domain:y,type:"methods-removed",peer_id:e,server_id:t,methods:r}}function qn(e,t,r,n){return x(e,xu(t,r,n))}function Su(e,t,r,n,i,o,s){return{domain:y,type:"invoke",invocation_id:e,peer_id:t,method_id:r,caller_id:n,arguments:i,arguments_kv:o,context:s}}function Zo(e,t,r,n,i,o,s,a){return x(e,Su(t,r,n,i,o,s,a))}function vu(e,t,r){return{domain:y,type:"result",request_id:e,peer_id:t,result:r}}function Xo(e,t,r,n){return x(e,vu(t,r,n))}function wu(e,t,r,n,i,o,s,a){return{domain:y,type:"add-interest",subscription_id:e,peer_id:t,method_id:r,caller_id:n,arguments:i,arguments_kv:o,flags:s,context:a}}function es$1(e,t,r,n,i,o,s,a,c){return x(e,wu(t,r,n,i,o,s,a,c))}function Iu(e,t,r,n,i){return{domain:y,type:"remove-interest",subscription_id:e,peer_id:t,method_id:r,caller_id:n,reason_uri:i.uri,reason:i.message}}function $n(e,t,r,n,i,o){return x(e,Iu(t,r,n,i,o))}function Tu(e,t,r){return{domain:y,type:"subscribed",request_id:e,peer_id:t,subscription_id:r}}function ts(e,t,r,n){return x(e,Tu(t,r,n))}function Au(e,t,r,n,i,o){return{domain:y,type:"event",peer_id:e,subscription_id:t,oob:r,sequence:n,snapshot:i,data:o}}function En(e,t,r,n,i,o,s){return x(e,Au(t,r,n,i,o,s))}function Cu(e,t,r){return{domain:y,type:"subscription-cancelled",subscription_id:e,peer_id:t,reason_uri:r.uri,reason:r.message}}function Un(e,t,r,n){return x(e,Cu(t,r,n))}function yr(e,t,r){let{server_id:n,method_id:i,arguments:o,arguments_kv:s}=r;e.id!==t.id&&!it$1("agm-domain",e,t)&&k(mt,"Unable to invoke methods across different users"),e["agm-domain"].methods?.[n]?.[i]||k(mt,`Unable to find method with id ${i} on server id ${n} registered with this peer`),o&&s&&k(mt,"Cant use positional and by-name arguments at the same time")}function Mu(e,t,r){let{request_id:n,peer_id:i,server_id:o,invocation_id:s,method_id:a,arguments:c,arguments_kv:l,context:u}=t;r=produce(r,e=>{let t=e["agm-domain"];t.invocations=t.invocations||{},t.invocations[s]={caller:i,method_id:a,request_id:n}});let d=!q(r);return[C(e,o,r),d?[K(w(A(e.ids),i),_e(r.source.node),{domain:y,type:"call",...t})]:[Zo(r.source,s,o,a,i,c,l,u)]]}function ns(e,t,r,n,i){let{request_id:o,peer_id:s,server_id:a,method_id:c}=t;return $(y,()=>{let e=i["agm-domain"]?.methods?.[n.id]?.[c]?.name;return`[${i.identity.application}#${i.id}] called method [${n.identity.application}#${n.id}:${e}#${c}] (request: ${o})`}),i=produce(i,e=>{let t=e["agm-domain"];t.calls=t.calls||{},t.calls[o]={callee:a,method_id:c,invocation_id:r}}),Mu(C(e,s,i),{...t,invocation_id:r},s===a?i:n)}function Pu(e,t,r){let{request_id:n,peer_id:i,server_id:o,invocation_id:s}=r,a=B(e,o,"agm-domain");return q(a)?ns(e,r,s,a,b(e,i,"agm-domain")):[e,[]]}function Du(e,t,r){let{peer_id:n,server_id:i}=r,o=b(e,i,"agm-domain"),s=b(e,n,"agm-domain"),[a,c]=Pe(e.ids);return yr(s,o,r),ns({...e,ids:a},r,c,o,s)}function is$2(e,t,r){return W(t)?Pu(e,t,r):Du(e,t,r)}function os(e,t,r,n){let i=n.id,[o,s]=Object.entries(r["agm-domain"]?.calls??{}).reduce(([e,t],[r,n])=>((n.callee===i?e:t).push([r,n]),[e,t]),[new Array,new Array]);return o.length>0?[Ee(e,r.id,e=>{let t=e["agm-domain"];s.length>0?t.calls=s.reduce((e,[t,r])=>(e=produce(e,e=>{e[t]=r}),e),{}):delete t.calls}),q(r)?o.map(function([e]){return h(y,t,e,r.id,S(mt,"Peer has left while waiting for result"))}):[]]:[e,[]]}function _u(e,t,r,n,i){let{request_id:o,caller:s,method_id:a}=r,c=g$2(e,s);if(c&&(c=produce(c,e=>{e["agm-domain"]&&e["agm-domain"].calls&&(delete e["agm-domain"].calls[o],0===Object.keys(e["agm-domain"].calls).length&&delete e["agm-domain"].calls)})),c){let r=g$2(e=C(e,s,c),t);r?.["agm-domain"]?.methods?.[t][a];let l=i.success,u=i.failure;return q(c)?l?($(y,()=>{let e=c?.["agm-domain"]?.methods?.[t]?.[a]?.name;return`[${c?.identity?.application}#${s}] received success for [${r?.identity.application}#${t}:${e}#${a}] (request: ${o})`}),[e,[Xo(c.source,o,s,l.result)]]):($(y,()=>{let e=c?.["agm-domain"]?.methods?.[t]?.[a]?.name;return`[${c?.identity?.application}#${s}] received failure for [${r?.identity.application}#${t}:${e}#${a}] (request: ${o})`}),[e,[h(y,c.source,o,s,Q(u),u.context)]]):[e,[K(w(A(e.ids),t),_e(c.source.node),n)]]}return[e,[]]}function Hn(e,t,r,n,i){let o=g$2(e,r),s=o?.["agm-domain"]?.invocations?.[t];if(s)return e=C(e,r,produce(o,e=>{e["agm-domain"]?.invocations&&(delete e["agm-domain"].invocations[t],0===Object.keys(e["agm-domain"].invocations).length&&delete e["agm-domain"].invocations)})),_u(e,r,s,n,i)}function ss(e,t,r){let{invocation_id:n,peer_id:i}=r;return b(e,i,"agm-domain"),Hn(e,n,i,r,{success:r})??[e,[]]}function Ou(e,t,r){return ss(e,t,r)}function ku(e,t,r){return ss(e,t,r)}function as(e,t,r){return T(t)?ku(e,t,r):Ou(e,t,r)}function cs$1(e,{parsedRestrictions:t}){return ee(t,[{type:"local"===e.source.type?"local":"cluster"},e.identity],[{type:"cluster"},void 0])}function ds(e,t,r,n,i){let{server:o,stream:s,method_id:a}=r,c=produce(_(e,o),Fn(t,n,s));return e=C(e,o,c),q(c)?[e,[$n(c.source,t,o,a,n,i)]]:[e,[]]}function us(e,t,r){let n=t["agm-domain"]?.subscriptions,i=t.id,[o,s]=Object.entries(n||{}).reduce(([e,t],[n,o])=>{let[s,a]=ds(e,n,o,i,r);return[s,t.concat(a)]},[e,[]]);return[o,s]}function Nu(e,t,r){return Object.entries(e).reduce((e,[n,i])=>(t!==i.server||r&&0!==r.size&&!r.has(i.method_id)?e.remaining[n]=i:e.removed[n]=i,e),{removed:{},remaining:{}})}function fr$1(e,t,r,n,i){let o=r.id,{removed:s,remaining:a}=Nu(t["agm-domain"]?.subscriptions||{},o,n),c=Object.entries(s).reduce((r,[n,o])=>{let s;return[e,s]=ds(e,n,o,t.id,i),e},e);return Object.keys(s).length>0?[Ee(c,t.id,e=>{Object.keys(a).length>0?e["agm-domain"].subscriptions=a:e["agm-domain"]&&delete e["agm-domain"].subscriptions}),T(t.source)?Object.keys(s).map(e=>Un(t.source,e,t.id,i)):[]]:[e,[]]}function qu(e,t,r){let{peer_id:n,server_id:i,subscriptionId:o,method_id:s,arguments:a,arguments_kv:c,context:l,flags:u}=r,d=g$2(t,i);if(d){d=produce(d,e=>{e["agm-domain"].interests=e["agm-domain"].interests||{},e["agm-domain"].interests[o]={subscriber:n,method_id:s}});let e=d.source;return d["agm-domain"].methods[i][s],[C(t,i,d),T(e)?[es$1(e,o,i,s,n,a,c,u,l)]:[K(w(A(t.ids),n),_e(e.node),r)]]}throw V(`unable to find server with id ${i}`,{})}function ps$1(e,t,r){let{request_id:n,peer_id:i,server_id:o,method_id:s}=t,a=produce(b(e,i,"agm-domain"),e=>{e["agm-domain"].subscriptions=e["agm-domain"].subscriptions||{},e["agm-domain"].subscriptions[r]={server:o,method_id:s,request_id:n}}),c=b(e,o,"agm-domain");yr(a,c,t),$(y,()=>`[${a.identity.application}#${a.id}] subscribed for [${c.identity.application}#${c.id}:${c["agm-domain"].methods?.[c.id]?.[s]?.name}#${s}] (subscription: ${r}, request: ${n})`);let l={...t,subscriptionId:r};return qu(a,C(e,i,a),l)}function $u(e,t,r){let[n,i]=Pe(e.ids);return ps$1({...e,ids:n},r,i)}function Eu(e,t){let{subscriptionId:r,server_id:n}=t;return g$2(e,n)?ps$1(e,t,r):[e,[]]}function ms$1(e,t,r){return T(t)?$u(e,t,r):Eu(e,r)}function ls(e,t,r,n,i,o,s){if(t){let a=t["agm-domain"]?.subscriptions?.[n]?.request_id,c=t.source;return $(y,()=>{let e=t["agm-domain"].subscriptions[n];return`[${t.identity.application}#${r}] dropped/rejected [${t["agm-domain"]?.methods?.[e.server][e.method_id].name}] (subscription: ${n}, stream ${e.stream}, request: ${a}, error?: ${s})`}),[C(e,r,produce(t,e=>{let t=e["agm-domain"];t.subscriptions&&(delete t.subscriptions[n],0===Object.keys(t.subscriptions).length&&delete t.subscriptions)})),T(c)?s?[h(y,c,a,r,i,o)]:[Un(c,n,r,i)]:[]]}return[e,[]]}me(),L();var Ln=R("gateway.domains.agm.subscriptions");function Uu(e,t,r,n,i,o){let s=g$2(e,t);if(s){let a=s["agm-domain"]?.subscriptions?.[r]?.request_id;e=C(e,t,produce(s,e=>{e["agm-domain"].subscriptions[r].stream=n}));let c=s.source;return $(y,()=>{let e=s["agm-domain"].subscriptions[r],i=e.method_id,c=s["agm-domain"]?.methods?.[e.server][i].name;return`[${s.identity.application}#${t}] accepted on ${n} for [${o.identity.application}#${e.server}:${c}#${i}] (subscription: ${r}, request: ${a})`}),q(s)?[e,[ts(c,a,t,r)]]:[e,[K(w(A(e.ids),i.peer_id),_e(c.node),i)]]}return[e,[]]}function ys(e,t,r){let{subscription_id:n,peer_id:i,stream_id:o}=r;o||k(Mt,"Invalid or missing stream id");let s=t["agm-domain"].interests?.[n];if(s){let a=s.subscriber;return e=C(e,i,produce(t,e=>{let t=e["agm-domain"];t.interests=t.interests||{},t.interests[n]=t.interests[n]||{},t.interests[n].stream=o,t.streams=t.streams||{},t.streams[o]=t.streams[o]||{},t.streams[o][a]=t.streams[o][a]||new Set,t.streams[o][a].add(n)})),Uu(e,a,n,o,r,t)}return Ln.enabledFor("debug")&&Ln.debug(`Subscription accept response ${JSON.stringify(r)} for missing interest`),[e,[]]}function Hu(e,t){let{subscription_id:r,peer_id:n,subscriber_id:i}=t,o=B(e,n,"agm-domain");return o?ys(e,o,t):(Ln.warn(`Subscription accept response ${JSON.stringify(t)} from missing peer`),ls(e,g$2(e,i),i,r,S(Vo,"Received a response from a missing server"),null,!0))}function Lu(e,t,r){let{subscription_id:n,peer_id:i}=r;return ys(e,b(e,i,"agm-domain"),r)}function fs(e,t,r){return T(t)?Lu(e,t,r):Hu(e,r)}function Fn(e,t,r){return n=>{let i=n["agm-domain"];i&&(i.interests&&(delete i.interests[e],0===Object.keys(i.interests).length&&delete i.interests),r&&i.streams&&(i.streams[r][t].delete(e),0===i.streams[r][t].size&&(delete i.streams[r][t],0===Object.keys(i.streams[r]).length&&(delete i.streams[r],0===Object.keys(i.streams).length&&delete i.streams))))}}function Gn(e,t,r,n){let i=r.peer_id,o=n?r.request_id:r.subscription_id,s=b(e,i,"agm-domain"),a=s["agm-domain"].interests?.[o];if(a){let c=a.subscriber,l=a.stream,u=g$2(e,c),d=u.source;if(l||n){let t;return e=C(e,i,produce(s,Fn(o,c,l))),[e,t]=ls(e,u,c,o,Q(r),r.context,n),u&&!T(d)&&(t=t.concat(K(w(A(e.ids),i),_e(d.node),r))),[e,t]}return[e,[h(y,t,o,i,Qo)]]}return[e,[h(y,t,o,i,S(Mt,"Trying to drop a non-existing subscription"))]]}function Fu(e,t,r,n,i){let o=g$2(e,r);if(o){let s=o["agm-domain"]?.interests?.[n];if(s){let a=t.id,c=o.source;return[e=C(e,r,produce(o,Fn(n,a,s.stream))),[T(c)?$n(c,n,r,s.method_id,a,Q(i)):K(w(A(e.ids),a),_e(c.node),i)]]}}}function gs(e,t,r,n,i){let o=b(e,r,"agm-domain"),s=o["agm-domain"].subscriptions?.[n];return s?.server||k(Mt,`Unable to find subscription with id ${n} on subscriber id ${r}`),$(y,()=>{let e=o["agm-domain"].methods?.[s.server]?.[s.method_id]?.name;return`[${o.identity.application}#${o.id}] unsubscribed [#${s.server}:${e}#${s.method_id}] (subscription: ${n}, request: ${i})`}),e=C(e,r,produce(o,e=>{let t=e["agm-domain"];t.subscriptions&&(delete t.subscriptions[n],0===Object.keys(t.subscriptions).length&&delete t.subscriptions)})),Fu(e,o,s.server,n,t)||[e,[]]}function Gu(e,t){let{request_id:r,peer_id:n,subscription_id:i}=t;return gs(e,t,n,i,r)}function Wu(e,t,r){let n,{request_id:i,peer_id:o,subscription_id:s}=r;return[e,n]=gs(e,r,o,s,i),[e,n.concat(I(y,t,i,o))]}function hs(e,t,r){return T(t)?Wu(e,t,r):Gu(e,r)}function bs(e,t,r){let{peer_id:n,stream_id:i,sequence:o,snapshot:s,data:a}=r,c=B(e,n,"agm-domain")?.["agm-domain"].streams?.[i]||{},l=new Set;return[e,Object.entries(c).flatMap(([t,i])=>{let c=g$2(e,t).source,u=[];if(T(c))u=Array.from(i,e=>En(c,t,e,!1,o,s,a));else{let t=c.node;l.has(t)||(l.add(t),u=[K(w(A(e.ids),n),_e(t),r)])}return u})]}function Rs(e,t,r){let{peer_id:n,subscription_id:i,sequence:o,snapshot:s,data:a}=r,c=B(e,n,"agm-domain")?.["agm-domain"].interests?.[i].subscriber,l=B(e,c,"agm-domain"),u=l?.source;if(u){let t;if(q(l))t=[En(u,c,i,!0,o,s,a)];else{let i={type:"node",node:u.node};t=[K(w(A(e.ids),n),i,r)]}return[e,t]}return[e,[]]}function Ju(e){let t=X(e.restrictions);return t?{...e,parsedRestrictions:t}:e}function ju(e){let t={...e};return delete t.parsedRestrictions,t}function Bu(e,t,r){let n=e.parsedRestrictions;return!n||ee(n,t,r)}function Jn(e,t,r,n,i){let o=t.id,s=n.id,a=n["agm-domain"]?.methods?.[t.id]||{},[c,l]=r.filter(q(t)?e=>!0:_t(n,i?.defaultMethodRestrictions)).filter(e=>Bu(e,[t.source,t.identity],[n.source,n.identity])).reduce(([e,t],r)=>(e=produce(e,e=>{e[r.id]=castDraft(r)}),[e,t.concat(ju(r))]),[a,new Array]);return l.length>0?(n=produce(n,e=>{e["agm-domain"].methods=e["agm-domain"].methods||{},e["agm-domain"].methods[o]=castDraft(c)}),[C(e,s,n),q(n)?Nn(n.source,s,o,l,t.source.type):[]]):[e,[]]}function xs(e,t,r,n){let i=t.id,o=r.map(e=>Ju(e));t=o.reduce((e,t)=>produce(e,e=>{e["agm-domain"].methods=e["agm-domain"].methods||{},e["agm-domain"].methods[i]=e["agm-domain"].methods[i]||{},e["agm-domain"].methods[i][t.id]=castDraft(t)}),t);let s=C(e,i,t);return $(y,()=>`[${t.identity.application}#${t.id}] registered method(s) [${o.map(e=>`${e.name}#${e.id}`).join(", ")}]`),ie(e,"agm-domain",t).reduce(([e,r],i)=>{let[s,a]=Jn(e,t,o,i,n);return[s,r.concat(a)]},[s,[]])}function Ku(e,t,r,n){let{peer_id:i,methods:o}=r,s=B(e,i,"agm-domain");return void 0!==s&&void 0!==o?xs(e,s,o,n):[e,[]]}function _t(e,t){return r=>{if((void 0===r.restrictions||null===r.restrictions)&&void 0!==t){let n=t.call(e.identity,r.name);return cs$1(e,{parsedRestrictions:n})}return!0}}function Vu(e,t,r,n){let{request_id:i,peer_id:o,methods:s}=r,a=b(e,o,"agm-domain"),[c,l]=xs(e,a,s,n);if(l=l.concat([Nn(t,o,o,s,"local"),I(y,t,i,o)]),re("agm-domain",a)){let t=s.filter(_t(a,n?.defaultMethodRestrictions));if(t.length>0){let n={...r,methods:t};l=l.concat([G(w(A(e.ids),o),n)])}}return[c,l]}function Ss(e,t,r,n){return W(t)?Ku(e,t,r,n):Vu(e,t,r,n)}function jn(e,t,r,n){if(!n&&(!(n=Object.keys(r["agm-domain"]?.methods?.[t]??{}))||0==n.length))return[Ee(e,r.id,e=>{let r=e["agm-domain"];r.methods&&(delete r.methods[t],0===Object.keys(r.methods).length&&delete r.methods)}),[]];let i;if([r,i]=n.reduce(([e,r],n)=>(e["agm-domain"]?.methods?.[t]?.[n]&&(e=produce(e,e=>{let r=e["agm-domain"]?.methods;r?.[t]?.[n]&&(delete r[t][n],0===Object.keys(r[t]).length&&delete r[t],0===Object.keys(r).length&&delete e["agm-domain"]?.methods)}),r.add(n)),[e,r]),[r,new Set]),e=C(e,r.id,nn(r,"agm-domain")),0==i.size)return[e,[]];{let n,o=_(e,t);return[e,n]=fr$1(e,r,o,i,zo),q(r)&&(n=n.concat(qn(r.source,r.id,t,Array.from(i)))),[e,n]}}function vs(e,t,r){let n=t.id,i=nn(r.reduce((e,t)=>(e["agm-domain"].methods?.[n][t]?e=produce(e,e=>{e["agm-domain"].methods[n]=e["agm-domain"].methods[n]||{},delete e["agm-domain"].methods[n][t],0===Object.keys(e["agm-domain"].methods[n]).length&&delete e["agm-domain"].methods[n],0===Object.keys(e["agm-domain"].methods).length&&delete e["agm-domain"].methods}):k(Ko,`Unable to unregister missing method ${t}`),e),t),"agm-domain"),[o,s]=[C(e,n,i),new Array];return[o,s]=ie(e,"agm-domain",i).filter(e=>e.id!==n).reduce(([e,t],i)=>{let[o,s]=jn(e,n,i,r);return[o,t.concat(s)]},[o,new Array]),$(y,()=>`[${t.identity.application}#${n}] unregistered method(s) [${r.map(e=>`${t["agm-domain"].methods?.[n]?.[e]?.name}#${e}`).join(", ")}]`),[o,s]}function zu(e,t){let{peer_id:r,methods:n}=t,i=B(e,r,"agm-domain");return i?vs(e,i,n):[e,[]]}function Qu(e,t,r,n){let{request_id:i,peer_id:o,methods:s}=r,a=b(e,o,"agm-domain"),[c,l]=vs(e,a,s);if(l=l.concat([qn(t,o,o,s),I(y,t,i,o)]),re("agm-domain",a)){let t=a["agm-domain"].methods?.[o]??{},i=s.map(e=>t[e]).filter(_t(a,n?.defaultMethodRestrictions)).map(e=>e.id);if(i.length>0){let t={...r,methods:i};l=l.concat([G(w(A(e.ids),o),t)])}}return[c,l]}function ws(e,t,r){return W(t)?zu(e,r):Qu(e,t,r)}var Ot=R("gateway.domains.agm");function Yu(e,t,r,n,i){let o,{identity:s,id:a}=n,c=Object.values(n["agm-domain"]?.methods?.[a]||{}),l=r.id,u=q(r),d=q(n),h=new Array;return u&&h.push(qe(y,t,l,a,s,{local:d})),d&&h.push(qe(y,n.source,a,l,r.identity,{local:u})),[e,o]=Jn(e,n,c,r,i),[e,h.concat(o)]}function Zu(e,t,r,n){return ie(e,"agm-domain",b(e,r,"agm-domain")).reduce(([e,i],o)=>{let[s,a]=Yu(e,t,b(e,r,"agm-domain"),o,n);return[s,i.concat(a)]},[e,[]])}function Is(e,t,r,n,i,o){return $(y,()=>`[${n.application}#${r}](by ${n.user??""}) added to agm domain (restrictions: ${i?JSON.stringify(i):""})`),Zu(e=he$1(e,r,"agm-domain",i),t,r,o)}function Xu(e,t,r,n){let{peer_id:i,identity:o,restrictions:s}=r;return de$1(e,i,"agm-domain")?[e,[]]:Is(e,t,i,o,s)}function ep(e,t,r,n){let{peer_id:i,request_id:o,identity:s,restrictions:a}=r;if(de$1(e,i,"agm-domain"))return[e,[I(y,t,o,i)]];{let c,l=X(a)??n?.defaultPeerRestrictions;[e,c]=Is(e,t,i,s,l,n),c=c.concat([I(y,t,o,i)]);let u=b(e,i,"agm-domain");if(re("agm-domain",u)){let t={...r,type:"join",restrictions:u["agm-domain"].restrictions};u.options&&(t.options=u.options),c=c.concat([G(w(A(e.ids),i),t)])}return[e,c]}}function tp(e,t,r,n){return W(t)?Xu(e,t,r):ep(e,t,r,n)}function rp(e,t,r,n){let i,o=_(e,r),s=o.source;return[e,i]=ue(e,e=>os(e,s,o,t),e=>fr$1(e,o,t,void 0,kn),e=>jn(e,t.id,_(e,o.id))),[e,T(s)?i.concat(Je(y,s,r,t.id,n)):i]}function Kn(e,t,r){let[n,i]=ie(e,"agm-domain",t).map(e=>e.id).reduce(([e,n],i)=>{let[o,s]=rp(e,t,i,r);return[o,n.concat(s)]},us(e,t,r));return $(y,()=>`[${t.identity.application}#${t.id}] removed from agm domain (reason: ${JSON.stringify(r)})`),[te(n,t.id,"agm-domain"),i]}function np(e,t,r){let{peer_id:n}=r,i=B(e,n,"agm-domain");return i?Kn(e,i,Q(r)):[e,[]]}function ip(e,t,r){let{request_id:n,peer_id:i}=r,o=b(e,i,"agm-domain"),[s,a]=Kn(e,o,Q(r)),c=a.concat(I(y,t,n,i));return re("agm-domain",o)&&(c=c.concat([G(w(A(e.ids),i),{...r,type:"leave"})])),[s,c]}function op(e,t,r){return W(t)?np(e,t,r):ip(e,t,r)}function sp(e,t,r){Ot.enabledFor("debug")&&Ot.debug(`removing source ${JSON.stringify(t)} from agm domain`);let n=Te(e,t,"agm-domain"),i=n.map(e=>e.id).reduce((e,t)=>te(e,t,"agm-domain"),e),o=n.reduce(([e,t],r)=>{let[n,i]=Kn(e,r,kn);return[n,t.concat(i)]},[i,[]]);return Ot.enabledFor("debug")&&Ot.debug(`removed source ${JSON.stringify(t)} from agm domain`),o}function ap(e,t,r){let{request_id:n,peer_id:i}=r;return _(e,i),Hn(e,n,i,r,{failure:r})||Gn(e,t,r,!0)}function cp(e,t,r,n){switch(r.type){case"domain/join":return tp(e,t,r,n);case"domain/leave":return op(e,t,r);case"register":return Ss(e,t,r,n);case"unregister":return ws(e,t,r);case"call":return is$2(e,t,r);case"yield":return as(e,t,r);case"subscribe":return ms$1(e,t,r);case"unsubscribe":return hs(e,t,r);case"drop-subscription":return Gn(e,t,r,!1);case"accepted":return fs(e,t,r);case"publish":return bs(e,t,r);case"post":return Rs(e,t,r);case"error":return ap(e,t,r);case"commands/source-removed":return sp(e,t);default:return Ot.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h(y,t,r.request_id??-1,r.peer_id,S(Bo,`Unhandled message ${JSON.stringify(r)}`))]]}}var Bn=class{constructor(e){this.options=e}info(){return{uri:y,description:"",version:1}}init(e){return e}destroy(e){return e}handleMessage(e,t){let{source:r,body:n}=t;try{return cp(e,r,n,this.options)}catch(t){return T(r)?[e,[h(y,r,n.request_id,n.peer_id,J(t,jo))]]:[e,[]]}}stateToMessages(e,t){let r=e.ids.nodeId;return ne(e,"agm-domain").filter(e=>T(e.source)&&re("agm-domain",e)).flatMap(e=>{let n=e.id,i=[st(void 0,n,e["agm-domain"].restrictions,y,e.identity,e.options)],o=Object.values(e["agm-domain"].methods?.[n]??{}).filter(_t(e,this.options?.defaultMethodRestrictions));return o.length>0&&i.push(Yo(void 0,n,o)),i.map(e=>K(w(r,n),t,e))})}};function Ts(e){return new Bn(e)}var v="activity",As=`${v}.errors.failure`,Vn=`${v}.errors.registration.failure`,Cs=`${v}.errors.missing_factory`,Ms=`${v}.errors.factory_already_registered`,Ps=`${v}.errors.owner_creation`,Ds=`${v}.errors.missing_type`,_s=`${v}.errors.invalid_activity`,zn=`${v}.errors.activity_is_child`,Os=`${v}.errors.invalid_peer`,ks=`${v}.errors.not_authorized`,Ns=`${v}.errors.unhandled_message`,qs=S(`${v}.peer-removed`,"Peer has been removed"),$s=S(`${v}.destroyed`,"Activity destroyed");L();var P="activity-domain";function Es(e,t,r){return t.reduce((e,t)=>produce(e,e=>{e.factories||(e.factories={}),e.factories[t]||(e.factories[t]=[]),e.factories[t].push(r)}),e)}function Qn(e,t,r){return t.length>0&&r?t.reduce((e,t)=>produce(e,e=>{e.factories&&(e.factories[t]=Zi(r,e.factories[t]),0==e.factories[t].length&&delete e.factories[t],0===Object.keys(e.factories).length&&delete e.factories)}),e):e}function Us(e){return e.factories}function Hs(e,t){return e.factories?.[t]}function lt(e,t){if(t)return e.activities?.[t]}function yt(e,t,r){return t?produce(e,e=>{e.activities=e.activities||{},e.activities[t]=r}):e}function Ls(e,t){return produce(e,e=>{e.activities&&(delete e.activities[t],0===Object.keys(e.activities).length&&delete e.activities)})}function Fs(e){return Object.values(e.activities??{})}function gr(e,t){if(t)return e.activityTypes?.[t]}function Gs(e,t,r){return r.reduce((e,r)=>produce(e,e=>{e.activityTypes=e.activityTypes||{},e.activityTypes[t]=e.activityTypes[t]||{},e.activityTypes[t][r.name]=castDraft(r)}),e)}function Ws(e,t,r){return Array.from(r).reduce((e,r)=>produce(e,e=>{e.activityTypes&&(e.activityTypes[t]&&(delete e.activityTypes[t][r],0===Object.keys(e.activityTypes[t]).length&&delete e.activityTypes[t]),0===Object.keys(e.activityTypes).length&&delete e.activityTypes)}),e)}function Yn(e,t){let r=new Set;return e.activitySubscribers?.byType?.[t].forEach(r.add),e.activitySubscribers?.all?.forEach(r.add),r}function Js(e,t,r){return produce(e,e=>{e.activitySubscribers=e.activitySubscribers||{},!0===r?(e.activitySubscribers.all=e.activitySubscribers.all||new Set,e.activitySubscribers.all.add(t)):(e.activitySubscribers.byType=e.activitySubscribers.byType||{},e.activitySubscribers.byType[r]=e.activitySubscribers.byType[r]||new Set,e.activitySubscribers.byType[r].add(t))})}function js(e,t,r){return produce(e,e=>{e.activitySubscribers&&(!0===r?e.activitySubscribers.all&&(e.activitySubscribers.all.delete(t),0===e.activitySubscribers.all.size&&delete e.activitySubscribers.all):e.activitySubscribers.byType&&(e.activitySubscribers.byType[r]&&(e.activitySubscribers.byType[r].delete(t),0===e.activitySubscribers.byType[r].size&&delete e.activitySubscribers.byType[r]),0===Object.keys(e.activitySubscribers.byType).length&&delete e.activitySubscribers.byType),0===Object.keys(e.activitySubscribers).length&&delete e.activitySubscribers)})}function ft(e,t){let r=lt(e,t);if(r)return r;k(_s,`Unable to find activity with id ${t}`)}function Bs(e,t){if(t)return ft(e,t)}function mp(e,t,r){return{domain:v,type:"peer-factories-added",peer_id:e,owner_id:t,factories:r}}function Zn(e,t,r,n){return x(e,mp(t,r,n))}function lp(e,t,r){return{domain:v,type:"peer-factories-removed",peer_id:e,owner_id:t,factory_ids:r}}function Vs(e,t,r,n){return x(e,lp(t,r,n))}function yp(e,t,r,n,i,o){return{domain:v,type:"peer-requested",request_id:e,peer_id:t,peer_factory:r,gateway_token:n,configuration:i,...o}}function zs(e,t,r,n,i,o,s){return x(e,yp(t,r,n,i,o,s))}function Xn(e,t,r,n){return x(e,{domain:v,type:"dispose-peer",peer_id:t,requestor_id:r,reason_uri:n.uri,reason:n.message})}function fp(e,t,r){return{domain:v,type:"peer-created",request_id:e,peer_id:t,created_id:r}}function Qs(e,t,r,n){return x(e,fp(t,r,n))}function ei(e,t,r){return x(e,{domain:v,type:"types-added",peer_id:t,types:r})}function Ys(e,t,r){return x(e,{domain:v,type:"types-removed",peer_id:t,types:r})}function Zs(e,t,r,n){return x(e,{domain:v,type:"initiated",request_id:t,peer_id:r,activity_id:n})}function ti(e){return Object.entries(e).reduce((e,[t,r])=>(e[t]=produce(r,e=>{e.context=e.context.data,e.children&&(e.children=ti(e.children))}),e),{})}function hr(e,t){let r=g$2(e,t);return{peer_id:t,name:r?.peerName,type:r?.peerType}}function gp(e,t,r,n){let i=r.children,o=t.peerName,s=t.peerType,a={domain:v,type:"joined",peer_id:t.id,activity_id:r.id,activity_type:r.type,initiator:r.initiator,context_id:r.contextId,owner:hr(e,r.owner),participants:Array.from(r.readyMembers||[]).map(t=>hr(e,t)),context_snapshot:n};return o&&(a.peer_name=o),s&&(a.peer_type=s),i&&(a.children=ti(i)),a}function br(e,t,r,n,i){return x(t,gp(e,r,n,i))}function hp(e,t,r){let n=t.peerName,i={domain:v,type:"activity-joined",peer_id:e,activity_id:r,joined_id:t.id,joined_type:t.peerType};return n&&(i.peer_name=n),i}function Xs(e,t,r,n){return x(e,hp(t,r,n))}function bp(e,t,r){let n=r.children,i={domain:v,type:"created",peer_id:t,activity_id:r.id,context_id:r.contextId,owner:hr(e,r.owner),participants:Array.from(r.readyMembers||[]).concat(Array.from(r.participants||[])).map(t=>hr(e,t)),activity_type:r.type,initiator:r.initiator};return n&&(i.children=ti(n)),i}function ri(e,t,r,n){return x(t,bp(e,r,n))}function ea(e,t,r,n,i){return x(e,{domain:v,type:"left",peer_id:t,activity_id:n,left_id:r,reason_uri:i.uri,reason:i.message})}function Rp(e,t,r){let n=r.peerName,i=r.peerType,o={domain:v,type:"owner-changed",peer_id:e,activity_id:t,owner_id:r.id};return n&&(o.peer_name=n),i&&(o.peer_type=i),o}function ta$1(e,t,r,n){return x(e,Rp(t,r,n))}function Ye(e,t,r){return I(v,e,t,r)}function kt(e,t,r,n,i){return h(v,e,t,r,n,i)}function ra(e,t,r,n){let i={type:"activity",id:e,peer_type:t.type,activity:{id:r.id,"owner?":n}};return t.name&&(i.peer_name=t.name),i}function na(e,t,r,n){let i={type:"create-peer",id:e,peer_type:t,clientRequest:n};return r&&(i.peer_name=r),i}function Sp(e,t,r){let n=r.reduce((e,t)=>(e[t.peer_type]?e[t.peer_type].push(t):e[t.peer_type]=[t],e),{});return e=C(e,t.id,produce(t,e=>{e[P].factories=e[P].factories||{};for(let[t,r]of Object.entries(n))e[P].factories[t]=r[0]})),e=Es(e,Object.keys(n),t.id)}function vp(e,t,r){return ie(e,P,t).map(e=>Zn(e.source,e.id,t.id,r))}function oa(e,t){return Array.from(new Set(Object.values(Us(e)||{}).flat(1))).map(t=>B(e,t,"activity-domain")).filter(e=>!!e).filter(e=>it$1("activity-domain",t,e)).map(e=>{let r=e["activity-domain"].factories;if(r)return Zn(t.source,t.id,e.id,Object.values(r))}).filter(pe)}function wp(e,t){let r=t.peer_type;e[P]?.factories?.[r]&&k(Ms,`Factory for type ${r} is already registered by this peer`)}function sa(e,t,r){let{request_id:n,peer_id:i,factories:o}=r,s=b(e,i,"activity-domain");o.forEach(e=>wp(s,e));let a=Sp(e,s,o);return[a,vp(a,s,o).concat(I(v,t,n,i))]}function aa(e,t,r,n){let i=t.id;return ie(e,P,t).filter(e=>n||i!==e.id).map(e=>Vs(e.source,e.id,t.id,r))}function Ip(e,t){return Object.values(e||{}).find(e=>e.id===t)}function Tp(e,t){let r=e[P]?.factories,[n,i]=t.reduce(([e,t],n)=>{let i=Ip(r,n);return i?[produce(e,e=>{e[P]?.factories&&(delete e[P]?.factories?.[i.peer_type],0===Object.keys(e[P]?.factories).length&&delete e[P]?.factories)}),t.concat(i)]:[e,t]},[e,[]]);return[n,i]}function ca$1(e,t,r){let{request_id:n,peer_id:i,factory_ids:o}=r,s=b(e,i,"activity-domain"),[a,c]=Tp(s,o),l=Qn(C(e,i,a),c.map(e=>e.peer_type),i),u=aa(l,s,c.map(e=>e.id),!0);return u=u.concat([I(v,t,n,i)]),[l,u]}function da$1(e,t,r,n,i,o,s,a,c){let l={};return s&&(l.activity={id:s.id,type:s.type,context_id:a?.id,"initial-context":a?.data}),c&&(l.peer_name=c),zs(t.source,o,t.id,r.id,i,{...r.configuration,...n},l)}function ua$1(e,t){let r=t.creationRequest?.clientRequest;r||k(Os,`Unable to find originating request for a ready message from peer ${t.id}`);let n=r.peer_id;return[e,[Qs(g$2(e,n).source,r.request_id,n,t.id)]]}function pa(e,t){let r=Object.values(t[P]?.factories||{});return r?[Qn(e,r.map(e=>e.peer_type),t.id),aa(e,t,r.map(e=>e.id),!1)]:[e,[]]}function Ap(e,t,r){let n=g$2(e,t?.peer_id);return n?[e,[h(v,n.source,t.request_id,n.id,r)]]:[e,[]]}function ma(e,t,r,n){return Ap(e,r,t)}function la(e,t,r){let n=g$2(e,t??Hs(e,r)?.[0]),i=n?.[P]?.factories?.[r];return i||k(Cs,`Unable to find factory owner for type ${r}`),[n,i]}function ni(e,t,r,n,i,o,s){let[a,c]=la(e,void 0,r.type),l=_(e,t),[u,d]=Pe(e.ids),h=ra(d,r,n,o),p=fn$1(e,l.identity,h);return{state:e=rn({...e,ids:u},d,h),messages:[da$1(e,a,c,s,p,d,n,i,null)],requestId:d}}function Cp(e,t,r,n,i,o,s,a){let[c,l]=la(e,r,n),u=_(e,t),[d,h]=Pe(e.ids),p=na(h,n,i,{request_id:a.request_id,peer_id:a.peer_id}),g=fn$1(e,u.identity,p);return{state:e=rn({...e,ids:d},h,p),messages:[da$1(e,c,l,s,g,h,o,He(e,o?.contextId),i)],requestId:h}}function ya(e,t,r){let{request_id:n,peer_id:i,owner_id:o,peer_type:s,peer_name:a,activity_id:c}=r;b(e,i,"activity-domain");let l=Cp(e,i,o,s,a??s,Bs(e,c),r.configuration,r);return[l.state,l.messages.concat(I(v,t,n,i))]}me(),L(),me();var Rr=R("gateway.domains.activity.activities");function Pp(e,t,r){let[n,i]=Kt(e.ids),o=X(t.read_permissions),s=X(t.write_permissions),a=o||s?{read:o,write:s}:void 0,c=ir(r,i,t.initial_context,"activity",t.read_permissions,t.write_permissions,a,i,or()),[l,u]=zi(n),d={id:u,type:t.activity_type,contextId:i,initiator:t.peer_id};return d.client_request=t,[{...e,ids:l},d,c]}function ga(e,t,r,n){let i=lt(e,t);if(i){let t=r.id,o=n.activity?.["owner?"],s=He(e,i.contextId);e=yt(e,i.id,produce(i,e=>{e.participants||(e.participants=new Set),e.participants.add(t),o&&(e.owner=r.id),e.gatewayRequests&&(e.gatewayRequests.delete(n.id),0===e.gatewayRequests.size&&delete e.gatewayRequests)})),e=C(e,t,produce(r,e=>{e["activity-domain"].member=i.id,e["activity-domain"].reload=n.reload})),e=dt(e,s,t)}return e}function Dp(e,t,r){return ne(e,P).filter(e=>e.identity.user===t).map(e=>ei(e.source,e.id,r))}function _p(e,t,r){return ne(e,P).filter(e=>e.identity.user===t).map(e=>Ys(e.source,e.id,r))}function ha(e,t,r,n,i){let o=b(e,n,"activity-domain"),s=o.identity.user;if(s){let o=Dp(e,s,i);return o=o.concat(Ye(t,r,n)),[Gs(e,s,i),o]}return[e,[kt(t,r,n,S(Vn,`Registering peer is missing an user in its identity ${JSON.stringify(o.identity)}`))]]}function ba(e,t,r){let{request_id:n,peer_id:i,types:o}=r,s=b(e,i,"activity-domain"),a=s.identity.user;if(a){let r=new Set(o),s=Array.from(new Set(Object.keys(gr(e,a)).filter(e=>r.has(e)))),c=_p(e,a,s);return c=c.concat(Ye(t,n,i)),[Ws(e,a,s),c]}return[e,[kt(t,n,i,S(Vn,`Removing peer is missing an user in its identity ${JSON.stringify(s.identity)}`))]]}function Ra(e,t){let r=gr(e,t.identity.user);if(r){let e=Object.values(r);return[ei(t.source,t.id,e)]}return[]}function Op(e,t,r){let n=gr(e,t.identity.user)?.[r];return n||k(Ds,`Unable to find activity type ${r}`),n}function xa(e,t){e.configuration}function kp(e,t,r,n,i){let{state:o,messages:s,requestId:a}=ni(e.state,r,t,e.activity,n,!0,xa(t));return produce(e,e=>{e.state=castDraft(o),e.messages=e.messages.concat(s),e.activity.gatewayRequests=e.activity.gatewayRequests||new Set,e.activity.gatewayRequests.add(a)})}function Np(e,t,r,n,i){return t?t.reduce((t,i)=>{let{state:o,messages:s,requestId:a}=ni(t.state,r,i,t.activity,n,!1,xa(i));return produce(e,e=>{e.state=castDraft(o),e.messages=e.messages.concat(s),e.activity.gatewayRequests=e.activity.gatewayRequests||new Set,e.activity.gatewayRequests.add(a)})},e):e}function Sa(e,t,r,n){let i,o,{request_id:s,peer_id:a}=r,c=b(e,a,"activity-domain"),l=Op(e,c,r.activity_type),u=(n||[]).reduce((e,t)=>(e[`[${t.type},${t.name??""}]`]=t.configuration??null,e),{}),d=r.types_override;d&&0!==Object.keys(u).length&&k(zn,"Cannot specify types override and custom configuration at the same time"),[e,o,i]=Pp(e,r,c);let h=[Zs(t,s,a,o.id)],p={state:e,messages:h,activity:o};return p=kp(p,d?.owner_type??l.owner_type,a,i),p=Np(p,d?.helper_types??l.helper_types,a,i),({state:e,activity:o,messages:h}=p),[e=yt(e=tr$1(e,i),o.id,o),h]}function qp(e,t,r){if(t["ready?"]){return ii(e,r.id,t,r).map(e=>ta$1(e.source,e.id,t.id,r))}return[]}function $p(e,t,r){let n=t.contextId,i=He(e,n)?.data||{},o=r.id,s=r[P]?.reload;t=produce(t,e=>{e.owner=o,e["ready?"]=!0,delete e.clientRequest});let a=[];return s?(a=a.concat(br(e,r.source,r,t,i)),a=a.concat(qp(e,t,r))):(a=a.concat(Lp(e,t,i)),a=a.concat(Gp(e,t))),{state:e,activity:t,messages:a}}function va(e,t,r){let n=r.id;return!(!e.readyMembers?.has(n)&&!e.participants?.has(n)&&e.owner!==n)||Qt([t.source,t.identity,e.read_permissions,t.options?.service],[r.source,r.identity,void 0,r.options?.service])}function Ep(e,t,r,n){return ii(e,t.id,r,n).map(e=>Xs(e.source,e.id,t,r.id))}function Up(e,t,r,n,i){let o=_(e,r.owner);return ii(e,t,r,o).map(e=>ea(e.source,e.id,t,r.id,n))}function Hp(e,t,r){let n=r.id;if(t.readyMembers?.has(n)||t.participants?.has(n)||t.owner===n)return!0;{let n=g$2(e,t.owner);return Qt([n?.source,n?.identity,t.write_permissions,!1],[r.source,r.identity,void 0,!1])}}function Lp(e,t,r){let n=t.owner,i=t.readyMembers;return(n?[n]:[]).concat(Array.from(i||[])).map(t=>g$2(e,t)).filter(e=>!!e).map(n=>br(e,n.source,n,t,r))}function Fp(e,t,r){let n=new Set;return r&&n.add(r),t.participants&&t.participants.forEach(n.add),t.readyMembers&&t.readyMembers.forEach(n.add),n}function ii(e,t,r,n,i){let o=new Set;return Yn(e,r.type).forEach(o.add),Fp(e,r,n?.id),o.delete(t),Array.from(o).map(t=>g$2(e,t)).filter(e=>!!e).filter(e=>va(r,n,e))}function Gp(e,t){let r=t.type,n=g$2(e,t.owner);return Array.from(Yn(e,r)).map(t=>g$2(e,t)).filter(e=>!!e).filter(e=>va(t,n,e)).map(r=>ri(e,r.source,r.id,t))}function Wp(e,t,r){let n=r.id,i=He(e,t.contextId);t=produce(t,e=>{e.readyMembers=e.readyMembers||new Set,e.readyMembers.add(n)});let o=new Array;if(t["ready?"]){let n=_(e,t.owner);o=o.concat(Ep(e,r,t,n)),o=o.concat(br(e,r.source,r,t,i?.data||{}))}return{state:dt(e,i,n),activity:t,messages:o}}function xr(e){return produce(e,e=>{delete e[P]?.member,delete e[P]?.owner})}function wa(e,t,r,n){let i=n.id,o=lt(e,r);if(o){let t=o.owner===i;o=produce(o,e=>{t||(e.readyMembers=e.readyMembers||new Set,e.readyMembers.add(i)),e.participants?.delete(i),0===e.participants?.size&&delete e.participants});let{state:s,activity:a,messages:c}=t?$p(e,o,n):Wp(e,o,n);return[yt(s,r,a),c]}return[C(e,i,xr(n)),[Xn(t,i,void 0,$s)]]}function Jp(e,t,r){return t.reduce(([e,t],n)=>{let i=g$2(e,n);return i?[C(e,n,xr(i)),t.concat(Xn(i.source,n,void 0,r))]:[e,t]},[e,[]])}function jp(e,t){return(t.gatewayRequests?Array.from(t.gatewayRequests):[]).reduce((e,t)=>tt(e,t).state,e)}function Bp(e,t){return e=rr(e=Ls(e=jp(e,t),t.id),t.contextId)}function oi(e,t,r){let n,i=t.clientRequest,o=t.owner;t.id,[e,n]=ue(e,e=>[Bp(e,t),[]],e=>{let n=new Set;return o&&n.add(o),t.participants&&t.participants.forEach(n.add),t.readyMembers&&t.readyMembers.forEach(n.add),Jp(e,Array.from(n),r)});let s=g$2(e,i?.peer_id);return s?[e,n.concat(kt(s.source,i?.request_id,i?.peer_id,r))]:[e,n]}function Ia(e,t,r){let{request_id:n,peer_id:i,activity_id:o}=r,s=_(e,i),a=ft(e,o);return Hp(e,a,s)?ue(e,e=>oi(e,a,Q(r)),e=>[e,[Ye(t,n,i)]]):[e,[kt(t,n,i,S(ks,"Not authorized to destroy activity"))]]}function Kp(e,t){return oi(e,ft(e,t.id),S(Ps,"Activity owner cannot be created"))}function Ta(e,t){return t["owner?"]?Kp(e,t):[e,[]]}function Vp(e,t,r){return{state:e,activity:t,messages:[]}}function Aa(e,t,r){let{request_id:n,peer_id:i,target_id:o,activity_id:s,peer_type:a,peer_name:c}=r;b(e,i,"activity-domain");let l=ft(e,s),u=produce(b(e,o,P),e=>{a&&(e.peerType=a),c&&(e.peerName=c)}),d=u[P]?.member,h=u[P]?.owner,p=lt(e,d??h);if(p?.id===s)return[e,[Ye(t,n,i)]];p&&k(zn,`Peer is already in activity ${p.id}`);let{state:g,messages:m}=Vp(e,l);return[g,m.concat(Ye(t,n,i))]}function zp(e,t){return produce(e,e=>{e.participants&&(e.participants.delete(t),0===e.participants.size&&delete e.participants),e.readyMembers&&(e.readyMembers.delete(t),0===e.readyMembers.size&&delete e.readyMembers)})}function Ca(e,t,r,n){Rr.enabledFor("debug")&&Rr.debug(`a participant ${r.id} of activity ${t.id} has left.`);let i=r.id,o=(t=zp(t,i)).id,s=Up(e,i,t,n);return e=yt(e=C(e,i,xr(r)),o,t),[e]=nr(e,He(e,t.contextId),i),{state:e,activity:t,messages:s}}function Qp(e,t,r,n,i){let o=r.id;if(Rr.enabledFor("debug")&&Rr.debug(`the owner ${o} of activity ${t.id} has left`),i)return oi(C(e,o,xr(r)),t,n);{let{state:i,messages:o}=Ca(e,t,r,n);return[i,o]}}function Ma(e,t,r){let n=t[P]?.member,i=lt(e,n);if(i){let n=i.owner,o=t.id,s=i.reloading&&i.reloading.has(o);if(i=produce(i,e=>{s&&e.reloading&&(e.reloading.delete(o),0===e.reloading.size&&delete e.reloading)}),n===o)return Qp(e,i,t,r,!s);{let{state:n,messages:o}=Ca(e,i,t,r);return[n,o]}}return[e,[]]}function Pa(e,t,r,n,i,o){return e=i?i.filter(e=>!!e).reduce((e,t)=>o(e,n,t),e):o(e,n,!0),[e,[Ye(t,r,n)]]}function Da(e,t,r){let n,{request_id:i,peer_id:o,activity_types:s}=r,a=b(e,o,"activity-domain");[e,n]=Pa(e,t,i,o,s,Js);let c=Fs(e).filter(e=>e["ready?"]);return n=n.concat((s?c.filter(e=>-1!==s.indexOf(e.type)):c).map(t=>ri(e,a.source,a.id,t))),[e,n]}function _a(e,t,r){let{request_id:n,peer_id:i,activity_types:o}=r;return b(e,i,"activity-domain"),Pa(e,t,n,i,o,js)}var gt=R("gateway.domains.activity");function Xp(e,t,r){let{state:n,removed:i}=tt(e,r.request_id);if(i){let e=i.type;switch(e){case"activity":{let e=i.activity;if(e)return Ta(n,e);break}case"create-peer":return ma(n,Q(r),i.clientRequest);default:gt.error("Unable to handle error for an unknown incoming request type "+e)}}return[e,[]]}function em(e,t){let r=t?.creationRequest;if(r){let{peer_name:n,peer_type:i}=r;switch(t=produce(t,e=>{n&&(e.peerName=n),i&&(e.peerType=i)}),r.type){case"activity":return ga(e,r.activity?.id,t,r);case"create-peer":return C(e,t.id,t)}}return e}function tm(e,t,r){let{request_id:n,peer_id:i,restrictions:o}=r;if(de$1(e,i,P))return[e,[I(v,t,n,i)]];let s=X(o),a=b(e=he$1(e,i,P,s),i,"activity-domain");e=em(e,a);let c=new Array;return c=c.concat(Yt(v,P,e,t,a)),c=c.concat(Ra(e,a)),c=c.concat(oa(e,a)),c=c.concat([I(v,t,n,i)]),[e,c]}function Oa(e,t,r,n){return ue(e,e=>Ma(e,t,r),e=>pa(e,t),e=>Zt(v,P,e,t,r,n))}function rm(e,t,r){let{request_id:n,peer_id:i}=r,o=b(e,i,"activity-domain");return ue(e,e=>Oa(e,o,Q(r),!1),e=>[e,[I(v,t,n,i)]])}function nm(e,t,r){let n=_(e,r.peer_id),i=n[P]?.member;return i?wa(e,t,i,n):ua$1(e,n)}function im(e,t){gt.enabledFor("debug")&>.debug(`removing source ${JSON.stringify(t)} from activity domain`);let r=Te(e,t,P),n=r.map(e=>e.id).reduce((e,t)=>te(e,t,P),e),i=r.reduce(([e,t],r)=>{let[n,i]=Oa(e,r,qs,!0);return[n,t.concat(i)]},[n,[]]);return gt.enabledFor("debug")&>.debug(`removed source ${JSON.stringify(t)} from activity domain`),i}function om(e,t,r){switch(r.type){case"domain/join":return tm(e,t,r);case"domain/leave":return rm(e,t,r);case"ready":return nm(e,t,r);case"add-types":{let{request_id:n,peer_id:i,types:o}=r;return ha(e,t,n,i,o)}case"remove-types":return ba(e,t,r);case"create":{let{configuration:n,...i}=r;return Sa(e,t,i,n)}case"destroy":return Ia(e,t,r);case"subscribe":return Da(e,t,r);case"unsubscribe":return _a(e,t,r);case"join-activity":return Aa(e,t,r);case"add-peer-factories":return sa(e,t,r);case"remove-peer-factories":return ca$1(e,t,r);case"create-peer":return ya(e,t,r);case"error":return Xp(e,t,r);case"update-context":return ut(v,e,t,r);case"commands/source-removed":return im(e,t);default:return gt.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h(v,t,r.request_id??-1,r.peer_id,S(Ns,`Unhandled message ${JSON.stringify(r)}`))]]}}var si=class{info(){return{uri:v,description:"",version:2}}init(e){return e}destroy(e){return e}handleMessage(e,t){let{source:r,body:n}=t;try{return om(e,r,n)}catch(t){return T(r)?[e,[h(v,r,n.request_id,n.peer_id,J(t,As))]]:[e,[]]}}stateToMessages(e,t){return[]}};function ka(){return new si}L();var Re="metrics",Na=`${Re}.errors.failure`,qa=`${Re}.errors.unhandled_message`,$a=`${Re}.errors.bad_identity`,ai=S(`${Re}.peer-removed`,"Peer has been removed"),oe="metrics-domain";ci();var Ge=R("gateway.domains.metrics"),cm=["system","service","instance"];function dm(e){let t=cm.find(t=>!(t in e));t&&k($a,`Repository is missing required ${t} property`)}function um(e,t){return{machine:t.machine,system:t.system,service:t.application,"start-time":Date.now()}}function pm$1(e,t,r){let{request_id:n,peer_id:i,identity:o,options:s}=r,a=Object.assign({},um(t,o),s,o);return de$1(e,i,oe)||(dm(a),e=produce(he$1(e,i,oe,void 0),e=>{let t=e.peers?.[i];t[oe]={restrictions:"local",repoId:a}})),[e,[I(Re,t,n,i)]]}function ui(e,t,r){let n=t.id,i=t[oe]?.repos;return i&&(Ge.info(`stopping metrics publishing for peer ${n}, reason: ${JSON.stringify(r)}`),i.forEach(e=>{e.stop()})),te(e,n,oe)}function mm(e,t,r){let{request_id:n,peer_id:i}=r;return[ui(e,_(e,i),Q(r)),[I(Re,t,n,i)]]}function lm(e,t,r,n){let i=produce(e,e=>{let i,o=e.peers?.[r];if(o){let e=o[oe];e&&(i=e.repos,i||(i=e.repos=t.map(e=>{let t=e.repository(n);return t.start(),t}),e.repos=i))}});return[i,i.peers?.[r]?.[oe]?.repos??[]]}function ym(e,t,r,n,i){let{peer_id:o,metrics:s}=r,a=b(e,o,oe),c=a[oe].repoId,l=s.filter(e=>Nt(c,e.name,i));if(l.length>0){Ge.enabledFor("debug")&&Ge.debug(`publisher ${JSON.stringify(c)} adding metrics [${l.map(e=>e.name).join(",")}]`);let[t,r]=lm(e,n,a.id,c);return r.forEach(e=>e.add(l)),[t,[]]}return[e,[]]}function fm(e,t,r,n){let{peer_id:i,values:o}=r,s=b(e,i,oe),a=s[oe].repoId,c=o.filter(e=>Nt(a,e.name,n));if(c.length>0){let e=s[oe].repos;e&&e.forEach(e=>e.publish(c))}return[e,[]]}function gm(e,t){return Ge.enabledFor("debug")&&Ge.debug(`removing source ${JSON.stringify(t)} from metrics domain`),e=Te(e,t,oe).reduce((e,t)=>ui(e,t,ai),e),[e,[]]}function hm(e,t,r,n,i){switch(r.type){case"domain/join":return pm$1(e,t,r);case"domain/leave":return mm(e,t,r);case"commands/source-removed":return gm(e,t);case"define":return ym(e,t,r,n,i);case"publish":return fm(e,t,r,i);default:return Ge.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h(Re,t,r.request_id??-1,r.peer_id,S(qa,`Unhandled message ${JSON.stringify(r)}`))]]}}var di=class{constructor(e,t){this.factories=e,this.filters=t}info(){return{uri:Re,description:"",version:1}}init(e){return e}destroy(e){return e=ne(e,oe).reduce((e,t)=>ui(e,t,ai),e),e}handleMessage(e,t){let{source:r,body:n}=t;try{return hm(e,r,n,this.factories,this.filters)}catch(t){return T(r)?[e,[h(Re,r,n.request_id,n.peer_id,J(t,Na))]]:[e,[]]}}stateToMessages(e,t){return[]}};function Ha(e,t){return Ge.enabledFor("debug")&&Ge.debug(`Initializing metrics domain with filters ${t?JSON.stringify(t):""}`),new di(e,t)}async function Ka(e){return Tr(e,await Ir(e,t=>Sr(e.split_size??1,t),e?.publishFn??"@interopio/gateway/metrics/publisher/custom"))}pi(),hi(),me(),L();var km=R("gateway.metrics");async function Nm(e,t){if("rest"===e){let{restRepositoryFactory:e}=await Promise.resolve().then(()=>(Qa(),za));return await e(t)}if("file"===e)throw new Error("file publisher is supported only in nodejs")}async function Za(e,t){let r=e??{publishers:[]};return Promise.all(r.publishers.map(async e=>{try{if("string"==typeof e)return await Nm(e,r[e]);{let r=produce(e,e=>{t&&(e.context=e.context||{},e.context.gw=e.context.gw||{url:t},e.context.gw.url=t)});return await Ka(r)}}catch(t){return void km.error(`failed to create repository factory ${JSON.stringify(e)}`,t)}})).then(e=>e.filter(pe))}L();var ht="context-domain",E=se,Xa=Ue(E),Ar=S(`${E}.peer-removed`,"Peer has been removed");function ec(e,t,r,n,i,o,s,a){return{domain:E,type:"create-context",request_id:e,peer_id:t,name:r,data:n,lifetime:i,read_permissions:o,write_permissions:s,version:a}}function tc(e,t,r){return{domain:E,type:"subscribe-context",peer_id:t,request_id:e,context_id:r.id,name:r.name}}var qt=R("gateway.domains.context");function $m(e,t){return ec(void 0,e,t.name,t.data,t.lifetime,t.read_permissions,t.write_permissions,t.version)}function Em(e,t,r,n){let i=b(e,r,"context-domain"),o=Yt(E,"context-domain",e,t,i).filter(t=>wn(e,t));n&&(o=o.filter(e=>r!==e.body.new_peer_id));let s=n?[]:Po(At(i),e,i);return o.concat(s)}function rc(e,t,r,n,i,o){let s=he$1(e,r,ht,i);return $(E,()=>`[${n.application}#${r}(by ${n.user??""})] added to context domain (restrictions: ${i?JSON.stringify(i):""})`),o&&(s=Ee(s,r,e=>{e.options&&(delete e.options["context-compatibility-mode?"],0===Object.keys(e.options).length&&delete e.options)})),[s,Em(s,t,r,o)]}function Um(e,t,r){let{request_id:n,peer_id:i,identity:o,restrictions:s}=r,a=r.options?.["context-compatibility-mode?"],c=g$2(e,i)?.options?.["context-compatibility-mode?"],l=de$1(e,i,ht);if(l&&!c)return[e,[I(E,t,n,i)]];{let u=X(s),[d,h]=rc(e,t,i,o,u,l&&c),p=g$2(d,i),g=[];if(a||g.push(I(E,t,n,i)),re("context-domain",p)){let t={...r,domain:D,type:"join",destination:E,identity:o};p?.options&&(t.options=p.options),u&&(t.restrictions=u),g.push(G(w(A(e.ids),i),t))}return[d,h.concat(g)]}}function Hm(e,t,r){let{peer_id:n,identity:i,restrictions:o}=r,s=g$2(e,n)?.options?.["context-compatibility-mode?"];return s&&de$1(e,n,ht)?[e,[]]:rc(e,t,n,i,o,s)}function Lm(e,t,r){return W(t)?Hm(e,t,r):Um(e,t,r)}function Fm(e,t,r){let{peer_id:n}=r,i=B(e,n,"context-domain");return i?lr(E,e,i,Q(r),!1):[e,[]]}function Gm(e,t,r){let{request_id:n,peer_id:i}=r,[o,s]=lr(E,e,b(e,i,"context-domain"),Q(r),!1);return[o,s.concat([I(E,t,n,i),G(w(A(o.ids),i),{...r,type:"leave"})])]}function Wm(e,t,r){return W(t)?Fm(e,t,r):Gm(e,t,r)}function Jm(e){return 1==e.local&&void 0!==e.version&&Le(e)}function jm(e,t){let r=e.ids.nodeId,n=new Set,i=ne(e,"context-domain").filter(e=>T(e.source)&&re("context-domain",e)).map(e=>{let i=e.id;return n.add(i),K(w(r,i),t,st(void 0,i,e["context-domain"].restrictions,E,e.identity,e.options))}),o=wo(e).filter(Jm).flatMap(e=>{let i=Array.from(e.members).filter(e=>n.has(e)),o=e.owner??i[0],s=[K(w(r,o),t,$m(o,e))],a=Array.from(i).map(n=>K(w(r,n),t,tc(void 0,n,e)));return s.concat(a)});return i.concat(o)}function Bm(e,t,r){qt.enabledFor("debug")&&qt.debug(`removing source ${JSON.stringify(t)} from context domain`);let n=Te(e,t,ht),i=n.map(e=>e.id).reduce((e,t)=>te(e,t,ht),e),o={domain:D,type:"leave",destination:E,reason_uri:Ar.uri,reason:Ar.message},s=n.reduce(([t,r],n)=>{let[i,s]=lr(E,t,n,Ar,!0),a=[];if(T(n.source)&&re("context-domain",n)){let t={...o,peer_id:n.id};a.push(G(w(A(e.ids),n.id),t))}return[i,r.concat(s.concat(a))]},[i,[]]);return qt.enabledFor("debug")&&qt.debug(`removed source ${JSON.stringify(t)} from context domain`),s}function Km(e,t,r,n){switch(r.type){case"domain/join":return Lm(e,t,r);case"domain/leave":return Wm(e,t,r);case"create-context":return pr(E,e,t,r,n);case"update-context":return ut(E,e,t,r);case"subscribe-context":return ur$1(E,e,t,r);case"unsubscribe-context":return dr(E,e,t,r);case"destroy-context":return mr(E,e,t,r);case"commands/source-removed":return Bm(e,t);default:return qt.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h(E,t,r.request_id??-1,r.peer_id,S(ho(E),`Unhandled message ${JSON.stringify(r)}`))]]}}var bi=class{constructor(e){this.options=e}destroy(e){return e}handleMessage(e,t){let{source:r,body:n}=t;try{return Km(e,r,n,this.options)}catch(t){return T(r)?[e,[h(E,r,n.request_id,n.peer_id,J(t,Xa))]]:[e,[]]}}info(){return{uri:E,description:"",version:3}}init(e){return e}stateToMessages(e,t){return jm(e,t)}};function nc(e){return new bi(e)}L();var ic="bus.errors.failure",oc="bus.errors.unhandled_message";function sc(e,t,r,n,i){return x(e,{domain:"bus",type:"event",peer_id:t,subscription_id:r,"publisher-identity":n,data:i})}function ac(e,t,r,n){return x(e,{domain:"bus",type:"subscribed",request_id:t,peer_id:r,subscription_id:n})}var Cr=R("gateway.domains.bus");function Vm(e,t,r){let{peer_id:n,restrictions:i}=r;return de$1(e,n,"bus-domain")?[e,[]]:[he$1(e,n,"bus-domain",i),[]]}function zm(e,t,r,n){let{request_id:i,peer_id:o,restrictions:s}=r;if(de$1(e,o,"bus-domain"))return[e,[I("bus",t,i,o)]];let a=b(e=he$1(e,o,"bus-domain",X(s)??n?.defaultPeerRestrictions),o,"bus-domain"),c=[I("bus",t,i,o)];if(re("bus-domain",a)){let t={...r,type:"join",options:a?.options,restrictions:a["bus-domain"].restrictions};c.push(G(w(A(e.ids),o),t))}return[e,c]}function Qm(e,t,r,n){return W(t)?Vm(e,t,r):zm(e,t,r,n)}function Ym(e,t){return Cr.enabledFor("debug")&&Cr.debug(`removing source ${JSON.stringify(t)} from bus domain`),e=Te(e,t,"bus-domain").reduce((e,t)=>te(e,t.id,"bus-domain"),e),[e,[]]}function Zm(e,t,r){let{peer_id:n}=r;return g$2(e,n)?[te(e,n,"bus-domain"),[]]:[e,[]]}function Xm(e,t,r){let{request_id:n,peer_id:i}=r,o=b(e,i,"bus-domain"),s=te(e,i,"bus-domain"),a=[I("bus",t,n,i)];return re("bus-domain",o)&&a.push(G(w(A(e.ids),i),{...r,type:"leave"})),[s,a]}function el(e,t,r){return W(t)?Zm(e,t,r):Xm(e,t,r)}function tl(e){return e.map(e=>[e,Object.entries(e["bus-domain"]?.subscriptions||{})]).flatMap(([e,t])=>t.map(([t,r])=>({peer:e,subscription:[t,r]})))}function rl({topic:e,topicRepattern:t},r){if(t){let e=r.match(t);return null!==e&&r===e[0]}return e===r}function nl$1(e,t){return!e||!t||e===t}function il(e,t,[,r]){return rl(r,e)&&nl$1(r.routingKey,t)}function ol(e,t){if(e){let r=t.identity;for(let[t,n]of Object.entries(e))if(r[t]!==n)return!1}return!0}function dc(e,t,r){let{data:n}=t;if(n){let{topic:i,routing_key:o,peer_id:s,target_identity:a}=t,c=e=>il(i,o,e),l=e=>ol(a,e),u=r.identity,d=new Set,h=tl(ie(e,"bus-domain",r,!0).filter(l)).filter(({subscription:e})=>c(e)).reduce((r,{peer:i,subscription:o})=>{let a=i.source,c=i.id,[l]=o,h=T(a)?sc(a,c,l,u,n):function(){if(s!==c){let r=a.node;if(d.has(r)){d.add(r);let n={type:"node",node:r};return K(w(A(e.ids),s),n,t)}}}();return h?r.concat(h):r},[]);return[e,h]}return[e,[]]}function sl$1(e,t){let{peer_id:r}=t,n=b(e,r,"bus-domain");return n?dc(e,t,n):[e,[]]}function al(e,t){let{peer_id:r}=t,n=B(e,r,"bus-domain");return n?dc(e,t,n):[e,[]]}function cl(e,t,r){return T(t)?sl$1(e,r):al(e,r)}function dl(e){return-1!==e.indexOf(">")||-1!==e.indexOf("*")}function ul(e){return new RegExp(e.replace(/\./g,"\\.").replace(/\*/g,"[a-zA-Z_0-9]+").replace(/>/g,".*"),"g")}function uc(e,t,r,n){let{topic:i,routing_key:o,request_id:s,peer_id:a}=t,c=n.source;n=produce(n,e=>{e["bus-domain"].subscriptions=e["bus-domain"].subscriptions||{},e["bus-domain"].subscriptions[r]={topic:i,routingKey:o},dl(i)&&(e["bus-domain"].subscriptions[r].topicRepattern=ul(i))});let l={...t,subscription_id:r};return[C(e,a,n),T(c)?[ac(c,s,a,r),G(w(A(e.ids),a),l)]:[]]}function pl$1(e,t,r){let[n,i]=Pe(e.ids),o=b(e,r.peer_id,"bus-domain");return uc({...e,ids:n},r,i,o)}function ml(e,t,r){let{subscription_id:n,peer_id:i}=r,o=B(e,i,"bus-domain");return o?uc(e,r,n,o):[e,[]]}function ll(e,t,r){return T(t)?pl$1(e,t,r):ml(e,t,r)}function pc(e,t,r){let{request_id:n,peer_id:i,subscription_id:o}=t,s=r.source;return r=produce(r,e=>{e["bus-domain"].subscriptions&&delete e["bus-domain"].subscriptions[o]}),[C(e,i,r),T(s)?[I("bus",s,n,i),G(w(A(e.ids),i),t)]:[]]}function yl(e,t,r){return pc(e,r,b(e,r.peer_id,"bus-domain"))}function fl(e,t){let r=B(e,t.peer_id,"bus-domain");return r?pc(e,t,r):[e,[]]}function gl(e,t,r){return T(t)?yl(e,t,r):fl(e,r)}function hl(e,t,r,n){switch(r.type){case"domain/join":return Qm(e,t,r,n);case"domain/leave":return el(e,t,r);case"commands/source-removed":return Ym(e,t);case"publish":return cl(e,t,r);case"subscribe":return ll(e,t,r);case"unsubscribe":return gl(e,t,r);default:return Cr.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h("bus",t,r.request_id??-1,r.peer_id,S(oc,`Unhandled message ${JSON.stringify(r)}`))]]}}var Ri=class{constructor(e){this.options=e}info(){return{uri:"bus",description:"",version:1}}init(e){return e}destroy(e){return e}handleMessage(e,t){let{source:r,body:n}=t;try{return hl(e,r,n,this.options)}catch(i){return je(i)||Cr.error(`Error processing message ${JSON.stringify(t)}`,i),[e,[h("bus",r,n.request_id,n.peer_id,J(i,ic))]]}}stateToMessages(e,t){let r=A(e.ids);return ne(e,"bus-domain").filter(e=>T(e.source)&&re("bus-domain",e)).flatMap(e=>{let n=e.id;return[st(void 0,n,e["bus-domain"].restrictions,"bus",e.identity,e.options)].map(e=>K(w(r,n),t,e))})}};function mc(e){return new Ri(e)}L();var Mr=R("gateway.clients");function lc(e,t,r,n,i,o){Mr.info(`adding client for key ${r}`);let s={source:n,lastAccess:Date.now(),onScavenge:i,onStop:o};e.set(r,s);try{t.addSource(n)}catch(e){Mr.error(`Unable to add client for key ${r}`,e)}}function Pr(e,t,r){Mr.info(`removing client for key ${r}`);let n=e.get(r);if(n){e.delete(r);try{t.removeSource(n.source)}catch(e){Mr.error(`Unable to remove client for ${r}`,e)}}}L();var $t=R("gateway.scavenger");function bl(e,t,r){$t.enabledFor("trace")&&$t.debug(`running client scavenger. collecting everything older than ${r}`),e.forEach((n,i)=>{if(n.lastAccess<=r){$t.info(`scavenging client for ${i}. Last access ${new Date(n.lastAccess)} < ${new Date(r)}`);try{Pr(e,t,i),n.onScavenge&&n.onScavenge()}catch(e){$t.warn(`error scavenging client for ${i}`,e)}}})}var Rl=10,yc=1e3,Et=class{constructor(e,t,r){this.clients=e,this.node=t,this.inactiveSeconds=r,r>0&&($t.info(`clients inactive for ${r} seconds will be scavenged`),this.cancel=setInterval(async()=>{this.scavengeClients()},yc))}scavenging=!1;cancel;scavengeClients(){if(!this.scavenging)try{this.scavenging=!0;let e=2*Math.max(this.inactiveSeconds,Rl)*yc,t=Date.now()-e;bl(this.clients,this.node,t)}finally{this.scavenging=!1}}stop(){clearTimeout(this.cancel)}},fc="0.22.2";function Dr(e){return"peer"===e?.type}function gc(e){return"node"===e?.type}function hc(e){return"cluster"===e?.type}me(),L(),me();var xi=class{#e;#t;#o;#r;constructor(e,t,r,n){this.#e=e,this.#t=t,this.#o=r,this.#r=n}init(){void 0!==this.#r&&this.#t.addUsers(this.#o,this.#r)}close(){void 0!==this.#r&&this.#t.removeUsers(this.#o,this.#r),this.#t.unregister(this.#o),this.#t.close()}message(e){this.#e(e)}addSource(e){}removeSource(e){let t={origin:"local",source:e,body:{type:"commands/source-removed"}};return this.#e(t)}},j=R("gateway.node.mesh");function xl(e,t){let{source:r,body:n,origin:i}=t;try{return n.dump?(j.info(`state dump:\n${JSON.stringify($e(e),null,"\t")}`),[e,[]]):"cluster"===i?Sl(e,t):ze(e,t,r)}catch(i){j.error(`Error handling message ${JSON.stringify(t)}`,i);let o=n;return[e,[h(void 0,r,o.request_id,o.peer_id,J(i,Ne))]]}}function bc(e,t,r){j.info(`Node ${t} is sending state to node ${r}`);let n={type:"node",node:r},i=Object.values(e.registeredDomains||[]).map(e=>e.domain).flatMap(t=>t.stateToMessages(e,n)).filter(pe);return[e,i]}function xc(e){return"receive"in e&&e.receive}function Sl(e,t){let r=e.ids.nodeId,{source:n,body:i,origin:o,receiver:s}=t;if(Dr(s)){if(r===s.node){let t=g$2(e,s.peer);t&&xc(t.source)&&t.source.receive(i)}return[e,[]]}return gc(s)?r===s.node?"send-state"===i.type?bc(e,r,n.node):ze(e,t,n):[e,[]]:hc(s)?r!==n.node?"send-state"===i.type?bc(e,r,n.node):ze(e,t,n):[e,[]]:ze(e,t,n)}function vl(e,t,r){switch(r.receiver.type){case"cluster":j.enabledFor("debug")&&j.debug(`broadcasting message ${JSON.stringify(r)}`),t.publish(e,r);break;case"node":j.enabledFor("debug")&&j.debug(`unicasting message ${JSON.stringify(r)}`),t.publish(e,r);break;case"peer":if(j.enabledFor("debug")){let{receiver:e,body:t}=r;j.enabledFor("debug")&&j.debug(`Sending message ${JSON.stringify(t,null,"\t")} to remote peer ${JSON.stringify(e)}`)}t.publish(e,r);break;case"local":{let{receiver:e,body:t}=r;j.enabledFor("debug")&&j.debug(`Sending message ${JSON.stringify(t,null,"\t")} to local peer ${JSON.stringify(e)}`),xc(e)&&e.receive(t);break}default:j.error(`Unable to process response ${JSON.stringify(r)}`)}}function Rc(e){return new Set(e.users?.byName?.keys())}function wl(e,t,r,n){try{j.enabledFor("trace")&&j.debug(`domain handler processing message ${JSON.stringify(n)}`);let i=e.ids.nodeId,[o,s]=xl(e,n);try{for(let e of s){vl(i,r,{...e,source:{...e.source,node:i}})}}catch(e){j.error("error processing responses",e)}if(t){let t=Rc(o),n=Rc(e),s=Array.from(t??[]).filter(e=>!n?.has(e));s&&s.length>0&&r.addUsers(i,s);let a=Array.from(n??[]).filter(e=>!t?.has(e));a&&a.length>0&&r.removeUsers(i,a)}return o??e}catch(t){return j.error(`error handling message ${JSON.stringify(n)}`,t),e}}function _r(e,t,r){let n,i=void 0===r.users,o=t=>{n=wl(n,i,e,t)},s=Xt(t),a={domains:Object.values(s).map(e=>e.info)},c=e.register(r.nodeId,a,{onMessage:(e,t)=>(j.enabledFor("debug")&&j.debug(`Node ${e} received a message from cluster ${JSON.stringify(t)}`),o({...t,origin:"cluster"})),onMemberAdded:(t,r)=>{j.enabledFor("debug")&&j.debug(`Node ${t} received a node ${r} add to cluster.`);let n={origin:"cluster",receiver:{type:"node",node:r},source:{type:"node",node:t},body:{type:"send-state"}};return e.publish(t,n)},onMemberRemoved:(e,t)=>(j.enabledFor("debug")&&j.debug(`Node ${e} received a node ${t} dropped from cluster`),o({origin:"cluster",receiver:{type:"node",node:e},source:{type:"node",node:t},body:{type:"commands/source-removed"}}))});n=t.reduce((e,t)=>t.init(e),{...zt(c,r.signingKey),registeredDomains:s,handler:e=>{o(e)}});let l=new xi(o,e,c,r.users);return l.init(),l}L();var U=R("gateway.ws.common"),vi$1=class{constructor(e,t,r){this.url=e,this.protocols="string"==typeof t?t:[...t],this.dynamicArguments=r.dynamicArguments,this.WebSocket=r.WebSocket,this.URL=r.URL,this.codec=r.codec,this.maxEnqueued=r.maxEnqueued??-1,this.retry=r.retry}dynamicArguments;url;protocols;WebSocket;URL;state="_initial";codec;socket;maxEnqueued;queue=[];retry;reconnectAttempt=0;reconnectTimeout;activeSocketId=0},Il=50,Si={min:1e3+4e3*Math.random(),max:6e4,factor:1.3};function Tl(e,t){let r=Math.max(Il,t?.min??Si.min),n=Math.max(r,t?.max??Si.max),i=Math.max(1,t?.factor??Si.factor);return Math.round(Math.min(n,r*Math.pow(i,e)))}var wi=class e{#e;#t;#o;static#r="interop.io:manual-disconnect";constructor(e){this.#e=e,this.#t="string"==typeof e.url?e.url:e.url.href}get url(){return this.#t}onConnect;onReceive;onError;onDisconnect;onClose;#s(e){let t=++this.#e.activeSocketId;U.enabledFor("debug")&&U.debug(`[${t}]: connecting to ${this.#e.url}`),this.#a(e).then(()=>{let e=new this.#e.WebSocket(this.#t,this.#o);e._internalSocketId=t,this.#i(e)}).catch(e=>{this.onError?this.onError(e instanceof Error?e:new Error(`Failed to create socket: ${e}`)):U.warn(`[${t}]: init socket error: ${e}`,e)})}#i(t){t.onopen=()=>{U.info(`[${t._internalSocketId}]: connection to ${this.#e.url} is up.`);let r="connecting"===this.#e.state;if(this.#e.queue.length>0)for(U.debug(`[${t._internalSocketId}]: flushing ${this.#e.queue.length} pending messages`);this.#e.queue.length>0;){let e=this.#e.queue.shift();e&&(r?t.send(e):U.warn(`[${t._internalSocketId}]: connection to ${this.#e.url} is ${this.#e.state} state, dropping message ${e}`))}return"closing"===this.#e.state?(U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: socket opened but in closing state, closing socket to ${this.#e.url}`),void t.close()):"_disconnecting"===this.#e.state?(U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: socket opened but in disconnecting state, closing socket to ${this.#e.url}`),this.#e.state="_initial",void t.close(1e3,e.#r)):(this.#e.state="connected",this.#e.socket=t,void(this.onConnect&&this.onConnect(t.url,t.protocol)))},t.onerror=e=>{this.onError?this.onError(e.error):U.warn(`[${t._internalSocketId}]: got error: ${JSON.stringify(e)}`,e.error)},t.onmessage=e=>{let r=this.#e.codec.decode(e.data);U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: got message ${JSON.stringify(r)} from ${this.#e.url}`),this.onReceive&&this.onReceive(r)},t.onclose=r=>{let n=!1;if(this.#e.socket?._internalSocketId===t._internalSocketId&&(n=!0,this.#e.socket=void 0),"closing"===this.#e.state)n&&this.onDisconnect&&this.onDisconnect(r.code,r.reason,r.wasClean),this.#e.state="closed",U.enabledFor("info")&&U.info(`[${t._internalSocketId}]: connection to ${this.#e.url} has closed (${r.reason}:${r.code}) (wasOpen: ${n})`),this.onClose&&this.onClose();else{let n="connected"===this.#e.state,i="_disconnecting"===this.#e.state;if(!1===this.#e.retry||r.reason===e.#r){if(U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: will not reconnect to ${this.#e.url} (manual disconnect or retry disabled) (wasConnected: ${n})`),"_initial"!==this.#e.state&&(this.#e.state="_initial"),!i)return}else{"connecting"!==this.#e.state&&(this.#e.reconnectAttempt=0,this.#e.state="connecting");let e=Tl(this.#e.reconnectAttempt,this.#e.retry),n=this.#e.reconnectAttempt++;U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: schedule reconnect to ${this.#e.url} in ${e} ms. [attempt: ${n}]`),this.#e.reconnectTimeout=setTimeout(()=>{this.#s(r)},e)}(n||i)&&(U.info(`[${t._internalSocketId}]: connection to ${this.#e.url} has disconnected (${r.reason}:${r.code})`),this.onDisconnect&&this.onDisconnect(r.code,r.reason,r.wasClean))}}}connect(){"_initial"!==this.#e.state&&"_disconnecting"!==this.#e.state||(this.#e.state="connecting",this.#s())}disconnect(){if("closing"===this.#e.state||"closed"===this.#e.state)throw new Error(`connection to ${this.#e.url} is already closing/closed.`);if("_disconnecting"===this.#e.state||"_initial"===this.#e.state)return;let t="connecting"===this.#e.state;this.#e.state="_disconnecting",this.#e.reconnectTimeout&&(clearTimeout(this.#e.reconnectTimeout),this.#e.reconnectTimeout=void 0,this.#e.reconnectAttempt=0);let r=this.#e.socket;U.enabledFor("debug")&&U.debug(`[${r?._internalSocketId}]: disconnecting connection to ${this.#e.url} (opened?: ${void 0!==r})`),r?(this.#e.socket=void 0,r.close(1e3,e.#r)):t||(this.#e.state="_initial",this.onDisconnect&&this.onDisconnect(1e3,e.#r,!0))}close(){if("closed"===this.#e.state||"closing"===this.#e.state)return;let e="connecting"===this.#e.state;this.#e.state="closing",this.#e.reconnectTimeout&&(clearTimeout(this.#e.reconnectTimeout),this.#e.reconnectTimeout=void 0);let t=this.#e.socket;U.enabledFor("debug")&&U.debug(`closing connection to ${this.#e.url} (opened?: ${void 0!==t})`),t?(this.#e.socket=void 0,t.close()):e||(this.#e.state="closed",this.onClose&&this.onClose())}send(e){if("closing"===this.#e.state||"closed"===this.#e.state)throw new Error(`connection to ${this.#e.url} is closed.`);let t=this.#e.socket,r=void 0===t&&this.#e.maxEnqueued>0&&this.#e.queue.length0;){let e=this.#r.pop();void 0!==e&&e.close()}}};function Or(e){let t=e?.codec??Gr(),r=e?.retry,n=e?.WebSocket;return new Ii(t,r,n)}function Sc(e){return Dr(e)?{type:"peer",node:e.node,"peer-id":e.peer}:e}function vc(e){return"peer"===e.type?w(e.node,e["peer-id"]):e}function kr(e){let{receiver:t,body:r,source:n}=e,i=Sc(t),o=Sc(n);return[t.type,{...e,source:o,receiver:i}]}function Nr(e){let{receiver:t,body:r,source:n}=e,i=vc(t),o=vc(n);return{...e,source:o,receiver:i}}function qr(){return Fr({namespaces:new Map([["commands","gateway.common.commands"]]),keywordize:new Map([["/type","*"],["/to",new Set(["all"])],["/message/origin","*"],["/message/receiver/type","*"],["/message/source/type","*"],["/message/body/type","*"],["/data/origin","*"],["/data/receiver/type","*"],["/data/source/type","*"],["/data/body/type","*"]])})}L();var Ze=R("gateway.mesh.ws.broker.client");function Al(e){return void 0!==e&&"node"in e&&void 0!==e.node}function Ic(e,t,r){let{receiver:n,body:i,source:o}=r;Al(n)?e.send({type:"data",from:t,to:n.node,message:r}):Ze.error(`Destination nodeId is missing when sending message ${JSON.stringify(r)}`)}function Cl(e,t,r){let[n,i]=kr(r);switch(n){case"cluster":e.send({type:"data",from:t,to:"all",message:i});break;case"node":case"peer":Ic(e,t,i);break;default:Ze.error(`Unhandled receiver type when publishing ${JSON.stringify(r)}`)}}var Ti=class{constructor(e){this.ch=e}close(){this.ch(void 0)}register(e,t,r){if("all"===e)throw new Error("cannot register with node id 'all'");return e=e??Me(),this.ch({type:"register",nodeId:e,gateway:t,callbacks:r}),e}unregister(e){this.ch({type:"unregister",nodeId:e})}publish(e,t){this.ch({type:"publish",nodeId:e,message:t})}addUsers(e,t){}removeUsers(e,t){}};function Ml(e,t,r){let{nodeId:n,gateway:i,callbacks:o}=e;t.set(n,{gateway:i,callbacks:o}),r.send({type:"hello","node-id":n,gateway:i})}function Pl(e,t,r){let n=e.nodeId;t.delete(n),r.send({type:"bye","node-id":n})}function Dl(e,t){Cl(t,e.nodeId,e.message)}function _l(e,t){Ze.info("connected to mesh broker");for(let[r,{gateway:n}]of e)t.send({type:"hello","node-id":r,gateway:n})}function Ol(e,t){Ze.info("disconnected from mesh broker");let r=new Set(e);e.clear();for(let e of r)for(let[r,{callbacks:n}]of t){let t=n?.onMemberRemoved;t&&t(r,e)}}function kl(e,t,r){let{"node-id":n,"new-node":i}=e;t.add(i);let o=r.get(n)?.callbacks?.onMemberAdded;o&&(Ze.info(`on-msg ${n}, ${i}`),o(n,i))}function Nl(e,t,r){let{"node-id":n,"removed-node":i}=e;t.delete(i);let o=r.get(n)?.callbacks?.onMemberRemoved;o&&o(n,i)}function ql(e,t){let{to:r,from:n}=e;for(let[r,{callbacks:i}]of t)if(r!==n){let t=i?.onMessage;t&&t(r,Nr(e.message))}}function $l(e,t,r,n){switch(e.type){case"register":Ml(e,r,t);break;case"unregister":Pl(e,r,t);break;case"publish":Dl(e,t);break;case"connected":_l(r,t);break;case"disconnected":Ol(n,r);break;case"node-added":kl(e,n,r);break;case"node-removed":Nl(e,n,r);break;case"data":ql(e,r)}}function Tc(e,t){let r=new Map,n=new Set,i=Or({codec:qr(),WebSocket:t?.WebSocket}).create(e,void 0,t),o=e=>{e&&(Ze.enabledFor("debug")&&Ze.debug(`mesh node processing command ${JSON.stringify(e,null,"\t")}`),$l(e,i,r,n))};return i.onConnect=()=>o({type:"connected"}),i.onReceive=e=>o(e),i.onDisconnect=()=>o({type:"disconnected"}),i.connect(),new Ti(o)}function El(e,t,r,n){let i=`${e}:${t}`,o=r.get(i);if(o)return o.connection;let s=new class{close(){n.send({type:"bye",from:t,to:e}),r.delete(i)}send(e){n.send(e)}toJSON(){return{type:"relay",from:e,to:t}}};return r.set(i,{from:e,to:t,connection:s}),s}function Ul(e,t,r,n){switch(n.type){case"hello":{let{from:i,to:o}=n,s=El(i,o,e,r);t.onConnect(o,i,s);break}case"bye":{let{from:e,to:r}=n;t.onDisconnect(r,e);break}case"data":{let{from:e,to:r,data:i}=n;t.onReceive(r,e,i);break}}}function Ac(e,t,r,n){let i=new Map;return{register:(o,s)=>{let a=i.get(o);if(void 0!==a){let e=s[0];if(a.owner===e)return;return a.connection.disconnect(),a.owner=e,a.connection.connect(),void r.onRegister?.(o,e,a.connection.url)}{let a=new Map,c=`${t}?node=${o}`,l=e.create(c,[],{...n,dynamicArguments:e=>{let t=i.get(o)?.owner;return"string"==typeof e?e=`${e}&owner=${t??""}`:e.searchParams.append("owner",t??""),{url:e}}}),u=s[0];l.onConnect=e=>{r.onRegister?.(o,u,l.url),l.send({type:"hello",from:o,to:"all"})},l.onReceive=e=>{Ul(a,r,l,e)},l.onDisconnect=()=>{for(let[,e]of a)e.connection.close(),r.onDisconnect(e.to,e.from)},l.onClose=()=>{r.onUnregister?.(o)},i.set(o,{node:o,owner:u,connected:a,connection:l}),l.connect()}},unregister:e=>{let t=i.get(e);void 0!==t&&t.connection.close(),i.delete(e)},stop:()=>{for(let[,e]of i)e.connection.close();i.clear()}}}L();var Hl=(e,t)=>"object"==typeof(t="string"==typeof t?[t]:t)?Array.isArray(t)?void 0!==e?{headers:{...e},protocols:[...t]}:[...t]:{...t,headers:{...t.headers,...e}}:void 0===t&&void 0!==e?{headers:{...e}}:void 0,Ai=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}create(e,t,r){return this.#e.create(e,t,this.#o(r))}close(){this.#e.close()}#o(e){let t={...e},r=e?.dynamicArguments,n=e?.URL??globalThis.URL??URL;return t.dynamicArguments=this.#r(n,r),t}#r(e,t){return async(r,n)=>{let i=await(t?.(r,n))??{},o={...this.#t.headers},s=this.#t.getHeaders?await this.#t.getHeaders():{};for(let[e,t]of Object.entries(s))o[e]=t;r=new e(i.url??r,i.baseUrl);let a=this.#t.getWebSocketSearchParams?.(o,r.search);if(a)for(let[e,t]of Object.entries(a))void 0===t?r.searchParams.delete(e):r.searchParams.set(e,t);i.url=r;let c=this.#t.getWebSocketProtocols??void 0===this.#t.getWebSocketSearchParams?Hl:void 0;return i.protocols=c?.(o,i.protocols??n),i}}},Cc=(e,t)=>t&&(t.getWebSocketProtocols||t.getWebSocketSearchParams||t.getHeaders||t.headers)?new Ai(e,t):e,F=R("gateway.mesh.ws");function Ll(e,t,r){let{receiver:n,body:i}=e,o=n.node;if(o){let n=r?.connections.get(o);n&&n.send({type:"data",from:t,to:o,data:e})}}function Fl(e,t,r){let[n,i]=kr(e);switch(n){case"cluster":r?.connections.forEach((e,r)=>{e.send({type:"data",from:t,to:r,data:i})});break;case"node":case"peer":Ll(i,t,r);break;default:F.error(`Unhandled receiver type when publishing ${JSON.stringify(e)}`)}}function Mc(e){for(let t of e.values())t.close()}function Gl(e,t,r){let n=t.node,i=t.to.node,o=t.to.endpoint;F.enabledFor("debug")&&F.debug(`directory connect ${n} to ${i} via ${o}`);let s=r.factory.create(o,void 0,{URL:r.URL});s.onConnect=()=>{e({type:"node-connected",from:n,to:i})},s.onReceive=t=>{"data"===t.type&&e({type:"node-data",to:n,from:i,msg:t.data})},s.onDisconnect=()=>{e({type:"node-disconnected",from:n,to:i})},e({type:"connecting-nodes",from:n,to:i,connection:s}),s.connect()}function Wl(e,t){let r=t.node,n=t.from.node;F.enabledFor("debug")&&F.debug(`directory disconnect ${r} to ${n}`),e({type:"disconnecting-nodes",from:r,to:n})}function Jl(e,t,r){F.enabledFor("debug")&&F.debug(`directory replica change for node ${t.node}: ${JSON.stringify(t.replicas)}`),r.register(t.node,t.replicas)}var Ci=class{#e;#t;#o;#r;#s;#i;constructor(e,t,r,n,i,o){this.#e=e,this.#t=t,this.#o=r,this.#r=n,this.#s=i,this.#i=o?.URL}register(e,t,r){return e=e??Me(),F.enabledFor("info")&&F.info(`registering local node ${e}`),this.#e.set(e,{callbacks:r,connections:new Map}),this.#o.add(e,void 0,{replicaChange:e=>{Jl(this.#r,e,this.#t)},connect:e=>{Gl(this.#r,e,{factory:this.#s,URL:this.#i})},disconnect:e=>{Wl(this.#r,e)}}),e}unregister(e){this.#o.remove(e);let t=this.#e.get(e);t&&(F.enabledFor("info")&&F.info(`unregistering local node ${e}`),this.#e.delete(e),Mc(t.connections)),this.#t.unregister(e)}publish(e,t){Fl(t,e,this.#e.get(e))}addUsers(e,t){this.#o.addUsers(e,...t)}removeUsers(e,t){this.#o.removeUsers(e,...t)}close(){this.#o.close();for(let[,e]of this.#e)Mc(e.connections);this.#e.clear(),this.#t.stop(),this.#s.close()}};function jl(e,t){let{from:r,to:n,connection:i}=t,o=e.get(r);o?(F.enabledFor("debug")&&F.debug(`processing connection request from ${n} to ${r}`),o.connections.set(n,i)):(F.warn(`discarding connection request from ${n} to ${r}`),i.close())}function Bl(e,t){let{from:r,to:n}=t,i=e.get(r);if(i){let e=i.connections.get(n);if(e)return F.enabledFor("debug")&&F.debug(`processing disconnection request from ${n} to ${r}`),i.connections.delete(n),void e.close()}F.warn(`discarding disconnection request from ${n} to ${r}`)}function Kl(e,t){let{from:r,to:n}=t,i=e.get(r);if(i){let e=i.connections.get(n);if(e){F.enabledFor("info")&&F.info(`mesh connected ${r} to ${n}, sending hello`),e.send({type:"hello",from:r,to:n});let t=i.callbacks?.onMemberAdded;t&&t(r,n)}}}function Vl(e,t){let{from:r,to:n}=t,i=e.get(r);if(i){F.enabledFor("info")&&F.info(`mesh disconnected ${r} from ${n}`);let e=i.callbacks?.onMemberRemoved;e&&e(r,n)}}function zl(e,t){let{from:r,to:n}=t,i=e.get(n);if(i&&i.connections.get(r)){let e=i.callbacks?.onMessage;e&&e(n,Nr(t.msg))}}function Mi(e,t,r){let n=new Map,i=e=>{if(e)switch(F.enabledFor("debug")&&F.debug(`mesh processing command ${JSON.stringify(e,(e,t)=>{if("connection"!==e)return t},"\t")}`),e.type){case"connecting-nodes":jl(n,e);break;case"disconnecting-nodes":Bl(n,e);break;case"node-connected":Kl(n,e);break;case"node-disconnected":Vl(n,e);break;case"node-data":zl(n,e)}},o=Cc(Or({codec:qr(),WebSocket:r?.WebSocket}),r),s=Ac(o,`${e.relays}`,{onConnect:(e,t,r)=>{F.enabledFor("debug")&&F.debug(`server relay connected ${e} to ${t}`),i({type:"connecting-nodes",from:e,to:t,connection:r}),i({type:"node-connected",from:e,to:t})},onDisconnect:(e,t)=>{i({type:"disconnecting-nodes",from:e,to:t}),i({type:"node-disconnected",from:e,to:t})},onReceive:(e,t,r)=>{i({type:"node-data",from:t,to:e,msg:r})}});return new Ci(n,s,t,i,o,r)}L();var ke=R("gateway.mesh.rest-directory");function Ql(e,t,r,n,i){let o=t?.replicaChange;o&&i&&o({cmd:"replica-change",node:e,replicas:[i]});let s=t?.disconnect;s&&n.forEach(t=>s({cmd:"disconnect",node:e,from:t}));let a=t?.connect;a&&r.forEach(t=>a({cmd:"connect",node:e,to:t}))}var Pi=class{#e;#t;#o;constructor(e,t,r,n){if(this.#e=e,this.#t=t,r>0){let e=async()=>{Di(this.#e,this.#t,n),clearTimeout(this.#o),this.#o=setTimeout(e,r)};this.#o=setTimeout(e,r)}}add(e,t,r){this.#e({command:"add",node:e,callbacks:r,endpoint:t})}remove(e){this.#e({command:"remove",node:e})}addUsers(e,...t){this.#e({command:"add-users",node:e,added:t})}removeUsers(e,...t){this.#e({command:"remove-users",node:e,removed:t})}close(){this.#o&&(clearTimeout(this.#o),this.#o=void 0)}};function Yl(e,t,r){r&&(ke.enabledFor("debug")&&ke.debug(`removing node ${r}`),e(`${t}/api/nodes/${r}`,{method:"delete",credentials:"include"}).catch(e=>{ke.warn("remove node request failed",e)}))}async function Zl(e){if(e.ok)return await e.json();throw new Error(`${e.status} ${e.statusText}`)}function Xl(e,t){return ke.enabledFor("debug")&&ke.debug(`processing response ${JSON.stringify(t)}`),t.reduce((e,t)=>{let r=t.node,n=e.get(r);if(n){let i=n.owner,o=t.owner,s=void 0===i||i!==o?o:void 0,a=n.connected,c=t.connect,l=(a??[]).filter(e=>void 0===c||void 0===c.find(t=>t.node===e.node&&t.endpoint===e.endpoint)),u=(c??[]).filter(e=>void 0===a||void 0===a.find(t=>e.node===t.node&&e.endpoint===t.endpoint));return Ql(r,n.callbacks,u,l,s),n.owner=o,n.connected=c,e}return e},e)}function Di(e,t,r){let n=Array.from(t.values()).map(e=>({node:e.node,endpoint:e.endpoint,users:Array.from(e.users),metadata:r}));n.length>0&&e({command:"announce",nodes:n})}function ey(e,t,r,n){let i=JSON.stringify(n);ke.enabledFor("debug")&&ke.debug(`announcing nodes ${i}`),t(`${r}/api/nodes`,{method:"post",body:i,credentials:"include",headers:[["content-type","application/json"]]}).then(async t=>{let r=await Zl(t);e({command:"response",response:r})}).catch(e=>{ke.warn(`announce node request failed. ${e.message}`,e)})}function ty(e,t,r,n,i,o){switch(n.command){case"add":{let{node:e,callbacks:t,endpoint:i}=n;r.set(e,{node:e,callbacks:t,endpoint:i,users:new Set});break}case"remove":{let{node:e}=n;Yl(i,t,e),r.delete(e);break}case"add-users":{let{node:t,added:i}=n,s=r.get(t);s&&(i.forEach(e=>s.users.add(e)),Di(e,r,o));break}case"remove-users":{let{node:t,removed:i}=n,s=r.get(t);s&&(i.forEach(e=>s.users.delete(e)),Di(e,r,o));break}case"announce":{let{nodes:r}=n;ey(e,i,t,r);break}case"response":{let{response:e}=n;Xl(r,e);break}}}function ry(e,t,r,n,i,o){ty(e,t,r,n,i,o)}function Pc(e,t){let r=e.uri,n=e.announceInterval??1e4,i=new Map,o=e=>{ry(o,r,i,e,ny(t),t?.metadata)};return ke.info(`rest directory with uri '${r}' and announce interval ${n}ms`),new Pi(o,i,n,t?.metadata)}function ny(e){let t=e?.fetch??globalThis.fetch??fetch,r=t;if(e?.getHeaders||e?.headers){let t=e?.Headers??globalThis.Headers??Headers;return async(n,i)=>{let o=new t(i?.headers);return e?.headers&&new t(e.headers).forEach((e,t)=>{o.set(t,e)}),e?.getHeaders&&new t(await e.getHeaders()).forEach((e,t)=>{o.set(t,e)}),await r(n,{...i,headers:o})}}return t}function Ut(e,t){return t?.filter(t=>t.domain===e)?.find(e=>{if(void 0===e.identity)return!0;throw new Error("identity in default restrictions rules set is not allowed")})?.restrictions}function _i(e,t){let r=t?.map(t=>iy(e,t));return function(e){return r?.find(t=>oy(t,this,e))?.restrictions}}function iy(e,t){let r={identity:{},restrictions:t.restrictions};if(t[e]&&(r.name=Lt(t[e])),t.identity)for(let[e,n]of Object.entries(t.identity))r.identity[e]=Lt(n);return r}function oy(e,t,r){for(let[r,n]of Object.entries(e.identity)){if(!We(n,t[r]))return!1}return!(e.name&&!We(e.name,r))}Ft();var Oi=class{#e;constructor(e){this.#e=e}add(e,t,r){if(this.#e.has(e)){this.#e.get(e).callbacks=r;let t=r.replicaChange;t&&t({cmd:"replica-change",node:e,replicas:[]});let n=r.connect,i=this.#e.get(e).memberId;n&&Array.from(this.#e.values()).filter(e=>e.memberId{n({cmd:"connect",node:e,to:t.member})})}}remove(e){if(this.#e.has(e)){let t=this.#e.get(e);delete t.callbacks,Array.from(this.#e.values()).filter(e=>e.memberId>t.memberId).filter(e=>e.callbacks?.disconnect).forEach(e=>{let r=e.callbacks?.disconnect;r&&r({cmd:"disconnect",node:e.member.node,from:t.member})})}}addUsers(){}removeUsers(){}close(){}};function Dc(e){let t=new Map;return e.forEach((e,r)=>{t.set(e.node,{member:{...e},memberId:r})}),new Oi(t)}var ae=R("gateway");function sy(e,t){let r=(e?.available??["basic"]).reduce((r,n)=>{if("basic"===n)return r[n]=Fo(e?.basic??{}),r;if("oauth2"===n)return r[n]=Go(e?.oauth2??{},{...t}),r;let i=e?.[n]??{};if(i.authenticator){let e=i.authenticator,t={...i};return delete t.authenticator,r[n]=Wo(t,e),r}return r},{});return{default:e?.default??"basic",available:r}}function ay(e,t,r,n,i){let o=r??e;if(void 0===r&&o.startsWith("http")&&(o=o.replace("http","ws"),o+=o.endsWith("/")?"":"/",o+="relays"),void 0!==n?.members)return Mi({relays:`${o}`},Dc(n.members),i);{let r=n?.uri??e,s=n?.interval;return Mi({relays:`${o}`},Pc({uri:r,announceInterval:s},{metadata:{...t.gateway,...n?.metadata},...i}),i)}}function cy(e,t,r,n,i,o){if(i){r=i.node??r;let s=null===i.auth.user?void 0:"string"==typeof i.auth.user?[i.auth.user]:i.auth.user,a=i.cluster;if(a){let{endpoint:i,relays:c,directory:l,opts:u}=a;return _r(ay(i,t,c,l,{...o,...u}),e,{nodeId:r,signingKey:n,users:s})}let c=i.channel;if(c){return _r(Jo(c),e,{nodeId:r,signingKey:n,users:s})}let l=i.broker?.endpoint;if(l){return _r(Tc(l,o),e,{nodeId:r,signingKey:n,users:s})}}return io(e,{nodeId:r,signingKey:n})}var _c=Wr({cljs:!0}),dy=100,uy="io.Gateway",ki={version:fc,description:uy},py=rt("token.key","metrics.rest.authentication.password","mesh.cluster.auth.basic.password","mesh.cluster.auth.token.value"),Ni=class{#e;#t;constructor(e){this.#t=e}async doStart(e,t){let r=sy(e.authentication,e.globals),n=e.contexts?.lifetime,i={retainedOverride:"retained"===n?void 0:n??"ref-counted",defaultPeerRestrictions:Ut("context",e.peers?.visibility)??"cluster",defaultContextRestrictions:_i("context",e.contexts?.visibility)},o=await Za(e.metrics,t?.endpoint),s=Ut("interop",e.peers?.visibility)??Ut("agm",e.peers?.visibility)??"local",a=cy([qo(r,{...i,welcomeInfo:ki}),nc(i),Ts({defaultPeerRestrictions:s,defaultMethodRestrictions:_i("method",e.methods?.visibility)}),ka(),mc({defaultPeerRestrictions:Ut("bus",e.peers?.visibility)}),Ha(o,e.metrics?.filters)],{gateway:ki,...t},e.node,e.token?.key,e.mesh,e.globals),c=new Map;return{config:e,auth:r,factories:o,node:a,clients:c,scavenger:new Et(c,a,e.clients?.inactive_seconds??0),environment:t}}async startGateway(e,t){return await this.doStart(e,t)}async start(e){let t=this.#t;return ae.info(`starting gateway with environment:\n${JSON.stringify(e)}\nconfiguration:${JSON.stringify(t,py,"\t")}`),this.#e=await this.startGateway(t,e),this}async doStop(e){ae.info(`stopping gateway [${JSON.stringify({environment:e.environment,clients:[...e.clients.keys()]})}]`),Object.values(e.clients).forEach(e=>{e.onStop&&e.onStop()}),e.scavenger.stop(),e.node.close();for(let t of e.factories)await t.shutdown();Object.values(e.auth.available).forEach(e=>e.stop())}async stop(){return this.#e&&(await this.doStop(this.#e),this.#e=void 0),this}info(){return{...ki,endpoint:this.#e?.environment?.endpoint}}cnt=0;async connect(e){if(!this.#e)throw new Error("(no gateway) did you call start?");let t=this.#e,r=this.#e?.config.clients?.buffer_size??dy;ae.info(`local client connected, buffer-size: ${r}`);let n="local:"+ ++this.cnt;return new $r(e,t,{key:n,codec:_c})}client(e,t){if(!this.#e)throw new Error("(no gateway) did you call start() and waited for completion?");if(1!==e.length)throw new Error("expecting function with one arg");let r="local:"+ ++this.cnt,n=this.#e;return new $r(e,n,{key:r,codec:_c,...t})}},$r=class{constructor(e,t,r){this.gw=t,this.receive=1===e.length?e:function(t){e(this,t)}.bind(this),this.key=r.key,this.codec=r.codec,this.host=r.host,this.ping=r.onPing?.bind(this),this.auth=r.onAuthenticate?.bind(this);let n={type:"local",receive:e=>{let t;try{"ping"===e.type&&this.ping?(ae.enabledFor("info")&&ae.info(`checking ${this.key}`),this.ping()):(t=this.codec.encode(e),ae.enabledFor("trace")&&ae.debug(`sending message ${t} to ${this.key}`),Promise.resolve().then(()=>{try{this.receive(t)}catch(e){ae.error(`custom client error, that we're looking for ${t}`,e)}}))}catch(e){ae.error(`unable to send message ${t}`,e)}},endpoint:this.key,host:this.host,auth:this.auth},i=r.onDisconnect?.bind(this);lc(this.gw.clients,this.gw.node,this.key,n,i?()=>{i("inactive")}:void 0,i?()=>{i("shutdown")}:void 0)}receive;key;codec;host;ping;auth;close(){Pr(this.gw.clients,this.gw.node,this.key)}async disconnect(){return this.close(),!0}send(e){try{let t=this.codec.decode(e);ae.enabledFor("debug")&&ae.debug(`processing incoming message from client [${this.key}]`);let r=this.gw.clients.get(this.key);if(r?.source)if("ping"===t.type){let e=Date.now();ae.enabledFor("debug")&&ae.debug(`received ping from ${this.key} at ${e}`),r.lastAccess=e}else this.gw.node.message({origin:"local",source:r.source,body:t});else ae.warn(`cannot process message from non-registered client key ${this.key}`)}catch(e){this.receive(e?.message)}}},qi=e=>new Ni(e),mv=qi,toStr$5=Object.prototype.toString,isArguments$3=function(e){var t=toStr$5.call(e),r="[object Arguments]"===t;return r||(r="[object Array]"!==t&&null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Function]"===toStr$5.call(e.callee)),r},implementation$a,hasRequiredImplementation$1;function requireImplementation$1(){if(hasRequiredImplementation$1)return implementation$a;var e;if(hasRequiredImplementation$1=1,!Object.keys){var t=Object.prototype.hasOwnProperty,r=Object.prototype.toString,n=isArguments$3,i=Object.prototype.propertyIsEnumerable,o=!i.call({toString:null},"toString"),s=i.call(function(){},"prototype"),a=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],c=function(e){var t=e.constructor;return t&&t.prototype===e},l={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},u=function(){if("undefined"==typeof window)return!1;for(var e in window)try{if(!l["$"+e]&&t.call(window,e)&&null!==window[e]&&"object"==typeof window[e])try{c(window[e])}catch(e){return!0}}catch(e){return!0}return!1}();e=function(e){var i=null!==e&&"object"==typeof e,l="[object Function]"===r.call(e),d=n(e),h=i&&"[object String]"===r.call(e),p=[];if(!i&&!l&&!d)throw new TypeError("Object.keys called on a non-object");var g=s&&l;if(h&&e.length>0&&!t.call(e,0))for(var m=0;m0)for(var f=0;f3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new $TypeError$b("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new $TypeError$b("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new $TypeError$b("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new $TypeError$b("`loose`, if provided, must be a boolean");var n=arguments.length>3?arguments[3]:null,i=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,s=arguments.length>6&&arguments[6],a=!!gopd&&gopd(e,t);if($defineProperty$2)$defineProperty$2(e,t,{configurable:null===o&&a?a.configurable:!o,enumerable:null===n&&a?a.enumerable:!n,value:r,writable:null===i&&a?a.writable:!i});else{if(!s&&(n||i||o))throw new $SyntaxError$2("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[t]=r}},$defineProperty$1=esDefineProperty,hasPropertyDescriptors=function(){return!!$defineProperty$1};hasPropertyDescriptors.hasArrayLengthDefineBug=function(){if(!$defineProperty$1)return null;try{return 1!==$defineProperty$1([],"length",{value:1}).length}catch(e){return!0}};var hasPropertyDescriptors_1=hasPropertyDescriptors,keys=objectKeys$2,hasSymbols$4="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),toStr$4=Object.prototype.toString,concat=Array.prototype.concat,defineDataProperty=defineDataProperty$1,isFunction$2=function(e){return"function"==typeof e&&"[object Function]"===toStr$4.call(e)},supportsDescriptors$2=hasPropertyDescriptors_1(),defineProperty$1=function(e,t,r,n){if(t in e)if(!0===n){if(e[t]===r)return}else if(!isFunction$2(n)||!n())return;supportsDescriptors$2?defineDataProperty(e,t,r,!0):defineDataProperty(e,t,r)},defineProperties$1=function(e,t){var r=arguments.length>2?arguments[2]:{},n=keys(t);hasSymbols$4&&(n=concat.call(n,Object.getOwnPropertySymbols(t)));for(var i=0;i1&&"boolean"!=typeof t)throw new $TypeError$9('"allowMissing" argument must be a boolean');if(null===$exec$1(/^%?[^%]*%?$/,e))throw new $SyntaxError$1("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=stringToPath(e),n=r.length>0?r[0]:"",i=getBaseIntrinsic("%"+n+"%",t),o=i.name,s=i.value,a=!1,c=i.alias;c&&(n=c[0],$spliceApply(r,$concat$1([0,1],c)));for(var l=1,u=!0;l=r.length){var g=$gOPD$1(s,d);s=(u=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:s[d]}else u=hasOwn$3(s,d),s=s[d];u&&!a&&(INTRINSICS[o]=s)}}return s},GetIntrinsic$8=getIntrinsic,define$5=defineDataProperty$1,hasDescriptors$1=hasPropertyDescriptors_1(),gOPD$4=gopd$1,$TypeError$8=type,$floor$1=GetIntrinsic$8("%Math.floor%"),setFunctionLength=function(e,t){if("function"!=typeof e)throw new $TypeError$8("`fn` is not a function");if("number"!=typeof t||t<0||t>4294967295||$floor$1(t)!==t)throw new $TypeError$8("`length` must be a positive 32-bit integer");var r=arguments.length>2&&!!arguments[2],n=!0,i=!0;if("length"in e&&gOPD$4){var o=gOPD$4(e,"length");o&&!o.configurable&&(n=!1),o&&!o.writable&&(i=!1)}return(n||i||!r)&&(hasDescriptors$1?define$5(e,"length",t,!0,!0):define$5(e,"length",t)),e},bind$1=requireFunctionBind(),$apply=requireFunctionApply(),actualApply=actualApply$1,applyBind=function(){return actualApply(bind$1,$apply,arguments)};!function(e){var t=setFunctionLength,r=esDefineProperty,n=callBindApplyHelpers,i=applyBind;e.exports=function(e){var r=n(arguments),i=e.length-(arguments.length-1);return t(r,1+(i>0?i:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(callBind$6);var callBindExports=callBind$6.exports,GetIntrinsic$7=getIntrinsic,callBindBasic=callBindApplyHelpers,$indexOf$2=callBindBasic([GetIntrinsic$7("%String.prototype.indexOf%")]),callBound$h=function(e,t){var r=GetIntrinsic$7(e,!!t);return"function"==typeof r&&$indexOf$2(e,".prototype.")>-1?callBindBasic([r]):r},objectKeys$1=objectKeys$2,hasSymbols$1=requireShams$1()(),callBound$g=callBound$h,$Object$1=esObjectAtoms,$push=callBound$g("Array.prototype.push"),$propIsEnumerable=callBound$g("Object.prototype.propertyIsEnumerable"),originalGetSymbols=hasSymbols$1?$Object$1.getOwnPropertySymbols:null,implementation$8=function(e,t){if(null==e)throw new TypeError("target must be an object");var r=$Object$1(e);if(1===arguments.length)return r;for(var n=1;n-1?callBind$4(r):r},functionsHaveNames=function(){return"string"==typeof function(){}.name},gOPD$3=Object.getOwnPropertyDescriptor;if(gOPD$3)try{gOPD$3([],"length")}catch(e){gOPD$3=null}functionsHaveNames.functionsHaveConfigurableNames=function(){if(!functionsHaveNames()||!gOPD$3)return!1;var e=gOPD$3(function(){},"name");return!!e&&!!e.configurable};var $bind=Function.prototype.bind;functionsHaveNames.boundFunctionsHaveNames=function(){return functionsHaveNames()&&"function"==typeof $bind&&""!==function(){}.bind().name};var functionsHaveNames_1=functionsHaveNames,define$3=defineDataProperty$1,hasDescriptors=hasPropertyDescriptors_1(),functionsHaveConfigurableNames=functionsHaveNames_1.functionsHaveConfigurableNames(),$TypeError$7=type,setFunctionName$1=function(e,t){if("function"!=typeof e)throw new $TypeError$7("`fn` is not a function");return arguments.length>2&&!!arguments[2]&&!functionsHaveConfigurableNames||(hasDescriptors?define$3(e,"name",t,!0,!0):define$3(e,"name",t)),e},setFunctionName=setFunctionName$1,$TypeError$6=type,$Object=Object,implementation$5=setFunctionName(function(){if(null==this||this!==$Object(this))throw new $TypeError$6("RegExp.prototype.flags getter called on non-object");var e="";return this.hasIndices&&(e+="d"),this.global&&(e+="g"),this.ignoreCase&&(e+="i"),this.multiline&&(e+="m"),this.dotAll&&(e+="s"),this.unicode&&(e+="u"),this.unicodeSets&&(e+="v"),this.sticky&&(e+="y"),e},"get flags",!0),implementation$4=implementation$5,supportsDescriptors$1=defineProperties_1.supportsDescriptors,$gOPD=Object.getOwnPropertyDescriptor,polyfill$2=function(){if(supportsDescriptors$1&&"gim"===/a/gim.flags){var e=$gOPD(RegExp.prototype,"flags");if(e&&"function"==typeof e.get&&"dotAll"in RegExp.prototype&&"hasIndices"in RegExp.prototype){var t="",r={};if(Object.defineProperty(r,"hasIndices",{get:function(){t+="d"}}),Object.defineProperty(r,"sticky",{get:function(){t+="y"}}),e.get.call(r),"dy"===t)return e.get}}return implementation$4},supportsDescriptors=defineProperties_1.supportsDescriptors,getPolyfill$3=polyfill$2,gOPD$2=gopd$1,defineProperty=Object.defineProperty,$TypeError$5=esErrors,getProto$1=requireGetProto(),regex=/a/,shim$3=function(){if(!supportsDescriptors||!getProto$1)throw new $TypeError$5("RegExp.prototype.flags requires a true ES5 environment that supports property descriptors");var e=getPolyfill$3(),t=getProto$1(regex),r=gOPD$2(t,"flags");return r&&r.get===e||defineProperty(t,"flags",{configurable:!0,enumerable:!1,get:e}),e},define$2=defineProperties_1,callBind$3=callBindExports,implementation$3=implementation$5,getPolyfill$2=polyfill$2,shim$2=shim$3,flagsBound=callBind$3(getPolyfill$2());define$2(flagsBound,{getPolyfill:getPolyfill$2,implementation:implementation$3,shim:shim$2});var regexp_prototype_flags=flagsBound,esGetIterator={exports:{}},shams,hasRequiredShams;function requireShams(){if(hasRequiredShams)return shams;hasRequiredShams=1;var e=requireShams$1();return shams=function(){return e()&&!!Symbol.toStringTag}}var hasToStringTag$6=requireShams()(),callBound$e=callBound$h,$toString$6=callBound$e("Object.prototype.toString"),isStandardArguments=function(e){return!(hasToStringTag$6&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===$toString$6(e)},isLegacyArguments=function(e){return!!isStandardArguments(e)||null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==$toString$6(e)&&"callee"in e&&"[object Function]"===$toString$6(e.callee)},supportsStandardArguments=function(){return isStandardArguments(arguments)}();isStandardArguments.isLegacyArguments=isLegacyArguments;var isArguments$2=supportsStandardArguments?isStandardArguments:isLegacyArguments,_nodeResolve_empty={},_nodeResolve_empty$1=Object.freeze({__proto__:null,default:_nodeResolve_empty}),require$$0=getAugmentedNamespace(_nodeResolve_empty$1),hasMap="function"==typeof Map&&Map.prototype,mapSizeDescriptor=Object.getOwnPropertyDescriptor&&hasMap?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,mapSize=hasMap&&mapSizeDescriptor&&"function"==typeof mapSizeDescriptor.get?mapSizeDescriptor.get:null,mapForEach=hasMap&&Map.prototype.forEach,hasSet="function"==typeof Set&&Set.prototype,setSizeDescriptor=Object.getOwnPropertyDescriptor&&hasSet?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,setSize=hasSet&&setSizeDescriptor&&"function"==typeof setSizeDescriptor.get?setSizeDescriptor.get:null,setForEach=hasSet&&Set.prototype.forEach,hasWeakMap="function"==typeof WeakMap&&WeakMap.prototype,weakMapHas=hasWeakMap?WeakMap.prototype.has:null,hasWeakSet="function"==typeof WeakSet&&WeakSet.prototype,weakSetHas=hasWeakSet?WeakSet.prototype.has:null,hasWeakRef="function"==typeof WeakRef&&WeakRef.prototype,weakRefDeref=hasWeakRef?WeakRef.prototype.deref:null,booleanValueOf=Boolean.prototype.valueOf,objectToString=Object.prototype.toString,functionToString=Function.prototype.toString,$match=String.prototype.match,$slice$1=String.prototype.slice,$replace=String.prototype.replace,$toUpperCase=String.prototype.toUpperCase,$toLowerCase=String.prototype.toLowerCase,$test=RegExp.prototype.test,$concat=Array.prototype.concat,$join=Array.prototype.join,$arrSlice=Array.prototype.slice,$floor=Math.floor,bigIntValueOf$1="function"==typeof BigInt?BigInt.prototype.valueOf:null,gOPS=Object.getOwnPropertySymbols,symToString="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,hasShammedSymbols="function"==typeof Symbol&&"object"==typeof Symbol.iterator,toStringTag$1="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===hasShammedSymbols||"symbol")?Symbol.toStringTag:null,isEnumerable=Object.prototype.propertyIsEnumerable,gPO$1=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function addNumericSeparator(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||$test.call(/e/,t))return t;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var n=e<0?-$floor(-e):$floor(e);if(n!==e){var i=String(n),o=$slice$1.call(t,i.length+1);return $replace.call(i,r,"$&_")+"."+$replace.call($replace.call(o,/([0-9]{3})/g,"$&_"),/_$/,"")}}return $replace.call(t,r,"$&_")}var utilInspect=require$$0,inspectCustom=utilInspect.custom,inspectSymbol=isSymbol$2(inspectCustom)?inspectCustom:null,quotes={__proto__:null,double:'"',single:"'"},quoteREs={__proto__:null,double:/(["\\])/g,single:/(['\\])/g},objectInspect=function e(t,r,n,i){var o=r||{};if(has(o,"quoteStyle")&&!has(quotes,o.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(has(o,"maxStringLength")&&("number"==typeof o.maxStringLength?o.maxStringLength<0&&o.maxStringLength!==1/0:null!==o.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var s=!has(o,"customInspect")||o.customInspect;if("boolean"!=typeof s&&"symbol"!==s)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(has(o,"indent")&&null!==o.indent&&"\t"!==o.indent&&!(parseInt(o.indent,10)===o.indent&&o.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(has(o,"numericSeparator")&&"boolean"!=typeof o.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var a=o.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return inspectString(t,o);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var c=String(t);return a?addNumericSeparator(t,c):c}if("bigint"==typeof t){var l=String(t)+"n";return a?addNumericSeparator(t,l):l}var u=void 0===o.depth?5:o.depth;if(void 0===n&&(n=0),n>=u&&u>0&&"object"==typeof t)return isArray$4(t)?"[Array]":"[Object]";var d=getIndent(o,n);if(void 0===i)i=[];else if(indexOf(i,t)>=0)return"[Circular]";function h(t,r,s){if(r&&(i=$arrSlice.call(i)).push(r),s){var a={depth:o.depth};return has(o,"quoteStyle")&&(a.quoteStyle=o.quoteStyle),e(t,a,n+1,i)}return e(t,o,n+1,i)}if("function"==typeof t&&!isRegExp$1(t)){var p=nameOf(t),g=arrObjKeys(t,h);return"[Function"+(p?": "+p:" (anonymous)")+"]"+(g.length>0?" { "+$join.call(g,", ")+" }":"")}if(isSymbol$2(t)){var m=hasShammedSymbols?$replace.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):symToString.call(t);return"object"!=typeof t||hasShammedSymbols?m:markBoxed(m)}if(isElement(t)){for(var f="<"+$toLowerCase.call(String(t.nodeName)),y=t.attributes||[],$=0;$"}if(isArray$4(t)){if(0===t.length)return"[]";var b=arrObjKeys(t,h);return d&&!singleLineValues(b)?"["+indentedJoin(b,d)+"]":"[ "+$join.call(b,", ")+" ]"}if(isError(t)){var v=arrObjKeys(t,h);return"cause"in Error.prototype||!("cause"in t)||isEnumerable.call(t,"cause")?0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+$join.call(v,", ")+" }":"{ ["+String(t)+"] "+$join.call($concat.call("[cause]: "+h(t.cause),v),", ")+" }"}if("object"==typeof t&&s){if(inspectSymbol&&"function"==typeof t[inspectSymbol]&&utilInspect)return utilInspect(t,{depth:u-n});if("symbol"!==s&&"function"==typeof t.inspect)return t.inspect()}if(isMap$3(t)){var w=[];return mapForEach&&mapForEach.call(t,function(e,r){w.push(h(r,t,!0)+" => "+h(e,t))}),collectionOf("Map",mapSize.call(t),w,d)}if(isSet$3(t)){var S=[];return setForEach&&setForEach.call(t,function(e){S.push(h(e,t))}),collectionOf("Set",setSize.call(t),S,d)}if(isWeakMap$1(t))return weakCollectionOf("WeakMap");if(isWeakSet$1(t))return weakCollectionOf("WeakSet");if(isWeakRef(t))return weakCollectionOf("WeakRef");if(isNumber$2(t))return markBoxed(h(Number(t)));if(isBigInt$1(t))return markBoxed(h(bigIntValueOf$1.call(t)));if(isBoolean$2(t))return markBoxed(booleanValueOf.call(t));if(isString$4(t))return markBoxed(h(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&t===globalThis||void 0!==commonjsGlobal$1&&t===commonjsGlobal$1)return"{ [object globalThis] }";if(!isDate$2(t)&&!isRegExp$1(t)){var _=arrObjKeys(t,h),E=gPO$1?gPO$1(t)===Object.prototype:t instanceof Object||t.constructor===Object,C=t instanceof Object?"":"null prototype",I=!E&&toStringTag$1&&Object(t)===t&&toStringTag$1 in t?$slice$1.call(toStr$3(t),8,-1):C?"Object":"",T=(E||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(I||C?"["+$join.call($concat.call([],I||[],C||[]),": ")+"] ":"");return 0===_.length?T+"{}":d?T+"{"+indentedJoin(_,d)+"}":T+"{ "+$join.call(_,", ")+" }"}return String(t)};function wrapQuotes(e,t,r){var n=r.quoteStyle||t,i=quotes[n];return i+e+i}function quote(e){return $replace.call(String(e),/"/g,""")}function canTrustToString(e){return!toStringTag$1||!("object"==typeof e&&(toStringTag$1 in e||void 0!==e[toStringTag$1]))}function isArray$4(e){return"[object Array]"===toStr$3(e)&&canTrustToString(e)}function isDate$2(e){return"[object Date]"===toStr$3(e)&&canTrustToString(e)}function isRegExp$1(e){return"[object RegExp]"===toStr$3(e)&&canTrustToString(e)}function isError(e){return"[object Error]"===toStr$3(e)&&canTrustToString(e)}function isString$4(e){return"[object String]"===toStr$3(e)&&canTrustToString(e)}function isNumber$2(e){return"[object Number]"===toStr$3(e)&&canTrustToString(e)}function isBoolean$2(e){return"[object Boolean]"===toStr$3(e)&&canTrustToString(e)}function isSymbol$2(e){if(hasShammedSymbols)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!symToString)return!1;try{return symToString.call(e),!0}catch(e){}return!1}function isBigInt$1(e){if(!e||"object"!=typeof e||!bigIntValueOf$1)return!1;try{return bigIntValueOf$1.call(e),!0}catch(e){}return!1}var hasOwn$2=Object.prototype.hasOwnProperty||function(e){return e in this};function has(e,t){return hasOwn$2.call(e,t)}function toStr$3(e){return objectToString.call(e)}function nameOf(e){if(e.name)return e.name;var t=$match.call(functionToString.call(e),/^function\s*([\w$]+)/);return t?t[1]:null}function indexOf(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,n=e.length;rt.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return inspectString($slice$1.call(e,0,t.maxStringLength),t)+n}var i=quoteREs[t.quoteStyle||"single"];return i.lastIndex=0,wrapQuotes($replace.call($replace.call(e,i,"\\$1"),/[\x00-\x1f]/g,lowbyte),"single",t)}function lowbyte(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+$toUpperCase.call(t.toString(16))}function markBoxed(e){return"Object("+e+")"}function weakCollectionOf(e){return e+" { ? }"}function collectionOf(e,t,r,n){return e+" ("+t+") {"+(n?indentedJoin(r,n):$join.call(r,", "))+"}"}function singleLineValues(e){for(var t=0;t=0)return!1;return!0}function getIndent(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=$join.call(Array(e.indent+1)," ")}return{base:r,prev:$join.call(Array(t+1),r)}}function indentedJoin(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+$join.call(e,","+r)+"\n"+t.prev}function arrObjKeys(e,t){var r=isArray$4(e),n=[];if(r){n.length=e.length;for(var i=0;i=e.length)return t+1;var r=$charCodeAt(e,t);if(r<55296||r>56319)return t+1;var n=$charCodeAt(e,t+1);return n<56320||n>57343?t+1:t+2},getArrayIterator=function(e){var t=0;return{next:function(){var r,n=t>=e.length;return n||(r=e[t],t+=1),{done:n,value:r}}}},getNonCollectionIterator=function(e,t){if(isArray$3(e)||isArguments$1(e))return getArrayIterator(e);if(isString$2(e)){var r=0;return{next:function(){var t=advanceStringIndex(e,r),n=$stringSlice(e,r,t);return r=t,{done:t>e.length,value:n}}}}return t&&void 0!==e["_es6-shim iterator_"]?e["_es6-shim iterator_"]():void 0};if($Map||$Set$1){var isMap$1=isMap$2,isSet$1=isSet$2,$mapForEach=callBound$b("Map.prototype.forEach",!0),$setForEach=callBound$b("Set.prototype.forEach",!0),$mapIterator=callBound$b("Map.prototype.iterator",!0),$setIterator=callBound$b("Set.prototype.iterator",!0),$mapAtAtIterator=callBound$b("Map.prototype.@@iterator",!0)||callBound$b("Map.prototype._es6-shim iterator_",!0),$setAtAtIterator=callBound$b("Set.prototype.@@iterator",!0)||callBound$b("Set.prototype._es6-shim iterator_",!0),getCollectionIterator=function(e){if(isMap$1(e)){if($mapIterator)return getStopIterationIterator($mapIterator(e));if($mapAtAtIterator)return $mapAtAtIterator(e);if($mapForEach){var t=[];return $mapForEach(e,function(e,r){$arrayPush(t,[r,e])}),getArrayIterator(t)}}if(isSet$1(e)){if($setIterator)return getStopIterationIterator($setIterator(e));if($setAtAtIterator)return $setAtAtIterator(e);if($setForEach){var r=[];return $setForEach(e,function(e){$arrayPush(r,e)}),getArrayIterator(r)}}};esGetIterator.exports=function(e){return getCollectionIterator(e)||getNonCollectionIterator(e)}}else esGetIterator.exports=function(e){if(null!=e)return getNonCollectionIterator(e,!0)}}var esGetIteratorExports=esGetIterator.exports,numberIsNaN=function(e){return e!=e},implementation$2=function(e,t){return 0===e&&0===t?1/e==1/t:e===t||!(!numberIsNaN(e)||!numberIsNaN(t))},implementation$1=implementation$2,polyfill$1=function(){return"function"==typeof Object.is?Object.is:implementation$1},getPolyfill$1=polyfill$1,define$1=defineProperties_1,shim$1=function(){var e=getPolyfill$1();return define$1(Object,{is:e},{is:function(){return Object.is!==e}}),e},define=defineProperties_1,callBind$2=callBindExports,implementation=implementation$2,getPolyfill=polyfill$1,shim=shim$1,polyfill=callBind$2(getPolyfill(),Object);define(polyfill,{getPolyfill:getPolyfill,implementation:implementation,shim:shim});var objectIs=polyfill,callBind$1=callBindExports,callBound$a=callBound$h,GetIntrinsic$2=getIntrinsic,$ArrayBuffer=GetIntrinsic$2("%ArrayBuffer%",!0),$byteLength$2=callBound$a("ArrayBuffer.prototype.byteLength",!0),$toString$5=callBound$a("Object.prototype.toString"),abSlice=!!$ArrayBuffer&&!$byteLength$2&&new $ArrayBuffer(0).slice,$abSlice=!!abSlice&&callBind$1(abSlice),isArrayBuffer$3=$byteLength$2||$abSlice?function(e){if(!e||"object"!=typeof e)return!1;try{return $byteLength$2?$byteLength$2(e):$abSlice(e,0),!0}catch(e){return!1}}:$ArrayBuffer?function(e){return"[object ArrayBuffer]"===$toString$5(e)}:function(e){return!1},callBound$9=callBound$h,getDay=callBound$9("Date.prototype.getDay"),tryDateObject=function(e){try{return getDay(e),!0}catch(e){return!1}},toStr$2=callBound$9("Object.prototype.toString"),dateClass="[object Date]",hasToStringTag$5=requireShams()(),isDateObject=function(e){return"object"==typeof e&&null!==e&&(hasToStringTag$5?tryDateObject(e):toStr$2(e)===dateClass)},callBound$8=callBound$h,hasToStringTag$4=requireShams()(),hasOwn=requireHasown(),gOPD$1=gopd$1,fn;if(hasToStringTag$4){var $exec=callBound$8("RegExp.prototype.exec"),isRegexMarker={},throwRegexMarker=function(){throw isRegexMarker},badStringifier={toString:throwRegexMarker,valueOf:throwRegexMarker};"symbol"==typeof Symbol.toPrimitive&&(badStringifier[Symbol.toPrimitive]=throwRegexMarker),fn=function(e){if(!e||"object"!=typeof e)return!1;var t=gOPD$1(e,"lastIndex");if(!(t&&hasOwn(t,"value")))return!1;try{$exec(e,badStringifier)}catch(e){return e===isRegexMarker}}}else{var $toString$4=callBound$8("Object.prototype.toString"),regexClass="[object RegExp]";fn=function(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&$toString$4(e)===regexClass}}var isRegex$1=fn,callBound$7=callBound$h,$byteLength$1=callBound$7("SharedArrayBuffer.prototype.byteLength",!0),isSharedArrayBuffer$1=$byteLength$1?function(e){if(!e||"object"!=typeof e)return!1;try{return $byteLength$1(e),!0}catch(e){return!1}}:function(e){return!1},callBound$6=callBound$h,$numToStr=callBound$6("Number.prototype.toString"),tryNumberObject=function(e){try{return $numToStr(e),!0}catch(e){return!1}},$toString$3=callBound$6("Object.prototype.toString"),numClass="[object Number]",hasToStringTag$3=requireShams()(),isNumberObject=function(e){return"number"==typeof e||!(!e||"object"!=typeof e)&&(hasToStringTag$3?tryNumberObject(e):$toString$3(e)===numClass)},callBound$5=callBound$h,$boolToStr=callBound$5("Boolean.prototype.toString"),$toString$2=callBound$5("Object.prototype.toString"),tryBooleanObject=function(e){try{return $boolToStr(e),!0}catch(e){return!1}},boolClass="[object Boolean]",hasToStringTag$2=requireShams()(),isBooleanObject=function(e){return"boolean"==typeof e||null!==e&&"object"==typeof e&&(hasToStringTag$2?tryBooleanObject(e):$toString$2(e)===boolClass)},isSymbol$1={exports:{}},safeRegexTest$1,hasRequiredSafeRegexTest;function requireSafeRegexTest(){if(hasRequiredSafeRegexTest)return safeRegexTest$1;hasRequiredSafeRegexTest=1;var e=isRegex$1,t=callBound$h("RegExp.prototype.exec"),r=type;return safeRegexTest$1=function(n){if(!e(n))throw new r("`regex` must be a RegExp");return function(e){return null!==t(n,e)}},safeRegexTest$1}var callBound$4=callBound$h,$toString$1=callBound$4("Object.prototype.toString"),hasSymbols=hasSymbols$3(),safeRegexTest=requireSafeRegexTest();if(hasSymbols){var $symToStr=callBound$4("Symbol.prototype.toString"),isSymString=safeRegexTest(/^Symbol\(.*\)$/),isSymbolObject=function(e){return"symbol"==typeof e.valueOf()&&isSymString($symToStr(e))};isSymbol$1.exports=function(e){if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||"[object Symbol]"!==$toString$1(e))return!1;try{return isSymbolObject(e)}catch(e){return!1}}}else isSymbol$1.exports=function(e){return!1};var isSymbolExports=isSymbol$1.exports,isBigint={exports:{}},$BigInt="undefined"!=typeof BigInt&&BigInt,hasBigints=function(){return"function"==typeof $BigInt&&"function"==typeof BigInt&&"bigint"==typeof $BigInt(42)&&"bigint"==typeof BigInt(42)},hasBigInts=hasBigints();if(hasBigInts){var bigIntValueOf=BigInt.prototype.valueOf,tryBigInt=function(e){try{return bigIntValueOf.call(e),!0}catch(e){}return!1};isBigint.exports=function(e){return null!=e&&"boolean"!=typeof e&&"string"!=typeof e&&"number"!=typeof e&&"symbol"!=typeof e&&"function"!=typeof e&&("bigint"==typeof e||tryBigInt(e))}}else isBigint.exports=function(e){return!1};var isBigintExports=isBigint.exports,isString$1=requireIsString(),isNumber$1=isNumberObject,isBoolean$1=isBooleanObject,isSymbol=isSymbolExports,isBigInt=isBigintExports,whichBoxedPrimitive$1=function(e){return null==e||"object"!=typeof e&&"function"!=typeof e?null:isString$1(e)?"String":isNumber$1(e)?"Number":isBoolean$1(e)?"Boolean":isSymbol(e)?"Symbol":isBigInt(e)?"BigInt":void 0},$WeakMap="function"==typeof WeakMap&&WeakMap.prototype?WeakMap:null,$WeakSet$1="function"==typeof WeakSet&&WeakSet.prototype?WeakSet:null,exported;$WeakMap||(exported=function(e){return!1});var $mapHas$2=$WeakMap?$WeakMap.prototype.has:null,$setHas$2=$WeakSet$1?$WeakSet$1.prototype.has:null;exported||$mapHas$2||(exported=function(e){return!1});var isWeakmap=exported||function(e){if(!e||"object"!=typeof e)return!1;try{if($mapHas$2.call(e,$mapHas$2),$setHas$2)try{$setHas$2.call(e,$setHas$2)}catch(e){return!0}return e instanceof $WeakMap}catch(e){}return!1},isWeakset={exports:{}},GetIntrinsic$1=getIntrinsic,callBound$3=callBound$h,$WeakSet=GetIntrinsic$1("%WeakSet%",!0),$setHas$1=callBound$3("WeakSet.prototype.has",!0);if($setHas$1){var $mapHas$1=callBound$3("WeakMap.prototype.has",!0);isWeakset.exports=function(e){if(!e||"object"!=typeof e)return!1;try{if($setHas$1(e,$setHas$1),$mapHas$1)try{$mapHas$1(e,$mapHas$1)}catch(e){return!0}return e instanceof $WeakSet}catch(e){}return!1}}else isWeakset.exports=function(e){return!1};var isWeaksetExports=isWeakset.exports,isMap=isMap$2,isSet=isSet$2,isWeakMap=isWeakmap,isWeakSet=isWeaksetExports,whichCollection$1=function(e){if(e&&"object"==typeof e){if(isMap(e))return"Map";if(isSet(e))return"Set";if(isWeakMap(e))return"WeakMap";if(isWeakSet(e))return"WeakSet"}return!1},fnToStr=Function.prototype.toString,reflectApply="object"==typeof Reflect&&null!==Reflect&&Reflect.apply,badArrayLike,isCallableMarker;if("function"==typeof reflectApply&&"function"==typeof Object.defineProperty)try{badArrayLike=Object.defineProperty({},"length",{get:function(){throw isCallableMarker}}),isCallableMarker={},reflectApply(function(){throw 42},null,badArrayLike)}catch(_){_!==isCallableMarker&&(reflectApply=null)}else reflectApply=null;var constructorRegex=/^\s*class\b/,isES6ClassFn=function(e){try{var t=fnToStr.call(e);return constructorRegex.test(t)}catch(e){return!1}},tryFunctionObject=function(e){try{return!isES6ClassFn(e)&&(fnToStr.call(e),!0)}catch(e){return!1}},toStr$1=Object.prototype.toString,objectClass="[object Object]",fnClass="[object Function]",genClass="[object GeneratorFunction]",ddaClass="[object HTMLAllCollection]",ddaClass2="[object HTML document.all class]",ddaClass3="[object HTMLCollection]",hasToStringTag$1="function"==typeof Symbol&&!!Symbol.toStringTag,isIE68=!(0 in[,]),isDDA=function(){return!1};if("object"==typeof document){var all$1=document.all;toStr$1.call(all$1)===toStr$1.call(document.all)&&(isDDA=function(e){if((isIE68||!e)&&(void 0===e||"object"==typeof e))try{var t=toStr$1.call(e);return(t===ddaClass||t===ddaClass2||t===ddaClass3||t===objectClass)&&null==e("")}catch(e){}return!1})}var isCallable$1=reflectApply?function(e){if(isDDA(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;try{reflectApply(e,null,badArrayLike)}catch(e){if(e!==isCallableMarker)return!1}return!isES6ClassFn(e)&&tryFunctionObject(e)}:function(e){if(isDDA(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(hasToStringTag$1)return tryFunctionObject(e);if(isES6ClassFn(e))return!1;var t=toStr$1.call(e);return!(t!==fnClass&&t!==genClass&&!/^\[object HTML/.test(t))&&tryFunctionObject(e)},isCallable=isCallable$1,toStr=Object.prototype.toString,hasOwnProperty$1=Object.prototype.hasOwnProperty,forEachArray=function(e,t,r){for(var n=0,i=e.length;n=3&&(n=r),isArray$2(e)?forEachArray(e,t,n):"string"==typeof e?forEachString(e,t,n):forEachObject(e,t,n)},possibleTypedArrayNames=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],possibleNames=possibleTypedArrayNames,g$1="undefined"==typeof globalThis?commonjsGlobal$1:globalThis,availableTypedArrays$1=function(){for(var e=[],t=0;t-1?t:"Object"===t&&trySlices(e)}return gOPD?tryTypedArrays(e):null},callBound$1=callBound$h,$byteLength=callBound$1("ArrayBuffer.prototype.byteLength",!0),isArrayBuffer$2=isArrayBuffer$3,arrayBufferByteLength=function(e){return isArrayBuffer$2(e)?$byteLength?$byteLength(e):e.byteLength:NaN},assign=object_assign,callBound=callBound$f,flags=regexp_prototype_flags,GetIntrinsic=getIntrinsic,getIterator=esGetIteratorExports,getSideChannel=sideChannel,is$1=objectIs,isArguments=isArguments$2,isArray$1=isarray,isArrayBuffer$1=isArrayBuffer$3,isDate$1=isDateObject,isRegex=isRegex$1,isSharedArrayBuffer=isSharedArrayBuffer$1,objectKeys=objectKeys$2,whichBoxedPrimitive=whichBoxedPrimitive$1,whichCollection=whichCollection$1,whichTypedArray=whichTypedArray$1,byteLength=arrayBufferByteLength,sabByteLength=callBound("SharedArrayBuffer.prototype.byteLength",!0),$getTime=callBound("Date.prototype.getTime"),gPO=Object.getPrototypeOf,$objToString=callBound("Object.prototype.toString"),$Set=GetIntrinsic("%Set%",!0),$mapHas=callBound("Map.prototype.has",!0),$mapGet=callBound("Map.prototype.get",!0),$mapSize=callBound("Map.prototype.size",!0),$setAdd=callBound("Set.prototype.add",!0),$setDelete=callBound("Set.prototype.delete",!0),$setHas=callBound("Set.prototype.has",!0),$setSize=callBound("Set.prototype.size",!0);function setHasEqualElement(e,t,r,n){for(var i,o=getIterator(e);(i=o.next())&&!i.done;)if(internalDeepEqual(t,i.value,r,n))return $setDelete(e,i.value),!0;return!1}function findLooseMatchingPrimitives(e){return void 0===e?null:"object"!=typeof e?"symbol"!=typeof e&&("string"!=typeof e&&"number"!=typeof e||+e==+e):void 0}function mapMightHaveLoosePrim(e,t,r,n,i,o){var s=findLooseMatchingPrimitives(r);if(null!=s)return s;var a=$mapGet(t,s),c=assign({},i,{strict:!1});return!(void 0===a&&!$mapHas(t,s)||!internalDeepEqual(n,a,c,o))&&(!$mapHas(e,s)&&internalDeepEqual(n,a,c,o))}function setMightHaveLoosePrim(e,t,r){var n=findLooseMatchingPrimitives(r);return null!=n?n:$setHas(t,n)&&!$setHas(e,n)}function mapHasEqualEntry(e,t,r,n,i,o){for(var s,a,c=getIterator(e);(s=c.next())&&!s.done;)if(internalDeepEqual(r,a=s.value,i,o)&&internalDeepEqual(n,$mapGet(t,a),i,o))return $setDelete(e,a),!0;return!1}function internalDeepEqual(e,t,r,n){var i=r||{};if(i.strict?is$1(e,t):e===t)return!0;if(whichBoxedPrimitive(e)!==whichBoxedPrimitive(t))return!1;if(!e||!t||"object"!=typeof e&&"object"!=typeof t)return i.strict?is$1(e,t):e==t;var o,s=n.has(e),a=n.has(t);if(s&&a){if(n.get(e)===n.get(t))return!0}else o={};return s||n.set(e,o),a||n.set(t,o),objEquiv(e,t,i,n)}function isBuffer$1(e){return!(!e||"object"!=typeof e||"number"!=typeof e.length)&&("function"==typeof e.copy&&"function"==typeof e.slice&&(!(e.length>0&&"number"!=typeof e[0])&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))))}function setEquiv(e,t,r,n){if($setSize(e)!==$setSize(t))return!1;for(var i,o,s,a=getIterator(e),c=getIterator(t);(i=a.next())&&!i.done;)if(i.value&&"object"==typeof i.value)s||(s=new $Set),$setAdd(s,i.value);else if(!$setHas(t,i.value)){if(r.strict)return!1;if(!setMightHaveLoosePrim(e,t,i.value))return!1;s||(s=new $Set),$setAdd(s,i.value)}if(s){for(;(o=c.next())&&!o.done;)if(o.value&&"object"==typeof o.value){if(!setHasEqualElement(s,o.value,r.strict,n))return!1}else if(!r.strict&&!$setHas(e,o.value)&&!setHasEqualElement(s,o.value,r.strict,n))return!1;return 0===$setSize(s)}return!0}function mapEquiv(e,t,r,n){if($mapSize(e)!==$mapSize(t))return!1;for(var i,o,s,a,c,l,u=getIterator(e),d=getIterator(t);(i=u.next())&&!i.done;)if(a=i.value[0],c=i.value[1],a&&"object"==typeof a)s||(s=new $Set),$setAdd(s,a);else if(void 0===(l=$mapGet(t,a))&&!$mapHas(t,a)||!internalDeepEqual(c,l,r,n)){if(r.strict)return!1;if(!mapMightHaveLoosePrim(e,t,a,c,r,n))return!1;s||(s=new $Set),$setAdd(s,a)}if(s){for(;(o=d.next())&&!o.done;)if(a=o.value[0],l=o.value[1],a&&"object"==typeof a){if(!mapHasEqualEntry(s,e,a,l,r,n))return!1}else if(!(r.strict||e.has(a)&&internalDeepEqual($mapGet(e,a),l,r,n)||mapHasEqualEntry(s,e,a,l,assign({},r,{strict:!1}),n)))return!1;return 0===$setSize(s)}return!0}function objEquiv(e,t,r,n){var i,o;if(typeof e!=typeof t)return!1;if(null==e||null==t)return!1;if($objToString(e)!==$objToString(t))return!1;if(isArguments(e)!==isArguments(t))return!1;if(isArray$1(e)!==isArray$1(t))return!1;var s=e instanceof Error,a=t instanceof Error;if(s!==a)return!1;if((s||a)&&(e.name!==t.name||e.message!==t.message))return!1;var c=isRegex(e),l=isRegex(t);if(c!==l)return!1;if((c||l)&&(e.source!==t.source||flags(e)!==flags(t)))return!1;var u=isDate$1(e),d=isDate$1(t);if(u!==d)return!1;if((u||d)&&$getTime(e)!==$getTime(t))return!1;if(r.strict&&gPO&&gPO(e)!==gPO(t))return!1;var h=whichTypedArray(e),p=whichTypedArray(t);if(h!==p)return!1;if(h||p){if(e.length!==t.length)return!1;for(i=0;i=0;i--)if(v[i]!=w[i])return!1;for(i=v.length-1;i>=0;i--)if(!internalDeepEqual(e[o=v[i]],t[o],r,n))return!1;var S=whichCollection(e),_=whichCollection(t);return S===_&&("Set"===S||"Set"===_?setEquiv(e,t,r,n):"Map"!==S||mapEquiv(e,t,r,n))}var deepEqual$1=function(e,t,r){return internalDeepEqual(e,t,r,getSideChannel())},deepEqual$2=getDefaultExportFromCjs$2(deepEqual$1),fastDeepEqual=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(i=n;0!==i--;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(o=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(i=n;0!==i--;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;0!==i--;){var s=o[i];if(!e(t[s],r[s]))return!1}return!0}return t!=t&&r!=r},equal=getDefaultExportFromCjs$2(fastDeepEqual);let urlAlphabet$3="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$5=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$3[64*Math.random()|0];return t};class IOError{extractErrorMsg(e){return"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e)}raiseError(e,t){const r=this.extractErrorMsg(e);if(errorChannel.port1.postMessage(r),t)throw e;throw new Error(r)}}const ioError=new IOError;var utils$6={};const WIN_SLASH="\\\\/",WIN_NO_SLASH=`[^${WIN_SLASH}]`,DOT_LITERAL="\\.",PLUS_LITERAL="\\+",QMARK_LITERAL="\\?",SLASH_LITERAL="\\/",ONE_CHAR="(?=.)",QMARK="[^/]",END_ANCHOR=`(?:${SLASH_LITERAL}|$)`,START_ANCHOR=`(?:^|${SLASH_LITERAL})`,DOTS_SLASH=`${DOT_LITERAL}{1,2}${END_ANCHOR}`,NO_DOT=`(?!${DOT_LITERAL})`,NO_DOTS=`(?!${START_ANCHOR}${DOTS_SLASH})`,NO_DOT_SLASH=`(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`,NO_DOTS_SLASH=`(?!${DOTS_SLASH})`,QMARK_NO_DOT=`[^.${SLASH_LITERAL}]`,STAR=`${QMARK}*?`,SEP="/",POSIX_CHARS={DOT_LITERAL:DOT_LITERAL,PLUS_LITERAL:PLUS_LITERAL,QMARK_LITERAL:QMARK_LITERAL,SLASH_LITERAL:SLASH_LITERAL,ONE_CHAR:ONE_CHAR,QMARK:QMARK,END_ANCHOR:END_ANCHOR,DOTS_SLASH:DOTS_SLASH,NO_DOT:NO_DOT,NO_DOTS:NO_DOTS,NO_DOT_SLASH:NO_DOT_SLASH,NO_DOTS_SLASH:NO_DOTS_SLASH,QMARK_NO_DOT:QMARK_NO_DOT,STAR:STAR,START_ANCHOR:START_ANCHOR,SEP:SEP},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:`[${WIN_SLASH}]`,QMARK:WIN_NO_SLASH,STAR:`${WIN_NO_SLASH}*?`,DOTS_SLASH:`${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,NO_DOT:`(?!${DOT_LITERAL})`,NO_DOTS:`(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,NO_DOT_SLASH:`(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,NO_DOTS_SLASH:`(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,QMARK_NO_DOT:`[^.${WIN_SLASH}]`,START_ANCHOR:`(?:^|[${WIN_SLASH}])`,END_ANCHOR:`(?:[${WIN_SLASH}]|$)`,SEP:"\\"},POSIX_REGEX_SOURCE$1={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};var constants$2={MAX_LENGTH:65536,POSIX_REGEX_SOURCE:POSIX_REGEX_SOURCE$1,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars:e=>({"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}),globChars:e=>!0===e?WINDOWS_CHARS:POSIX_CHARS};!function(e){const{REGEX_BACKSLASH:t,REGEX_REMOVE_BACKSLASH:r,REGEX_SPECIAL_CHARS:n,REGEX_SPECIAL_CHARS_GLOBAL:i}=constants$2;e.isObject=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),e.hasRegexChars=e=>n.test(e),e.isRegexChar=t=>1===t.length&&e.hasRegexChars(t),e.escapeRegex=e=>e.replace(i,"\\$1"),e.toPosixSlashes=e=>e.replace(t,"/"),e.isWindows=()=>{if("undefined"!=typeof navigator&&navigator.platform){const e=navigator.platform.toLowerCase();return"win32"===e||"windows"===e}return!1},e.removeBackslashes=e=>e.replace(r,e=>"\\"===e?"":e),e.escapeLast=(t,r,n)=>{const i=t.lastIndexOf(r,n);return-1===i?t:"\\"===t[i-1]?e.escapeLast(t,r,i-1):`${t.slice(0,i)}\\${t.slice(i)}`},e.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r},e.wrapOutput=(e,t={},r={})=>{let n=`${r.contains?"":"^"}(?:${e})${r.contains?"":"$"}`;return!0===t.negated&&(n=`(?:^(?!${n}).*$)`),n},e.basename=(e,{windows:t}={})=>{const r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return""===n?r[r.length-2]:n}}(utils$6);const utils$5=utils$6,{CHAR_ASTERISK:CHAR_ASTERISK,CHAR_AT:CHAR_AT,CHAR_BACKWARD_SLASH:CHAR_BACKWARD_SLASH,CHAR_COMMA:CHAR_COMMA,CHAR_DOT:CHAR_DOT,CHAR_EXCLAMATION_MARK:CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH:CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE:CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES:CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET:CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS:CHAR_PLUS,CHAR_QUESTION_MARK:CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE:CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES:CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET:CHAR_RIGHT_SQUARE_BRACKET}=constants$2,isPathSeparator=e=>e===CHAR_FORWARD_SLASH||e===CHAR_BACKWARD_SLASH,depth=e=>{!0!==e.isPrefix&&(e.depth=e.isGlobstar?1/0:1)},scan$1=(e,t)=>{const r=t||{},n=e.length-1,i=!0===r.parts||!0===r.scanToEnd,o=[],s=[],a=[];let c,l,u=e,d=-1,h=0,p=0,g=!1,m=!1,f=!1,y=!1,$=!1,b=!1,v=!1,w=!1,S=!1,_=!1,E=0,C={value:"",depth:0,isGlob:!1};const I=()=>d>=n,T=()=>u.charCodeAt(d+1),A=()=>(c=l,u.charCodeAt(++d));for(;d0&&(x=u.slice(0,h),u=u.slice(h),p-=h),D&&!0===f&&p>0?(D=u.slice(0,p),R=u.slice(p)):!0===f?(D="",R=u):D=u,D&&""!==D&&"/"!==D&&D!==u&&isPathSeparator(D.charCodeAt(D.length-1))&&(D=D.slice(0,-1)),!0===r.unescape&&(R&&(R=utils$5.removeBackslashes(R)),D&&!0===v&&(D=utils$5.removeBackslashes(D)));const O={prefix:x,input:e,start:h,base:D,glob:R,isBrace:g,isBracket:m,isGlob:f,isExtglob:y,isGlobstar:$,negated:w,negatedExtglob:S};if(!0===r.tokens&&(O.maxDepth=0,isPathSeparator(l)||s.push(C),O.tokens=s),!0===r.parts||!0===r.tokens){let t;for(let n=0;n{if("function"==typeof t.expandRange)return t.expandRange(...e,t);e.sort();const r=`[${e.join("-")}]`;try{new RegExp(r)}catch(t){return e.map(e=>utils$4.escapeRegex(e)).join("..")}return r},syntaxError=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,parse$3=(e,t)=>{if("string"!=typeof e)throw new TypeError("Expected a string");e=REPLACEMENTS[e]||e;const r={...t},n="number"==typeof r.maxLength?Math.min(MAX_LENGTH,r.maxLength):MAX_LENGTH;let i=e.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);const o={type:"bos",value:"",output:r.prepend||""},s=[o],a=r.capture?"":"?:",c=constants$1.globChars(r.windows),l=constants$1.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:h,ONE_CHAR:p,DOTS_SLASH:g,NO_DOT:m,NO_DOT_SLASH:f,NO_DOTS_SLASH:y,QMARK:$,QMARK_NO_DOT:b,STAR:v,START_ANCHOR:w}=c,S=e=>`(${a}(?:(?!${w}${e.dot?g:u}).)*?)`,_=r.dot?"":m,E=r.dot?$:b;let C=!0===r.bash?S(r):v;r.capture&&(C=`(${C})`),"boolean"==typeof r.noext&&(r.noextglob=r.noext);const I={input:e,index:-1,start:0,dot:!0===r.dot,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:s};e=utils$4.removePrefix(e,I),i=e.length;const T=[],A=[],D=[];let x,R=o;const O=()=>I.index===i-1,N=I.peek=(t=1)=>e[I.index+t],P=I.advance=()=>e[++I.index]||"",k=()=>e.slice(I.index+1),M=(e="",t=0)=>{I.consumed+=e,I.index+=t},L=e=>{I.output+=null!=e.output?e.output:e.value,M(e.value)},F=()=>{let e=1;for(;"!"===N()&&("("!==N(2)||"?"===N(3));)P(),I.start++,e++;return e%2!=0&&(I.negated=!0,I.start++,!0)},j=e=>{I[e]++,D.push(e)},U=e=>{I[e]--,D.pop()},B=e=>{if("globstar"===R.type){const t=I.braces>0&&("comma"===e.type||"brace"===e.type),r=!0===e.extglob||T.length&&("pipe"===e.type||"paren"===e.type);"slash"===e.type||"paren"===e.type||t||r||(I.output=I.output.slice(0,-R.output.length),R.type="star",R.value="*",R.output=C,I.output+=R.output)}if(T.length&&"paren"!==e.type&&(T[T.length-1].inner+=e.value),(e.value||e.output)&&L(e),R&&"text"===R.type&&"text"===e.type)return R.output=(R.output||R.value)+e.value,void(R.value+=e.value);e.prev=R,s.push(e),R=e},H=(e,t)=>{const n={...l[t],conditions:1,inner:""};n.prev=R,n.parens=I.parens,n.output=I.output;const i=(r.capture?"(":"")+n.open;j("parens"),B({type:e,value:t,output:I.output?"":p}),B({type:"paren",extglob:!0,value:P(),output:i}),T.push(n)},q=e=>{let n,i=e.close+(r.capture?")":"");if("negate"===e.type){let o=C;if(e.inner&&e.inner.length>1&&e.inner.includes("/")&&(o=S(r)),(o!==C||O()||/^\)+$/.test(k()))&&(i=e.close=`)$))${o}`),e.inner.includes("*")&&(n=k())&&/^\.[^\\/.]+$/.test(n)){const r=parse$3(n,{...t,fastpaths:!1}).output;i=e.close=`)${r})${o})`}"bos"===e.prev.type&&(I.negatedExtglob=!0)}B({type:"paren",extglob:!0,value:x,output:i}),U("parens")};if(!1!==r.fastpaths&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=!1,i=e.replace(REGEX_SPECIAL_CHARS_BACKREF,(e,t,r,i,o,s)=>"\\"===i?(n=!0,e):"?"===i?t?t+i+(o?$.repeat(o.length):""):0===s?E+(o?$.repeat(o.length):""):$.repeat(r.length):"."===i?u.repeat(r.length):"*"===i?t?t+i+(o?C:""):C:t?e:`\\${e}`);return!0===n&&(i=!0===r.unescape?i.replace(/\\/g,""):i.replace(/\\+/g,e=>e.length%2==0?"\\\\":e?"\\":"")),i===e&&!0===r.contains?(I.output=e,I):(I.output=utils$4.wrapOutput(i,I,t),I)}for(;!O();){if(x=P(),"\0"===x)continue;if("\\"===x){const e=N();if("/"===e&&!0!==r.bash)continue;if("."===e||";"===e)continue;if(!e){x+="\\",B({type:"text",value:x});continue}const t=/^\\+/.exec(k());let n=0;if(t&&t[0].length>2&&(n=t[0].length,I.index+=n,n%2!=0&&(x+="\\")),!0===r.unescape?x=P():x+=P(),0===I.brackets){B({type:"text",value:x});continue}}if(I.brackets>0&&("]"!==x||"["===R.value||"[^"===R.value)){if(!1!==r.posix&&":"===x){const e=R.value.slice(1);if(e.includes("[")&&(R.posix=!0,e.includes(":"))){const e=R.value.lastIndexOf("["),t=R.value.slice(0,e),r=R.value.slice(e+2),n=POSIX_REGEX_SOURCE[r];if(n){R.value=t+n,I.backtrack=!0,P(),o.output||1!==s.indexOf(R)||(o.output=p);continue}}}("["===x&&":"!==N()||"-"===x&&"]"===N())&&(x=`\\${x}`),"]"!==x||"["!==R.value&&"[^"!==R.value||(x=`\\${x}`),!0===r.posix&&"!"===x&&"["===R.value&&(x="^"),R.value+=x,L({value:x});continue}if(1===I.quotes&&'"'!==x){x=utils$4.escapeRegex(x),R.value+=x,L({value:x});continue}if('"'===x){I.quotes=1===I.quotes?0:1,!0===r.keepQuotes&&B({type:"text",value:x});continue}if("("===x){j("parens"),B({type:"paren",value:x});continue}if(")"===x){if(0===I.parens&&!0===r.strictBrackets)throw new SyntaxError(syntaxError("opening","("));const e=T[T.length-1];if(e&&I.parens===e.parens+1){q(T.pop());continue}B({type:"paren",value:x,output:I.parens?")":"\\)"}),U("parens");continue}if("["===x){if(!0!==r.nobracket&&k().includes("]"))j("brackets");else{if(!0!==r.nobracket&&!0===r.strictBrackets)throw new SyntaxError(syntaxError("closing","]"));x=`\\${x}`}B({type:"bracket",value:x});continue}if("]"===x){if(!0===r.nobracket||R&&"bracket"===R.type&&1===R.value.length){B({type:"text",value:x,output:`\\${x}`});continue}if(0===I.brackets){if(!0===r.strictBrackets)throw new SyntaxError(syntaxError("opening","["));B({type:"text",value:x,output:`\\${x}`});continue}U("brackets");const e=R.value.slice(1);if(!0===R.posix||"^"!==e[0]||e.includes("/")||(x=`/${x}`),R.value+=x,L({value:x}),!1===r.literalBrackets||utils$4.hasRegexChars(e))continue;const t=utils$4.escapeRegex(R.value);if(I.output=I.output.slice(0,-R.value.length),!0===r.literalBrackets){I.output+=t,R.value=t;continue}R.value=`(${a}${t}|${R.value})`,I.output+=R.value;continue}if("{"===x&&!0!==r.nobrace){j("braces");const e={type:"brace",value:x,output:"(",outputIndex:I.output.length,tokensIndex:I.tokens.length};A.push(e),B(e);continue}if("}"===x){const e=A[A.length-1];if(!0===r.nobrace||!e){B({type:"text",value:x,output:x});continue}let t=")";if(!0===e.dots){const e=s.slice(),n=[];for(let t=e.length-1;t>=0&&(s.pop(),"brace"!==e[t].type);t--)"dots"!==e[t].type&&n.unshift(e[t].value);t=expandRange(n,r),I.backtrack=!0}if(!0!==e.comma&&!0!==e.dots){const r=I.output.slice(0,e.outputIndex),n=I.tokens.slice(e.tokensIndex);e.value=e.output="\\{",x=t="\\}",I.output=r;for(const e of n)I.output+=e.output||e.value}B({type:"brace",value:x,output:t}),U("braces"),A.pop();continue}if("|"===x){T.length>0&&T[T.length-1].conditions++,B({type:"text",value:x});continue}if(","===x){let e=x;const t=A[A.length-1];t&&"braces"===D[D.length-1]&&(t.comma=!0,e="|"),B({type:"comma",value:x,output:e});continue}if("/"===x){if("dot"===R.type&&I.index===I.start+1){I.start=I.index+1,I.consumed="",I.output="",s.pop(),R=o;continue}B({type:"slash",value:x,output:h});continue}if("."===x){if(I.braces>0&&"dot"===R.type){"."===R.value&&(R.output=u);const e=A[A.length-1];R.type="dots",R.output+=x,R.value+=x,e.dots=!0;continue}if(I.braces+I.parens===0&&"bos"!==R.type&&"slash"!==R.type){B({type:"text",value:x,output:u});continue}B({type:"dot",value:x,output:u});continue}if("?"===x){if(!(R&&"("===R.value)&&!0!==r.noextglob&&"("===N()&&"?"!==N(2)){H("qmark",x);continue}if(R&&"paren"===R.type){const e=N();let t=x;("("===R.value&&!/[!=<:]/.test(e)||"<"===e&&!/<([!=]|\w+>)/.test(k()))&&(t=`\\${x}`),B({type:"text",value:x,output:t});continue}if(!0!==r.dot&&("slash"===R.type||"bos"===R.type)){B({type:"qmark",value:x,output:b});continue}B({type:"qmark",value:x,output:$});continue}if("!"===x){if(!0!==r.noextglob&&"("===N()&&("?"!==N(2)||!/[!=<:]/.test(N(3)))){H("negate",x);continue}if(!0!==r.nonegate&&0===I.index){F();continue}}if("+"===x){if(!0!==r.noextglob&&"("===N()&&"?"!==N(2)){H("plus",x);continue}if(R&&"("===R.value||!1===r.regex){B({type:"plus",value:x,output:d});continue}if(R&&("bracket"===R.type||"paren"===R.type||"brace"===R.type)||I.parens>0){B({type:"plus",value:x});continue}B({type:"plus",value:d});continue}if("@"===x){if(!0!==r.noextglob&&"("===N()&&"?"!==N(2)){B({type:"at",extglob:!0,value:x,output:""});continue}B({type:"text",value:x});continue}if("*"!==x){"$"!==x&&"^"!==x||(x=`\\${x}`);const e=REGEX_NON_SPECIAL_CHARS.exec(k());e&&(x+=e[0],I.index+=e[0].length),B({type:"text",value:x});continue}if(R&&("globstar"===R.type||!0===R.star)){R.type="star",R.star=!0,R.value+=x,R.output=C,I.backtrack=!0,I.globstar=!0,M(x);continue}let t=k();if(!0!==r.noextglob&&/^\([^?]/.test(t)){H("star",x);continue}if("star"===R.type){if(!0===r.noglobstar){M(x);continue}const n=R.prev,i=n.prev,o="slash"===n.type||"bos"===n.type,s=i&&("star"===i.type||"globstar"===i.type);if(!0===r.bash&&(!o||t[0]&&"/"!==t[0])){B({type:"star",value:x,output:""});continue}const a=I.braces>0&&("comma"===n.type||"brace"===n.type),c=T.length&&("pipe"===n.type||"paren"===n.type);if(!o&&"paren"!==n.type&&!a&&!c){B({type:"star",value:x,output:""});continue}for(;"/**"===t.slice(0,3);){const r=e[I.index+4];if(r&&"/"!==r)break;t=t.slice(3),M("/**",3)}if("bos"===n.type&&O()){R.type="globstar",R.value+=x,R.output=S(r),I.output=R.output,I.globstar=!0,M(x);continue}if("slash"===n.type&&"bos"!==n.prev.type&&!s&&O()){I.output=I.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type="globstar",R.output=S(r)+(r.strictSlashes?")":"|$)"),R.value+=x,I.globstar=!0,I.output+=n.output+R.output,M(x);continue}if("slash"===n.type&&"bos"!==n.prev.type&&"/"===t[0]){const e=void 0!==t[1]?"|$":"";I.output=I.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type="globstar",R.output=`${S(r)}${h}|${h}${e})`,R.value+=x,I.output+=n.output+R.output,I.globstar=!0,M(x+P()),B({type:"slash",value:"/",output:""});continue}if("bos"===n.type&&"/"===t[0]){R.type="globstar",R.value+=x,R.output=`(?:^|${h}|${S(r)}${h})`,I.output=R.output,I.globstar=!0,M(x+P()),B({type:"slash",value:"/",output:""});continue}I.output=I.output.slice(0,-R.output.length),R.type="globstar",R.output=S(r),R.value+=x,I.output+=R.output,I.globstar=!0,M(x);continue}const n={type:"star",value:x,output:C};!0!==r.bash?!R||"bracket"!==R.type&&"paren"!==R.type||!0!==r.regex?(I.index!==I.start&&"slash"!==R.type&&"dot"!==R.type||("dot"===R.type?(I.output+=f,R.output+=f):!0===r.dot?(I.output+=y,R.output+=y):(I.output+=_,R.output+=_),"*"!==N()&&(I.output+=p,R.output+=p)),B(n)):(n.output=x,B(n)):(n.output=".*?","bos"!==R.type&&"slash"!==R.type||(n.output=_+n.output),B(n))}for(;I.brackets>0;){if(!0===r.strictBrackets)throw new SyntaxError(syntaxError("closing","]"));I.output=utils$4.escapeLast(I.output,"["),U("brackets")}for(;I.parens>0;){if(!0===r.strictBrackets)throw new SyntaxError(syntaxError("closing",")"));I.output=utils$4.escapeLast(I.output,"("),U("parens")}for(;I.braces>0;){if(!0===r.strictBrackets)throw new SyntaxError(syntaxError("closing","}"));I.output=utils$4.escapeLast(I.output,"{"),U("braces")}if(!0===r.strictSlashes||"star"!==R.type&&"bracket"!==R.type||B({type:"maybe_slash",value:"",output:`${h}?`}),!0===I.backtrack){I.output="";for(const e of I.tokens)I.output+=null!=e.output?e.output:e.value,e.suffix&&(I.output+=e.suffix)}return I};parse$3.fastpaths=(e,t)=>{const r={...t},n="number"==typeof r.maxLength?Math.min(MAX_LENGTH,r.maxLength):MAX_LENGTH,i=e.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);e=REPLACEMENTS[e]||e;const{DOT_LITERAL:o,SLASH_LITERAL:s,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:h,START_ANCHOR:p}=constants$1.globChars(r.windows),g=r.dot?u:l,m=r.dot?d:l,f=r.capture?"":"?:";let y=!0===r.bash?".*?":h;r.capture&&(y=`(${y})`);const $=e=>!0===e.noglobstar?y:`(${f}(?:(?!${p}${e.dot?c:o}).)*?)`,b=e=>{switch(e){case"*":return`${g}${a}${y}`;case".*":return`${o}${a}${y}`;case"*.*":return`${g}${y}${o}${a}${y}`;case"*/*":return`${g}${y}${s}${a}${m}${y}`;case"**":return g+$(r);case"**/*":return`(?:${g}${$(r)}${s})?${m}${a}${y}`;case"**/*.*":return`(?:${g}${$(r)}${s})?${m}${y}${o}${a}${y}`;case"**/.*":return`(?:${g}${$(r)}${s})?${o}${a}${y}`;default:{const t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;const r=b(t[1]);if(!r)return;return r+o+t[2]}}},v=utils$4.removePrefix(e,{negated:!1,prefix:""});let w=b(v);return w&&!0!==r.strictSlashes&&(w+=`${s}?`),w};var parse_1=parse$3;const scan=scan_1,parse$2=parse_1,utils$3=utils$6,constants=constants$2,isObject$2=e=>e&&"object"==typeof e&&!Array.isArray(e),picomatch$1=(e,t,r=!1)=>{if(Array.isArray(e)){const n=e.map(e=>picomatch$1(e,t,r)),i=e=>{for(const t of n){const r=t(e);if(r)return r}return!1};return i}const n=isObject$2(e)&&e.tokens&&e.input;if(""===e||"string"!=typeof e&&!n)throw new TypeError("Expected pattern to be a non-empty string");const i=t||{},o=i.windows,s=n?picomatch$1.compileRe(e,t):picomatch$1.makeRe(e,t,!1,!0),a=s.state;delete s.state;let c=()=>!1;if(i.ignore){const e={...t,ignore:null,onMatch:null,onResult:null};c=picomatch$1(i.ignore,e,r)}const l=(r,n=!1)=>{const{isMatch:l,match:u,output:d}=picomatch$1.test(r,s,t,{glob:e,posix:o}),h={glob:e,state:a,regex:s,posix:o,input:r,output:d,match:u,isMatch:l};return"function"==typeof i.onResult&&i.onResult(h),!1===l?(h.isMatch=!1,!!n&&h):c(r)?("function"==typeof i.onIgnore&&i.onIgnore(h),h.isMatch=!1,!!n&&h):("function"==typeof i.onMatch&&i.onMatch(h),!n||h)};return r&&(l.state=a),l};picomatch$1.test=(e,t,r,{glob:n,posix:i}={})=>{if("string"!=typeof e)throw new TypeError("Expected input to be a string");if(""===e)return{isMatch:!1,output:""};const o=r||{},s=o.format||(i?utils$3.toPosixSlashes:null);let a=e===n,c=a&&s?s(e):e;return!1===a&&(c=s?s(e):e,a=c===n),!1!==a&&!0!==o.capture||(a=!0===o.matchBase||!0===o.basename?picomatch$1.matchBase(e,t,r,i):t.exec(c)),{isMatch:Boolean(a),match:a,output:c}},picomatch$1.matchBase=(e,t,r)=>(t instanceof RegExp?t:picomatch$1.makeRe(t,r)).test(utils$3.basename(e)),picomatch$1.isMatch=(e,t,r)=>picomatch$1(t,r)(e),picomatch$1.parse=(e,t)=>Array.isArray(e)?e.map(e=>picomatch$1.parse(e,t)):parse$2(e,{...t,fastpaths:!1}),picomatch$1.scan=(e,t)=>scan(e,t),picomatch$1.compileRe=(e,t,r=!1,n=!1)=>{if(!0===r)return e.output;const i=t||{},o=i.contains?"":"^",s=i.contains?"":"$";let a=`${o}(?:${e.output})${s}`;e&&!0===e.negated&&(a=`^(?!${a}).*$`);const c=picomatch$1.toRegex(a,t);return!0===n&&(c.state=e),c},picomatch$1.makeRe=(e,t={},r=!1,n=!1)=>{if(!e||"string"!=typeof e)throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return!1===t.fastpaths||"."!==e[0]&&"*"!==e[0]||(i.output=parse$2.fastpaths(e,t)),i.output||(i=parse$2(e,t)),picomatch$1.compileRe(i,t,r,n)},picomatch$1.toRegex=(e,t)=>{try{const r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(e){if(t&&!0===t.debug)throw e;return/$^/}},picomatch$1.constants=constants;var picomatch_1$1=picomatch$1;const pico=picomatch_1$1,utils$2=utils$6;function picomatch(e,t,r=!1){return!t||null!==t.windows&&void 0!==t.windows||(t={...t,windows:utils$2.isWindows()}),pico(e,t,r)}Object.assign(picomatch,pico);var picomatch_1=picomatch,pm=getDefaultExportFromCjs$2(picomatch_1);const getRelativeBounds=(e,t,r)=>"bottom"===r?{left:t.left,top:t.top+t.height+0,width:t.width,height:e.height}:"top"===r?{left:t.left,top:t.top-e.height-0,width:t.width,height:e.height}:"right"===r?{left:t.left+t.width+0,top:t.top,width:e.width,height:t.height}:"left"===r?{left:t.left-e.width-0,top:t.top,width:e.width,height:t.height}:ioError.raiseError("invalid relativeDirection"),objEqual=(e,t)=>deepEqual$2(e,t,{strict:!0}),objEqualFast=(e,t)=>equal(e,t),waitFor=(e,t)=>{let r=e;return()=>{r--,0===r&&t()}},wait=e=>new Promise(t=>setTimeout(()=>t(),e)),extractErrorMsg$1=e=>"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),checkMatch=(e,t)=>{if(!e.count)return!1;const r=t();return r&&(e.count=--e.count<0?0:e.count),r},clearNullUndefined=e=>{Object.keys(e).forEach(t=>{null!==e[t]&&void 0!==e[t]||delete e[t]})},runDecoderWithIOError=(e,t)=>{try{return e.runWithException(t)}catch(e){return ioError.raiseError(e,!0)}},checkIsOriginBlocked=(e,t=[])=>{const r=new URL(e);if(!t.length)return!1;if(t.includes("*"))return!0;return t.some(e=>pm(e)(r.origin))},getSafeTimeoutDelay=e=>Math.min(e,MAX_SET_TIMEOUT_DELAY);function generateLayoutToken(){return nanoid$5(10)}const getLastUpdateTimestamp=()=>(new Date).toISOString(),escapeRegex$1=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");class Gateway{_gatewayInstance;configureLogging=Oc.Logging.configure;create=mv;async start(e,t){if(e?.logging){const t=e.logging.appender;this.configureLogging({level:e.logging.level||"error",appender:e=>{if(t){const r={time:e.time,output:e.message,level:e.level,line:-1,message:e.message,namespace:e.name,stacktrace:""};t(r)}}})}const r=this.getGatewayConfig(e,t);this._gatewayInstance=this.create(r),await this._gatewayInstance.start()}async connectClient(e){return this._gatewayInstance.connect((t,r)=>e.postMessage(r))}async connectExtClient(e,t){const r=await this._gatewayInstance.connect((t,r)=>e.postMessage({glue42ExtInc:r}));e.onMessage.addListener(n=>{const i=n?.glue42ExtOut?.glue42core;if(i&&i.type===Glue42CoreMessageTypes.clientUnload.name)return r.close(),e.disconnect(),void(t&&t(i.data.clientId,!0));if(n.glue42ExtOut&&!i){const e=n.glue42ExtOut;return void r.send(e)}})}async setupInternalClient(e){let t;e.onmessage=async r=>{const n=r.data?.glue42core;if(n&&n.type===Glue42CoreMessageTypes.gatewayInternalConnect.name)t=await this.handleInternalGatewayConnectionRequest(e);else if(t&&!e.closed)return n&&n.type===Glue42CoreMessageTypes.gatewayDisconnect.name?(e.closed=!0,void t?.close()):void t?.send(r.data)}}async handleInternalGatewayConnectionRequest(e){e.closed=!1;try{const t=await this._gatewayInstance.connect((t,r)=>e.postMessage(r));return e.postMessage({glue42core:{type:Glue42CoreMessageTypes.gatewayInternalConnect.name,success:!0}}),t}catch(t){const r="string"==typeof t?t:JSON.stringify(t.message);return void e.postMessage({glue42core:{type:Glue42CoreMessageTypes.gatewayInternalConnect.name,error:r}})}}getGatewayConfig(e,t){const r={clients:{inactive_seconds:0,buffer_size:"number"==typeof e?.clients?.buffer_size?e.clients.buffer_size:1e3},contexts:{lifetime:"retained"}};if(!e?.bridge)return r;if(!t)return ioError.raiseError("Platform initialization failed due to missing user details. Providing configuration settings for connecting to io.Bridge also requires providing user details via the `user` property.");const n=t.id;return r.authentication={basic:{usernameResolver:()=>n}},r.mesh={auth:{user:n},cluster:{endpoint:e.bridge.url,directory:{interval:6e4,metadata:{type:"io.Connect Browser"}},opts:{headers:e.bridge.headers,getHeaders:e.bridge.getHeaders,getWebSocketSearchParams:e.bridge.getWebSocketSearchParams}}},r.contexts={...r.contexts,visibility:[{context:new RegExp(/^___instance___.+/),restrictions:"local"},{context:new RegExp(/^___window___.+/),restrictions:"local"},{context:new RegExp(/^___window-hibernation___.+/),restrictions:"local"},{context:new RegExp(/^___workspace___.+/),restrictions:"local"},{context:new RegExp(`^${escapeRegex$1(ChannelContextPrefix)}.+`),restrictions:e.bridge.channels?.enabled??1?"cluster":"local"},...e.bridge.contexts?.visibility??[],{context:new RegExp(/[\s\S]*/),restrictions:e.bridge.contexts?.enabled??1?"cluster":"local"}]},r.methods={visibility:[{method:new RegExp(`^${escapeRegex$1(GlueWebIntentsPrefix)}.+`),restrictions:e.bridge.intents?.enabled??1?"cluster":"local"},{method:/^T42\.Search\.(Client|Provider)$/,restrictions:e.bridge.search?.enabled??1?"cluster":"local"},{method:/^T42\..+/,restrictions:"local"},...e.bridge.interop?.visibility??[],{method:new RegExp(/[\s\S]*/),restrictions:e.bridge.interop?.enabled??1?"cluster":"local"}]},r.peers={visibility:[{domain:"context",restrictions:"cluster"},{domain:"interop",restrictions:"cluster"}]},r}}function createRegistry$2(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;ir(e)).catch(e=>n(e))}async handlePluginMessage(e,t){return this.processControllerCommand(e,"plugin",t)}async processControllerCommand(e,t,r){try{this.domainsController.validateDomain(e.domain)}catch(e){const n=extractErrorMsg$1(e);return this.logger?.trace(`rejecting execution of a command issued by a ${t}: ${r}, because of a domain validation error: ${n}`),ioError.raiseError(`Cannot execute this platform control, because of domain validation error: ${n}`)}const n=Object.assign({},e,{commandId:nanoid$5(10),callerId:r,callerType:t});this.logger?.trace(`[${n.commandId}] received a command for a valid domain: ${e.domain} from ${t}: ${r}, forwarding to the appropriate controller`);try{const e=await this.executeCommand(n);return this.logger?.trace(`[${n.commandId}] this command was executed successfully, sending the result to the caller.`),e}catch(t){const r="string"==typeof t?t:t.message?JSON.stringify(t.message):JSON.stringify(t);throw this.logger?.trace(`[${n.commandId}] this command's execution was rejected, reason: ${r}`),new Error(`The platform rejected operation ${n.operation} for domain: ${e.domain} with reason: ${r}`)}}handleClientUnloaded(e){this.domainsController.notifyDomainsClientUnloaded(e)}executeCommand(e){const t=this.interceptionController.getOperationInterceptor({domain:e.domain,operation:e.operation});return t&&!e.settings?.skipInterception?(this.logger?.trace(`[${e.commandId}] The operation is being intercepted and executed by: ${t.name}`),t.intercept(e)):this.domainsController.executeControlMessage(e)}buildPlatformApi(){return{version:this.glueController.platformVersion,contextTrackGlue:this.ctxTrackingGlue,systemGlue:this.systemGlue,connectExtClient:(e,t)=>this.connectExtClient(e,t),onSystemReconnect:e=>this.onSystemReconnect(e),system:{shutdown:this.shutDown.bind(this),cache:{clear:this.idbCacheController.clear.bind(this.idbCacheController),deleteOtherDBs:this.idbCacheController.deleteOtherDBs.bind(this.idbCacheController)},connection:{switchGW:this.preferredConnectionController.connectPreferred.bind(this.preferredConnectionController),switchToInternal:this.preferredConnectionController.revertToDefault.bind(this.preferredConnectionController)}}}}async connectExtClient(e,t){await this.portsBridge.handleExtConnectionRequest(e,t)}onSystemReconnect(e){return this.preferredConnectionController.onReconnect(e)}async shutDown(){this.restScheduler.stop(),await this.glueController.sendShutDownSignals(),this.stateController.cancel(),this.portsBridge.shutdown(),this.domainsController.shutdown(),this.serviceWorkerController.shutdown(),await this.pluginsController.shutdown(),this.interceptionController.shutdown(),this.preferredConnectionController.shutdown(),this.glueController.shutdown(),this.sessionController.shutdown(),this.localStorageController.stop(),this.idbController.stop(),this.idbCacheController.stop();const e=window.iobrowser?.system;window.iobrowser={webStarted:!1,system:e}}verifyLicense(e){if(!e||"string"!=typeof e||!e.length)return ioError.raiseError("The provided license key is not a valid string");if(!this.licenseController.verifyLicense(e).valid)return this.logExpirationErrors(),ioError.raiseError("io.Connect Browser cannot initialize, because there was no license token provided or it was invalid.");const t=this.licenseController.getLicensePayload(e),r=window.location;return this.licenseController.isPlatformOriginAllowed(r,t.platformAllowOrigins)?"trial"===t.type&&this.licenseController.checkExpired(t.expiration)?(this.logExpirationErrors(),ioError.raiseError("io.Connect Browser cannot initialize, because the provided trial license has expired.")):(this.licenseController.checkExpired(t.expiration)&&this.logExpirationErrors(),void console.info(`This io.Connect Browser is running with a ${t.type} license, which expires on: ${new Date(t.expiration).toString()}`)):ioError.raiseError("io.Connect Browser cannot initialize, because the platform origin is not allowed by the provided license.")}logExpirationErrors(){console.error("***********************************************************************************************************"),console.error("***********************************************************************************************************"),console.error("********************** This io.Connect Browser has an expired or invalid license **************************"),console.error("***********************************************************************************************************"),console.error("***********************************************************************************************************")}getProfileData(e,t){const r=this.licenseController.getLicensePayload(e),n={license:{type:r.type,expiration:r.expiration},productsInfo:{platform:{apiVersion:this.glueController.platformVersion},client:{apiVersion:this.glueController.clientGlue.version}},plugins:this.pluginsController.registeredPlugins.map(e=>({name:e.name,version:e.version}))};return t&&(n.user={id:t.id,username:t.username,email:t.email,firstName:t.firstName,lastName:t.lastName,type:t.type,role:t.role,meta:t.meta}),this.glueController.clientGlue.workspaces&&(n.productsInfo.workspaces={apiVersion:this.glueController.clientGlue.workspaces.version,container:window.ioworkspaces?{type:window.ioworkspaces.type,version:window.ioworkspaces.version}:void 0}),this.glueController.clientGlue.search&&(n.productsInfo.search={apiVersion:this.glueController.clientGlue.search.version}),this.glueController.clientGlue.modals&&(n.productsInfo.modals={apiVersion:this.glueController.clientGlue.modals.version}),window.iohome&&(n.productsInfo.home={version:window.iohome.version}),n}async startCacheIdb(e){const t=e.applicationPreferences?.store?.rest?.cache?.enabled,r=e.layouts?.rest?.cache?.enabled,n=e.applications?.remote?.cache?.enabled;(t||r||n)&&(this.logger?.info("Starting IDB cache..."),await this.idbCacheController.start(e.user))}}const connectBrowserAppProps=["name","title","version","customProperties","icon","caption","type"],fdc3v2AppProps=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var ok$3=function(e){return{ok:!0,result:e}},err$3=function(e){return{ok:!1,error:e}},asPromise$3=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$3=function(e,t){return!0===t.ok?t.result:e},withException$3=function(e){if(!0===e.ok)return e.result;throw e.error},map$4=function(e,t){return!0===t.ok?ok$3(e(t.result)):t},map2$3=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$3(e(t.result,r.result))},mapError$3=function(e,t){return!0===t.ok?t:err$3(e(t.error))},andThen$3=function(e,t){return!0===t.ok?e(t.result):t},__assign$3=function(){return __assign$3=Object.assign||function(e){for(var t,r=1,n=arguments.length;re.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$3=number$6().where(e=>e>=0,"Expected a non-negative number"),regexDecoder$1=anyJson$3().andThen(e=>e instanceof RegExp?anyJson$3():fail("expected a regex, got a "+typeof e)),intentDefinitionDecoder$1=object$4({name:nonEmptyStringDecoder$4,displayName:optional$4(string$6()),contexts:optional$4(array$4(string$6())),customConfig:optional$4(object$4())}),v2TypeDecoder=oneOf$2(constant$3("web"),constant$3("native"),constant$3("citrix"),constant$3("onlineNative"),constant$3("other")),v2DetailsDecoder=object$4({url:nonEmptyStringDecoder$4}),v2IconDecoder=object$4({src:nonEmptyStringDecoder$4,size:optional$4(nonEmptyStringDecoder$4),type:optional$4(nonEmptyStringDecoder$4)}),v2ScreenshotDecoder=object$4({src:nonEmptyStringDecoder$4,size:optional$4(nonEmptyStringDecoder$4),type:optional$4(nonEmptyStringDecoder$4),label:optional$4(nonEmptyStringDecoder$4)}),v2ListensForIntentDecoder=object$4({contexts:array$4(nonEmptyStringDecoder$4),displayName:optional$4(nonEmptyStringDecoder$4),resultType:optional$4(nonEmptyStringDecoder$4),customConfig:optional$4(anyJson$3())}),v2IntentsDecoder=object$4({listensFor:optional$4(dict(v2ListensForIntentDecoder)),raises:optional$4(dict(array$4(nonEmptyStringDecoder$4)))}),v2UserChannelDecoder=object$4({broadcasts:optional$4(array$4(nonEmptyStringDecoder$4)),listensFor:optional$4(array$4(nonEmptyStringDecoder$4))}),v2AppChannelDecoder=object$4({name:nonEmptyStringDecoder$4,description:optional$4(nonEmptyStringDecoder$4),broadcasts:optional$4(array$4(nonEmptyStringDecoder$4)),listensFor:optional$4(array$4(nonEmptyStringDecoder$4))}),v2InteropDecoder=object$4({intents:optional$4(v2IntentsDecoder),userChannels:optional$4(v2UserChannelDecoder),appChannels:optional$4(array$4(v2AppChannelDecoder))}),glue42ApplicationDetailsDecoder=object$4({url:optional$4(nonEmptyStringDecoder$4),top:optional$4(number$6()),left:optional$4(number$6()),width:optional$4(nonNegativeNumberDecoder$3),height:optional$4(nonNegativeNumberDecoder$3)}),glue42HostManifestsBrowserDecoder=object$4({name:optional$4(nonEmptyStringDecoder$4),type:optional$4(nonEmptyStringDecoder$4.where(e=>"window"===e,"Expected a value of window")),title:optional$4(nonEmptyStringDecoder$4),version:optional$4(nonEmptyStringDecoder$4),customProperties:optional$4(anyJson$3()),icon:optional$4(string$6()),caption:optional$4(string$6()),details:optional$4(glue42ApplicationDetailsDecoder),intents:optional$4(array$4(intentDefinitionDecoder$1)),hidden:optional$4(boolean$5())}),v1DefinitionDecoder=object$4({name:nonEmptyStringDecoder$4,appId:nonEmptyStringDecoder$4,title:optional$4(nonEmptyStringDecoder$4),version:optional$4(nonEmptyStringDecoder$4),manifest:nonEmptyStringDecoder$4,manifestType:nonEmptyStringDecoder$4,tooltip:optional$4(nonEmptyStringDecoder$4),description:optional$4(nonEmptyStringDecoder$4),contactEmail:optional$4(nonEmptyStringDecoder$4),supportEmail:optional$4(nonEmptyStringDecoder$4),publisher:optional$4(nonEmptyStringDecoder$4),images:optional$4(array$4(object$4({url:optional$4(nonEmptyStringDecoder$4)}))),icons:optional$4(array$4(object$4({icon:optional$4(nonEmptyStringDecoder$4)}))),customConfig:anyJson$3(),intents:optional$4(array$4(intentDefinitionDecoder$1))}),v2LocalizedDefinitionDecoder=object$4({appId:optional$4(nonEmptyStringDecoder$4),name:optional$4(nonEmptyStringDecoder$4),details:optional$4(v2DetailsDecoder),version:optional$4(nonEmptyStringDecoder$4),title:optional$4(nonEmptyStringDecoder$4),tooltip:optional$4(nonEmptyStringDecoder$4),lang:optional$4(nonEmptyStringDecoder$4),description:optional$4(nonEmptyStringDecoder$4),categories:optional$4(array$4(nonEmptyStringDecoder$4)),icons:optional$4(array$4(v2IconDecoder)),screenshots:optional$4(array$4(v2ScreenshotDecoder)),contactEmail:optional$4(nonEmptyStringDecoder$4),supportEmail:optional$4(nonEmptyStringDecoder$4),moreInfo:optional$4(nonEmptyStringDecoder$4),publisher:optional$4(nonEmptyStringDecoder$4),customConfig:optional$4(array$4(anyJson$3())),hostManifests:optional$4(anyJson$3()),interop:optional$4(v2InteropDecoder)}),v2DefinitionDecoder=object$4({appId:nonEmptyStringDecoder$4,name:optional$4(nonEmptyStringDecoder$4),type:v2TypeDecoder,details:v2DetailsDecoder,version:optional$4(nonEmptyStringDecoder$4),title:optional$4(nonEmptyStringDecoder$4),tooltip:optional$4(nonEmptyStringDecoder$4),lang:optional$4(nonEmptyStringDecoder$4),description:optional$4(nonEmptyStringDecoder$4),categories:optional$4(array$4(nonEmptyStringDecoder$4)),icons:optional$4(array$4(v2IconDecoder)),screenshots:optional$4(array$4(v2ScreenshotDecoder)),contactEmail:optional$4(nonEmptyStringDecoder$4),supportEmail:optional$4(nonEmptyStringDecoder$4),moreInfo:optional$4(nonEmptyStringDecoder$4),publisher:optional$4(nonEmptyStringDecoder$4),customConfig:optional$4(array$4(anyJson$3())),hostManifests:optional$4(anyJson$3()),interop:optional$4(v2InteropDecoder),localizedVersions:optional$4(dict(v2LocalizedDefinitionDecoder))}),allDefinitionsDecoder=oneOf$2(v1DefinitionDecoder,v2DefinitionDecoder),parseDecoderErrorToStringMessage=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class FDC3Service{fdc3ToDesktopDefinitionType={web:"window",native:"exe",citrix:"citrix",onlineNative:"clickonce",other:"window"};toApi(){return{isFdc3Definition:this.isFdc3Definition.bind(this),parseToBrowserBaseAppData:this.parseToBrowserBaseAppData.bind(this),parseToDesktopAppConfig:this.parseToDesktopAppConfig.bind(this)}}isFdc3Definition(e){const t=allDefinitionsDecoder.run(e);return t.ok?e.appId&&e.details?{isFdc3:!0,version:"2.0"}:e.manifest?{isFdc3:!0,version:"1.2"}:{isFdc3:!1,reason:"The passed definition is not FDC3"}:{isFdc3:!1,reason:parseDecoderErrorToStringMessage(t.error)}}parseToBrowserBaseAppData(e){const{isFdc3:t,version:r}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const n=allDefinitionsDecoder.run(e);if(!n.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage(n.error)}`);const i=this.getUserPropertiesFromDefinition(e,r),o={url:this.getUrl(e,r)},s={name:e.appId,type:"window",createOptions:o,userProperties:{...i,intents:"1.2"===r?i.intents:this.getIntentsFromV2AppDefinition(e),details:o},title:e.title,version:e.version,icon:this.getIconFromDefinition(e,r),caption:e.description,fdc3:"2.0"===r?{...e,definitionVersion:"2.0"}:void 0},a=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!a)return s;const c=glue42HostManifestsBrowserDecoder.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(s,c.result):s}parseToDesktopAppConfig(e){const{isFdc3:t,version:r}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const n=allDefinitionsDecoder.run(e);if(!n.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage(n.error)}`);if("1.2"===r){const t=e;return{name:t.appId,type:"window",details:{url:this.getUrl(e,r)},version:t.version,title:t.title,tooltip:t.tooltip,caption:t.description,icon:t.icons?.[0].icon,intents:t.intents,customProperties:{manifestType:t.manifestType,images:t.images,contactEmail:t.contactEmail,supportEmail:t.supportEmail,publisher:t.publisher,icons:t.icons,customConfig:t.customConfig}}}const i=e,o={name:i.appId,type:this.fdc3ToDesktopDefinitionType[i.type],details:i.details,version:i.version,title:i.title,tooltip:i.tooltip,caption:i.description,icon:this.getIconFromDefinition(i,"2.0"),intents:this.getIntentsFromV2AppDefinition(i),fdc3:{...i,definitionVersion:"2.0"}},s=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!s)return o;if("object"!=typeof s||Array.isArray(s))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(o,s)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!connectBrowserAppProps.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!connectBrowserAppProps.includes(e)&&!fdc3v2AppProps.includes(e)))}getUrl(e,t){let r;if("1.2"===t){const t=JSON.parse(e.manifest);r=t.details?.url||t.url}else r=e.details?.url;if(!r||"string"!=typeof r)throw new Error(`Invalid FDC3 ${t} definition. Provide valid 'url' under '${"1.2"===t?"manifest":"details"}' key`);return r}getIntentsFromV2AppDefinition(e){const t=e.interop?.intents?.listensFor;if(!t)return;return Object.entries(t).map(e=>{const[t,r]=e;return{name:t,...r}})}getIconFromDefinition(e,t){return"1.2"===t?e.icons?.find(e=>e.icon)?.icon||void 0:e.icons?.find(e=>e.src)?.src||void 0}mergeBaseAppDataWithGlueManifest(e,t){let r=e;if(t.customProperties&&(r.userProperties={...e.userProperties,...t.customProperties}),t.details){const n={...e.createOptions,...t.details};r.createOptions=n,r.userProperties.details=n}return Array.isArray(t.intents)&&(r.userProperties.intents=(r.userProperties.intents||[]).concat(t.intents)),r={...r,...t},delete r.details,delete r.intents,r}mergeDesktopConfigWithGlueManifest(e,t){const r=Object.assign({},e,t,{details:{...e.details,...t.details}});return Array.isArray(t.intents)&&(r.intents=(e.intents||[]).concat(t.intents)),r}}const decoders$1={common:{nonEmptyStringDecoder:nonEmptyStringDecoder$4,nonNegativeNumberDecoder:nonNegativeNumberDecoder$3,regexDecoder:regexDecoder$1},fdc3:{allDefinitionsDecoder:allDefinitionsDecoder,v1DefinitionDecoder:v1DefinitionDecoder,v2DefinitionDecoder:v2DefinitionDecoder}};var INTENTS_ERRORS;!function(e){e.USER_CANCELLED="User Closed Intents Resolver UI without choosing a handler",e.CALLER_NOT_DEFINED="Caller Id is not defined",e.TIMEOUT_HIT="Timeout hit",e.INTENT_NOT_FOUND="Cannot find Intent",e.HANDLER_NOT_FOUND="Cannot find Intent Handler",e.TARGET_INSTANCE_UNAVAILABLE="Cannot start Target Instance",e.INTENT_DELIVERY_FAILED="Target Instance did not add a listener",e.RESOLVER_UNAVAILABLE="Intents Resolver UI unavailable",e.RESOLVER_TIMEOUT="User did not choose a handler",e.INVALID_RESOLVER_RESPONSE="Intents Resolver UI returned invalid response",e.INTENT_HANDLER_REJECTION="Intent Handler function processing the raised intent threw an error or rejected the promise it returned"}(INTENTS_ERRORS||(INTENTS_ERRORS={}));let IoC$2=class{_fdc3;_decoders=decoders$1;_errors={intents:INTENTS_ERRORS};get fdc3(){return this._fdc3||(this._fdc3=(new FDC3Service).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};const ioc=new IoC$2,fdc3=ioc.fdc3,decoders=ioc.decoders,errors=ioc.errors;var ok$2=function(e){return{ok:!0,result:e}},err$2=function(e){return{ok:!1,error:e}},asPromise$2=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$2=function(e,t){return!0===t.ok?t.result:e},withException$2=function(e){if(!0===e.ok)return e.result;throw e.error},map$3=function(e,t){return!0===t.ok?ok$2(e(t.result)):t},map2$2=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$2(e(t.result,r.result))},mapError$2=function(e,t){return!0===t.ok?t:err$2(e(t.error))},andThen$2=function(e,t){return!0===t.ok?e(t.result):t},__assign$2=function(){return __assign$2=Object.assign||function(e){for(var t,r=1,n=arguments.length;r"string"==typeof e.color&&e.color.length>0,"Expected color to be a non-empty string"),layoutTypeDecoder=oneOf$1(constant$2("Global"),constant$2("Activity"),constant$2("ApplicationDefault"),constant$2("Swimlane"),constant$2("Workspace")),componentTypeDecoder=oneOf$1(constant$2("application"),constant$2("activity")),functionCheck$1=(e,t)=>{const r=typeof e;return"function"===r?anyJson$2():fail$2(`The provided argument as ${t} should be of type function, provided: ${typeof r}`)},operationCheckConfigDecoder=object$3({operation:nonEmptyStringDecoder$2}),operationCheckResultDecoder=object$3({isSupported:boolean$4()}),layoutSummaryDecoder$1=object$3({name:nonEmptyStringDecoder$2,type:layoutTypeDecoder,context:optional$3(anyJson$2()),metadata:optional$3(anyJson$2())}),windowComponentStateDecoder=object$3({context:optional$3(anyJson$2()),bounds:windowBoundsDecoder,createArgs:object$3({name:optional$3(nonEmptyStringDecoder$2),url:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),windowState:optional$3(nonEmptyStringDecoder$2),restoreState:optional$3(nonEmptyStringDecoder$2),instanceId:nonEmptyStringDecoder$2,isCollapsed:optional$3(boolean$4()),isSticky:optional$3(boolean$4()),restoreSettings:object$3({groupId:optional$3(nonEmptyStringDecoder$2),groupZOrder:optional$3(number$5())}),channelId:optional$3(nonEmptyStringDecoder$2)}),windowLayoutComponentDecoder=object$3({type:constant$2("window"),componentType:optional$3(componentTypeDecoder),application:nonEmptyStringDecoder$2,state:windowComponentStateDecoder}),libDomainDecoder=oneOf$1(constant$2("system"),constant$2("windows"),constant$2("appManager"),constant$2("layouts"),constant$2("workspaces"),constant$2("intents"),constant$2("notifications"),constant$2("extension"),constant$2("channels"),constant$2("search"),constant$2("themes"),constant$2("manager"),constant$2("prefs"),constant$2("ui")),systemOperationTypesDecoder=oneOf$1(constant$2("getEnvironment"),constant$2("getBase"),constant$2("operationCheck"),constant$2("workspacesInitCheck"),constant$2("clientError"),constant$2("systemHello"),constant$2("getProfileData")),windowLayoutItemDecoder=object$3({type:constant$2("window"),config:object$3({appName:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),url:optional$3(nonEmptyStringDecoder$2),title:optional$3(string$5()),showCloseButton:optional$3(boolean$4()),allowExtract:optional$3(boolean$4()),allowReorder:optional$3(boolean$4()),isMaximized:optional$3(boolean$4())})}),groupLayoutItemDecoder$1=object$3({type:constant$2("group"),config:anyJson$2(),children:array$3(oneOf$1(windowLayoutItemDecoder))}),columnLayoutItemDecoder$1=object$3({type:constant$2("column"),config:anyJson$2(),children:array$3(oneOf$1(groupLayoutItemDecoder$1,windowLayoutItemDecoder,lazy$1(()=>columnLayoutItemDecoder$1),lazy$1(()=>rowLayoutItemDecoder$1)))}),rowLayoutItemDecoder$1=object$3({type:constant$2("row"),config:anyJson$2(),children:array$3(oneOf$1(columnLayoutItemDecoder$1,groupLayoutItemDecoder$1,windowLayoutItemDecoder,lazy$1(()=>rowLayoutItemDecoder$1)))}),workspaceLayoutComponentStateDecoder=object$3({config:anyJson$2(),context:anyJson$2(),children:array$3(oneOf$1(rowLayoutItemDecoder$1,columnLayoutItemDecoder$1,groupLayoutItemDecoder$1,windowLayoutItemDecoder))}),workspaceLayoutComponentDecoder=object$3({type:constant$2("Workspace"),application:optional$3(string$5()),state:workspaceLayoutComponentStateDecoder}),workspaceFrameComponentStateDecoder=object$3({bounds:windowBoundsDecoder,instanceId:nonEmptyStringDecoder$2,selectedWorkspace:nonNegativeNumberDecoder$2,workspaces:array$3(workspaceLayoutComponentStateDecoder),windowState:optional$3(nonEmptyStringDecoder$2),restoreState:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),workspaceFrameComponentDecoder=object$3({type:constant$2("workspaceFrame"),application:nonEmptyStringDecoder$2,componentType:optional$3(componentTypeDecoder),state:workspaceFrameComponentStateDecoder}),glueLayoutDecoder=object$3({name:nonEmptyStringDecoder$2,type:layoutTypeDecoder,token:optional$3(nonEmptyStringDecoder$2),components:array$3(oneOf$1(windowLayoutComponentDecoder,workspaceLayoutComponentDecoder,workspaceFrameComponentDecoder)),context:optional$3(anyJson$2()),metadata:optional$3(anyJson$2()),version:optional$3(number$5())}),iframePermissionsPolicyConfigDecoder=object$3({flags:string$5()}),workspacesSandboxDecoder=object$3({flags:string$5()}),channelSelectorDecoder=object$3({enabled:boolean$4()}),applicationDetailsDecoder=object$3({url:nonEmptyStringDecoder$2,top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),workspacesSandbox:optional$3(workspacesSandboxDecoder),channelSelector:optional$3(channelSelectorDecoder),iframePermissionsPolicy:optional$3(iframePermissionsPolicyConfigDecoder)}),intentDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,displayName:optional$3(string$5()),contexts:optional$3(array$3(string$5())),customConfig:optional$3(object$3()),resultType:optional$3(nonEmptyStringDecoder$2)}),glueCoreAppDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,type:nonEmptyStringDecoder$2.where(e=>"window"===e,"Expected a value of window"),title:optional$3(nonEmptyStringDecoder$2),version:optional$3(nonEmptyStringDecoder$2),customProperties:optional$3(anyJson$2()),icon:optional$3(string$5()),caption:optional$3(string$5()),details:applicationDetailsDecoder,intents:optional$3(array$3(intentDefinitionDecoder)),hidden:optional$3(boolean$4()),fdc3:optional$3(decoders.fdc3.v2DefinitionDecoder)}),remoteStoreCacheConfigDecoder=object$3({enabled:optional$3(boolean$4())}),remoteStoreDecoder=object$3({url:nonEmptyStringDecoder$2,pollingInterval:optional$3(nonNegativeNumberDecoder$2),requestTimeout:optional$3(nonNegativeNumberDecoder$2),customHeaders:optional$3(anyJson$2()),getRequestInit:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"remote store getRequestInit"))),waitInitialResponse:optional$3(boolean$4()),cache:optional$3(remoteStoreCacheConfigDecoder)}),channelDefinitionDecoder$1=object$3({name:nonEmptyStringDecoder$2,meta:channelMetaDecoder$1,data:optional$3(anyJson$2())}),pluginDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,start:anyJson$2(),stop:optional$3(anyJson$2()),version:optional$3(nonEmptyStringDecoder$2),config:optional$3(anyJson$2()),critical:optional$3(boolean$4())}),allApplicationDefinitionsDecoder=anyJson$2().andThen(e=>{const t=fdc3.isFdc3Definition(e),{isFdc3:r}=t;return r?"2.0"===t.version?decoders.fdc3.v2DefinitionDecoder:decoders.fdc3.v1DefinitionDecoder:glueCoreAppDefinitionDecoder});array$3(allApplicationDefinitionsDecoder);const applicationsConfigDecoder=object$3({local:optional$3(array$3(allApplicationDefinitionsDecoder)),remote:optional$3(remoteStoreDecoder)}),layoutsConfigDecoder=object$3({mode:optional$3(oneOf$1(constant$2("idb"),constant$2("session"),constant$2("rest"),constant$2("manager"))),local:optional$3(array$3(glueLayoutDecoder)),rest:optional$3(remoteStoreDecoder)}),channelsModeDecoder=oneOf$1(constant$2("single"),constant$2("multi")),channelsConfigDecoder=object$3({definitions:array$3(channelDefinitionDecoder$1),mode:optional$3(channelsModeDecoder)}),pluginsConfigDecoder=object$3({definitions:array$3(pluginDefinitionDecoder)}),gatewayVisibilityRestrictionsDecoder=oneOf$1(constant$2("local"),constant$2("cluster")),gatewayConfigDecoder=object$3({logging:optional$3(object$3({level:optional$3(logLevelDecoder),appender:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"gateway log appender")))})),clients:optional$3(object$3({buffer_size:optional$3(number$5())})),bridge:optional$3(object$3({url:nonEmptyStringDecoder$2,headers:optional$3(anyJson$2()),getHeaders:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"getHeaders function"))),getWebSocketSearchParams:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"getWebSocketSearchParams function"))),channels:optional$3(object$3({enabled:optional$3(boolean$4())})),contexts:optional$3(object$3({enabled:optional$3(boolean$4()),visibility:optional$3(array$3(object$3({context:oneOf$1(nonEmptyStringDecoder$2,regexDecoder),restrictions:gatewayVisibilityRestrictionsDecoder})))})),intents:optional$3(object$3({enabled:optional$3(boolean$4())})),interop:optional$3(object$3({enabled:optional$3(boolean$4()),visibility:optional$3(array$3(object$3({method:oneOf$1(nonEmptyStringDecoder$2,regexDecoder),restrictions:gatewayVisibilityRestrictionsDecoder})))})),search:optional$3(object$3({enabled:optional$3(boolean$4())}))}))}),glueConfigDecoder=anyJson$2(),maximumActiveWorkspacesDecoder=object$3({threshold:number$5().where(e=>e>1,"Expected a number larger than 1")}),idleWorkspacesDecoder=object$3({idleMSThreshold:number$5().where(e=>e>100,"Expected a number larger than 100")}),hibernationConfigDecoder=object$3({maximumActiveWorkspaces:optional$3(maximumActiveWorkspacesDecoder),idleWorkspaces:optional$3(idleWorkspacesDecoder)}),loadingConfigDecoder=object$3({delayed:optional$3(object$3({batch:optional$3(number$5()),initialOffsetInterval:optional$3(number$5()),interval:optional$3(number$5())})),defaultStrategy:optional$3(oneOf$1(constant$2("direct"),constant$2("delayed"),constant$2("lazy"))),showDelayedIndicator:optional$3(boolean$4())}),iframeSandBoxConfigDecoder=object$3({flags:string$5()}),workspacesConfigDecoder=object$3({src:nonEmptyStringDecoder$2,hibernation:optional$3(hibernationConfigDecoder),loadingStrategy:optional$3(loadingConfigDecoder),isFrame:optional$3(boolean$4()),initAsEmpty:optional$3(boolean$4()),frameCache:optional$3(boolean$4()),iframeSandbox:optional$3(iframeSandBoxConfigDecoder),iframePermissionsPolicy:optional$3(iframePermissionsPolicyConfigDecoder)}),preferredConnectionSettingsDecoder=object$3({url:nonEmptyStringDecoder$2,auth:optional$3(object$3({username:optional$3(nonEmptyStringDecoder$2),password:optional$3(nonEmptyStringDecoder$2),sessionId:optional$3(nonEmptyStringDecoder$2),provider:optional$3(nonEmptyStringDecoder$2),providerContext:optional$3(anyJson$2()),token:optional$3(nonEmptyStringDecoder$2),gatewayToken:optional$3(nonEmptyStringDecoder$2),flowName:optional$3(constant$2("sspi")),flowCallback:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"flowCallback function")))})),forceIncompleteSwitch:optional$3(boolean$4()),discoveryIntervalMS:optional$3(nonNegativeNumberDecoder$2)}),connectionConfigDecoder=object$3({preferred:optional$3(preferredConnectionSettingsDecoder),enableManualSwitching:optional$3(boolean$4()),alwaysPlatform:optional$3(boolean$4()),allowedClientFallbackOrigin:optional$3(nonEmptyStringDecoder$2),blockList:optional$3(array$3(nonEmptyStringDecoder$2))}),windowsConfigDecoder=object$3({windowResponseTimeoutMs:optional$3(nonNegativeNumberDecoder$2),defaultWindowOpenBounds:optional$3(windowBoundsDecoder)}),serviceWorkerConfigDecoder=object$3({url:optional$3(nonEmptyStringDecoder$2),registrationPromise:optional$3(anyJson$2())}),notificationFilterDecoder=object$3({allowed:optional$3(array$3(nonEmptyStringDecoder$2)),blocked:optional$3(array$3(nonEmptyStringDecoder$2))}),notificationsConfigDecoder=object$3({enabled:optional$3(boolean$4()),enableToasts:optional$3(boolean$4()),sourceFilter:optional$3(notificationFilterDecoder),clearNotificationOnClick:optional$3(boolean$4())}),themesConfigDecoder=object$3({defaultTheme:optional$3(oneOf$1(constant$2("os"),constant$2("light"),constant$2("dark")))}),userConfigDecoder=object$3({id:nonEmptyStringDecoder$2,username:optional$3(nonEmptyStringDecoder$2),firstName:optional$3(nonEmptyStringDecoder$2),lastName:optional$3(nonEmptyStringDecoder$2),email:optional$3(nonEmptyStringDecoder$2),type:optional$3(nonEmptyStringDecoder$2),role:optional$3(nonEmptyStringDecoder$2),meta:optional$3(anyJson$2())}),managerAuthConfig=object$3({basic:optional$3(object$3({username:nonEmptyStringDecoder$2,password:nonEmptyStringDecoder$2})),username:optional$3(nonEmptyStringDecoder$2),token:optional$3(object$3({bearer:optional$3(nonEmptyStringDecoder$2)})),includeCredentials:optional$3(boolean$4())}),managerConfigDecoder=object$3({url:nonEmptyStringDecoder$2,auth:managerAuthConfig,critical:optional$3(boolean$4()),headers:optional$3(anyJson$2()),fetchIntervalMS:optional$3(nonNegativeNumberDecoder$2),tokenRefreshIntervalMS:optional$3(nonNegativeNumberDecoder$2),responseTimeoutMS:optional$3(nonNegativeNumberDecoder$2),requests:optional$3(object$3({timeout:optional$3(nonNegativeNumberDecoder$2),openSessionTimeout:optional$3(nonNegativeNumberDecoder$2),closeSessionTimeout:optional$3(nonNegativeNumberDecoder$2)})),cache:optional$3(object$3({enabled:optional$3(boolean$4()),clearOld:optional$3(boolean$4())})),getHeaders:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"dynamic headers function"))),features:optional$3(object$3({applicationsStore:optional$3(boolean$4()),layoutsStore:optional$3(boolean$4()),preferencesStore:optional$3(boolean$4())}))}),applicationPreferencesStoreDecoder=object$3({type:optional$3(oneOf$1(constant$2("local"),constant$2("manager"),constant$2("rest"))),rest:optional$3(remoteStoreDecoder)}),applicationPreferencesConfigDecoder=object$3({store:optional$3(applicationPreferencesStoreDecoder),validNonExistentApps:optional$3(array$3(nonEmptyStringDecoder$2))}),otelMetricTypeDecoder=oneOf$1(constant$2("app_started"),constant$2("app_stopped"),constant$2("app_startup"),constant$2("app_count"),constant$2("app_duration"),constant$2("app_error"),constant$2("layout_startup"),constant$2("workspace_startup"),constant$2("workspace_stopped"),constant$2("workspace_count"),constant$2("platform_startup"),constant$2("platform_error")),otelMetricDefinitionDecoder=object$3({enabled:optional$3(boolean$4()),name:optional$3(nonEmptyStringDecoder$2),description:optional$3(nonEmptyStringDecoder$2),buckets:optional$3(array$3(number$5())),type:otelMetricTypeDecoder}),otelMetricsDefinitionDecoder=object$3({url:nonEmptyStringDecoder$2,publishInterval:optional$3(nonNegativeNumberDecoder$2),metrics:optional$3(array$3(otelMetricDefinitionDecoder)),additionalResourceAttributes:optional$3(object$3()),getAdditionalAttributes:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"getAdditionalAttributes function"))),headers:optional$3(anyJson$2())}),otelConfigDecoder=object$3({additionalResourceAttributes:optional$3(object$3()),getAdditionalAttributes:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"getAdditionalAttributes function"))),headers:optional$3(anyJson$2()),metrics:optional$3(otelMetricsDefinitionDecoder)}),platformConfigDecoder=object$3({licenseKey:nonEmptyStringDecoder$2,windows:optional$3(windowsConfigDecoder),applications:optional$3(applicationsConfigDecoder),notifications:optional$3(notificationsConfigDecoder),layouts:optional$3(layoutsConfigDecoder),channels:optional$3(channelsConfigDecoder),plugins:optional$3(pluginsConfigDecoder),serviceWorker:optional$3(serviceWorkerConfigDecoder),gateway:optional$3(gatewayConfigDecoder),connection:optional$3(connectionConfigDecoder),browser:optional$3(glueConfigDecoder),workspaces:optional$3(workspacesConfigDecoder),environment:optional$3(anyJson$2()),themes:optional$3(themesConfigDecoder),manager:optional$3(managerConfigDecoder),user:optional$3(userConfigDecoder),browserFactory:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"glueFactory"))),applicationPreferences:optional$3(applicationPreferencesConfigDecoder),otel:optional$3(otelConfigDecoder),widget:optional$3(widgetConfigDecoder),modals:optional$3(modalsConfigDecoder),intentResolver:optional$3(intentResolverConfigDecoder)}),windowOpenSettingsDecoder=object$3({top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),context:optional$3(anyJson$2()),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(windowRelativeDirectionDecoder),windowId:optional$3(nonEmptyStringDecoder$2),layoutComponentId:optional$3(nonEmptyStringDecoder$2)}),interceptorRegistrationRequestDecoder=object$3({callInterceptor:anyJson$2().andThen(e=>functionCheck$1(e,"callInterceptor")),interceptions:array$3(object$3({domain:libDomainDecoder,operation:nonEmptyStringDecoder$2}))}),focusEventDataDecoder=object$3({windowId:nonEmptyStringDecoder$2,hasFocus:boolean$4()}),bringBackToWorkspaceDataDecoder=object$3({windowId:nonEmptyStringDecoder$2}),workspacesInitCheckResultDecoder=object$3({initialized:boolean$4()}),clientErrorDataDecoder=object$3({message:nonEmptyStringDecoder$2}),systemHelloSuccessDecoder=object$3({isClientErrorOperationSupported:boolean$4()});var isMergeableObject=function(e){return isNonNullObject(e)&&!isSpecial(e)};function isNonNullObject(e){return!!e&&"object"==typeof e}function isSpecial(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||isReactElement(e)}var canUseSymbol="function"==typeof Symbol&&Symbol.for,REACT_ELEMENT_TYPE=canUseSymbol?Symbol.for("react.element"):60103;function isReactElement(e){return e.$$typeof===REACT_ELEMENT_TYPE}function emptyTarget(e){return Array.isArray(e)?[]:{}}function cloneUnlessOtherwiseSpecified(e,t){return!1!==t.clone&&t.isMergeableObject(e)?deepmerge(emptyTarget(e),e,t):e}function defaultArrayMerge(e,t,r){return e.concat(t).map(function(e){return cloneUnlessOtherwiseSpecified(e,r)})}function getMergeFunction(e,t){if(!t.customMerge)return deepmerge;var r=t.customMerge(e);return"function"==typeof r?r:deepmerge}function getEnumerableOwnPropertySymbols(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}function getKeys(e){return Object.keys(e).concat(getEnumerableOwnPropertySymbols(e))}function propertyIsOnObject(e,t){try{return t in e}catch(e){return!1}}function propertyIsUnsafe(e,t){return propertyIsOnObject(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}function mergeObject(e,t,r){var n={};return r.isMergeableObject(e)&&getKeys(e).forEach(function(t){n[t]=cloneUnlessOtherwiseSpecified(e[t],r)}),getKeys(t).forEach(function(i){propertyIsUnsafe(e,i)||(propertyIsOnObject(e,i)&&r.isMergeableObject(t[i])?n[i]=getMergeFunction(i,r)(e[i],t[i],r):n[i]=cloneUnlessOtherwiseSpecified(t[i],r))}),n}function deepmerge(e,t,r){(r=r||{}).arrayMerge=r.arrayMerge||defaultArrayMerge,r.isMergeableObject=r.isMergeableObject||isMergeableObject,r.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified;var n=Array.isArray(t);return n===Array.isArray(e)?n?r.arrayMerge(e,t,r):mergeObject(e,t,r):cloneUnlessOtherwiseSpecified(t,r)}deepmerge.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,r){return deepmerge(e,r,t)},{})};var deepmerge_1=deepmerge,cjs=deepmerge_1,deepMerge=getDefaultExportFromCjs$2(cjs);let urlAlphabet$2="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$4=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$2[64*Math.random()|0];return t};function getDefaultExportFromCjs$1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createRegistry$1(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;ie.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$1=number$4().where(e=>e>=0,"Expected a non-negative number"),searchTypeDecoder=object$2({name:nonEmptyStringDecoder$1,displayName:optional$2(nonEmptyStringDecoder$1)}),providerData=object$2({id:nonEmptyStringDecoder$1,interopId:nonEmptyStringDecoder$1,name:nonEmptyStringDecoder$1,appName:optional$2(nonEmptyStringDecoder$1),types:optional$2(array$2(searchTypeDecoder))}),providerLimitsDecoder=object$2({maxResults:optional$2(nonNegativeNumberDecoder$1),maxResultsPerType:optional$2(nonNegativeNumberDecoder$1)}),queryConfigDecoder=object$2({search:nonEmptyStringDecoder$1,providers:optional$2(array$2(providerData)),types:optional$2(array$2(searchTypeDecoder)),providerLimits:optional$2(providerLimitsDecoder)}),providerRegistrationConfig=object$2({name:nonEmptyStringDecoder$1,types:optional$2(array$2(searchTypeDecoder))}),operationDecoder=oneOf(constant$1("cancel"),constant$1("info"),constant$1("search")),queryStatusDecoder=oneOf(constant$1("done"),constant$1("in-progress"),constant$1("error")),searchCancelRequestDecoder=object$2({id:nonEmptyStringDecoder$1}),mainActionDecoder=object$2({method:nonEmptyStringDecoder$1,target:optional$2(oneOf(object$2({instance:nonEmptyStringDecoder$1}),constant$1("all"))),params:optional$2(anyJson$1())}),secondaryActionDecoder=object$2({name:nonEmptyStringDecoder$1,method:nonEmptyStringDecoder$1,target:optional$2(oneOf(object$2({instance:nonEmptyStringDecoder$1}),constant$1("all"))),params:optional$2(anyJson$1())}),queryResultDecoder=object$2({type:searchTypeDecoder,id:optional$2(nonEmptyStringDecoder$1),displayName:optional$2(nonEmptyStringDecoder$1),description:optional$2(nonEmptyStringDecoder$1),iconURL:optional$2(nonEmptyStringDecoder$1),metadata:optional$2(anyJson$1()),action:optional$2(mainActionDecoder),secondaryActions:optional$2(array$2(secondaryActionDecoder))}),legacySearchResultItemDecoder=object$2({type:string$4(),category:optional$2(string$4()),id:optional$2(string$4()),displayName:optional$2(string$4()),description:optional$2(string$4()),iconURL:optional$2(string$4()),action:optional$2(mainActionDecoder)}),protocolSearchResultsBatchDecoder=object$2({items:array$2(oneOf(queryResultDecoder,legacySearchResultItemDecoder)),provider:optional$2(providerData),queryId:nonEmptyStringDecoder$1,status:constant$1("in-progress")}),protocolSearchCompletedDecoder=object$2({items:array$2(oneOf(queryResultDecoder,legacySearchResultItemDecoder)),queryId:nonEmptyStringDecoder$1,status:constant$1("done")}),protocolProviderErrorDecoder=object$2({items:array$2(oneOf(queryResultDecoder,legacySearchResultItemDecoder)),provider:optional$2(providerData),queryId:nonEmptyStringDecoder$1,errorMessage:nonEmptyStringDecoder$1,status:constant$1("error")});class ClientController{logger;glueController;modelFactory;registry=CallbackRegistryFactory$1();activeQueryLookup={};queryIdToMasterIdLookup={};pendingDebounce=[];debounceTimer;debounceMS=0;constructor(e,t,r){this.logger=e,this.glueController=t,this.modelFactory=r}setDebounceMS(e){this.logger.info(`[${e.commandId}] Setting the debounceMS to: ${e.milliseconds}`),this.debounceMS=e.milliseconds,this.logger.info(`[${e.commandId}] debounceMS set to: ${e.milliseconds}`)}getDebounceMS(e){return this.logger.info(`[${e.commandId}] Getting the debounceMS`),this.debounceMS}async query(e,t){if(this.debounceMS&&!t)return this.debounceQuery(e);await this.glueController.registerMainClientMethod(this.handleProviderCall.bind(this));const{queryConfig:r,commandId:n}=e;this.logger.info(`[${n}] Initiating a query request`);let i=await this.glueController.getAllProvidersInfo();this.logger.trace(`[${n}] Got all available providers: ${JSON.stringify(i)}`),r.providers&&(this.logger.info(`[${n}] Filtering providers by explicitly allowed providers.`),i=this.filterProvidersByAllowList(i,r.providers)),r.types&&(this.logger.info(`[${n}] Filtering providers by explicitly allowed types.`),i=this.filterProvidersByAllowedTypes(i,r.types)),i.length||this.logger.warn(`[${n}] There are no providers that can handle the query for ${e.queryConfig.search}`),this.logger.info(`[${n}] Sending query request to providers: ${JSON.stringify(i)}`);const o=await this.glueController.sendQueryRequest(r,i);this.logger.info(`[${n}] Received responses from the providers: ${JSON.stringify(o)}`);const s=this.generateMasterQueryId(),a=this.modelFactory.buildClientQueryModel(s,this);return this.logger.info(`[${n}] The query is in progress with master id: ${s}`),this.activeQueryLookup[s]={servers:o,model:a},o.forEach(e=>{this.queryIdToMasterIdLookup[e.queryId]=s}),o.length||setTimeout(()=>{this.registry.execute(`on-query-completed-${s}`),this.cleanUpQuery(s)},0),a.exposeFacade()}async cancelQuery(e,t){const r=this.activeQueryLookup[e];if(!r)throw new Error(`[${t}] Cannot cancel query: ${e}, because this query does not exist`);const n=r.servers;this.logger.info(`[${t}] Sending cancel query requests`),await Promise.all(n.map(e=>(this.logger.trace(`[${t}] Sending cancel query request to ${e.interopId} with queryId: ${e.queryId}`),this.glueController.sendQueryCancelRequest({id:e.queryId},{instance:e.interopId})))),this.logger.info(`[${t}] The query was cancelled`)}processClientOnResults(e){return this.registry.add(`on-query-results-${e.masterQueryId}`,e.callback)}processClientOnCompleted(e){return this.registry.add(`on-query-completed-${e.masterQueryId}`,e.callback)}processClientOnError(e){return this.registry.add(`on-query-error-${e.masterQueryId}`,e.callback)}async handleProviderCall(e){const{status:t}=e,r=queryStatusDecoder.runWithException(t),n=nanoid$4(10);switch(r){case SEARCH_QUERY_STATUSES.done:return this.handleQueryCompleted({completedConfig:e,commandId:n});case SEARCH_QUERY_STATUSES.inProgress:return this.handleQueryResults({resultsBatch:e,commandId:n});case SEARCH_QUERY_STATUSES.error:return this.handleQueryError({error:e,commandId:n});default:throw new Error(`Unrecognized status: ${t}`)}}handleQueryResults(e){const{resultsBatch:t,commandId:r}=e;this.logger.trace(`[${r}] Processing a results batch from provider: ${t.provider?.name} with id: ${t.provider?.id}`);const n=protocolSearchResultsBatchDecoder.runWithException(t),i=this.queryIdToMasterIdLookup[n.queryId];if(!i)return void this.logger.warn(`[${r}] Received results for an unknown query. Provider ${JSON.stringify(n.provider)}, items: ${JSON.stringify(n.items)}`);this.logger.trace(`[${r}] The results batch is validated, forwarding to the callbacks`);const o=this.checkTransformLegacyResults(n.items),s={provider:n.provider,results:o};this.registry.execute(`on-query-results-${i}`,s)}handleQueryCompleted(e){const{completedConfig:t,commandId:r}=e;this.logger.trace(`[${r}] Processing a query completed message from query id: ${t.queryId}`);const n=protocolSearchCompletedDecoder.runWithException(t),i=this.queryIdToMasterIdLookup[n.queryId];if(!i)return void this.logger.warn(`[${r}] Received completed message for an unknown query. Provider query id: ${JSON.stringify(n.queryId)}`);if(n.items.length){const e={results:this.checkTransformLegacyResults(n.items)};this.registry.execute(`on-query-results-${i}`,e)}delete this.queryIdToMasterIdLookup[n.queryId];const o=this.activeQueryLookup[i];o.servers=o.servers.filter(e=>e.queryId!==n.queryId),o.servers.length?this.logger.trace(`[${r}] Waiting for more providers to complete`):(this.logger.trace(`[${r}] All providers are done, marking this query as completed`),this.registry.execute(`on-query-completed-${i}`),this.cleanUpQuery(i))}handleQueryError(e){const{error:t,commandId:r}=e;this.logger.trace(`[${r}] Processing an error message from query: ${t.queryId}`);const n=protocolProviderErrorDecoder.runWithException(t),i=this.queryIdToMasterIdLookup[n.queryId];if(!i)return void this.logger.warn(`[${r}] Received error message for an unknown query. Provider query id: ${JSON.stringify(n.queryId)} and message: ${JSON.stringify(n.errorMessage)}`);const o={error:n.errorMessage,provider:n.provider};this.registry.execute(`on-query-error-${i}`,o)}filterProvidersByAllowList(e,t){const r=t.reduce((e,t)=>(e[t.id]=!0,e),{});return e.filter(e=>e.info.providers.some(e=>r[e.id]))}filterProvidersByAllowedTypes(e,t){const r=t.reduce((e,t)=>(e[t.name]=!0,e),{});return e.filter(e=>{const t=e.info.supportedTypes;return!!t.some(e=>"*"===e)||(!t||!t.length||t.some(e=>r[e]))})}generateMasterQueryId(){const e=nanoid$4(10);return this.activeQueryLookup[e]?this.generateMasterQueryId():e}cleanUpQuery(e){this.registry.clearKey(`on-query-results-${e}`),this.registry.clearKey(`on-query-completed-${e}`),this.registry.clearKey(`on-query-error-${e}`),delete this.activeQueryLookup[e]}debounceQuery(e){return new Promise((t,r)=>{clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{const t=[...this.pendingDebounce];this.pendingDebounce=[],this.query(e,!0).then(e=>t.forEach(({resolve:t})=>t(e))).catch(e=>t.forEach(({reject:t})=>t(e)))},this.debounceMS),this.pendingDebounce.push({resolve:t,reject:r})})}checkTransformLegacyResults(e){if(!e.length)return[];const t=e[0];return t&&"object"!=typeof t.type?e.map(e=>({type:{name:e.type,displayName:e.category},id:e.id,displayName:e.displayName,description:e.description,iconURL:e.iconURL,action:e.action})):e}}const MAIN_PROVIDER_METHOD_NAME="T42.Search.Provider",MAIN_CLIENT_METHOD_NAME="T42.Search.Client",SEQUELIZER_INTERVAL_MS=10,FLUSH_SEQUELIZER_INTERVAL_MS=10,FLUSH_TIMEOUT_MS=100,STALE_QUERY_TIMEOUT_MS=9e5;let GlueController$1=class{glue;constructor(e){this.glue=e}get myAppName(){return this.glue.interop.instance.applicationName}get myInteropId(){return this.glue.interop.instance.instance}async registerMainProviderMethod(e){this.checkMyMethodExists(MAIN_PROVIDER_METHOD_NAME).exists||await this.glue.interop.register(MAIN_PROVIDER_METHOD_NAME,e)}async registerMainClientMethod(e){this.checkMyMethodExists(MAIN_CLIENT_METHOD_NAME).exists||await this.glue.interop.register(MAIN_CLIENT_METHOD_NAME,e)}async clearMainProviderMethod(){await this.glue.interop.unregister(MAIN_PROVIDER_METHOD_NAME)}async sendClientResultsBatch(e,t,r){const n={items:e.results,provider:e.provider,queryId:r,status:SEARCH_QUERY_STATUSES.inProgress};await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME,n,{instance:t})}async sendClientQueueCompleted(e,t){const r={items:[],queryId:t,status:SEARCH_QUERY_STATUSES.done};await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME,r,{instance:e})}async sendClientErrorMessage(e,t,r,n){const i={items:[],provider:n,errorMessage:e,queryId:r,status:SEARCH_QUERY_STATUSES.error};await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME,i,{instance:t})}async sendQueryRequest(e,t){if(!t.length)return[];const r=t.map(e=>({instance:e.interopId})),n={operation:CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search,apiVersion:"1",...e};return((await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME,n,r)).all_return_values||[]).map(e=>({interopId:e.executed_by?.instance,queryId:e.returned.id}))}async sendQueryCancelRequest(e,t){const r={operation:CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel,id:e.id};await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME,r,t)}async getAllProvidersInfo(){if(this.glue.interop.methods().every(e=>e.name!==MAIN_PROVIDER_METHOD_NAME))return[];const e={operation:CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info},t=await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME,e,"all");return(t.all_return_values||[]).map(e=>{const r=void 0===e.returned.apiVersion?{supportedTypes:e.returned.supportedTypes,apiVersion:e.returned.apiVersion,providers:[{interopId:e.executed_by?.instance,id:e.executed_by?.instance,name:e.executed_by?.instance,appName:t.executed_by?.application,types:e.returned.supportedTypes.map(e=>({name:e}))}]}:e.returned;return{interopId:e.executed_by?.instance,info:r}})}checkMyMethodExists(e){return{exists:this.glue.interop.methodsForInstance({instance:this.glue.interop.instance.instance}).some(t=>t.name===e)}}};class MainController{logger;glueController;clientController;providerController;constructor(e,t,r,n){this.logger=e,this.glueController=t,this.clientController=r,this.providerController=n}setDebounceMS(e){this.logger.info(`[${e.commandId}] Starting setDebounceMS operation with duration ${e.milliseconds}`),this.clientController.setDebounceMS(e),this.logger.info(`[${e.commandId}] Operation setDebounceMS with duration ${e.milliseconds} completed`)}getDebounceMS(e){return this.logger.info(`[${e.commandId}] Starting getDebounceMS operation.`),this.clientController.getDebounceMS(e)}async query(e){if(this.logger.info(`[${e.commandId}] Starting query operation with config ${JSON.stringify(e.queryConfig)}`),Array.isArray(e.queryConfig.providers)&&!e.queryConfig.providers.length)throw new Error("Cannot sent a query with a defined empty array of providers, because this is an impossible query for complete.");if(Array.isArray(e.queryConfig.types)&&!e.queryConfig.types.length)throw new Error("Cannot sent a query with a defined empty array of types, because this is an impossible query for complete.");const t=await this.clientController.query(e);return this.logger.info(`[${e.commandId}] Operation query with config ${JSON.stringify(e.queryConfig)} completed.`),t}async registerProvider(e){this.logger.info(`[${e.commandId}] Starting registerProvider operation with config ${JSON.stringify(e.config)}`);const t=await this.providerController.processRegisterProvider(e);return this.logger.info(`[${e.commandId}] Operation registerProvider with config ${JSON.stringify(e.config)} completed.`),t}async providers(e){this.logger.info(`[${e.commandId}] Starting providers operation.`);const t=(await this.glueController.getAllProvidersInfo()).flatMap(e=>e.info.providers);return this.logger.info(`[${e.commandId}] Operation providers completed.`),t}async types(e){this.logger.info(`[${e.commandId}] Starting types operation.`);const t=(await this.glueController.getAllProvidersInfo()).flatMap(e=>e.info.providers).filter(e=>!!e.types).flatMap(e=>e.types),r=[...new Set(t)];return this.logger.info(`[${e.commandId}] Operation types completed.`),r}}const extractErrorMsg=e=>"string"==typeof e?e:e.message?JSON.stringify(e.message):JSON.stringify(e);class ProviderController{logger;glueController;sequelizer;limitsTracker;modelsFactory;registry=CallbackRegistryFactory$1();providersModels={};activeQueries={};constructor(e,t,r,n,i){this.logger=e,this.glueController=t,this.sequelizer=r,this.limitsTracker=n,this.modelsFactory=i}async processRegisterProvider(e){const{config:t,commandId:r}=e;this.logger.info(`[${r}] enqueueing the provider registration process with config: ${JSON.stringify(t)}`);const n=await this.sequelizer.enqueue(async()=>{if((await this.glueController.getAllProvidersInfo()).flatMap(e=>e.info.providers).some(e=>e&&e.name===t.name))throw new Error(`Cannot register a new provider with name: ${t.name}, because there already is a provider with this name`);await this.glueController.registerMainProviderMethod(this.handleSearchQueryRequest.bind(this));const e={id:nanoid$4(10),name:t.name,interopId:this.glueController.myInteropId,appName:this.glueController.myAppName,types:t.types},r=this.modelsFactory.buildProviderModel(e,this);return this.providersModels[e.id]=r,r.exposeFacade()});return this.logger.info(`[${r}] the provider with name: ${t.name} has been registered.`),n}processProviderOnQuery(e){return this.registry.add(`on-search-query-${e.id}`,e.callback)}processProviderOnQueryCancel(e){return this.registry.add(`on-cancel-query-${e.id}`,e.callback)}async processProviderUnregister(e){this.logger.info(`[${e.commandId}] enqueueing the provider un-registration with id: ${e.id}`),await this.sequelizer.enqueue(async()=>{this.cleanUpProvider(e.id,e.commandId),Object.keys(this.providersModels).length||await this.glueController.clearMainProviderMethod()}),this.logger.info(`[${e.commandId}] the provider un-registration with id: ${e.id} completed`)}async processProviderQueryDone(e){const{commandId:t,identification:r}=e;this.activeQueries[r.queryId]?.publisher.syncSuspendProvider(r.providerId,t),await this.sequelizer.enqueue(async()=>{this.logger.trace(`[${t}] Processing a query done command with identification: ${JSON.stringify(r)}`);const e=this.activeQueries[r.queryId];e?(await this.cleanUpProviderQuery(r.queryId,r.providerId,t),e.providersAtWork.length?this.logger.trace(`[${t}] Query done command completed, but there are more providers still at work.`):(this.cleanUpQuery(r.queryId,t),this.logger.trace(`[${t}] Query is completed, signalling.`))):this.logger.warn(`[${t}] Cannot mark provider: ${r.providerId} done with query ${r.queryId}, because there is no active query with this id`)})}processProviderQueryError(e){const{commandId:t,identification:r,error:n}=e;return this.logger.warn(`[${t}] Processing an error sent by provider: ${r.providerId} for query id: ${r.queryId} -> ${n}`),this.activeQueries[r.queryId]?.publisher.markProviderError(e),this.processProviderQueryDone(e)}processProviderQueryResult(e){const{commandId:t,identification:r}=e,n=this.activeQueries[r.queryId];if(!n){const t=`Will not send this result to the client, because there is no active query with id ${r.queryId}. Most likely this query was cancelled.`;throw this.logger.warn(`[${e}] ${t}`),new Error(t)}if(n.publisher.checkProviderSuspended(r.providerId)){const t=`Will not send this result to the client, because there is no info about this provider in the active query with id ${r.queryId}. Most likely this query was marked as done by this provider already.`;throw this.logger.warn(`[${e}] ${t}`),new Error(t)}const i=n.requestedTypes;if(i&&i.every(t=>t.name!==e.result.type.name)){const t=`Will not send this result to the client, because this result has a defined type: ${e.result.type.name} which is not in the explicitly requested list of types by the client.`;throw this.logger.warn(`[${e}] ${t}`),new Error(t)}const o=this.limitsTracker.testResultLimit(e);if(o?.maxLimitHit){const t=`Will not process this result from provider ${e.identification.providerId}, because this provider has reached the max results limit set by the client. This provider cannot send more result, marking it as done.`;throw this.logger.info(t),setTimeout(()=>this.processProviderQueryDone(e),0),new Error(t)}if(o?.maxLimitPerTypeHit){const t=`Will not process this result from provider ${e.identification.providerId}, because this provider has reached the max results limit per type as set by the client.`;throw this.logger.info(t),new Error(t)}this.logger.trace(`[${t}] An active query for query ${r.queryId} was found and the provider is within limits, queueing the result`),this.limitsTracker.update(e),n.publisher.queueResult(e),this.logger.trace(`[${t}] The query result was queued successfully.`)}async handleSearchQueryRequest(e,t){const{operation:r}=e,n=operationDecoder.runWithException(r),i=nanoid$4(10);switch(n){case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info:return this.handleInfoOperation({commandId:i});case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search:return this.handleSearchOperation({args:e,commandId:i},t);case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel:return this.handleCancelOperation({args:e,commandId:i});default:throw new Error(`Unrecognized operation: ${r}`)}}async handleInfoOperation(e){this.logger.info(`[${e.commandId}] handling an info operation`);const t=Object.values(this.providersModels).flatMap(e=>e.myProviderData.types||[]),r=[...new Set(t)];Object.values(this.providersModels).some(e=>!e.myProviderData.types)&&r.push({name:"*"});const n=Object.values(this.providersModels).map(e=>e.myProviderData),i={supportedTypes:r.map(e=>e.name),providers:n,apiVersion:"1"};return this.logger.info(`[${e.commandId}] responding to an info operation with: ${JSON.stringify(i)}`),i}async handleSearchOperation(e,t){const r=e.commandId,n=this.generateQueryId();this.logger.info(`[${r}] Processing search operation with queryId: ${n} request details: ${JSON.stringify(e.args)}`);const i=this.checkRequestLegacy(e.args),o=this.prepareRequest(e.args,i,r);return this.logger.info(`[${r}] Search operation with queryId: ${n} is validated. Creating an active query and enqueueing calling the providers.`),this.activeQueries[n]={queryId:n,callerInstanceId:t.instance,providersAtWork:[],requestedTypes:o.types,publisher:this.modelsFactory.buildPublisher(t.instance,n,i),staleTimer:this.setClearStaleQueryTimer(n)},o.providerLimits&&this.limitsTracker.enableTracking(o.providerLimits,n),setTimeout(()=>{this.sequelizer.enqueue(async()=>{try{this.logger.info(`[${r}] Calling the providers.`),this.callProviders(o,n,r)}catch(e){this.logger.error(`[${r}] Error calling the providers: ${extractErrorMsg(e)}`)}})},0),this.logger.info(`[${r}] Search operation with queryID: ${n} processed successfully.`),{id:n}}async handleCancelOperation(e){await this.sequelizer.enqueue(async()=>{const t=searchCancelRequestDecoder.run(e.args);if(!t.ok){const r=`Cannot process a cancel request, because of validation error: ${JSON.stringify(t.error)}`;throw this.logger.warn(`[${e.commandId}] ${r}`),new Error(r)}const r=t.result,n=this.activeQueries[r.id];n&&(clearTimeout(n.staleTimer),n.publisher.cancel(e.commandId),delete this.activeQueries[r.id],n.providersAtWork.forEach(e=>this.registry.execute(`on-cancel-query-${e.myProviderData.id}`,{id:r.id})))})}generateQueryId(){const e=nanoid$4(10);return this.activeQueries[e]?this.generateQueryId():e}translateLegacySearchRequest(e){return{search:e.search,types:e.types?.map(e=>({name:e})),providerLimits:{maxResults:e.limit,maxResultsPerType:e.categoryLimit}}}checkRequestLegacy(e){return void 0===e.apiVersion}callProviders(e,t,r){let n=e.providers?this.getFilteredProviderModels(e.providers):Object.values(this.providersModels);this.logger.trace(`[${r}] initial providers filtration yielded: ${JSON.stringify(n.map(e=>e.myProviderData.name).join(", "))}`),n=e.types?this.getFilteredProvidersBySearchTypes(n,e.types):n,this.logger.trace(`[${r}] search type providers filtration yielded: ${JSON.stringify(n.map(e=>e.myProviderData.name).join(", "))}`),this.activeQueries[t].publisher.configureProviders(n),this.activeQueries[t].providersAtWork.push(...n),n.forEach(n=>this.callProvider(n,e,t,r))}callProvider(e,t,r,n){const i=this.modelsFactory.buildProviderQueryModel(t,{queryId:r,providerId:e.myProviderData.id},this).exposeFacade();this.logger.info(`[${n}] The query facade for provider: ${e.myProviderData.id} with name ${e.myProviderData.name} is ready, raising the event for query ID: ${r}.`),this.registry.execute(`on-search-query-${e.myProviderData.id}`,i)}getFilteredProviderModels(e){const t=e.reduce((e,t)=>(this.providersModels[t.id]&&e.push(this.providersModels[t.id]),e),[]);return t}getFilteredProvidersBySearchTypes(e,t){return e.filter(e=>!e.myProviderData.types||!e.myProviderData.types.length||e.myProviderData.types?.some(e=>t.some(t=>t.name===e.name)))}setClearStaleQueryTimer(e){return setTimeout(()=>{const t=nanoid$4(10);this.logger.info(`[${t}] Stale query timer is activated for queryId: ${e}`);this.activeQueries[e]?(this.logger.info(`[${t}] force-marking the query as done`),this.cleanUpQuery(e,t),this.logger.info(`[${t}] the stale query was cleared.`)):this.logger.info(`[${t}] No active query was found, this was a false activation.`)},STALE_QUERY_TIMEOUT_MS)}prepareRequest(e,t,r){const n=t?this.translateLegacySearchRequest(e):e,i=queryConfigDecoder.run(n);if(!i.ok){const e=`Cannot process a search request, because of validation error: ${JSON.stringify(i.error)}`;throw this.logger.warn(`[${r}] ${e}`),new Error(e)}return i.result}cleanUpQuery(e,t){const r=this.activeQueries[e];clearTimeout(r.staleTimer),r.publisher.cleanPublisher(t),delete this.activeQueries[e],this.limitsTracker.cleanTracking(e)}cleanUpProvider(e,t){this.registry.clearKey(`on-search-query-${e}`),this.registry.clearKey(`on-cancel-query-${e}`),delete this.providersModels[e];Object.values(this.activeQueries).filter(t=>!t.publisher.checkProviderSuspended(e)).forEach(r=>{this.processProviderQueryDone({identification:{queryId:r.queryId,providerId:e},commandId:t})})}async cleanUpProviderQuery(e,t,r){const n=this.activeQueries[e];n?(n.providersAtWork=n.providersAtWork.filter(e=>e.myProviderData.id!==t),await n.publisher.markProviderDone(t,r)):this.logger.warn(`[${r}] Cannot clean up a provider query ${e} for provider ${t} because there is no such active query`)}}var version$3="3.2.1";class SearchFacade{main;constructor(e){this.main=e}exposeApi(){const e={version:version$3,setDebounceMS:this.setDebounceMS.bind(this),getDebounceMS:this.getDebounceMS.bind(this),listProviders:this.providers.bind(this),listTypes:this.types.bind(this),query:this.query.bind(this),registerProvider:this.registerProvider.bind(this)};return Object.freeze(e)}setDebounceMS(e){nonNegativeNumberDecoder$1.runWithException(e);const t=nanoid$4(10);return this.main.setDebounceMS({milliseconds:e,commandId:t})}getDebounceMS(){const e=nanoid$4(10);return this.main.getDebounceMS({commandId:e})}async providers(){const e=nanoid$4(10);return this.main.providers({commandId:e})}async types(){const e=nanoid$4(10);return this.main.types({commandId:e})}async query(e){const t=queryConfigDecoder.runWithException(e),r=nanoid$4(10);return this.main.query({queryConfig:t,commandId:r})}async registerProvider(e){const t=providerRegistrationConfig.runWithException(e),r=nanoid$4(10);return this.main.registerProvider({config:t,commandId:r})}}let AsyncSequelizer$2=class{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}};class LimitsTracker{limitsLookup={};limitsData={};enableTracking(e,t){this.limitsLookup[t]={},this.limitsData[t]={maxResults:e.maxResults?e.maxResults:Number.MAX_SAFE_INTEGER,maxResultsPerType:e.maxResultsPerType?e.maxResultsPerType:Number.MAX_SAFE_INTEGER}}testResultLimit(e){const t=this.limitsLookup[e.identification.queryId],r=this.limitsData[e.identification.queryId];if(!t||!r)return;let n=t[e.identification.providerId];if(n||(n={total:0},t[e.identification.providerId]=n),n.total+1>r.maxResults)return{maxLimitHit:!0};const i=e.result.type.name;if(!i)return;return(n[i]||0)+1>r.maxResultsPerType?{maxLimitPerTypeHit:!0}:void 0}update(e){const t=this.limitsLookup[e.identification.queryId],r=this.limitsData[e.identification.queryId];if(!t||!r)return;const n=t[e.identification.providerId];n.total+=1;const i=e.result.type.name;i&&(n[i]=n[i]?n[i]+1:1)}cleanTracking(e){delete this.limitsLookup[e],delete this.limitsData[e]}}class ClientQuery{controller;logger;masterQueryId;constructor(e,t,r){this.controller=e,this.logger=t,this.masterQueryId=r}exposeFacade(){const e={cancel:this.cancel.bind(this),onResults:this.onResults.bind(this),onCompleted:this.onCompleted.bind(this),onError:this.onError.bind(this)};return Object.freeze(e)}async cancel(){const e=nanoid$4(10);this.logger.info(`[${e}] received a valid query cancel request, forwarding to the controller.`),await this.controller.cancelQuery(this.masterQueryId,e),this.logger.info(`[${e}] the cancel request was completed.`)}onResults(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid query onResults request, forwarding to the controller.`);const r=this.controller.processClientOnResults({callback:e,masterQueryId:this.masterQueryId,commandId:t});return this.logger.info(`[${t}] the onResults request was completed.`),r}onCompleted(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid query onCompleted request, forwarding to the controller.`);const r=this.controller.processClientOnCompleted({callback:e,masterQueryId:this.masterQueryId,commandId:t});return this.logger.info(`[${t}] the onCompleted request was completed.`),r}onError(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid query onError request, forwarding to the controller.`);const r=this.controller.processClientOnError({callback:e,masterQueryId:this.masterQueryId,commandId:t});return this.logger.info(`[${t}] the onError request was completed.`),r}}class ProviderModel{myData;controller;logger;constructor(e,t,r){this.myData=e,this.controller=t,this.logger=r}get id(){return this.myData.id}get name(){return this.myData.name}get appName(){return this.myData.appName}get types(){return this.myData.types}get myProviderData(){return Object.assign({},this.myData)}exposeFacade(){const e={interopId:this.myData.interopId,id:this.id,name:this.name,appName:this.appName,types:this.types,onQuery:this.onQuery.bind(this),onQueryCancel:this.onQueryCancel.bind(this),unregister:this.unregister.bind(this)};return Object.freeze(e)}onQuery(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid onQuery request, forwarding to the controller.`);const r=this.controller.processProviderOnQuery({callback:e,id:this.id,commandId:t});return this.logger.info(`[${t}] the onQuery request was completed.`),r}onQueryCancel(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid onQueryCancel request, forwarding to the controller.`);const r=this.controller.processProviderOnQueryCancel({callback:e,id:this.id,commandId:t});return this.logger.info(`[${t}] the onQueryCancel request was completed.`),r}async unregister(){const e=nanoid$4(10);this.logger.info(`[${e}] received a valid unregister request, forwarding to the controller.`),await this.controller.processProviderUnregister({id:this.id,commandId:e}),this.logger.info(`[${e}] the unregister request was completed.`)}}class ProviderQueryModel{myData;controller;logger;identification;constructor(e,t,r,n){this.myData=e,this.controller=t,this.logger=r,this.identification=n}get id(){return this.identification.queryId}get search(){return this.myData.search}get providers(){return this.myData.providers}get types(){return this.myData.types}get providerLimits(){return this.myData.providerLimits}get myQueryData(){return Object.assign({},this.myData)}exposeFacade(){const e={id:this.id,search:this.search,providers:this.providers,types:this.types,providerLimits:this.providerLimits,sendResult:this.sendResult.bind(this),error:this.error.bind(this),done:this.done.bind(this)};return Object.freeze(e)}sendResult(e){queryResultDecoder.runWithException(e);const t=nanoid$4(10);return this.logger.trace(`[${t}] Received a valid result, forwarding to the controller`),this.controller.processProviderQueryResult({identification:this.identification,result:e,commandId:t})}error(e){const t=nanoid$4(10);nonEmptyStringDecoder$1.runWithException(e),this.logger.trace(`[${t}] Received a valid error, forwarding to the controller`),this.controller.processProviderQueryError({identification:this.identification,error:e,commandId:t}).catch(e=>this.logger.warn(`Error processing the error signal for this provider: ${this.id}, error: ${extractErrorMsg(e)}`))}done(){const e=nanoid$4(10);this.logger.trace(`[${e}] Received a valid done, forwarding to the controller`),this.controller.processProviderQueryDone({identification:this.identification,commandId:e}).catch(e=>this.logger.warn(`Error processing the done signal for this provider: ${this.identification.providerId}, error: ${extractErrorMsg(e)}`))}}class QueryResultsPublisher{sequelizer;glueController;logger;clientInstanceId;queryId;isLegacy;queues={};constructor(e,t,r,n,i,o){this.sequelizer=e,this.glueController=t,this.logger=r,this.clientInstanceId=n,this.queryId=i,this.isLegacy=o}checkProviderSuspended(e){return!!this.queues[e]&&!!this.queues[e].suspended}syncSuspendProvider(e,t){const r=this.queues[e];r?r.suspended=!0:this.logger.warn(`[${t}] Cannot suspend provider: ${e}, because there is no provider queue. This happens when the provider queue was already cancelled or completed`)}configureProviders(e){e.forEach(e=>{this.queues[e.myProviderData.id]={providerData:e,pendingResults:[]}})}queueResult(e){const{commandId:t,identification:r}=e;this.logger.trace(`[${t}] Queuing a new result from provider: ${r.providerId}`);const n=this.queues[r.providerId];if(!n)return void this.logger.warn(`[${t}] Cannot queue this result, because there is no provider queue. This happens when the provider queue was already cancelled or completed`);const i=this.isLegacy?this.translateLegacySearchItem(e.result):e.result;if(n.pendingResults.push(i),clearTimeout(n.flushTimer),10===n.pendingResults.length)return this.logger.trace(`[${t}] Reached the limit in the queue buffer, flushing to the client.`),void this.flushProviderQueue(r.providerId,t);this.logger.trace(`[${t}] The limit in the queue buffer is not reached yet, setting a flush timer.`),n.flushTimer=setTimeout(()=>{this.logger.trace(`[${t}] Reached the time limit in the queue buffer, flushing to the client.`),this.flushProviderQueue(r.providerId,t)},FLUSH_TIMEOUT_MS)}cancel(e){this.logger.trace(`[${e}] Cancelling queue ${this.queryId}.`),Object.values(this.queues).forEach(e=>clearTimeout(e.flushTimer)),this.queues={},this.logger.trace(`[${e}] Queue ${this.queryId} publisher cancelled.`)}async markProviderDone(e,t){this.logger.trace(`[${t}] Marking provider ${e} as done.`);const r=this.queues[e];r?(clearTimeout(r.flushTimer),await this.flushProviderQueue(e,t),delete this.queues[e],this.logger.trace(`[${t}] Provider ${e} marked as done.`)):this.logger.info(`[${t}] Cannot mark this queue as done, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent an error`)}markProviderError(e){const t=this.queues[e.identification.providerId];t?this.glueController.sendClientErrorMessage(e.error,this.clientInstanceId,this.queryId,t.providerData.myProviderData).catch(t=>this.logger.warn(`[${e.commandId}] The client errored when handling error message for query: ${this.queryId} -> ${extractErrorMsg(t)}`)):this.logger.warn(`[${e.commandId}] Cannot mark this provider as errored, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`)}cleanPublisher(e){Object.values(this.queues).forEach(e=>clearTimeout(e.flushTimer)),this.queues={},this.glueController.sendClientQueueCompleted(this.clientInstanceId,this.queryId).catch(t=>this.logger.warn(`[${e}] The client errored when handling search end message for query: ${this.queryId} -> ${extractErrorMsg(t)}`))}async flushProviderQueue(e,t){await this.sequelizer.enqueue(async()=>{const r=this.queues[e];if(!r)return void this.logger.warn(`[${t}] Cannot flush this queue, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`);if(!r.pendingResults.length)return void this.logger.info(`[${t}] This provider does not have any pending results to flush.`);const n={results:r.pendingResults,provider:r.providerData.myProviderData};r.pendingResults=[];try{await this.glueController.sendClientResultsBatch(n,this.clientInstanceId,this.queryId)}catch(e){this.logger.warn(`[${t}] The client errored when handling search results for query: ${this.queryId} -> ${extractErrorMsg(e)}`)}})}translateLegacySearchItem(e){return{type:e.type.name,category:e.type.displayName,id:e.id,displayName:e.displayName,description:e.description,iconURL:e.iconURL,action:e.action}}}class ModelFactory{glueController;glue;flushSequelizer;constructor(e,t,r){this.glueController=e,this.glue=t,this.flushSequelizer=r}buildProviderModel(e,t){return new ProviderModel(e,t,this.glue.logger.subLogger(`search.provider.model.${e.name}`))}buildProviderQueryModel(e,t,r){return new ProviderQueryModel(e,r,this.glue.logger.subLogger(`search.provider.${t.providerId}.query.${t.queryId}`),t)}buildPublisher(e,t,r){return new QueryResultsPublisher(this.flushSequelizer,this.glueController,this.glue.logger.subLogger(`search.results.publisher.${t}`),e,t,r)}buildClientQueryModel(e,t){return new ClientQuery(t,this.glue.logger.subLogger(`search.provider.model.${e}`),e)}}let IoC$1=class{glue;config;_glueController;_facade;_mainController;_providerController;_clientController;_asyncSequelizer;_flushSequelizer;_limitsTracker;_modelFactory;constructor(e,t){this.glue=e,this.config=t}get glueController(){return this._glueController||(this._glueController=new GlueController$1(this.glue)),this._glueController}get main(){return this._mainController||(this._mainController=new MainController(this.glue.logger.subLogger("search.main.controller"),this.glueController,this.clientController,this.providerController)),this._mainController}get clientController(){return this._clientController||(this._clientController=new ClientController(this.glue.logger.subLogger("search.client.controller"),this.glueController,this.modelFactory)),this._clientController}get providerController(){return this._providerController||(this._providerController=new ProviderController(this.glue.logger.subLogger("search.provider.controller"),this.glueController,this.sequelizer,this.limitsTracker,this.modelFactory)),this._providerController}get facade(){return this._facade||(this._facade=new SearchFacade(this.main)),this._facade}get sequelizer(){return this._asyncSequelizer||(this._asyncSequelizer=new AsyncSequelizer$2(SEQUELIZER_INTERVAL_MS)),this._asyncSequelizer}get flushSequelizer(){return this._flushSequelizer||(this._flushSequelizer=new AsyncSequelizer$2(FLUSH_SEQUELIZER_INTERVAL_MS)),this._flushSequelizer}get limitsTracker(){return this._limitsTracker||(this._limitsTracker=new LimitsTracker),this._limitsTracker}get modelFactory(){return this._modelFactory||(this._modelFactory=new ModelFactory(this.glueController,this.glue,this.flushSequelizer)),this._modelFactory}};const factoryFunction=async(e,t)=>{const r=new IoC$1(e,t);e.search=r.facade.exposeApi()};"undefined"!=typeof window&&(window.IOSearch=factoryFunction);class Platform{controller;session;localStorage;config;platformConfig;constructor(e,t,r,n){this.controller=e,this.session=t,this.localStorage=r,this.config=n}async ready(){this.session.start(),this.processConfig(this.config),await this.controller.start(this.platformConfig)}getClientGlue(){return this.controller.getClientGlue()}getPlatformApi(){return this.controller.platformApi}processConfig(e){if(!e)return ioError.raiseError("Cannot start the IoConnect Browser Platform without a config object.");const t=runDecoderWithIOError(platformConfigDecoder,e);if(t.gateway?.bridge&&!t.user)return ioError.raiseError("Platform initialization failed due to missing user details. Providing configuration settings for connecting to io.Bridge also requires providing user details via the `user` property.");this.addSearch(t),this.validatePlugins(t),this.platformConfig=deepMerge(defaultPlatformConfig,t),this.platformConfig.manager&&(this.platformConfig.manager.features=deepMerge(defaultManagerFeatures,this.platformConfig.manager.features||{})),this.platformConfig.manager&&!e?.layouts?.mode&&(this.platformConfig.layouts.mode="manager");const r=deepMerge(defaultNotificationsConfig,t.notifications||{}),n=this.session.getSystemSettings()||{systemInstanceId:nanoid$5(),ctxTrackInstanceId:nanoid$5()};this.session.setSystemSettings(n),this.localStorage.start(this.platformConfig.user);const i=this.localStorage.getNotificationsConfig()||r;void 0===i.showNotificationBadge&&(i.showNotificationBadge=!0),this.localStorage.setNotificationsConfig(i),this.platformConfig.workspacesFrameCache="boolean"!=typeof t.workspaces?.frameCache||t.workspaces?.frameCache,this.transferPromiseObjects(t);const o=window.iobrowser?.system,s={system:o,isPlatformFrame:!!t.workspaces?.isFrame,initAsEmptyFrame:!!t.workspaces?.initAsEmpty,workspacesFrameCache:this.platformConfig.workspacesFrameCache,platformStarted:!0,environment:Object.assign({},this.platformConfig.environment,{extension:void 0}),communicationId:n.systemInstanceId,workspaces:{frameCache:this.platformConfig.workspacesFrameCache,isPlatform:!!t.workspaces?.isFrame,initAsEmpty:!!t.workspaces?.initAsEmpty}};window.iobrowser=s}transferPromiseObjects(e){if(void 0!==e.serviceWorker?.registrationPromise&&(this.platformConfig.serviceWorker.registrationPromise=e.serviceWorker.registrationPromise),e.plugins&&e.plugins.definitions.length){e.plugins.definitions.forEach(e=>{const t=this.platformConfig.plugins?.definitions.find(t=>t.name===e.name);t&&(t.config=e.config)})}}validatePlugins(e){if(!e.plugins?.definitions)return;const t=e.plugins.definitions.reduce((e,t)=>{const r=typeof t.start,n=typeof t.stop,i=t.name;return("function"!==r||t.stop&&"function"!==n)&&e.push({name:i,startType:r,stopType:n}),e},[]);if(t.length){const e=t.map(e=>`The start and stop functions for plugin ${e.name} were expected to be of type function, but was provided start: ${e.startType} and stop: ${e.stopType}`).join("\n");return ioError.raiseError(e)}}addSearch(e){e.browser?e.browser.libraries?e.browser.libraries.push(factoryFunction):e.browser.libraries||(e.browser.libraries=[factoryFunction]):e.browser={libraries:[factoryFunction]}}}var MetricTypes={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function getMetricTypeByValue(e){return e.type===MetricTypes.TIMESTAMP?"timestamp":e.type===MetricTypes.NUMBER?"number":e.type===MetricTypes.STRING?"string":e.type===MetricTypes.OBJECT?"object":"unknown"}function getTypeByValue(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function serializeMetric(e){const t={},r=getMetricTypeByValue(e);if("object"===r){const r=Object.keys(e.value).reduce((t,r)=>{const n=getTypeByValue(e.value[r]);if("object"===n){const n=defineNestedComposite(e.value[r]);t[r]={type:"object",description:"",context:{},composite:n}}else t[r]={type:n,description:"",context:{}};return t},{});t.composite=r}return t.name=normalizeMetricName(e.path.join("/")+"/"+e.name),t.type=r,t.description=e.description,t.context={},t}function defineNestedComposite(e){return Object.keys(e).reduce((t,r)=>{const n=getTypeByValue(e[r]);return t[r]="object"===n?{type:"object",description:"",context:{},composite:defineNestedComposite(e[r])}:{type:n,description:"",context:{}},t},{})}function normalizeMetricName(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function getMetricValueByType(e){return"timestamp"===getMetricTypeByValue(e)?Date.now():publishNestedComposite(e.value)}function publishNestedComposite(e){return"object"!=typeof e?e:Object.keys(e).reduce((t,r)=>{const n=e[r];return"object"==typeof n&&n.constructor!==Date?t[r]=publishNestedComposite(n):n.constructor===Date?t[r]=new Date(n).getTime():n.constructor===Boolean?t[r]=n.toString():t[r]=n,t},{})}function flatten(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?flatten(t):t),[])}function getHighestState(e){return e.sort((e,t)=>e.state?t.state?t.state-e.state:-1:1)[0]}function aggregateDescription(e){let t="";return e.forEach((e,r,n)=>{const i=e.path.join(".");r===n.length-1?t+=i+"."+e.name+": "+e.description:t+=i+"."+e.name+": "+e.description+","}),t.length>100?t.slice(0,100)+"...":t}function composeMsgForRootStateMetric(e){const t=flatten(e.root.getAggregateState()),r=getHighestState(t);return{description:aggregateDescription(t),value:r.state}}function gw3(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let r,n;const i=e=>{o(e.root)},o=e=>{s(e),e.metrics.forEach(e=>{a(e)}),e.subSystems.forEach(e=>{o(e)})},s=async e=>{if(void 0===e.parent)return;await r;const i={type:"define",metrics:[{name:normalizeMetricName(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};n.sendFireAndForget(i).catch(r=>{t.logger.warn(`Failed to send define for system state metric of ${e.name}: ${JSON.stringify(r)}`)})},a=async e=>{const i=l(e);await r;const o={type:"define",metrics:[serializeMetric(i)]};n.sendFireAndForget(o).catch(r=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(r)}`)}),void 0!==i.value&&c(i)},c=e=>{if(u()){const r=getMetricValueByType(e),i={type:"publish",values:[{name:normalizeMetricName(e.path.join("/")+"/"+e.name),value:r,timestamp:Date.now()}]};return n.sendFireAndForget(i).catch(r=>{t.logger.warn(`Failed to publish metric ${e.name}: ${JSON.stringify(r)}`)})}return Promise.resolve()},l=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},u=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:o=>{let s;r=new Promise(e=>{s=e}),n=e.domain("metrics"),n.onJoined(e=>{!e&&s&&(s(),s=void 0);const r={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};n.sendFireAndForget(r).catch(e=>{t.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(e)}`)}),e&&i(o)}),n.join({system:t.system,service:t.service,instance:t.instance})},createSystem:s,updateSystem:async(i,o)=>{await r;const s={type:"publish",values:[{name:normalizeMetricName(i.path.join("/")+"/"+i.name+"/State"),value:{Description:o.description,Value:o.state},timestamp:Date.now()}]};n.sendFireAndForget(s).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${i.name}: ${JSON.stringify(e)}`)});const a=composeMsgForRootStateMetric(i),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};n.sendFireAndForget(c).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${i.name}: ${JSON.stringify(e)}`)})},createMetric:a,updateMetric:async e=>{const t=l(e);await r,c(t)}}}var Helpers={validate:(e,t,r)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===r||"object"!=typeof r)throw new Error("Missing transport")}};class BaseMetric{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,r,n,i){this.definition=e,this.system=t,this.transport=r,this.value=n,this.type=i,Helpers.validate(e,t,r),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,r.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}}class NumberMetric extends BaseMetric{constructor(e,t,r,n){super(e,t,r,n,MetricTypes.NUMBER)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class ObjectMetric extends BaseMetric{constructor(e,t,r,n){super(e,t,r,n,MetricTypes.OBJECT)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach(t=>{void 0!==e[t]&&(this.value[t]=e[t])})}}class StringMetric extends BaseMetric{constructor(e,t,r,n){super(e,t,r,n,MetricTypes.STRING)}}class TimestampMetric extends BaseMetric{constructor(e,t,r,n){super(e,t,r,n,MetricTypes.TIMESTAMP)}now(){this.update(new Date)}}function system(e,t,r,n,i){if(!t)throw new Error("Repository is required");if(!r)throw new Error("Transport is required");const o=r,s=e,a=i||"",c=t,l=n,u=function e(t){if(!t||!t.parent)return[];const r=e(t.parent);return r.push(t.name),r}(n);let d={};const h=(g="/",((p=u)&&p.length>0?p.join(g):"")+e);var p,g;const m=t.root,f=[],y=[];function $(e,t,r,n){let i={name:""};i="string"==typeof e?{name:e}:e;const o=y.filter(e=>e.name===i.name);if(o.length>0){const e=o[0];if(e.type!==t)throw new Error(`A metric named ${i.name} is already defined with different type.`);return void 0!==r&&e.update(r).catch(()=>{}),e}const s=n(i);return y.push(s),s}const b={get name(){return s},get description(){return a},get repo(){return c},get parent(){return l},path:u,id:h,root:m,get subSystems(){return f},get metrics(){return y},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const r=f.filter(t=>t.name===e);if(r.length>0)return r[0];const n=system(e,c,o,b,t);return f.push(n),n},getState:()=>d,setState:function(e,t){d={state:e,description:t},o.updateSystem(b,d)},stringMetric:function(e,t){return $(e,MetricTypes.STRING,t,e=>new StringMetric(e,b,o,t))},timestampMetric:function(e,t){return $(e,MetricTypes.TIMESTAMP,t,e=>new TimestampMetric(e,b,o,t))},objectMetric:function(e,t){return $(e,MetricTypes.OBJECT,t,e=>new ObjectMetric(e,b,o,t))},numberMetric:function(e,t){return $(e,MetricTypes.NUMBER,t,e=>new NumberMetric(e,b,o,t))},getAggregateState:function(){const e=[];return Object.keys(d).length>0&&e.push({name:s,path:u,state:d.state,description:d.description}),f.forEach(t=>{const r=t.getAggregateState();r.length>0&&e.push(...r)}),e}};return o.createSystem(b),b}class Repository{root;constructor(e,t){t.init(this),this.root=system("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),r=e=>{if(!e.target)return;const r=e.target,n=r?r.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:n,id:r.id,type:"<"+r.tagName.toLowerCase()+">",href:r.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",r):document.attachEvent("onclick",r)}e.stringMetric("StartTime",(new Date).toString());const r=e.stringMetric("StartURL",""),n=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;r.update(e)}void 0!==window.glue42gd&&n.update(window.glue42gd.appName)}}}class NullProtocol{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class PerfTracker{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,r){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=r??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout(()=>{this.collect(),setInterval(()=>{this.collect()},this.publishInterval)},this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map(e=>e.toJSON());this.system.stringMetric("entries",JSON.stringify(t))}}var metrics=e=>{let t;t=e.connection&&"object"==typeof e.connection?gw3(e.connection,e):new NullProtocol;let r=new Repository(e,t).root;e.disableAutoAppSystem||(r=r.subSystem("App"));const n=addFAVSupport(r);return initPerf(n,e.pagePerformanceMetrics),n};function initPerf(e,t){if("undefined"==typeof window)return;const r=window?.glue42gd?.metrics?.pagePerformanceMetrics;r&&(t=r),t?.enabled&&new PerfTracker(e,t.initialPublishTimeout,t.publishInterval)}function addFAVSupport(e){const t=e.subSystem("reporting"),r={name:"features"};let n;return e.featureMetric=(e,i,o)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===i||""===i)throw new Error("action is mandatory");if(void 0===o||""===o)throw new Error("payload is mandatory");n?n.update({name:e,action:i,payload:o}):n=t.objectMetric(r,{name:e,action:i,payload:o})},e}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createRegistry(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;i{this.messageHandler(t)}).then(e=>{this.client=e})}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class SharedWorkerTransport{logger;worker;registry=CallbackRegistryFactory();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class Utils{static isNode(){if(void 0!==Utils._isNode)return Utils._isNode;if("undefined"!=typeof window)return Utils._isNode=!1,!1;try{Utils._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){Utils._isNode=!1}return Utils._isNode}static _isNode}let PromiseWrapper$1=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve;reject;promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};const timers={};function getAllTimers(){return timers}function timer(e){const t=timers[e];if(t)return t;const r=[];function n(){return(new Date).getTime()}const i=n();let o,s;function a(e,t){const i=t??n();let o=0;r.length>0&&(o=i-r[r.length-1].time),r.push({name:e,time:i,diff:o})}a("start",i);const c={get startTime(){return i},get endTime(){return o},get period(){return s},stop:function(){return o=n(),a("end",o),s=o-i,s},mark:a,marks:r};return timers[e]=c,c}const WebSocketConstructor=Utils.isNode()?null:window.WebSocket;class WS{ws;logger;settings;startupTimer=timer("connection");_running=!0;_registry=CallbackRegistryFactory();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise((t,r)=>{this.waitForSocketConnection(()=>{try{this.ws?.send(e),t()}catch(e){r(e)}},r)})}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise((e,t)=>{this.waitForSocketConnection(e,t)})}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new PromiseWrapper$1;return this.waitForSocketConnection(()=>{e.resolve()}),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout(()=>{const r=void 0===t?void 0:t-1;this.openSocket(e,r)},e)}}initiateSocket(){const e=new PromiseWrapper$1;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new WebSocketConstructor(this.settings.ws??"");let t=!1;return this.ws.onerror=r=>{let n;try{n=JSON.stringify(r)}catch(e){const t=new WeakSet,i=(e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r instanceof Error?{message:r.message,name:r.name,stack:r.stack}:r};n=JSON.stringify(r,i)}this.logger.info(`ws error - reason: ${n}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error")),this.notifyStatusChanged(!1,n)},this.ws.onclose=r=>{this.logger.info(`ws closed - code: ${r?.code} reason: ${r?.reason}`),e.reject("closed"),t&&(t=!1,this.notifyForSocketState("closed")),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),t=!0,this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach(t=>{e?t.failed&&t.failed(e):t.callback()}),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}}class MessageReplayerImpl{specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const r of this.specs[t].types){let t=this.subsRefCount[r];if(t||(t=0),t+=1,this.subsRefCount[r]=t,t>1)continue;const n=e.on(r,e=>this.processMessage(r,e));this.subs[r]=n}}processMessage(e,t){if(!this.isDone&&t)for(const r of this.specsNames)if(-1!==this.specs[r].types.indexOf(e)){const e=this.messages[r]||[];this.messages[r]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}}let urlAlphabet$1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$3=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$1[64*Math.random()|0];return t};const PromisePlus$1=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});class WebPlatformTransport{settings;logger;identity;isPreferredActivated;_connectionProtocolVersion;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=CallbackRegistryFactory();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:()=>{}},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,r){this.settings=e,this.logger=t,this.identity=r,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId||"unknown"}, client connected: ${this.iAmConnected}`);const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=r=>{if(this.iAmConnected&&!r.data?.glue42core)return void this.registry.execute("onMessage",r.data);const n=r.data?.glue42core;n&&(n.type===this.messages.gatewayInternalConnect.name&&n.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),n.type===this.messages.gatewayInternalConnect.name&&n.error&&t(n.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))})}initiateRemoteConnection(e){return PromisePlus$1((t,r)=>{this.connectionResolve=t,this.connectionReject=r,this.myClientId=this.myClientId??nanoid$3(10);const n=this.getMyWindowId()||nanoid$3(10),i={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:n,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug(`sending connection request - clientId: ${this.myClientId}`),this.extContentConnecting)return i.glue42core.clientType="child",i.glue42core.bridgeInstanceId=this.myClientId,i.glue42core.parentWindowId=this.parentWindowId,window.postMessage(i,window.origin);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(i,this.defaultTargetString)},this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):(this.logger.debug("setting up window message listener"),window.addEventListener("message",e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const r=this.settings.allowedOrigins||[];if(r.length&&!r.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const n=t.type;this.logger.debug(`received valid glue42core message of type: ${n}`),this.messages[n].handle(e)}))}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):(this.logger.debug("setting up unload event listeners"),window.addEventListener("beforeunload",()=>{this._connectionProtocolVersion||this.signalClientDisappearing()}),window.addEventListener("pagehide",()=>{this._connectionProtocolVersion&&this.signalClientDisappearing()}))}signalClientDisappearing(){if(this.extContentConnected)return;this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`);const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent?.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId!==t.clientId?this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${t.clientId}`):this.handleAcceptanceOfMyRequest(t)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this._connectionProtocolVersion=e.connectionProtocolVersion,this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||nanoid$3(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",e=>{const t=e.data?.glue42ExtInc;if(!t)return;const r=this.settings.allowedOrigins||[];!r.length||r.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)}),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleConnectionRejected(e){if(this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"),!this.connectionReject)return;const t="string"==typeof e.data.glue42core?.error?`Connection was rejected. ${e.data.glue42core?.error}`:"The platform connection was rejected. Most likely because this window was not created by a glue API call";this.connectionReject(t),delete this.connectionReject}handleConnectionRequest(){this.extContentConnecting&&this.logger.debug("This connection request event is targeted at the extension content")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const r=e.source;this.logger.debug("responding to a parent ping with a ready message"),r.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.logger.debug("setting up platform unload listener"),this.onMessage(e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))})}handleManualUnload(){this.logger.debug("handling manual unload");const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);this.port?.postMessage(e)}handlePlatformPing(){}notifyStatusChanged(e,t){this.logger.debug(`status changed - connected: ${e}, reason: ${t||"none"}`),this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}requestConnectionPermissionFromExt(){return this.waitForContentScript().then(()=>PromisePlus$1((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},window.origin)},this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out"))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():PromisePlus$1(e=>{window.addEventListener("Glue42EXTReady",()=>{e()})},this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),r=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),n=new Set([...t,...r]);if(!n.size&&!this.extContentAvailable)throw new Error(e);if(!n.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(n)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e?.parent&&e!==e.parent?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=PromisePlus$1(t=>{this.parentPingResolve=t;const r={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval(()=>{e.forEach(e=>{e.postMessage(r,this.defaultTargetString)})},1e3)},this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch(()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)}),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${nanoid$3(10)}`,this.selfAssignedWindowId):void 0}}const waitForInvocations=(e,t)=>{let r=e;return()=>{r--,0===r&&t()}};let AsyncSequelizer$1=class{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}};function domainSession(e,t,r,n,i){null==e&&(e="global"),n=n??["success"],i=i??["error"];let o,s="global"===e,a=!1,c=!1;const l=CallbackRegistryFactory();t.disconnected(function(){r.debug("connection is down"),c=!1,s=!1,a=!0,Object.keys(u).forEach(e=>{const t=u[e];t&&(r.trace(`failing pending request ${e} due to connection lost`),t.error({err:"Connection lost - gateway connection was disconnected"}))}),l.execute("onLeft",{disconnected:!0})}),t.loggedIn(async function(){if(c=!0,a){r.debug("connection is now up - trying to reconnect...");try{await d(o)}catch{r.trace("failed to reconnect")}}}),t.on("success",e=>g(e)),t.on("error",e=>p(e)),t.on("result",e=>g(e)),n&&n.forEach(e=>{t.on(e,e=>g(e))}),i&&i.forEach(e=>{t.on(e,e=>p(e))});const u={};function d(t){return o=t,new Promise((n,i)=>{if(s)return void n({});let o;if("global"===e)o=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{r.debug(`joining domain ${e}`);o=y({type:"join",destination:e,domain:"global",options:t})}o.then(()=>{!function(){r.debug("did join "+e),s=!0;const t=a;a=!1,l.execute("onJoined",t)}(),n({})}).catch(t=>{r.debug("error joining "+e+" domain: "+JSON.stringify(t)),i(t)})})}function h(e){return s&&e(!1),l.add("onJoined",e)}function p(t){if(e!==t.domain)return;const r=t.request_id;if(!r)return;const n=u[r];n&&n.error(t)}function g(t){if(t.domain!==e)return;const r=t.request_id;if(!r)return;const n=u[r];n&&n.success(t)}function m(){return nanoid$3(10)}let f=[];function y(n,i,o){if(n.type&&-1===["hello","join"].indexOf(n.type)&&!s){console.warn(`trying to send a message (${n.domain} ${n.type}) but not connected, will queue`);const e=new PromiseWrapper$1;if(f.push({msg:n,tag:i,options:o,pw:e}),1===f.length){const e=h(()=>{r.info(`joined - will now send queued messages (${f.length} -> [${f.map(e=>e.msg.type)}])`),f.forEach(e=>{y(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),f=[],e()})}return e.promise}o=o??{},n.request_id=n.request_id??m(),n.domain=n.domain??e,o.skipPeerId||(n.peer_id=t.peerId);const a=n.request_id;return new Promise((e,r)=>{u[a]={success:t=>{delete u[a],t._tag=i,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete u[a],e._tag=i,r(e)}},t.send(n,o).catch(e=>{u[a]?.error({err:e})})})}return{join:d,leave:function(){return"global"===e?Promise.resolve():(r.debug("stopping session "+e+"..."),a=!1,y({type:"leave",destination:e,domain:"global"}).then(()=>{s=!1,l.execute("onLeft")}).catch(()=>{s=!1,l.execute("onLeft")}))},onJoined:h,onLeft:function(e){return s||e(),l.add("onLeft",e)},send:y,sendFireAndForget:function(r){return r.request_id=r.request_id?r.request_id:m(),r.domain=r.domain??e,r.peer_id=t.peerId,t.send(r)},on:(n,i)=>{t.on(n,t=>{if(t.domain===e)try{i(t)}catch(e){r.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}})},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}class Connection{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=CallbackRegistryFactory();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new AsyncSequelizer$1;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;loginRetryInProgress=!1;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new InProcTransport(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new SharedWorkerTransport(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new WebPlatformTransport(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new WS(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const r=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),n=this.transport.onMessage(this.handleTransportMessage.bind(this));this._transportSubscriptions.push(r),this._transportSubscriptions.push(n),this._defaultTransport=this.transport,this.ping()}async switchTransport(e){return this._sequelizer.enqueue(async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const r=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await r;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}})}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const r=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(r)}`),this.transport.sendObject(r,t)}{const r=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${r}`),this.transport.send(r,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const r=this.ids++;return this.messageHandlers[e][r]=t,{type:e,id:r}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn(()=>{const t=this.transport.name();e(t)})}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this.logger.debug(`Login initiated - reconnect: ${t}, transport: ${this.transport.name()}`),this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}try{await this.transport.open(),this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`),timer("connection").mark("transport-opened");const r=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(r)}`),timer("connection").mark("protocol-logged-in"),r}catch(e){throw this._switchInProgress&&(this.logger.debug("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,r){let n=this.sessions.find(t=>t.domain===e);return n||(n=domainSession(e,this,this.logger.subLogger(`domain=${e}`),t,r),this.sessions.push(n)),n}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then(e=>e.token):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&(this.initialLogin=!1,this.registry.execute("onLoggedIn"))}distributeMessage(e,t){const r=this.messageHandlers[t.toLowerCase()];void 0!==r&&Object.keys(r).forEach(t=>{const n=r[t];if(void 0!==n)try{n(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}})}handleConnectionChanged(e){this._connected!==e?(this.logger.info("connection state changed to "+(e?"connected":"disconnected")),this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new MessageReplayerImpl(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&this.attemptLoginWithRetry(),this.registry.execute("disconnected"))):this.logger.trace("connection state unchanged, skipping")}async attemptLoginWithRetry(){if(!this.loginConfig)throw new Error("no login info");if(this.loginRetryInProgress)this.logger.debug("login attempt already in progress, ignoring request...");else if(this._isLoggedIn)this.logger.debug("already logged in, ignoring request...");else{if(this.initialLogin){if(this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`),this.initialLoginAttempts<=0)return void this.logger.info("maximum initial login attempts reached, will not try to login again");this.initialLoginAttempts--}try{this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`),this.loginRetryInProgress=!0,await this.login(this.loginConfig,!0)}catch(e){this.logger.error(`error trying to login: ${e?.message}`,e),setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3)}finally{this.loginRetryInProgress=!1}}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return PromisePlus$1(e=>{let t;const r=waitForInvocations(2,()=>{t&&t(),e()});t=this.onLibReAnnounced(e=>"interop"===e.name||"contexts"===e.name?r():void 0)},1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new WS(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport.close().catch(e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`)),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,(e,t)=>{if("string"!=typeof t)return t;if(t.lengthe.leave());await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout(()=>{this.ping()},3e4))}}const order=["trace","debug","info","warn","error","off"];class Logger{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,r){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!r,r&&(this.logFn=r,this.customLogFn=!0)}subLogger(e){const t=this.subLoggers.filter(t=>t.name===e)[0];if(void 0!==t)return t;Object.keys(this).forEach(t=>{if(t===e)throw new Error("This sub logger name is not allowed.")});const r=new Logger(e,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(r),r}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,r){this.publishMessage(t||"info",e,r)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error",t)}canPublish(e,t){return order.indexOf(e)>=order.indexOf(t||this.consoleLevel()||"trace")}publishMessage(e,t,r){const n=this.loggerFullName;if("error"===e&&!r){const e=new Error;e.stack&&(t=t+"\n"+e.stack.split("\n").slice(4).join("\n"))}if(this.canPublish(e,this.publishLevel())){const i=Logger.Interop;if(i)try{if(i.methods({name:Logger.InteropMethodName}).length>0){const o={msg:t,logger:n,level:e};r&&r instanceof Error&&(o.error={message:r.message,stack:r.stack??""}),i.invoke(Logger.InteropMethodName,o).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${e.message}`,e)})}}catch{}}if(this.canPublish(e)){let i="";if(this.includeTimeAndLevel){const t=new Date;i=`[${`${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}:${t.getMilliseconds()}`}] [${e}] `}const o=`${i}${n}: ${t}`;switch(e){case"trace":this.logFn.debug(o);break;case"debug":this.logFn.debug?this.logFn.debug(o):this.logFn.log(o);break;case"info":this.logFn.info(o);break;case"warn":this.logFn.warn(o);break;case"error":r?this.logFn.error(o,r):this.logFn.error(o)}}}}const GW_MESSAGE_CREATE_CONTEXT="create-context",GW_MESSAGE_ACTIVITY_CREATED="created",GW_MESSAGE_ACTIVITY_DESTROYED="destroyed",GW_MESSAGE_CONTEXT_CREATED="context-created",GW_MESSAGE_CONTEXT_ADDED="context-added",GW_MESSAGE_SUBSCRIBE_CONTEXT="subscribe-context",GW_MESSAGE_SUBSCRIBED_CONTEXT="subscribed-context",GW_MESSAGE_UNSUBSCRIBE_CONTEXT="unsubscribe-context",GW_MESSAGE_DESTROY_CONTEXT="destroy-context",GW_MESSAGE_CONTEXT_DESTROYED="context-destroyed",GW_MESSAGE_UPDATE_CONTEXT="update-context",GW_MESSAGE_CONTEXT_UPDATED="context-updated",GW_MESSAGE_JOINED_ACTIVITY="joined",ContextMessageReplaySpec={get name(){return"context"},get types(){return[GW_MESSAGE_CREATE_CONTEXT,GW_MESSAGE_ACTIVITY_CREATED,GW_MESSAGE_ACTIVITY_DESTROYED,GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_CONTEXT_ADDED,GW_MESSAGE_SUBSCRIBE_CONTEXT,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_UNSUBSCRIBE_CONTEXT,GW_MESSAGE_DESTROY_CONTEXT,GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_UPDATE_CONTEXT,GW_MESSAGE_CONTEXT_UPDATED,GW_MESSAGE_JOINED_ACTIVITY]}};var version$2="6.8.1";function prepareConfig(e,t,r){let n;if(Utils.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{n=JSON.parse(e)}catch{}}function i(){if(e.application)return e.application;if(r)return r.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=nanoid$3(10);return Utils.isNode()?n?n.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const o=function(){const o=e.gateway,s=o?.protocolVersion??3,a=o?.reconnectInterval,c=o?.reconnectAttempts;let l=o?.ws;const u=o?.sharedWorker,d=o?.inproc,h=o?.webPlatform??void 0;let p,g,m,f,y;r&&(l=r.gwURL),Utils.isNode()&&n&&n.gwURL&&(l=n.gwURL),l||u||d||(l="ws://localhost:8385");const $=i();let b=$;void 0!==r?(g=r.windowId,m=r.pid,r.env&&(f=r.env.env,y=r.env.region),b=r.application??"glue-app",p=r.appInstanceId):Utils.isNode()?(m=process.pid,n&&(f=n.env,y=n.region,p=n.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,m=window?.glue42electron.pid,f=window?.glue42electron.env,y=window?.glue42electron.region,b=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const v=e.gateway?.replaySpecs??[];v.push(ContextMessageReplaySpec);let w={application:b,applicationName:$,windowId:g,instance:p,process:m,region:y,environment:f,api:t.version||version$2};return e.identity&&(w=Object.assign(w,e.identity)),{identity:w,reconnectInterval:a,ws:l,sharedWorker:u,webPlatform:h,inproc:d,protocolVersion:s,reconnectAttempts:c,replaySpecs:v}}();let s=i();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(s=t)}return{bus:e.bus??!1,application:s,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Utils.isNode()&&n&&n.gwToken?{gatewayToken:n.gwToken}:e.gateway?.webPlatform?{username:"glue42",password:""}:void 0,logger:function(){let t=e.logger;const n="warn";let i;return t||(t=n),r&&(i=r.consoleLogLevel),"string"==typeof t?{console:i??t,publish:n}:{console:i??t.console??n,publish:t.publish??n}}(),connection:o,metrics:e.metrics??!0,contexts:function(){const t={reAnnounceKnownContexts:!0,subscribeOnUpdate:!0,subscribeOnGet:!0,onlyReAnnounceSubscribedContexts:!0};return void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?t:"object"==typeof e.contexts&&{...t,...e.contexts}}(),version:t.version||version$2,libs:t.libs??[],customLogger:e.customLogger}}class GW3ContextData{name;contextId;context;isAnnounced;createdByUs;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;get hasReceivedSnapshot(){return this.snapshotPromiseWrapper.resolved}set hasReceivedSnapshot(e){e?this.snapshotPromiseWrapper.resolve():this.snapshotPromiseWrapper=new PromiseWrapper$1}get snapshotPromise(){return this.snapshotPromiseWrapper.promise}snapshotPromiseWrapper;constructor(e,t,r,n){this.contextId=e,this.name=t,this.isAnnounced=r,this.activityId=n,this.context={},this.snapshotPromiseWrapper=new PromiseWrapper$1}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var lodash_clonedeep={exports:{}};lodash_clonedeep.exports,function(e,t){var r="__lodash_hash_undefined__",n=9007199254740991,i="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",l="[object Map]",u="[object Number]",d="[object Object]",h="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",$="[object ArrayBuffer]",b="[object DataView]",v="[object Float32Array]",w="[object Float64Array]",S="[object Int8Array]",_="[object Int16Array]",E="[object Int32Array]",C="[object Uint8Array]",I="[object Uint8ClampedArray]",T="[object Uint16Array]",A="[object Uint32Array]",D=/\w*$/,x=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,O={};O[i]=O["[object Array]"]=O[$]=O[b]=O[o]=O[s]=O[v]=O[w]=O[S]=O[_]=O[E]=O[l]=O[u]=O[d]=O[p]=O[g]=O[m]=O[f]=O[C]=O[I]=O[T]=O[A]=!0,O["[object Error]"]=O[a]=O[y]=!1;var N="object"==typeof commonjsGlobal&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,P="object"==typeof self&&self&&self.Object===Object&&self,k=N||P||Function("return this")(),M=t&&!t.nodeType&&t,L=M&&e&&!e.nodeType&&e,F=L&&L.exports===M;function j(e,t){return e.set(t[0],t[1]),e}function U(e,t){return e.add(t),e}function B(e,t,r,n){for(var i=-1,o=e?e.length:0;++i-1},Ie.prototype.set=function(e,t){var r=this.__data__,n=Re(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new Ce,map:new(pe||Ie),string:new Ce}},Te.prototype.delete=function(e){return Me(this,e).delete(e)},Te.prototype.get=function(e){return Me(this,e).get(e)},Te.prototype.has=function(e){return Me(this,e).has(e)},Te.prototype.set=function(e,t){return Me(this,e).set(e,t),this},Ae.prototype.clear=function(){this.__data__=new Ie},Ae.prototype.delete=function(e){return this.__data__.delete(e)},Ae.prototype.get=function(e){return this.__data__.get(e)},Ae.prototype.has=function(e){return this.__data__.has(e)},Ae.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Ie){var n=r.__data__;if(!pe||n.length<199)return n.push([e,t]),this;r=this.__data__=new Te(n)}return r.set(e,t),this};var Fe=le?z(le,Object):function(){return[]},je=function(e){return ee.call(e)};function Ue(e,t){return!!(t=null==t?n:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=n}(e.length)&&!Je(e)}var Ge=ue||function(){return!1};function Je(e){var t=Ke(e)?ee.call(e):"";return t==a||t==c}function Ke(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ve(e){return We(e)?De(e):function(e){if(!Be(e))return de(e);var t=[];for(var r in Object(e))Q.call(e,r)&&"constructor"!=r&&t.push(r);return t}(e)}e.exports=function(e){return Oe(e,!0,!0)}}(lodash_clonedeep,lodash_clonedeep.exports);var lodash_clonedeepExports=lodash_clonedeep.exports,cloneDeep=getDefaultExportFromCjs(lodash_clonedeepExports);function applyContextDelta(e,t,r){try{if(r?.canPublish("trace")&&r?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=deepClone(e,void 0),t.commands){for(const r of t.commands)"remove"===r.type?deletePath(e,r.path):"set"===r.type&&setValueToPath(e,r.value,r.path);return e}const n=t.added,i=t.updated,o=t.removed;return n&&Object.keys(n).forEach(t=>{e[t]=n[t]}),i&&Object.keys(i).forEach(t=>{mergeObjectsProperties(t,e,i)}),o&&o.forEach(t=>{delete e[t]}),e}catch(n){return r?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,n),e}}function deepClone(e,t){return cloneDeep(e)}const mergeObjectsProperties=(e,t,r)=>{const n=r[e];if(void 0===n)return t;const i=t[e];return i&&n?"string"==typeof i||"number"==typeof i||"boolean"==typeof i||"string"==typeof n||"number"==typeof n||"boolean"==typeof n||Array.isArray(i)||Array.isArray(n)?(t[e]=n,t):(t[e]=Object.assign({},i,n),t):(t[e]=n,t)};function deepEqual(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const r in e)if(e.hasOwnProperty(r)){if(!t.hasOwnProperty(r))return!1;if(e[r]!==t[r]){if("object"!=typeof e[r])return!1;if(!deepEqual(e[r],t[r]))return!1}}for(const r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}function setValueToPath(e,t,r){const n=r.split("."),i=["__proto__","constructor","prototype"];let o;for(o=0;o"object"==typeof t[r]?isSubset(e?.[r]||{},t[r]||{}):t[r]===e?.[r])}function deletePath(e,t){const r=t.split(".");let n;for(n=0;n"context"===e.uri);this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._subscribeOnUpdate=e.subscribeOnUpdate??!0,this._subscribeOnGet=e.subscribeOnGet??!0,this._onlyReAnnounceSubscribedContexts=e.onlyReAnnounceSubscribedContexts??!0,this._gw3Session=this._connection.domain("global",[GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_CONTEXT_UPDATED]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined(e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then(()=>this._connection.setLibReAnnounced({name:"contexts"})).catch(e=>{this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(e)}`)}):(this._contextsTempCache={},this._connection.setLibReAnnounced({name:"contexts"}))}),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED||t===GW_MESSAGE_CONTEXT_ADDED||t===GW_MESSAGE_ACTIVITY_CREATED?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT||t===GW_MESSAGE_CONTEXT_UPDATED||t===GW_MESSAGE_JOINED_ACTIVITY?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED&&t!==GW_MESSAGE_ACTIVITY_DESTROYED||this.handleContextDestroyedMessage(e))})}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:GW_MESSAGE_CREATE_CONTEXT,domain:"global",name:e,data:t,lifetime:"retained"}).then(r=>{this._contextNameToId[e]=r.context_id,this._contextIdToName[r.context_id]=e;const n=this._contextNameToData[e]||new GW3ContextData(r.context_id,e,!0,void 0);return n.isAnnounced=!0,n.name=e,n.contextId=r.context_id,n.context=r.data||deepClone(t),n.hasReceivedSnapshot=!0,this._contextNameToData[e]=n,delete this._creationPromises[e],n.sentExplicitSubscription=!0,n.createdByUs=!0,this.subscribe(e,()=>{}),r.context_id})),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter(e=>this._contextNameToData[e].isAnnounced)}async update(e,t){t&&(t=deepClone(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return void await this.createContext(e,t);const n=await this.get(r.name),i=this.setPathSupported?this.calculateContextDeltaV2(n,t):this.calculateContextDeltaV1(n,t);if(!(Object.keys(i.added).length||Object.keys(i.updated).length||i.removed.length||i.commands?.length))return Promise.resolve();const o=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:r.contextId,delta:i},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&(await r.snapshotPromise,this.handleUpdated(r,i,{updaterId:o.peer_id}))}async set(e,t){t&&(t=deepClone(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return this.createContext(e,t);const n=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:r.contextId,delta:{reset:t}},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&this.handleUpdated(r,{reset:t,added:{},removed:[],updated:{}},{updaterId:n.peer_id})}setPath(e,t,r){return this.setPathSupported?this.setPaths(e,[{path:t,value:r}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=deepClone(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced){const r={};for(const e of t)setValueToPath(r,e.value,e.path);return this.createContext(e,r)}const n=[];for(const e of t)null===e.value?n.push({type:"remove",path:e.path}):n.push({type:"set",path:e.path,value:e.value});const i=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:r.contextId,delta:{commands:n}},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&(await r.snapshotPromise,this.handleUpdated(r,{added:{},removed:[],updated:{},commands:n},{updaterId:i.peer_id}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return!t&&this._subscribeOnGet&&this.subscribe(e,()=>{}),Promise.resolve({});if(t&&!t.sentExplicitSubscription)return new Promise((t,r)=>{this.subscribe(e,(e,r,n,i)=>{this._subscribeOnGet||this.unsubscribe(i),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):r(e)})});await t.snapshotPromise;const r=t?.context??{};return Promise.resolve(deepClone(r))}isInvalidContextError(e){return e.reason_uri===this.ERROR_URI_INVALID_CONTEXT||e.reason_uri===this.ERROR_URI_FAILURE&&e.reason?.startsWith("Unable to find context with id")}async subscribe(e,t,r){e in this._creationPromises&&await this._creationPromises[e];const n=void 0===r?this._nextCallbackSubscriptionNumber:r;void 0===r&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:n,callback:t}));let i=this._contextNameToData[e];if(!i||!i.isAnnounced)return i=i||new GW3ContextData(void 0,e,!1,void 0),this._contextNameToData[e]=i,i.updateCallbacks[n]=t,Promise.resolve(n);const o=i.hasCallbacks();if(i.updateCallbacks[n]=t,o){if(i.hasReceivedSnapshot&&!r){const e=deepClone(i.context);t(e,e,[],n)}return Promise.resolve(n)}if(i.joinedActivity||i.createdByUs){if(i.hasReceivedSnapshot&&!r){const e=deepClone(i.context);t(e,e,[],n)}return Promise.resolve(n)}if(i.context&&i.sentExplicitSubscription){if(i.hasReceivedSnapshot&&!r){const e=deepClone(i.context);t(e,e,[],n)}return Promise.resolve(n)}return this.sendSubscribe(i).then(()=>n,()=>(this.unsubscribe(n,!0),n))}unsubscribe(e,t){t||(this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter(t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const r=this._contextNameToData[t];if(!r)continue;const n=r.hasCallbacks();delete r.updateCallbacks[e],r.isAnnounced&&n&&!r.hasCallbacks()&&r.sentExplicitSubscription&&(r.hasReceivedSnapshot=!1,r.context={},this.sendUnsubscribe(r).catch(()=>{})),r.isAnnounced||r.hasCallbacks()||(delete this._contextNameToData[t],delete this._contextNameToId[t],r.contextId&&delete this._contextIdToName[r.contextId])}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e],r=t?.contextId;return t&&r?this._gw3Session.send({type:GW_MESSAGE_DESTROY_CONTEXT,domain:"global",context_id:t.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,r){const n=e.context;e.context=applyContextDelta(e.context,t,this._logger),this._contextNameToData[e.name]!==e||deepEqual(n,e.context)||this.invokeUpdateCallbacks(e,t,r)}subscribeToContextCreatedMessages(){const e=[GW_MESSAGE_CONTEXT_ADDED,GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_ACTIVITY_CREATED];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===GW_MESSAGE_ACTIVITY_CREATED?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===GW_MESSAGE_CONTEXT_ADDED&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const r=this._contextIdToName[e.context_id];if(!r)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[r])throw new Error("Received created event for context with unknown id: "+e.context_id);let n=this._contextNameToData[r];if(n){if(n.isAnnounced)return;if(!n.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");n.isAnnounced=!0,n.contextId=e.context_id,n.activityId=e.activity_id,n.sentExplicitSubscription||this.sendSubscribe(n).catch(()=>{})}else this._contextNameToData[r]=n=new GW3ContextData(e.context_id,r,!0,e.activity_id),this._trackAllContexts&&this.subscribe(r,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[GW_MESSAGE_CONTEXT_UPDATED,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_JOINED_ACTIVITY];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,r=e.context_id;let n=this._contextNameToData[this._contextIdToName[r]];const i=!n||!n.isAnnounced;if(t===GW_MESSAGE_JOINED_ACTIVITY)n||(n=this._contextNameToData[e.activity_id]||new GW3ContextData(r,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=n,this._contextIdToName[r]=e.activity_id,this._contextNameToId[e.activity_id]=r,n.contextId=r,n.isAnnounced=!0,n.activityId=e.activity_id,n.joinedActivity=!0;else if(!n||!n.isAnnounced)return void(t===GW_MESSAGE_SUBSCRIBED_CONTEXT?(n=n||new GW3ContextData(r,e.name,!0,void 0),n.sentExplicitSubscription=!0,this._contextNameToData[e.name]=n,this._contextIdToName[r]=e.name,this._contextNameToId[e.name]=r):this._logger.error(`Received 'update' for unknown context: ${r}`));const o=n.context;if(n.hasReceivedSnapshot=!0,t===GW_MESSAGE_SUBSCRIBED_CONTEXT)n.context=e.data??{};else if(t===GW_MESSAGE_JOINED_ACTIVITY)n.context=e.context_snapshot??{};else{if(t!==GW_MESSAGE_CONTEXT_UPDATED)throw new Error("Unrecognized context update message "+t);n.context=applyContextDelta(n.context,e.delta,this._logger)}!i&&deepEqual(n.context,o)&&t!==GW_MESSAGE_SUBSCRIBED_CONTEXT||this.invokeUpdateCallbacks(n,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,r){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),setValueToPath(t.updated,null,e.path)):"set"===e.type&&setValueToPath(t.updated,e.value,e.path)}for(const n in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(n))try{(0,e.updateCallbacks[n])(deepClone(e.context),deepClone(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(n,10),r)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_ACTIVITY_DESTROYED];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,r;if(e.type===GW_MESSAGE_ACTIVITY_DESTROYED){if(r=e.activity_id,t=this._contextNameToId[r],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,r=this._contextIdToName[t],!r)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[r];const n=this._contextNameToData[r];delete this._contextNameToData[r],n&&n.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}async sendSubscribe(e){e.sentExplicitSubscription=!0;try{return void await this._gw3Session.send({type:GW_MESSAGE_SUBSCRIBE_CONTEXT,domain:"global",context_id:e.contextId})}catch(t){throw e.sentExplicitSubscription=!1,t}}async sendUnsubscribe(e){const t=e.sentExplicitSubscription;e.sentExplicitSubscription=!1;try{return void await this._gw3Session.send({type:GW_MESSAGE_UNSUBSCRIBE_CONTEXT,domain:"global",context_id:e.contextId})}catch(r){throw e.sentExplicitSubscription=t,r}}calculateContextDeltaV1(e,t){const r={added:{},updated:{},removed:[],reset:void 0};if(e)for(const n of Object.keys(e))-1===Object.keys(t).indexOf(n)||null===t[n]||deepEqual(e[n],t[n])||(r.updated[n]=t[n]);for(const n of Object.keys(t))e&&-1!==Object.keys(e).indexOf(n)?null===t[n]&&r.removed.push(n):null!==t[n]&&(r.added[n]=t[n]);return r}calculateContextDeltaV2(e,t){const r={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const n of Object.keys(t))if(null!==t[n]){deepEqual(e?e[n]:null,t[n])||r.commands?.push({type:"set",path:n,value:t[n]})}else r.commands?.push({type:"remove",path:n});return r}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey,!0),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((e,t)=>{const r=this._contextNameToData[t];return(!this._onlyReAnnounceSubscribedContexts||r.hasReceivedSnapshot)&&(e[t]=this._contextNameToData[t].context),e},{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED||t===GW_MESSAGE_CONTEXT_ADDED||t===GW_MESSAGE_ACTIVITY_CREATED?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT||t===GW_MESSAGE_CONTEXT_UPDATED||t===GW_MESSAGE_JOINED_ACTIVITY?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED&&t!==GW_MESSAGE_ACTIVITY_DESTROYED||this.handleContextDestroyedMessage(e))}),await Promise.all(this._contextsSubscriptionsCache.map(e=>this.subscribe(e.contextName,e.callback,e.subKey))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise(e=>setTimeout(()=>e(),0))}}class ContextsModule{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new GW3Bridge(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,r){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(r),this.set(e,r)):this._bridge.setPath(e,t,r)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:r}of t){this.checkPath(e);""===e&&this.checkData(r)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(e,r,n,i,o)=>t(e,r,n,()=>this._bridge.unsubscribe(i),o)).then(e=>()=>{this._bridge.unsubscribe(e)})}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}}function promisify(e,t,r){return"function"!=typeof t&&"function"!=typeof r?e:("function"!=typeof t?t=()=>{}:"function"!=typeof r&&(r=()=>{}),e.then(t,r))}function rejectAfter(e=0,t,r){let n;const i=()=>{n&&clearTimeout(n)};return t.then(()=>{i()}).catch(()=>{i()}),new Promise((t,i)=>{n=setTimeout(()=>i(r),e)})}var ok=function(e){return{ok:!0,result:e}},err=function(e){return{ok:!1,error:e}},asPromise=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault=function(e,t){return!0===t.ok?t.result:e},withException=function(e){if(!0===e.ok)return e.result;throw e.error},map$1=function(e,t){return!0===t.ok?ok(e(t.result)):t},map2=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok(e(t.result,r.result))},mapError=function(e,t){return!0===t.ok?t:err(e(t.error))},andThen=function(e,t){return!0===t.ok?e(t.result):t},__assign=function(){return __assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{const r=typeof e;return"function"===r?anyJson():fail$1(`The provided argument as ${t} should be of type function, provided: ${typeof r}`)},nonEmptyStringDecoder=string$3().where(e=>e.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder=number$3().where(e=>e>=0,"Expected a non-negative number or 0"),methodDefinitionDecoder=object$1({name:nonEmptyStringDecoder,objectTypes:optional$1(array$1(nonEmptyStringDecoder)),displayName:optional$1(nonEmptyStringDecoder),accepts:optional$1(nonEmptyStringDecoder),returns:optional$1(nonEmptyStringDecoder),description:optional$1(nonEmptyStringDecoder),version:optional$1(nonNegativeNumberDecoder),supportsStreaming:optional$1(boolean$3()),flags:optional$1(object$1()),getServers:optional$1(anyJson().andThen(e=>functionCheck(e,"method definition getServers")))}),methodFilterDecoder=union$1(nonEmptyStringDecoder,methodDefinitionDecoder),instanceDecoder=object$1({application:optional$1(nonEmptyStringDecoder),applicationName:optional$1(nonEmptyStringDecoder),pid:optional$1(nonNegativeNumberDecoder),machine:optional$1(nonEmptyStringDecoder),user:optional$1(nonEmptyStringDecoder),environment:optional$1(nonEmptyStringDecoder),region:optional$1(nonEmptyStringDecoder),service:optional$1(nonEmptyStringDecoder),instance:optional$1(nonEmptyStringDecoder),windowId:optional$1(nonEmptyStringDecoder),peerId:optional$1(nonEmptyStringDecoder),isLocal:optional$1(boolean$3()),api:optional$1(nonEmptyStringDecoder),getMethods:optional$1(anyJson().andThen(e=>functionCheck(e,"instance getMethods"))),getStreams:optional$1(anyJson().andThen(e=>functionCheck(e,"instance getStreams")))}),targetDecoder=union$1(constant("best"),constant("all"),constant("skipMine"),instanceDecoder,array$1(instanceDecoder)),invokeOptionsDecoder=object$1({waitTimeoutMs:optional$1(nonNegativeNumberDecoder),methodResponseTimeoutMs:optional$1(nonNegativeNumberDecoder)});var InvokeStatus;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(InvokeStatus||(InvokeStatus={}));class Client{protocol;repo;instance;configuration;constructor(e,t,r,n){this.protocol=e,this.repo=t,this.instance=r,this.configuration=n}subscribe(e,t,r,n,i){const o=(e,r,n,o)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(r,t,e,n,o,i)},s=new Promise((r,n)=>{const i=e=>{r(e)},s=e=>{n(e)};if(!e)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void n(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let l=0,u=this.getServerMethodsByFilterAndTarget(a,c);if(u.length>0)o(u,u[0].methods[0],i,s);else{const r=()=>{if(c&&t.waitTimeoutMs)if(l+=500,u=this.getServerMethodsByFilterAndTarget(a,c),u.length>0){const e=u[0].methods[0];o(u,e,i,s)}else if(l>=t.waitTimeoutMs){o(u,"string"==typeof e?{name:e}:e,i,s)}else setTimeout(r,500)};setTimeout(r,500)}});return promisify(s,r,n)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map(e=>e.server.instance)}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved((t,r)=>{e(t,r)})}serverMethodAdded(e){return this.repo.onServerMethodAdded((t,r)=>{e({server:t,method:r})})}serverMethodRemoved(e){return this.repo.onServerMethodRemoved((t,r)=>{e({server:t,method:r})})}async invoke(e,t,r,n,i,o){return promisify((async()=>{const s="string"==typeof e?{name:e}:{...e};t||(t={}),r||(r="best"),n||(n={});const a=methodFilterDecoder.run(s);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if("object"!=typeof t){const e="The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const c=targetDecoder.run(r);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const l=invokeOptionsDecoder.run(n);if(!l.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(l.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(i&&"function"!=typeof i){const e="The provided 'success' function is invalid. Error: The success should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(o&&"function"!=typeof o){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=n.method_response_timeout,void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=n.wait_for_method_timeout,void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=this.configuration.waitTimeoutMs));let u=this.getServerMethodsByFilterAndTarget(s,r);if(0===u.length)try{u=await this.tryToAwaitForMethods(s,r,n)}catch(n){const i=`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(r)}`;return Promise.reject(this.generateInvalidInputInvocationResult(i,s,t))}const d=n.methodResponseTimeoutMs,h=n,p=u.map(e=>{const r=nanoid$3(10),n=e.methods[0],i=e.server,o=this.protocol.client.invoke(r,n,t,i,h);return Promise.race([o,rejectAfter(d,o,{invocationId:r,message:`Invocation timeout (${d} ms) reached for method name: ${n?.name}, target instance: ${JSON.stringify(i.instance)}, options: ${JSON.stringify(h)}`,status:InvokeStatus.Error})])}),g=await Promise.all(p),m=this.getInvocationResultObj(g,s,t);return g.every(e=>e.status===InvokeStatus.Error)?Promise.reject(m):m})(),i,o)}generateInvalidInputInvocationResult(e,t,r){const n={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},i={invocationId:nanoid$3(10),status:InvokeStatus.Error,message:e};return this.getInvocationResultObj([i],n,r)}getInvocationResultObj(e,t,r){const n=e.filter(e=>e.status===InvokeStatus.Success).reduce((e,n)=>e=[...e,{executed_by:n.instance,returned:n.result,called_with:r,method:t,message:n.message,status:n.status}],[]),i=e.filter(e=>e.status===InvokeStatus.Error).reduce((e,n)=>e=[...e,{executed_by:n.instance,called_with:r,name:t.name,message:n.message}],[]),o=e[0];return{method:t,called_with:r,returned:o.result,executed_by:o.instance,all_return_values:n,all_errors:i,message:o.message,status:o.status}}tryToAwaitForMethods(e,t,r){return new Promise((n,i)=>{if(0===r.waitTimeoutMs)return void i();let o=0;const s=setInterval(()=>{o+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(s),n(a);else if(o>=(r.waitTimeoutMs||1e4))return clearInterval(s),void i()},500)})}filterByTarget(e,t){if("string"!=typeof e){let r;r=Array.isArray(e)?e:[e];const n=r.reduce((e,r)=>{const n=t.filter(e=>this.instanceMatch(r,e.server.instance));return e.concat(n)},[]);return n}if("all"===e)return[...t];if("best"===e){const e=t.find(e=>e.server.instance.isLocal);if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter(({server:e})=>e.instance.peerId!==this.instance.peerId);return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter(t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0]).every(r=>{let n;const i=e[r],o=t[r];switch(r){case"objectTypes":n=(i||[]).every(e=>(o||[]).includes(e));break;case"flags":n=isSubset(o||{},i||{});break;default:n=String(i).toLowerCase()===String(o).toLowerCase()}return n})}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter(t=>this.methodMatch(e,t))}getMethodsForInstance(e){const t=this.repo.getServers().filter(t=>this.instanceMatch(e,t.instance));if(0===t.length)return[];let r={};return 1===t.length?r=t[0].methods:t.forEach(e=>{Object.keys(e.methods).forEach(t=>{const n=e.methods[t];r[n.identifier]=n})}),Object.keys(r).map(e=>r[e])}getServers(e){const t=this.repo.getServers();return void 0===e?t.map(e=>({server:e,methods:[]})):t.reduce((t,r)=>{const n=Object.values(r.methods).filter(t=>this.methodMatch(e,t));return n.length>0&&t.push({server:r,methods:n}),t},[])}getServerMethodsByFilterAndTarget(e,t){const r=this.getServers(e);return this.filterByTarget(t,r)}}class ServerSubscription{protocol;repoMethod;subscription;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.subscription=r}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}}let Request$1=class{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.requestContext=r,this.arguments=r.arguments,this.instance=r.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}},ServerStreaming$1=class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest((e,t)=>this.handleSubRequest(e,t)),e.server.onSubAdded((e,t)=>this.handleSubAdded(e,t)),e.server.onSubRemoved((e,t)=>this.handleSubRemoved(e,t))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const r=new Request$1(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(r)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const r=new ServerSubscription(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(r)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const r=new ServerSubscription(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(r)}};class ServerBranch{key;protocol;repoMethod;constructor(e,t,r){this.key=e,this.protocol=t,this.repoMethod=r}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map(e=>new ServerSubscription(this.protocol,this.repoMethod,e))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}}class ServerStream{_protocol;_repoMethod;_server;name;constructor(e,t,r){this._protocol=e,this._repoMethod=t,this._server=r,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new ServerBranch(e,this._protocol,this._repoMethod):void 0:t.map(e=>new ServerBranch(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new ServerSubscription(this._protocol,this._repoMethod,e))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}close(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}class Server{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new ServerStreaming$1(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,r,n,i){const o=new Promise((r,n)=>{if(!e)return void n("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let o;if(o="string"==typeof e?{name:""+e}:{...e},!o.name)return n(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(o)}`);if(this.serverRepository.getList().some(e=>e.definition.name===o.name))return n(`A stream with the name "${o.name}" already exists! Please, provide a unique name for the stream.`);o.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const s=this.serverRepository.add({definition:o,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(s).then(()=>{let e;i?(e=i,i.updateRepoMethod(s)):e=new ServerStream(this.protocol,s,this),s.stream=e,r(e)}).catch(e=>{s.repoId&&this.serverRepository.remove(s.repoId),n(e)})});return promisify(o,r,n)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const r=async(e,r)=>{try{const n=t(e.args,e.instance);if(n&&"function"==typeof n.then){r(void 0,await n)}else r(void 0,n)}catch(e){r(e??"",e??"")}};return r.userCallback=t,this.registerCore(e,r)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const r=async(e,r)=>{try{let n=!1;const i=e=>{n||r(void 0,e),n=!0},o=e=>{n||(e||(e=""),r(e,e)),n=!0},s=t(e.args,e.instance,i,o);s&&"function"==typeof s.then&&s.then(i).catch(o)}catch(e){r(e,void 0)}};return r.userCallbackAsync=t,this.registerCore(e,r)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let r;if(r="string"==typeof e?{name:e}:e,void 0===r.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const n=this.serverRepository.getList().find(e=>e.definition.name===r.name&&(e.definition.supportsStreaming||!1)===t);if(!n)return Promise.reject(`Method with a name "${r.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([n])}async unregisterWithPredicate(e,t){const r=this.serverRepository.getList().filter(t=>e(t.definition)).filter(e=>(e.definition.supportsStreaming||!1)===t);if(!r||0===r.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(r)}removeMethodsOrStreams(e){const t=[];return e.forEach(e=>{const r=this.protocol.server.unregister(e).then(()=>{e.repoId&&this.serverRepository.remove(e.repoId)});t.push(r),this.addAsCurrentlyUnregistering(e.definition.name,r)}),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const r=new Promise(e=>setTimeout(e,5e3));this.currentlyUnregistering[e]=Promise.race([t,r]).then(()=>{delete this.currentlyUnregistering[e]})}async registerCore(e,t){let r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const n=this.currentlyUnregistering[r.name];void 0!==n&&await n;if(this.serverRepository.getList().some(e=>e.definition.name===r.name))return Promise.reject(`A method with the name "${r.name}" already exists! Please, provide a unique name for the method.`);if(r.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${r.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const i=this.serverRepository.add({definition:r,theFunction:t,protocolState:{}});return this.protocol.server.register(i).catch(e=>{throw i?.repoId&&this.serverRepository.remove(i.repoId),e})}onMethodInvoked(e,t,r){e&&e.theFunction&&e.theFunction(r,(r,n)=>{if(null!=r)if(r.message&&"string"==typeof r.message)r=r.message;else if("string"!=typeof r)try{r=JSON.stringify(r)}catch(e){r=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(r)}`}n?("object"!=typeof n||Array.isArray(n))&&(n={_value:n}):n={},this.protocol.server.methodInvocationResult(e,t,r,n)})}}class InstanceWrapper{wrapped={};constructor(e,t,r){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter(e=>e.supportsStreaming)},t&&this.refreshWrappedObject(t),r&&(r.loggedIn(()=>{this.refresh(r)}),this.refresh(r))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,r=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(r)}refreshWrappedObject(e){Object.keys(e).forEach(t=>{this.wrapped[t]=e[t]}),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??nanoid$3(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}}const hideMethodSystemFlags=e=>({...e,flags:e.flags.metadata||{}});class ClientRepository{logger;API;servers={};myServer;methodsCount={};callbacks=CallbackRegistryFactory();constructor(e,t){this.logger=e,this.API=t;const r=this.API.instance.peerId;this.myServer={id:r,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[r]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const r=this.servers[t];if(r)return r.id;const n=new InstanceWrapper(this.API,e),i={id:t,methods:{},instance:n.unwrap(),wrapper:n};return this.servers[t]=i,this.callbacks.execute("onServerAdded",i.instance),t}removeServerById(e,t){const r=this.servers[e];r?(this.logger.debug(`removing server ${e}`),Object.keys(r.methods).forEach(t=>{this.removeServerMethod(e,t)}),delete this.servers[e],this.callbacks.execute("onServerRemoved",r.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");if(r.methods[t.id])return;const n=this.createMethodIdentifier(t),i=this,o={identifier:n,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>i.getServersByMethod(n)};o.object_types=o.objectTypes,o.display_name=o.displayName,o.version=o.version,r.methods[t.id]=o;const s=hideMethodSystemFlags(o);return this.methodsCount[n]||(this.methodsCount[n]=0,this.callbacks.execute("onMethodAdded",s)),this.methodsCount[n]=this.methodsCount[n]+1,this.callbacks.execute("onServerMethodAdded",r.instance,s),o}removeServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");const n=r.methods[t];delete r.methods[t];const i=hideMethodSystemFlags(n);this.methodsCount[n.identifier]=this.methodsCount[n.identifier]-1,0===this.methodsCount[n.identifier]&&this.callbacks.execute("onMethodRemoved",i),this.callbacks.execute("onServerMethodRemoved",r.instance,i)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),r=this.getServers().map(e=>e.instance);return this.returnUnsubWithDelayedReplay(t,r,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),r=this.getMethods();return this.returnUnsubWithDelayedReplay(t,r,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let r=!1;const n=this.getServers();return setTimeout(()=>{n.forEach(t=>{const n=t.methods;Object.keys(n).forEach(i=>{r||e(t.instance,n[i])})})},0),()=>{r=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach(e=>{this.removeServerById(e,"reset")}),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",r=e.result_signature??"";return(e.name+t+r).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach(r=>{Object.values(r.methods).forEach(n=>{n.identifier===e&&t.push(r.instance)})}),t}returnUnsubWithDelayedReplay(e,t,r){let n=!1;return setTimeout(()=>{t.forEach(e=>{n||r(e)})},0),()=>{n=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach(([e,r])=>{t[e]=hideMethodSystemFlags(r)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}}class ServerRepository{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter(t=>t.repoId!==e)}getById(e){if("string"==typeof e)return this.methods.find(t=>t.repoId===e)}getList(){return this.methods.map(e=>e)}length(){return this.methods.length}reset(){this.methods=[]}}const SUBSCRIPTION_REQUEST="onSubscriptionRequest",SUBSCRIPTION_ADDED="onSubscriptionAdded",SUBSCRIPTION_REMOVED="onSubscriptionRemoved";class ServerStreaming{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=CallbackRegistryFactory();nextStreamId=0;constructor(e,t,r,n){this.session=e,this.repository=t,this.serverRepository=r,this.logger=n,e.on("add-interest",e=>{this.handleAddInterest(e)}),e.on("remove-interest",e=>{this.handleRemoveInterest(e)})}acceptRequestOnBranch(e,t,r){if("string"!=typeof r&&(r=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const n=this.getStreamId(t,r),i=e.msg.subscription_id,o={id:i,arguments:e.arguments,instance:e.instance,branchKey:r,streamId:n,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[i]=o,this.session.sendFireAndForget({type:"accepted",subscription_id:i,stream_id:n}).catch(e=>{this.logger.warn(`Failed to send accepted message for subscription ${i}: ${JSON.stringify(e)}`)}),this.callbacks.execute(SUBSCRIPTION_ADDED,o,t)}rejectRequest(e,t,r){"string"!=typeof r&&(r=""),this.sendSubscriptionFailed("Subscription rejected by user. "+r,e.msg.subscription_id)}pushData(e,t,r){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof r?r=[r]:(!Array.isArray(r)||r.length<=0)&&(r=[]);const n=e.protocolState.branchKeyToStreamIdMap.filter(e=>!r||0===r.length||r.indexOf(e.key)>=0).map(e=>e.streamId);n.forEach(e=>{const r={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(r).catch(t=>{this.logger.warn(`Failed to send publish message for stream ${e}: ${JSON.stringify(t)}`)})})}pushDataToSingle(e,t,r){if("object"!=typeof r)throw new Error("Invalid arguments. Data must be an object.");const n={type:"post",subscription_id:t.id,data:r};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send post message for subscription ${t.id}: ${JSON.stringify(e)}`)})}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const r={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${t.id}: ${JSON.stringify(e)}`)}),t.instance,this.callbacks.execute(SUBSCRIPTION_REMOVED,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const r=e.protocolState.subscriptionsMap;let n=Object.keys(r).map(e=>r[e]);"string"==typeof t&&(n=n.filter(e=>e.branchKey===t)),n.forEach(e=>{delete r[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t).catch(t=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${e.id}: ${JSON.stringify(t)}`)})})}getSubscriptionList(e,t){if("object"!=typeof e)return[];let r=[];if(!e.protocolState.subscriptionsMap)return[];const n=e.protocolState.subscriptionsMap,i=Object.keys(n).map(e=>n[e]);return r="string"!=typeof t?i:i.filter(e=>e.branchKey===t),r}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,r=Object.keys(t).map(e=>t[e]),n=[];return r.forEach(e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===n.indexOf(t)&&n.push(t)}),n}onSubAdded(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const r=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(SUBSCRIPTION_REMOVED,r,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),r=t?.instance??{},n={msg:e,arguments:e.arguments_kv||{},instance:r},i=this.serverRepository.getById(e.method_id);if(void 0===i){const t="No method with id "+e.method_id+" on this server.";return void this.sendSubscriptionFailed(t,e.subscription_id)}i.protocolState.subscriptionsMap&&i.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(SUBSCRIPTION_REQUEST,n,i)}sendSubscriptionFailed(e,t){const r={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send subscription failed message for subscription ${t}: ${JSON.stringify(e)}`)})}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const r=e.protocolState.branchKeyToStreamIdMap.filter(e=>e.key===t)[0];let n=r?r.streamId:void 0;return"string"==typeof n&&""!==n||(n=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:n})),n}}class ServerProtocol{session;clientRepository;serverRepository;logger;callbacks=CallbackRegistryFactory();streaming;constructor(e,t,r,n){this.session=e,this.clientRepository=t,this.serverRepository=r,this.logger=n,this.streaming=new ServerStreaming(e,t,r,n.subLogger("streaming")),this.session.on("invoke",e=>this.handleInvokeMessage(e))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const r=e.definition,n=Object.assign({},{metadata:r.flags??{}},{streaming:t||!1}),i={type:"register",methods:[{id:e.repoId,name:r.name,display_name:r.displayName,description:r.description,version:r.version,flags:n,object_types:r.objectTypes||r.object_types,input_signature:r.accepts,result_signature:r.returns,restrictions:void 0}]};return this.session.send(i,{methodId:e.repoId}).then(()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)}).catch(t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t})}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,r,n){let i;i=r||""===r?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:r,context:n,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:n,request_id:void 0},this.session.sendFireAndForget(i).catch(r=>{this.logger.warn(`Failed to send method invocation result for method ${e.definition.name} invocation ${t} - ${JSON.stringify(r)}`)})}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,r){this.streaming.pushData(e,t,r)}pushDataToSingle(e,t,r){this.streaming.pushDataToSingle(e,t,r)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,r){this.streaming.acceptRequestOnBranch(e,t,r)}rejectRequest(e,t,r){this.streaming.rejectRequest(e,t,r)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,r=e.caller_id,n=e.method_id,i=e.arguments_kv,o=this.serverRepository.getList().filter(e=>e.repoId===n)[0];if(void 0===o)return;const s=this.clientRepository.getServerById(r)?.instance,a={args:i,instance:s};this.callbacks.execute("onInvoked",o,t,a)}}class UserSubscription{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce((e,t)=>{if(t.subscriptionId){const r=this.repository.getServerById(t.serverId)?.instance;r&&e.push(r)}return e},[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach(t=>{e(t)})}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}}class TimedCache{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=nanoid$3(10);this.cache.push({id:t,element:e});const r=setTimeout(()=>{const e=this.cache.findIndex(e=>e.id===t);e<0||this.cache.splice(e,1)},this.config.ELEMENT_TTL_MS);this.timeoutIds.push(r)}flush(){const e=this.cache.map(e=>e.element);return this.timeoutIds.forEach(e=>clearInterval(e)),this.cache=[],this.timeoutIds=[],e}}const STATUS_AWAITING_ACCEPT="awaitingAccept",STATUS_SUBSCRIBED="subscribed",ERR_MSG_SUB_FAILED="Subscription failed.",ERR_MSG_SUB_REJECTED="Subscription rejected.",ON_CLOSE_MSG_SERVER_INIT="ServerInitiated",ON_CLOSE_MSG_CLIENT_INIT="ClientInitiated";class ClientStreaming{session;repository;logger;subscriptionsList={};timedCache=new TimedCache({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,r,n,i,o){if(0===r.length)return void i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED+" No available servers matched the target params."});const s=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(s,e,t,n,i,t.methodResponseTimeout||1e4,o);"object"==typeof a?r.forEach(r=>{const n=r.server.id,i=r.methods.find(t=>t.name===e.name);if(!i)return void this.logger.error(`can not find method ${e.name} for target ${r.server.id}`);a.trackedServers.push({serverId:n,subscriptionId:void 0});const o={type:"subscribe",server_id:n,method_id:i.gatewayId,arguments_kv:t.arguments};this.session.send(o,{serverId:n,subLocalKey:s}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,r,n,i,o,s){const a={localKey:e,status:STATUS_AWAITING_ACCEPT,method:t,params:r,success:n,error:i,trackedServers:[],handlers:{onData:s?.handlers.onData||[],onClosed:s?.handlers.onClosed||[],onConnected:s?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:s?.subscription};return s||(r.onData&&a.handlers.onData.push(r.onData),r.onClosed&&a.handlers.onClosed.push(r.onClosed),r.onConnected&&a.handlers.onConnected.push(r.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout(()=>{if(void 0===this.subscriptionsList[e])return;const n=this.subscriptionsList[e];n.status===STATUS_AWAITING_ACCEPT?(i({method:t,called_with:r.arguments,message:ERR_MSG_SUB_FAILED+" Subscription attempt timed out after "+o+" ms."}),delete this.subscriptionsList[e]):n.status===STATUS_SUBSCRIBED&&n.trackedServers.length>0&&(n.trackedServers=n.trackedServers.filter(e=>void 0!==e.subscriptionId),delete n.timeoutId,n.trackedServers.length<=0&&(this.callOnClosedHandlers(n),delete this.subscriptionsList[e]))},o),a}handleErrorSubscribing=e=>{const t=e._tag,r=t.subLocalKey,n=this.subscriptionsList[r];if("object"==typeof n&&(n.trackedServers=n.trackedServers.filter(e=>e.serverId!==t.serverId),n.trackedServers.length<=0)){if(clearTimeout(n.timeoutId),n.status===STATUS_AWAITING_ACCEPT){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",r="object"==typeof n.params.arguments?JSON.stringify(n.params.arguments):"{}";n.error({message:ERR_MSG_SUB_REJECTED+t+" Called with:"+r,called_with:n.params.arguments,method:n.method})}else n.status===STATUS_SUBSCRIBED&&this.callOnClosedHandlers(n);delete this.subscriptionsList[r]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=e._tag.serverId,i=r.trackedServers.filter(e=>e.serverId===n)[0];if("object"!=typeof i)return;i.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const o=r.status===STATUS_AWAITING_ACCEPT;if(r.status=STATUS_SUBSCRIBED,o){let e=!1,t=r.subscription;t?(t.setNewSubscription(r),r.success(t),e=!0):(t=new UserSubscription(this.repository,r),r.subscription=t,r.success(t));for(const n of r.handlers.onConnected)try{n(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.filter(t=>t.subscriptionId===e.subscription_id);if(1!==n.length)return;const i=e.oob,o=n[0].serverId,s=this.repository.getServerById(o),a=()=>({data:e.data,server:s?.instance??{},requestArguments:r.params.arguments,message:void 0,private:i}),c=r.handlers.onData,l=r.queued.data;c.length>0?c.forEach(e=>{"function"==typeof e&&e(a())}):l.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.length-1;r.trackedServers=r.trackedServers.filter(t=>t.subscriptionId!==e.subscription_id||(r.queued.closers.push(t.serverId),!1)),r.trackedServers.length===n&&(r.trackedServers.length<=0&&(this.timedCache.add(r),clearTimeout(r.timeoutId),this.callOnClosedHandlers(r),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const r=e.queued.closers.length,n=r>0?e.queued.closers[r-1]:null;let i;void 0!==n&&"string"==typeof n&&(i=this.repository.getServerById(n)?.instance??{}),e.handlers.onClosed.forEach(r=>{"function"==typeof r&&r({message:t||ON_CLOSE_MSG_SERVER_INIT,requestArguments:e.params.arguments||{},server:i,stream:e.method})})}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach(e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:ON_CLOSE_MSG_CLIENT_INIT}).catch(t=>{this.logger.warn(`Error sending unsubscribe for subscription id ${e.subscriptionId}: ${JSON.stringify(t)}`)}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])}),t.trackedServers=[],this.callOnClosedHandlers(t,ON_CLOSE_MSG_CLIENT_INIT),delete this.subscriptionsList[e])}}class ClientProtocol{session;repository;logger;streaming;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("peer-added",e=>this.handlePeerAdded(e)),e.on("peer-removed",e=>this.handlePeerRemoved(e)),e.on("methods-added",e=>this.handleMethodsAddedMessage(e)),e.on("methods-removed",e=>this.handleMethodsRemovedMessage(e)),this.streaming=new ClientStreaming(e,t,r)}subscribe(e,t,r,n,i,o){this.streaming.subscribe(e,t,r,n,i,o)}invoke(e,t,r,n){const i=n.id,o={type:"call",server_id:i,method_id:t.gatewayId,arguments_kv:r};return this.session.send(o,{invocationId:e,serverId:i}).then(e=>this.handleResultMessage(e)).catch(e=>this.handleInvocationError(e))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,r=e.identity,n=!e.meta||e.meta.local,i=Number(r.process),o={machine:r.machine,pid:isNaN(i)?r.process:i,instance:r.instance,application:r.application,applicationName:r.applicationName,environment:r.environment,region:r.region,user:r.user,windowId:r.windowId,peerId:t,api:r.api,isLocal:n};this.repository.addServer(o,t)}handlePeerRemoved(e){const t=e.removed_id,r=e.reason;this.repository.removeServerById(t,r)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach(e=>{this.repository.addServerMethod(t,e)})}handleMethodsRemovedMessage(e){const t=e.server_id,r=e.methods,n=this.repository.getServerById(t);if(n){Object.keys(n.methods).forEach(e=>{const i=n.methods[e];r.indexOf(i.gatewayId)>-1&&this.repository.removeServerMethod(t,e)})}}handleResultMessage(e){const t=e._tag.invocationId,r=e.result,n=e._tag.serverId,i=this.repository.getServerById(n);return{invocationId:t,result:r,instance:i?.instance,status:InvokeStatus.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,r=e._tag.serverId,n=this.repository.getServerById(r),i=e.reason;return{invocationId:t,result:e.context,instance:n?.instance,status:InvokeStatus.Error,message:i}}return{invocationId:"",message:e.message,status:InvokeStatus.Error,error:e}}}function gW3ProtocolFactory(e,t,r,n,i,o){const s=i.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),l=t.domain("agm",["subscribed"]),u=new ServerProtocol(l,r,n,s.subLogger("server")),d=new ClientProtocol(l,r,s.subLogger("client"));return l.onJoined(i=>{r.addServer(e,t.peerId),i?async function(){s.info("reconnected - will replay registered methods and subscriptions"),d.drainSubscriptionsCache().forEach(e=>{const t=e.method,r=Object.assign({},e.params);s.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(r)}`),o.client.subscribe(t,r,void 0,void 0,e).then(()=>s.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>s.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=d.drainSubscriptions();for(const r of t){const t=r.method,n=Object.assign({},r.params);s.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),e.push(o.client.subscribe(t,n,void 0,void 0,r).then(()=>s.info(`subscribing to method ${t.name} DONE`)))}const r=n.getList();n.reset();for(const t of r){const r=t.definition;t.stream?e.push(o.server.createStream(r,t.streamCallbacks,void 0,void 0,t.stream).then(()=>s.info(`subscribing to method ${r.name} DONE`)).catch(()=>s.warn(`subscribing to method ${r.name} FAILED`))):t?.theFunction?.userCallback?e.push(o.register(r,t.theFunction.userCallback).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(o.registerAsync(r,t.theFunction.userCallbackAsync).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`)))}await Promise.all(e),s.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>s.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:d,server:u}),a=void 0)}),l.onLeft(()=>{r.reset()}),l.join(),c}class Interop{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let r;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new InstanceWrapper(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new ClientRepository(e.logger.subLogger("cRep"),this),this.serverRepository=new ServerRepository,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);r=gW3ProtocolFactory(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=r.then(t=>(this.protocol=t,this.client=new Client(this.protocol,this.clientRepository,this.instance,e),this.server=new Server(this.protocol,this.serverRepository),this))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,r,n){return this.client.subscribe(e,t,r,n)}createStream(e,t,r,n){return this.server.createStream(e,t,r,n)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,r,n,i,o){return this.client.invoke(e,t,r,n,i,o)}waitForMethod(e){const t=new PromiseWrapper$1,r=this.client.methodAdded(n=>{n.name===e&&(r(),t.resolve(n))});return t.promise}}const successMessages=["subscribed","success"];class MessageBus{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",successMessages),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()})}ready(){return this.readyPromise}publish=(e,t,r)=>{const{routingKey:n,target:i}=r||{},o=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:n,target_identity:i});this.session.send(o).catch(t=>{this.logger.error(`Failed to publish message to topic ${e} with routing key ${n} for ${JSON.stringify(i)}: ${JSON.stringify(t)}`)})};subscribe=(e,t,r)=>new Promise((n,i)=>{const{routingKey:o,target:s}=r||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:o,source:s});this.session.send(a).then(r=>{const{subscription_id:i}=r;this.subscriptions.push({subscription_id:i,topic:e,callback:t,source:s}),n({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:i,peer_id:this.peerId}).then(()=>{this.subscriptions=this.subscriptions.filter(e=>e.subscription_id!==i)}).catch(e=>{this.logger.warn(`Failed to send unsubscribe request for ${i}: ${JSON.stringify(e)}`)}),Promise.resolve())})}).catch(e=>i(e))});watchOnEvent=()=>{this.session.on("event",e=>{const{data:t,subscription_id:r}=e,n=e["publisher-identity"],i=this.subscriptions.find(e=>e.subscription_id===r);i&&(i.source?this.keysMatch(i.source,n)&&i.callback(t,i.topic,n):i.callback(t,i.topic,n))})};removeEmptyValues(e){const t={};return Object.keys(e).forEach(r=>{void 0!==e[r]&&null!==e[r]&&(t[r]=e[r])}),t}keysMatch(e,t){const r=Object.keys(e);let n=!0;return r.forEach(r=>{e[r]!==t[r]&&(n=!1)}),n}}const IOConnectCoreFactory=(e,t)=>{const r="object"==typeof window?window.iodesktop??window.glue42gd:void 0,n="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),i=timer("glue"),o=prepareConfig(e=e||{},t=t||{},r);let s,a,c,l,u,d,h;const p={};function g(e,t,r){h=c.canPublish("trace"),h&&c.trace(`registering ${e} module`);const n=n=>{if(t.initTime=r.stop(),t.initEndTime=r.endTime,t.marks=r.marks,!h)return;const i=n?`${e} failed - ${n.message}`:`${e} is ready - ${r.endTime-r.startTime}`;c.trace(i)};t.initStartTime=r.startTime,t.ready?t.ready().then(()=>{n()}).catch(e=>{const t="string"==typeof e?new Error(e):e;n(t)}):n(),Array.isArray(e)||(e=[e]),e.forEach(e=>{p[e]=t,IOConnectCoreFactory[e]=t})}function m(){const e=timer("metrics"),t=o.metrics,n=r?.getMetricsPublishingEnabled,i=o.connection.identity,a=n||(()=>!0),u=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return l=metrics({connection:t?s:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:i?.service??r?.applicationName??o.application,instance:i?.instance??i?.windowId??nanoid$3(10),disableAutoAppSystem:u,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",l,e),Promise.resolve()}function f(){const e=timer("interop"),t={connection:s,logger:c.subLogger("interop")};return a=new Interop(t),Logger.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function y(){const e=o.activities&&3===s.protocolVersion;if(o.contexts||e){const e=timer("contexts");u=new ContextsModule({connection:s,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof o.contexts&&o.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof o.contexts&&o.contexts.reAnnounceKnownContexts,subscribeOnGet:"object"!=typeof o.contexts||o.contexts.subscribeOnGet,subscribeOnUpdate:"object"!=typeof o.contexts||o.contexts.subscribeOnUpdate,onlyReAnnounceSubscribedContexts:"object"!=typeof o.contexts||o.contexts.onlyReAnnounceSubscribedContexts}),g("contexts",u,e)}else{const e=s.replayer;e&&e.drain(ContextMessageReplaySpec.name)}return Promise.resolve()}async function $(){if(!o.bus)return Promise.resolve();const e=timer("bus");return d=new MessageBus(s,c.subLogger("bus")),g("bus",d,e),Promise.resolve()}function b(e){try{return e.forEach(e=>{!function(e,t){const r=timer(e),n=t(p);n&&g(e,n,r)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return n.then(function(){const e=timer("logger");return c=new Logger(`${o.connection.identity?.application}`,void 0,o.customLogger),c.consoleLevel(o.logger.console),c.publishLevel(o.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)}).then(function(){const e=timer("connection");s=new Connection(o.connection,c.subLogger("connection"));let t=Promise.resolve(o.auth);return o.connection&&!o.auth&&(r?t=r.getGWToken().then(e=>({gatewayToken:e})):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then(t=>{let r;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return r=t,s.login(r)}).then(()=>(g("connection",s,e),o)).catch(e=>{throw s&&s.logout(),e})}).then(()=>Promise.all([m(),f(),y(),$()])).then(()=>a.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(Utils.isNode()&&"undefined"==="undefined".env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>b(o.libs||[])).then(function(){const e=Object.keys(p).map(e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const n={coreVersion:version$2,version:o.version};i.stop();const h={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:c,interop:a,agm:a,connection:s,metrics:l,contexts:u,bus:d,version:o.version,userConfig:e,done:()=>(c?.info("done called by user..."),s.logout())};if(h.performance={get glueVer(){return o.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=getAllTimers();return Object.keys(e).map(t=>{const r=e[t];return{name:t,duration:r.endTime-r.startTime,marks:r.marks,startTime:r.startTime,endTime:r.endTime}})}},Object.keys(p).forEach(e=>{const t=p[e];h[e]=t}),h.config={},Object.keys(o).forEach(e=>{h.config[e]=o[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{h.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(h),r&&r.updatePerfData&&r.updatePerfData(h.performance),h.agm){const e=(e,t,r)=>function(){return h.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${r}' instead.`),e.apply(h.agm,arguments)},t=h.agm;t.method_added=e(h.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(h.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(h.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(h.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(h.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return h}).catch(e=>Promise.reject({err:e,libs:p}))};"undefined"!=typeof window&&(window.IOConnectCore=IOConnectCoreFactory),IOConnectCoreFactory.version=version$2,IOConnectCoreFactory.default=IOConnectCoreFactory;const PromiseWrap=(e,t,r)=>new Promise((n,i)=>{let o=!0;const s=setTimeout(()=>{if(!o)return;o=!1;i(r||`Promise timeout hit: ${t}`)},t);e().then(e=>{o&&(o=!1,clearTimeout(s),n(e))}).catch(e=>{o&&(o=!1,clearTimeout(s),i(e))})}),PromisePlus=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});var version$1="4.2.4";class GlueController{portsBridge;sessionStorage;_config;_systemGlue;_contextsTrackingGlue;_clientGlue;_systemStream;_workspacesStream;_platformClientWindowId;_systemSettings;constructor(e,t){this.portsBridge=e,this.sessionStorage=t}get logger(){return logger.get("glue.controller")}get workspaces(){return this._clientGlue.workspaces?this._clientGlue.workspaces:ioError.raiseError("Cannot access the Workspaces API")}get isWorkspacesEnabled(){return!!this._clientGlue.workspaces}get me(){return this._clientGlue.interop.instance}get platformVersion(){return version$1}get clientGlue(){return this._clientGlue}get contextsTrackingGlue(){return this._contextsTrackingGlue}get systemGlue(){return this._systemGlue}get platformWindowId(){return this._platformClientWindowId.slice()}async start(e){this._config=e;const t=this.sessionStorage.getSystemSettings();if(!t)return ioError.raiseError("Cannot initiate the glue controller, because the system settings are not defined");this._systemSettings=t,this._systemGlue=await this.initSystemGlue(e.browser),logger.setLogger(this._systemGlue.logger),this.logger?.debug(`system glue initialized successfully with config ${JSON.stringify(e.browser)}`),this._contextsTrackingGlue=await this.setUpCtxTracking(e),this.logger?.debug("glueController started successfully")}async initClientGlue(e,t,r,n){this.logger?.debug(`initializing client glue with config: ${JSON.stringify(e)}, factory: ${t?"custom":"default"}, isWorkspaceFrame: ${r}, platformApi: ${n?"provided":"none"}`);const i=await this.portsBridge.createInternalClient();this.registerClientWindow(r);const o={application:"Platform",gateway:{webPlatform:{port:i,windowId:this.platformWindowId}}},s=Object.assign({},e,o);return this._clientGlue=t?await t(s):await iOConnectBrowserFactory(s),this._clientGlue.webPlatform=n,this.logger?.debug("client glue initialized successfully"),this._clientGlue}async createPlatformSystemMethod(e){await this.createMethodAsync(GlueWebPlatformControlName,e)}async createPlatformSystemStream(){this._systemStream=await this.createStream(GlueWebPlatformStreamName)}async createSystemStream(e){return this.createStream(e)}async createWorkspacesStream(){this._workspacesStream=await this.createStream(GlueWebPlatformWorkspacesStreamName)}async createWorkspacesEventsReceiver(e){await this._systemGlue.interop.register(GlueWorkspacesEventsReceiverName,t=>e(t))}pushSystemMessage(e,t,r){if(!this._systemStream)return ioError.raiseError(`Cannot push data to domain: ${e}, because the system stream is not created`);this._systemStream.push({domain:e,operation:t,data:r})}pushWorkspacesMessage(e){if(!this._workspacesStream)return ioError.raiseError("Cannot push data to domain: workspaces, because the workspaces stream is not created");this._workspacesStream.push({data:e})}async callFrame(e,t,r){const n={operation:e.name,operationArguments:t},i=`Internal Platform->Frame Communication Error. Attempted calling workspace frame: ${r} for operation ${e.name} `;if(e.dataDecoder){const t=e.dataDecoder.run(n.operationArguments);if(!t.ok)return ioError.raiseError(`${i} OutBound validation failed: ${JSON.stringify(t.error)}`)}const o=GlueWorkspaceFrameClientControlName,s=await this.transmitMessage(o,n,i,{windowId:r},{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS});if(e.resultDecoder){const t=e.resultDecoder.run(s);if(!t.ok)return ioError.raiseError(`${i} Result validation failed: ${JSON.stringify(t.error)}`)}return s}async isFrameOperationSupported(e,t){try{return!0===(await this.callFrame({name:"operationCheck",execute:()=>Promise.resolve()},{operation:e},t)).isSupported}catch{return!1}}isValidWindowId(e){if(!e)return!1;return[...this.sessionStorage.getAllWindowsData(),...this.sessionStorage.getAllNonGlue()].some(t=>t.windowId===e)}async sendShutDownSignals(){const e=this.clientGlue.windows.list().filter(e=>e.id!==this.platformWindowId);await Promise.all(e.map(e=>e.close()));const t={domain:"system",operation:"platformShutdown"},r=`Internal Platform-> ${t.domain} Domain Communication Error. Attempted sending shutdown signal to all clients.`,n=this.getLocalServers().filter(t=>e.every(e=>e.id!==t.windowId)).map(e=>({instance:e.instance}));try{await this.transmitMessage(GlueClientControlName,t,r,n,{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS})}catch(e){console.warn("Failed to send shutdown signal to all clients",e)}}shutdown(){this.systemGlue.connection.logout(),this.contextsTrackingGlue?.connection.logout(),this.clientGlue.connection.logout()}async checkClientOperationSupport(e,t,r){try{return await this.callInstance(e,{name:"operationCheck",execute:async()=>{}},{operation:t.name},r)}catch(e){return{isSupported:!1}}}async callInstance(e,t,r,n,i){return this.callClient(e,t,r,n,"instance",i)}async callWindow(e,t,r,n,i){return this.callClient(e,t,r,n,"window",i)}async callClient(e,t,r,n,i="window",o){const s=t.name,a={domain:e,operation:s,data:r},c={...n,isLocal:!0},l=`Internal Platform-> ${e} Domain Communication Error. Attempted calling client ${i}: ${JSON.stringify(c)} for operation ${s}.`;if(t.dataDecoder){const e=t.dataDecoder.run(a.data);if(!e.ok)return ioError.raiseError(`${l} OutBound validation failed: ${JSON.stringify(e.error)}`)}const u=await this.transmitMessage(GlueClientControlName,a,l,c,{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS,...o});if(t.resultDecoder){const e=t.resultDecoder.run(u);if(!e.ok)return ioError.raiseError(`${l} Result validation failed when calling ${i}: ${JSON.stringify(c)} for operation ${s}: ${JSON.stringify(e.error)}`)}return u}setStartContext(e,t,r){return PromisePlus((n,i)=>{let o;const s=waitFor(2,()=>{n(),o()}),a=`___${r}___${e}`;(this._clientGlue.contexts.all().some(e=>e===a)?this.waitContextDestroy(a):Promise.resolve()).then(()=>this._clientGlue.contexts.subscribe(a,s)).then(e=>(o=e,this._systemGlue.contexts.set(a,t))).then(s).catch(i)},1e4,`Timed out waiting to set the ${r} context for: ${e}`)}waitContextDestroy(e){return new Promise((t,r)=>{let n=0;const i=setInterval(()=>{const o=this._clientGlue.contexts.all().some(t=>t===e);if(++n,!o)return clearInterval(i),void t();50===n&&(clearInterval(i),r(`Timed out waiting for context: ${e} to disappear`))},100)})}async clearContext(e,t){const r=`___${t}___${e}`,n=this._systemGlue.contexts.all().some(e=>e===r);n&&await this._systemGlue.contexts.destroy(r)}async preserveAllWorkspaceWindowsContext(e){const t=this.sessionStorage.pickWorkspaceClients(t=>t.workspaceId===e);for(const e of t){const t=await this._systemGlue.contexts.get(`___window___${e.windowId}`);t&&("object"!=typeof t||Object.keys(t).length)&&await this._systemGlue.contexts.set(`___window-hibernation___${e.windowId}`,t)}}async pullHibernatedContext(e){const t=`___window-hibernation___${e}`,r=this._systemGlue.contexts.all().some(e=>e===t);if(!r)return;const n=await this._systemGlue.contexts.get(t);return await this._systemGlue.contexts.destroy(t),n}getServers(){return this._clientGlue.interop.servers()}getLocalServers(){return this.getServers().filter(e=>e.isLocal)}subscribeForServerAdded(e){return this._clientGlue.interop.serverAdded(e)}subscribeForMethodAdded(e){return this._clientGlue.interop.methodAdded(e)}invokeMethod(e,t,r,n,i,o){return this._clientGlue.interop.invoke(e,t,r,n,i,o)}setContext(e,t){return this._systemGlue.contexts.set(e,t)}destroyContext(e){return this._systemGlue.contexts.destroy(e)}getAllContexts(){return this._clientGlue.contexts.all()}switchTransport(e,t){if("contextsTrack"===t)return this._contextsTrackingGlue?this._contextsTrackingGlue.connection.switchTransport(e):Promise.resolve({success:!0});return("system"===t?this._systemGlue:this._clientGlue).connection.switchTransport(e)}onDisconnected(e){return this._systemGlue.connection.disconnected(e)}getSystemGlueTransportName(){return this._systemGlue.connection.transport.name()}async importLayout(e){await this._clientGlue.layouts.import([e],"merge")}async getLayout(e){return await this._clientGlue.layouts.get(e,"Global")}async openWindow(e){this._clientGlue.windows.list().find(t=>t.name===e.name)&&(e.name=`${e.name}-${nanoid$5(7)}`);const t={context:e.context,top:e.bounds?.top,left:e.bounds?.left,width:e.bounds?.width,height:e.bounds?.height,layoutComponentId:e.layoutComponentId};return await this._clientGlue.windows.open(e.name,e.url,t)}async startApp(e){const t={waitForAGMReady:!1,top:e.bounds?.top,left:e.bounds?.left,width:e.bounds?.width,height:e.bounds?.height,layoutComponentId:e.layoutComponentId,channelId:e.channelId};return await this._clientGlue.appManager.application(e.name).start(e.context,t)}async getOrCreateWorkspaceFrame({bounds:e,layoutComponentId:t,frameId:r}){return r?await this.workspaces.getFrame(e=>e.id===r):await this.workspaces.createEmptyFrame({frameConfig:{bounds:e||void 0},layoutComponentId:t||void 0})}getAppNameByInstanceId(e){return this._clientGlue.interop.servers().find(t=>t.instance===e)?.application}getAllWindowNames(){return this._clientGlue.windows.list().map(e=>e.name)}getAllOpenedIds(){return this._clientGlue.windows.list().map(e=>e.id)}getAllOtherNonPlatformWindows(e){return this._clientGlue.windows.list().filter(t=>"Platform"!==t.name&&t.id!==e)}async getAllOpenedFrameIds(){return(await this.workspaces.getAllFrames()).map(e=>e.id)}getAllApplicationNames(){return this._clientGlue.appManager.applications().map(e=>e.name)}getAllApplications(){return this._clientGlue.appManager.applications()}getAllLayoutsSummaries(){return this._clientGlue.layouts.getAll("Global")}getAllWorkspacesSummaries(){return this._clientGlue.layouts.getAll("Workspace")}async getWorkspaceWindowById(e){return this._clientGlue.workspaces?.getWindow(t=>t.id===e)}getWindowById(e){return this._clientGlue.windows.list().find(t=>t.id===e)}async getAllWorkspacesFrames(){return await this.workspaces.getAllFrames()}async getWorkspacesByFrameId(e){return await this.workspaces.getAllWorkspaces(t=>t.frameId===e)}registerProvider(e){return this._clientGlue.search?this._clientGlue.search.registerProvider(e):ioError.raiseError("Cannot start the search provider for Glue42 Core Plus, because the Search API is missing")}async processServerApplicationsData(e){const t=e,r=await this._clientGlue.appManager.inMemory.import(t,"merge");r.errors&&r.errors.length&&r.errors.forEach(e=>{this.logger?.warn(`App: ${e.app} was not imported, because of error: ${e.error}`)})}async initSystemGlue(e){const t=await this.portsBridge.createInternalClient(),r=e?.systemLogger?.level??"warn",n=await IOConnectCoreFactory({application:"Platform-System",gateway:{webPlatform:{port:t}},logger:r,customLogger:e?.systemLogger?.customLogger,identity:{instance:this._systemSettings.systemInstanceId}});return this.logger?.debug("system glue initialized successfully"),n}async setUpCtxTracking(e){if(this._config.connection.preferred)return await this.initContextsTrackingGlue({reAnnounceKnownContexts:!0,trackAllContexts:!0},e)}async initContextsTrackingGlue(e,t){this.logger?.debug(`initializing contexts tracking glue with contexts settings - ${JSON.stringify(e)}`);const r=await this.portsBridge.createInternalClient(),n=await IOConnectCoreFactory({application:"Platform-Contexts-Track",gateway:{webPlatform:{port:r}},logger:t?.browser?.systemLogger?.level??"warn",customLogger:t?.browser?.systemLogger?.customLogger,contexts:e,identity:{instance:this._systemSettings.ctxTrackInstanceId}});return this.logger?.debug("contexts tracking glue initialized successfully"),n}registerClientWindow(e){const t=window.name?window.name:`g42-${nanoid$5(10)}`;if(e){const e=this.sessionStorage.getPlatformFrame();if(this._platformClientWindowId=e?e.windowId:t,!e){const e={windowId:this.platformWindowId,active:!0,isPlatform:!0};this.sessionStorage.saveFrameData(e)}return void(window.name=this.platformWindowId)}const r=this.sessionStorage.getWindowDataByName("Platform");this._platformClientWindowId=r?r.windowId:t,r||this.sessionStorage.saveWindowData({name:"Platform",windowId:this.platformWindowId}),window.name=this.platformWindowId}async createMethodAsync(e,t){await this._systemGlue.interop.registerAsync(e,t)}async createStream(e){return this._systemGlue.interop.createStream(e)}async transmitMessage(e,t,r,n,i){let o;try{if(o=await this._systemGlue.interop.invoke(e,t,n,i),!o)throw new Error(`${r} Received unsupported result from the client - empty result`);if(!Array.isArray(o.all_return_values)||0===o.all_return_values.length)throw new Error(`${r} Received unsupported result from the client - empty values collection`)}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;return ioError.raiseError(`${r} -> Inner message: ${t}`)}return ioError.raiseError(`${r} -> Inner message: ${e.message}`)}return o.all_return_values[0].returned}}class PortsBridge{gateway;sessionStorage;windowsStateController;ioc;registry=CallbackRegistryFactory$2();transactionsController;allPorts={};allClients=[];unLoadStarted=!1;isPreferredActivated=!1;activePreferredTransportConfig;_communicationId;startUpPromise;startupResolve;_genericMessageHandler;_unloaderHandler;connectionConfig;constructor(e,t,r,n){this.gateway=e,this.sessionStorage=t,this.windowsStateController=r,this.ioc=n,this.transactionsController=this.ioc.transactionsController}get logger(){return logger.get("ports.bridge.controller")}shutdown(){window.removeEventListener("message",this._genericMessageHandler),window.removeEventListener("pagehide",this._unloaderHandler),this.registry.clear(),this.allPorts={},this.allClients=[],this.isPreferredActivated=!1,this.unLoadStarted=!1}async configure(e){this.connectionConfig=e.connection,this.startUpPromise=new Promise(e=>{this.startupResolve=e});const t=this.sessionStorage.getSystemSettings();if(!t)return ioError.raiseError("Cannot initiate the platform port bridge, because the system settings are not defined");this._communicationId=t.systemInstanceId,await this.gateway.start(e?.gateway,e?.user),this.setupListeners()}start(){this.startupResolve()}async createInternalClient(){const e=this.ioc.createMessageChannel();return await this.gateway.setupInternalClient(e.port1),e.port2}onClientUnloaded(e){return this.registry.add("client-unloaded",e)}async handleExtConnectionRequest(e,t){const r=e.glue42core;if(!!!r.parentWindowId){const e=r.clientId,t={windowId:e,name:e};await this.ioc.windowsController.processNewWindow(t)}await this.gateway.connectExtClient(t,(e,t)=>{this.removeClient({clientId:e},t)});const n=this.sessionStorage.getWindowDataByName("Platform")?.windowId,i={glue42core:{type:Glue42CoreMessageTypes.connectionAccepted.name,parentWindowId:n,appName:"ext-no-app",clientId:r.clientId,clientType:"child"}};this.allPorts[r.clientId]=t,t.postMessage(i)}setActivePreferredTransportConfig(e){"secondary"!==e.type?delete this.activePreferredTransportConfig:this.activePreferredTransportConfig=e}setPreferredActivated(){this.isPreferredActivated=!0}async switchAllClientsTransport(e){const t=Object.keys(this.allPorts).map(t=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.transportSwitchRequest.name,timeout:defaultClientPortRequestTimeoutMS,clientId:t,args:{switchSettings:e}}));await Promise.all(t)}async checkClientsPreferredLogic(){const e=Object.keys(this.allPorts).map(e=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.checkPreferredLogic.name,timeout:defaultClientPreferredLogicTestTimeoutMS,clientId:e}));try{return await Promise.all(e),{success:!0}}catch(e){return{success:!1}}}async checkClientsPreferredConnection(e){const t=Object.keys(this.allPorts).map(t=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.checkPreferredConnection.name,args:{url:e},timeout:defaultClientPortRequestTimeoutMS,clientId:t}));try{return await Promise.all(t),{success:!0}}catch(e){return{success:!1}}}removeGwClient(e){const t=this.allClients.find(t=>t.bridgeInstanceId===e);t&&(this.allClients=this.allClients.filter(t=>t.bridgeInstanceId!==e),t.client.close(),this.allPorts[t.clientId]&&delete this.allPorts[t.clientId])}unloader(){this.unLoadStarted=!0;for(const e in this.allPorts)this.allPorts[e].postMessage({type:"platformUnload"});this.sessionStorage.handlePlatformUnloadCleanup()}genericMessageHandler(e){if(e.data?.type===FDC3HelloRequestType)return void this.processFDC3WebRequest(e);const t=e.data?.glue42core;t&&!this.unLoadStarted&&(t.type!==Glue42CoreMessageTypes.connectionRequest.name?t.type!==Glue42CoreMessageTypes.platformPing.name?t.type!==Glue42CoreMessageTypes.parentPing.name||this.startUpPromise.then(()=>this.handleParentPing(e.source,e.origin)):this.startUpPromise.then(()=>this.handlePlatformPing(e.source,e.origin)):this.startUpPromise.then(()=>this.handleRemoteConnectionRequest(e.source,e.origin,t.clientId,t.clientType,t.bridgeInstanceId,t.selfAssignedWindowId)))}async handleRemoteConnectionRequest(e,t,r,n,i,o){if(checkIsOriginBlocked(t,this.connectionConfig.blockList)){const r=`Origin '${t}' is blocked by the Platform.`;return this.rejectClientConnection(e,r,t)}const s=this.ioc.createMessageChannel(),a=await this.gateway.connectClient(s.port1);this.setupGwClientPort({client:a,clientId:r,clientPort:s.port1}),this.allClients.push({client:a,bridgeInstanceId:i,clientId:r,source:e});const c=this.sessionStorage.getBridgeInstanceData(i),l=c?.appName,u=this.sessionStorage.getWindowDataByName("Platform")?.windowId,d={glue42core:{type:Glue42CoreMessageTypes.connectionAccepted.name,port:s.port2,connectionProtocolVersion:connectionProtocolVersion,communicationId:this._communicationId,isPreferredActivated:this.isPreferredActivated,parentWindowId:u,appName:l,clientId:r,clientType:n}};o&&await this.ioc.windowsController.registerSelfAssignedWindow({windowId:o,name:o},o),e.postMessage(d,t,[s.port2])}rejectClientConnection(e,t,r){this.logger?.error(t);const n={glue42core:{type:Glue42CoreMessageTypes.connectionRejected.name,error:t}};e.postMessage(n,r)}processFDC3WebRequest(e){const t=this.windowsStateController.getAll().find(t=>t.window===e.source);if(!t)return void this.logger?.warn("[Browser Platform] FDC3 Hello request received from an unknown source, ignoring it.");const r={type:FDC3HelloResponseType,meta:{connectionAttemptUuid:e.data?.meta.connectionAttemptUuid,timestamp:(new Date).toISOString()},payload:{iframeUrl:`${window.fdc3ProxyUrl??FDC3ProxyUrl}?parentId=${t.windowId}`}};e.source.postMessage(r,e.origin)}handleParentPing(e,t){const r={glue42core:{type:Glue42CoreMessageTypes.parentReady.name}};e.postMessage(r,t)}handlePlatformPing(e,t){const r={glue42core:{type:Glue42CoreMessageTypes.platformReady.name}};e.postMessage(r,t)}removeClient(e,t,r){const{clientId:n,ownWindowId:i}=e;this.allPorts[n]&&!r&&delete this.allPorts[n];const o=this.allClients.find(e=>e.clientId===n);if(!o)return void this.logger?.warn(`Received client unload for unknown client: ${n}, ignoring it`);if(this.allClients=this.allClients.filter(e=>e.clientId!==n),o.client.close(),!t)return;const s={windowId:i,win:o.source};this.registry.execute("client-unloaded",s)}setupGwClientPort(e){this.allPorts[e.clientId]&&this.allPorts[e.clientId].onmessage&&(this.allPorts[e.clientId].onmessage=null),this.allPorts[e.clientId]=e.clientPort,e.clientPort.onmessage=t=>{const r=t.data?.glue42core,n=r?.type;if(n!==Glue42CoreMessageTypes.clientUnload.name&&n!==Glue42CoreMessageTypes.gatewayDisconnect.name){if(n===Glue42CoreMessageTypes.transportSwitchResponse.name){return void(r.args.success?this.transactionsController.completeTransaction(r.transactionId):this.transactionsController.failTransaction(r.transactionId,`The client: ${e.clientId} could not connect using the provided transport config.`))}if(n===Glue42CoreMessageTypes.getCurrentTransport.name){const t=r.transactionId;return void e.clientPort.postMessage({type:Glue42CoreMessageTypes.getCurrentTransportResponse.name,args:{transportState:this.getCurrentTransportState()},transactionId:t})}if(n===Glue42CoreMessageTypes.checkPreferredLogicResponse.name)return this.transactionsController.completeTransaction(r.transactionId);if(n===Glue42CoreMessageTypes.checkPreferredConnectionResponse.name){const t=r.args;return t.error?this.transactionsController.failTransaction(r.transactionId,t.error):t.live?this.transactionsController.completeTransaction(r.transactionId):this.transactionsController.failTransaction(r.transactionId,`Client ${e.clientId} could not connect to the preferred WS.`)}this.allClients.every(t=>t.client!==e.client)?this.logger?.trace(`Ignoring a protocol message, because the destination client has been disconnected: ${JSON.stringify(t.data)}`):e.client.send(t.data)}else this.removeClient(r.data,!0,r.type===Glue42CoreMessageTypes.gatewayDisconnect.name)}}getCurrentTransportState(){const e=this.ioc.glueController.getSystemGlueTransportName();return{transportName:e,type:e===webPlatformTransportName?"default":"secondary",transportConfig:e===webPlatformTransportName?void 0:this.activePreferredTransportConfig?.transportConfig}}sendClientPortRequest(e){const t=this.allPorts[e.clientId];if(!t)return ioError.raiseError(`Cannot sent port request: ${e.type} to ${e.clientId}, because there is no such client`);const r=this.transactionsController.createTransaction(e.type,e.timeout||defaultClientPortRequestTimeoutMS),n=e.type,i=e.args;return t.postMessage({type:n,args:i,transactionId:r.id}),r.lock}setupListeners(){this._genericMessageHandler=this.genericMessageHandler.bind(this),window.addEventListener("message",this._genericMessageHandler),this._unloaderHandler=this.unloader.bind(this),window.addEventListener("pagehide",this._unloaderHandler)}}const windowOperationDecoder=oneOf$1(constant$2("openWindow"),constant$2("windowHello"),constant$2("getUrl"),constant$2("getTitle"),constant$2("setTitle"),constant$2("moveResize"),constant$2("focus"),constant$2("close"),constant$2("getBounds"),constant$2("getFrameBounds"),constant$2("registerWorkspaceWindow"),constant$2("unregisterWorkspaceWindow"),constant$2("operationCheck"),constant$2("focusChange"),constant$2("getChannel"),constant$2("setZoomFactor"),constant$2("refresh")),openWindowConfigDecoder=object$3({name:nonEmptyStringDecoder$2,url:nonEmptyStringDecoder$2,options:optional$3(windowOpenSettingsDecoder)});object$3({windowId:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2});const simpleWindowDecoder=object$3({windowId:nonEmptyStringDecoder$2}),windowBoundsResultDecoder=object$3({windowId:nonEmptyStringDecoder$2,bounds:windowBoundsDecoder}),frameWindowBoundsResultDecoder=object$3({bounds:windowBoundsDecoder}),windowUrlResultDecoder=object$3({windowId:nonEmptyStringDecoder$2,url:nonEmptyStringDecoder$2}),windowMoveResizeConfigDecoder=object$3({windowId:nonEmptyStringDecoder$2,top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relative:optional$3(boolean$4())}),windowTitleConfigDecoder=object$3({windowId:nonEmptyStringDecoder$2,title:string$5()}),windowChannelResultDecoder=object$3({channel:optional$3(nonEmptyStringDecoder$2)}),windowZoomFactorConfigDecoder=object$3({windowId:nonEmptyStringDecoder$2,factorIndex:nonNegativeNumberDecoder$2}),workspacesOperationDecoder=oneOf$1(constant$2("isWindowInWorkspace"),constant$2("createWorkspace"),constant$2("createFrame"),constant$2("initFrame"),constant$2("getAllFramesSummaries"),constant$2("getFrameSummary"),constant$2("getAllWorkspacesSummaries"),constant$2("getWorkspaceSnapshot"),constant$2("getAllLayoutsSummaries"),constant$2("openWorkspace"),constant$2("deleteLayout"),constant$2("saveLayout"),constant$2("importLayout"),constant$2("exportAllLayouts"),constant$2("restoreItem"),constant$2("maximizeItem"),constant$2("focusItem"),constant$2("closeItem"),constant$2("closeWorkspace"),constant$2("resizeItem"),constant$2("moveFrame"),constant$2("getFrameSnapshot"),constant$2("forceLoadWindow"),constant$2("ejectWindow"),constant$2("setItemTitle"),constant$2("moveWindowTo"),constant$2("addWindow"),constant$2("addContainer"),constant$2("bundleWorkspace"),constant$2("bundleItem"),constant$2("changeFrameState"),constant$2("getFrameState"),constant$2("getFrameBounds"),constant$2("frameHello"),constant$2("hibernateWorkspace"),constant$2("resumeWorkspace"),constant$2("getWorkspacesConfig"),constant$2("lockWorkspace"),constant$2("lockContainer"),constant$2("lockWindow"),constant$2("pinWorkspace"),constant$2("unpinWorkspace"),constant$2("getWorkspaceIcon"),constant$2("setWorkspaceIcon"),constant$2("checkStarted"),constant$2("getPlatformFrameId"),constant$2("getWorkspaceWindowsOnLayoutSaveContext"),constant$2("getWorkspacesLayouts"),constant$2("setMaximizationBoundary"),constant$2("operationCheck"),constant$2("getWorkspaceWindowFrameBounds"),constant$2("focusChange"),constant$2("bringBackToWorkspace"),constant$2("showChannelsLink")),frameHelloDecoder=object$3({windowId:optional$3(nonEmptyStringDecoder$2)}),workspaceWindowDataDecoder=object$3({name:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,workspaceId:optional$3(nonEmptyStringDecoder$2),appName:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),channelId:optional$3(nonEmptyStringDecoder$2)}),isWindowInSwimlaneResultDecoder=object$3({inWorkspace:boolean$4()}),allParentDecoder=oneOf$1(constant$2("workspace"),constant$2("row"),constant$2("column"),constant$2("group")),subParentDecoder=oneOf$1(constant$2("row"),constant$2("column"),constant$2("group")),frameStateDecoder=oneOf$1(constant$2("maximized"),constant$2("minimized"),constant$2("normal"));object$3({saveLayout:optional$3(boolean$4())});const deleteLayoutConfigDecoder=object$3({name:nonEmptyStringDecoder$2}),swimlaneWindowDefinitionDecoder=object$3({type:optional$3(constant$2("window")),appName:optional$3(nonEmptyStringDecoder$2),windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),strictSwimlaneWindowDefinitionDecoder=object$3({type:constant$2("window"),appName:optional$3(nonEmptyStringDecoder$2),windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),parentDefinitionDecoder=object$3({type:optional$3(subParentDecoder),children:optional$3(lazy$1(()=>array$3(oneOf$1(swimlaneWindowDefinitionDecoder,parentDefinitionDecoder)))),config:optional$3(anyJson$2())}),groupDefinitionConfigDecoder=object$3({minWidth:optional$3(number$5()),maxWidth:optional$3(number$5()),minHeight:optional$3(number$5()),maxHeight:optional$3(number$5()),allowExtract:optional$3(boolean$4()),allowReorder:optional$3(boolean$4()),allowDrop:optional$3(boolean$4()),allowDropHeader:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),showMaximizeButton:optional$3(boolean$4()),showEjectButton:optional$3(boolean$4()),showAddWindowButton:optional$3(boolean$4())}),rowDefinitionConfigDecoder=object$3({minHeight:optional$3(number$5()),maxHeight:optional$3(number$5()),allowDrop:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),isPinned:optional$3(boolean$4()),maximizationBoundary:optional$3(boolean$4())}),columnDefinitionConfigDecoder=object$3({minWidth:optional$3(number$5()),maxWidth:optional$3(number$5()),allowDrop:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),isPinned:optional$3(boolean$4()),maximizationBoundary:optional$3(boolean$4())}),strictColumnDefinitionDecoder=object$3({type:constant$2("column"),children:optional$3(lazy$1(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(columnDefinitionConfigDecoder)}),strictRowDefinitionDecoder=object$3({type:constant$2("row"),children:optional$3(lazy$1(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(rowDefinitionConfigDecoder)}),strictGroupDefinitionDecoder=object$3({type:constant$2("group"),children:optional$3(lazy$1(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(groupDefinitionConfigDecoder)}),strictParentDefinitionDecoder=oneOf$1(strictGroupDefinitionDecoder,strictColumnDefinitionDecoder,strictRowDefinitionDecoder);oneOf$1(string$5().where(e=>"maximized"===e.toLowerCase(),"Expected a case insensitive variation of 'maximized'"),string$5().where(e=>"normal"===e.toLowerCase(),"Expected a case insensitive variation of 'normal'"));const newFrameConfigDecoder=object$3({bounds:optional$3(object$3({left:optional$3(number$5()),top:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2)})),frameId:optional$3(nonEmptyStringDecoder$2)}),loadStrategyDecoder=oneOf$1(constant$2("direct"),constant$2("delayed"),constant$2("lazy")),restoreWorkspaceConfigDecoder=object$3({app:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),loadStrategy:optional$3(loadStrategyDecoder),title:optional$3(nonEmptyStringDecoder$2),reuseWorkspaceId:optional$3(nonEmptyStringDecoder$2),frameId:optional$3(nonEmptyStringDecoder$2),lockdown:optional$3(boolean$4()),activateFrame:optional$3(boolean$4()),newFrame:optional$3(oneOf$1(newFrameConfigDecoder,boolean$4())),noTabHeader:optional$3(boolean$4()),inMemoryLayout:optional$3(boolean$4()),isPinned:optional$3(boolean$4()),icon:optional$3(nonEmptyStringDecoder$2),isSelected:optional$3(boolean$4()),positionIndex:optional$3(nonNegativeNumberDecoder$2)}),openWorkspaceConfigDecoder=object$3({name:nonEmptyStringDecoder$2,restoreOptions:optional$3(restoreWorkspaceConfigDecoder)}),workspaceDefinitionDecoder=object$3({children:optional$3(array$3(oneOf$1(swimlaneWindowDefinitionDecoder,parentDefinitionDecoder))),context:optional$3(anyJson$2()),config:optional$3(object$3({title:optional$3(nonEmptyStringDecoder$2),position:optional$3(nonNegativeNumberDecoder$2),isFocused:optional$3(boolean$4()),loadStrategy:optional$3(loadStrategyDecoder),noTabHeader:optional$3(boolean$4()),allowDrop:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),allowExtract:optional$3(boolean$4()),allowWindowReorder:optional$3(boolean$4()),allowSystemHibernation:optional$3(boolean$4()),showSaveButton:optional$3(boolean$4()),allowWorkspaceTabReorder:optional$3(boolean$4()),allowWorkspaceTabExtract:optional$3(boolean$4()),showCloseButton:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),positionIndex:optional$3(nonNegativeNumberDecoder$2)})),frame:optional$3(object$3({reuseFrameId:optional$3(nonEmptyStringDecoder$2),newFrame:optional$3(oneOf$1(boolean$4(),newFrameConfigDecoder))}))});object$3({type:allParentDecoder,definition:optional$3(oneOf$1(workspaceDefinitionDecoder,parentDefinitionDecoder))});const workspaceCreateConfigDecoder=intersection$1(workspaceDefinitionDecoder,object$3({saveConfig:optional$3(object$3({saveLayout:optional$3(boolean$4())}))})),getFrameSummaryConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2}),frameSummaryDecoder=object$3({id:nonEmptyStringDecoder$2,isFocused:optional$3(boolean$4()),isInitialized:optional$3(boolean$4()),initializationContext:optional$3(object$3({context:optional$3(anyJson$2())}))});object$3({id:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,positionIndex:number$5(),title:nonEmptyStringDecoder$2,focused:boolean$4(),layoutName:optional$3(nonEmptyStringDecoder$2),isSelected:optional$3(boolean$4())}),object$3({type:subParentDecoder,id:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,positionIndex:number$5()});const eventTypeDecoder=oneOf$1(constant$2("frame"),constant$2("workspace"),constant$2("container"),constant$2("window"));object$3({type:eventTypeDecoder,branch:nonEmptyStringDecoder$2}),oneOf$1(constant$2("opened"),constant$2("closing"),constant$2("closed"),constant$2("focus"),constant$2("added"),constant$2("loaded"),constant$2("removed"),constant$2("childrenUpdate"),constant$2("containerChange"),constant$2("maximized"),constant$2("restored"),constant$2("minimized"),constant$2("normal"),constant$2("selected"),constant$2("lock-configuration-changed"),constant$2("hibernated"),constant$2("resumed"));const workspaceConfigResultDecoder=object$3({frameId:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2,positionIndex:nonNegativeNumberDecoder$2,name:nonEmptyStringDecoder$2,layoutName:optional$3(nonEmptyStringDecoder$2),isHibernated:boolean$4(),isSelected:boolean$4(),lastActive:number$5(),allowDrop:optional$3(boolean$4()),allowExtract:optional$3(boolean$4()),allowWindowReorder:optional$3(boolean$4()),allowSystemHibernation:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),showCloseButton:optional$3(boolean$4()),showSaveButton:optional$3(boolean$4()),allowWorkspaceTabReorder:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),showAddWindowButtons:optional$3(boolean$4()),showEjectButtons:optional$3(boolean$4()),showWindowCloseButtons:optional$3(boolean$4()),minWidth:optional$3(number$5()),maxWidth:optional$3(number$5()),minHeight:optional$3(number$5()),maxHeight:optional$3(number$5()),widthInPx:optional$3(number$5()),heightInPx:optional$3(number$5())}),baseChildSnapshotConfigDecoder=object$3({frameId:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,positionIndex:number$5()}),parentSnapshotConfigDecoder=anyJson$2(),swimlaneWindowSnapshotConfigDecoder=intersection$1(baseChildSnapshotConfigDecoder,object$3({windowId:optional$3(nonEmptyStringDecoder$2),isMaximized:optional$3(boolean$4()),isFocused:boolean$4(),isSelected:optional$3(boolean$4()),title:optional$3(string$5()),appName:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),channel:optional$3(nonEmptyStringDecoder$2)})),childSnapshotResultDecoder=object$3({id:optional$3(nonEmptyStringDecoder$2),config:oneOf$1(parentSnapshotConfigDecoder,swimlaneWindowSnapshotConfigDecoder),children:optional$3(lazy$1(()=>array$3(childSnapshotResultDecoder))),type:oneOf$1(constant$2("window"),constant$2("row"),constant$2("column"),constant$2("group"))}),workspaceSnapshotResultDecoder=object$3({id:nonEmptyStringDecoder$2,config:workspaceConfigResultDecoder,children:array$3(childSnapshotResultDecoder),frameSummary:frameSummaryDecoder,context:optional$3(anyJson$2())}),customWorkspaceChildSnapshotDecoder=object$3({id:nonEmptyStringDecoder$2,config:oneOf$1(parentSnapshotConfigDecoder,swimlaneWindowSnapshotConfigDecoder),children:optional$3(lazy$1(()=>array$3(customWorkspaceChildSnapshotDecoder))),type:oneOf$1(constant$2("window"),constant$2("row"),constant$2("column"),constant$2("group"))}),groupLayoutItemDecoder=object$3({type:constant$2("group"),config:anyJson$2(),children:array$3(oneOf$1(windowLayoutItemDecoder))}),columnLayoutItemDecoder=object$3({type:constant$2("column"),config:anyJson$2(),children:array$3(oneOf$1(groupLayoutItemDecoder,windowLayoutItemDecoder,lazy$1(()=>columnLayoutItemDecoder),lazy$1(()=>rowLayoutItemDecoder)))}),rowLayoutItemDecoder=object$3({type:constant$2("row"),config:anyJson$2(),children:array$3(oneOf$1(columnLayoutItemDecoder,groupLayoutItemDecoder,windowLayoutItemDecoder,lazy$1(()=>rowLayoutItemDecoder)))}),workspaceLayoutDecoder=object$3({name:nonEmptyStringDecoder$2,type:constant$2("Workspace"),metadata:optional$3(anyJson$2()),components:array$3(object$3({type:constant$2("Workspace"),application:optional$3(nonEmptyStringDecoder$2),state:object$3({config:anyJson$2(),context:anyJson$2(),children:array$3(oneOf$1(rowLayoutItemDecoder,columnLayoutItemDecoder,groupLayoutItemDecoder,windowLayoutItemDecoder))})}))}),workspacesLayoutImportConfigDecoder=object$3({layout:workspaceLayoutDecoder,mode:oneOf$1(constant$2("replace"),constant$2("merge"))}),exportedLayoutsResultDecoder=object$3({layouts:array$3(workspaceLayoutDecoder)}),frameSummaryResultDecoder=frameSummaryDecoder,frameSummariesResultDecoder=object$3({summaries:array$3(frameSummaryResultDecoder)}),workspaceSummaryResultDecoder=object$3({id:nonEmptyStringDecoder$2,config:workspaceConfigResultDecoder}),workspaceSummariesResultDecoder=object$3({summaries:array$3(workspaceSummaryResultDecoder)}),frameSnapshotResultDecoder=object$3({id:nonEmptyStringDecoder$2,config:anyJson$2(),workspaces:array$3(workspaceSnapshotResultDecoder)}),layoutSummaryDecoder=object$3({name:nonEmptyStringDecoder$2}),layoutSummariesDecoder=object$3({summaries:array$3(layoutSummaryDecoder)}),simpleWindowOperationSuccessResultDecoder=object$3({windowId:nonEmptyStringDecoder$2}),voidResultDecoder=anyJson$2(),frameStateResultDecoder=object$3({state:frameStateDecoder}),frameBoundsDecoder=object$3({top:number$5(),left:number$5(),width:nonNegativeNumberDecoder$2,height:nonNegativeNumberDecoder$2}),frameBoundsResultDecoder=object$3({bounds:frameBoundsDecoder}),resizeConfigDecoder=object$3({width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relative:optional$3(boolean$4())}),moveConfigDecoder=object$3({top:optional$3(number$5()),left:optional$3(number$5()),relative:optional$3(boolean$4())}),simpleItemConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2}),ejectWindowDataDecoder=object$3({itemId:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2)}),frameSnapshotConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2,excludeIds:optional$3(boolean$4())}),frameStateConfigDecoder=object$3({frameId:nonEmptyStringDecoder$2,requestedState:frameStateDecoder}),setItemTitleConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2}),moveWindowConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2,containerId:nonEmptyStringDecoder$2}),resizeItemConfigDecoder=intersection$1(simpleItemConfigDecoder,resizeConfigDecoder),moveFrameConfigDecoder=intersection$1(simpleItemConfigDecoder,moveConfigDecoder);object$3({id:nonEmptyStringDecoder$2,type:subParentDecoder});const addWindowConfigDecoder=object$3({definition:swimlaneWindowDefinitionDecoder,parentId:nonEmptyStringDecoder$2,parentType:allParentDecoder}),addContainerConfigDecoder=object$3({definition:strictParentDefinitionDecoder,parentId:nonEmptyStringDecoder$2,parentType:allParentDecoder}),addItemResultDecoder=object$3({itemId:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2)});object$3({live:boolean$4()});const bundleWorkspaceConfigDecoder=object$3({type:oneOf$1(constant$2("row"),constant$2("column")),workspaceId:nonEmptyStringDecoder$2}),bundleItemConfigDecoder=object$3({type:oneOf$1(constant$2("row"),constant$2("column")),itemId:nonEmptyStringDecoder$2}),workspaceSelectorDecoder=object$3({workspaceId:nonEmptyStringDecoder$2}),containerSummaryResultDecoder=object$3({itemId:nonEmptyStringDecoder$2,config:parentSnapshotConfigDecoder});object$3({frameSummary:frameSummaryDecoder,frameBounds:optional$3(frameBoundsDecoder)}),object$3({workspaceSummary:workspaceSummaryResultDecoder,frameSummary:frameSummaryDecoder,frameBounds:optional$3(frameBoundsDecoder)}),object$3({containerSummary:containerSummaryResultDecoder}),object$3({windowSummary:object$3({itemId:nonEmptyStringDecoder$2,parentId:nonEmptyStringDecoder$2,config:swimlaneWindowSnapshotConfigDecoder})});const workspaceLayoutSaveConfigDecoder=object$3({name:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,saveContext:optional$3(boolean$4())}),lockWorkspaceDecoder=object$3({workspaceId:nonEmptyStringDecoder$2,config:optional$3(object$3({allowDrop:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),allowExtract:optional$3(boolean$4()),allowWindowReorder:optional$3(boolean$4()),allowSystemHibernation:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),showCloseButton:optional$3(boolean$4()),showSaveButton:optional$3(boolean$4()),allowWorkspaceTabReorder:optional$3(boolean$4()),showWindowCloseButtons:optional$3(boolean$4()),showEjectButtons:optional$3(boolean$4()),showAddWindowButtons:optional$3(boolean$4())}))}),lockWindowDecoder=object$3({windowPlacementId:nonEmptyStringDecoder$2,config:optional$3(object$3({allowExtract:optional$3(boolean$4()),allowReorder:optional$3(boolean$4()),showCloseButton:optional$3(boolean$4())}))}),lockRowDecoder=object$3({itemId:nonEmptyStringDecoder$2,type:constant$2("row"),config:optional$3(object$3({allowDrop:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4())}))}),lockColumnDecoder=object$3({itemId:nonEmptyStringDecoder$2,type:constant$2("column"),config:optional$3(object$3({allowDrop:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4())}))}),lockGroupDecoder=object$3({itemId:nonEmptyStringDecoder$2,type:constant$2("group"),config:optional$3(object$3({allowExtract:optional$3(boolean$4()),allowReorder:optional$3(boolean$4()),allowDrop:optional$3(boolean$4()),allowDropHeader:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),showMaximizeButton:optional$3(boolean$4()),showEjectButton:optional$3(boolean$4()),showAddWindowButton:optional$3(boolean$4())}))}),lockContainerDecoder=oneOf$1(lockColumnDecoder,lockGroupDecoder,lockRowDecoder),pinWorkspaceDecoder=object$3({workspaceId:nonEmptyStringDecoder$2,icon:optional$3(nonEmptyStringDecoder$2)}),setWorkspaceIconDecoder=object$3({workspaceId:nonEmptyStringDecoder$2,icon:optional$3(nonEmptyStringDecoder$2)}),workspaceIconDecoder=object$3({icon:optional$3(nonEmptyStringDecoder$2)});object$3({applicationName:optional$3(string$5()),frameConfig:optional$3(newFrameConfigDecoder),context:optional$3(object$3()),layoutComponentId:optional$3(nonEmptyStringDecoder$2)});const restoreWorkspaceDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,restoreOptions:optional$3(restoreWorkspaceConfigDecoder)});object$3({frameId:nonEmptyStringDecoder$2,workspaces:array$3(oneOf$1(workspaceDefinitionDecoder,restoreWorkspaceDefinitionDecoder))});const getWorkspaceWindowsOnLayoutSaveContextConfigDecoder=object$3({layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),layoutName:nonEmptyStringDecoder$2,windowIds:array$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreContexts:optional$3(boolean$4())}),setMaximizationBoundaryConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2,enabled:boolean$4()}),workspaceWindowOnSaveDataDecoder=object$3({windowId:nonEmptyStringDecoder$2,windowContext:optional$3(anyJson$2())}),getWorkspaceWindowsOnLayoutSaveContextResult=object$3({windowsOnSaveData:array$3(workspaceWindowOnSaveDataDecoder)}),getWorkspacesLayoutsConfigDecoder=object$3({frameId:nonEmptyStringDecoder$2,layoutName:nonEmptyStringDecoder$2,layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),context:optional$3(anyJson$2()),ignoreContexts:optional$3(boolean$4())}),getWorkspacesLayoutsResponseDecoder=object$3({workspaces:array$3(workspaceSnapshotResultDecoder)}),showChannelsLinkDecoder=object$3({windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,channelsNames:array$3(nonEmptyStringDecoder$2)}),ZOOM_FACTORS=Object.freeze({0:24,1:33,2:50,3:67,4:75,5:80,6:90,7:100,8:110,9:125,10:150,11:175,12:200,13:250,14:300,15:400,16:500});class WindowsController{glueController;sessionController;stateController;ioc;started=!1;clientResponseTimeoutMs;defaultBounds;explicitClosingWindowIds={};connectionConfig;refreshLocks={};operations={openWindow:{name:"openWindow",execute:this.openWindow.bind(this),dataDecoder:openWindowConfigDecoder},windowHello:{name:"windowHello",execute:this.handleWindowHello.bind(this)},getBounds:{name:"getBounds",dataDecoder:simpleWindowDecoder,resultDecoder:windowBoundsResultDecoder,execute:this.handleGetBounds.bind(this)},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleWindowDecoder,resultDecoder:frameWindowBoundsResultDecoder,execute:this.handleGetBounds.bind(this)},getUrl:{name:"getUrl",dataDecoder:simpleWindowDecoder,resultDecoder:windowUrlResultDecoder,execute:this.handleGetUrl.bind(this)},moveResize:{name:"moveResize",dataDecoder:windowMoveResizeConfigDecoder,execute:this.handleMoveResize.bind(this)},focus:{name:"focus",dataDecoder:simpleWindowDecoder,execute:this.handleFocus.bind(this)},close:{name:"close",dataDecoder:simpleWindowDecoder,execute:this.handleClose.bind(this)},getTitle:{name:"getTitle",dataDecoder:simpleWindowDecoder,resultDecoder:windowTitleConfigDecoder,execute:this.handleGetTitle.bind(this)},setTitle:{name:"setTitle",dataDecoder:windowTitleConfigDecoder,execute:this.handleSetTitle.bind(this)},registerWorkspaceWindow:{name:"registerWorkspaceWindow",dataDecoder:workspaceWindowDataDecoder,execute:this.registerWorkspaceWindow.bind(this)},unregisterWorkspaceWindow:{name:"unregisterWorkspaceWindow",dataDecoder:simpleWindowDecoder,execute:this.handleWorkspaceClientRemoval.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder,execute:this.handleFocusEvent.bind(this)},getChannel:{name:"getChannel",dataDecoder:simpleWindowDecoder,resultDecoder:windowChannelResultDecoder,execute:this.handleGetChannel.bind(this)},setZoomFactor:{name:"setZoomFactor",dataDecoder:windowZoomFactorConfigDecoder,execute:this.handleSetZoomFactor.bind(this)},refresh:{name:"refresh",dataDecoder:simpleWindowDecoder,execute:this.handleRefresh.bind(this)}};constructor(e,t,r,n){this.glueController=e,this.sessionController=t,this.stateController=r,this.ioc=n}get logger(){return logger.get("windows.controller")}get moveResizeOperation(){return this.operations.moveResize}get getFrameBoundsOperation(){return this.operations.getFrameBounds}get setTitleOperation(){return this.operations.setTitle}get getBoundsOperation(){return this.operations.getBounds}handlePlatformShutdown(){this.started=!1}async start(e){this.clientResponseTimeoutMs=e.windows.windowResponseTimeoutMs,this.defaultBounds=e.windows.defaultWindowOpenBounds,this.started=!0,this.connectionConfig=e.connection,this.stateController.onWindowDisappeared(e=>this.cleanUpWindow(e).catch(t=>this.logger?.warn(`error while cleaning up window ${e}: ${t?.message}`)))}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=windowOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This window request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Windows request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Windows request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async getWindowTitle(e,t){return(await this.handleGetTitle({windowId:e},t)).title}async getWindowBounds(e,t){return(await this.handleGetBounds({windowId:e},t)).bounds}async processNewWindow(e,t,r){this.logger?.trace(`processing a new window with id: ${e.windowId} and name: ${e.name}`),this.sessionController.saveWindowData(e),r&&this.stateController.add(r,e.windowId),t&&(this.logger?.trace(`setting the context for window ${e.windowId}`),await this.glueController.setStartContext(e.windowId,t,"window")),this.emitStreamData("windowAdded",e)}async handleWorkspaceClientRemoval(e){this.sessionController.removeEjectedWindowId(e.windowId),await this.cleanUpWindow(e.windowId),this.ioc.portsBridge.removeGwClient(e.windowId)}handleClientUnloaded(e,t){if(this.logger?.trace(`handling unloading of ${e}`),e&&!this.explicitClosingWindowIds[e]){if(!t||t.closed)return this.logger?.trace(`${e} detected as closed, processing window cleanup`),void this.cleanUpWindow(e).catch(t=>this.logger?.warn(`error while cleaning up window ${e}: ${t.message}`));this.logger?.trace(`${e} detected as not closed, adding to state controller`),this.stateController.add(t,e)}}setExplicitClosingWindowId(e){this.explicitClosingWindowIds[e]=!0}async cleanUpWindow(e){this.stateController.remove(e);if(this.sessionController.fullWindowClean(e)){try{await this.glueController.clearContext(e,"window")}catch(t){this.logger?.warn(`error while clearing the context of window ${e}: ${t?.message}`)}this.emitStreamData("windowRemoved",{windowId:e}),delete this.explicitClosingWindowIds[e],await this.waitEventFlush()}}async registerSelfAssignedWindow(e,t){this.logger?.trace(`[${t}] handling workspace window registration with id: ${e.windowId} and name: ${e.name}`),this.sessionController.saveWindowData({windowId:e.windowId,name:e.name,selfAssigned:!0}),this.sessionController.saveNonGlue({windowId:e.windowId}),this.emitStreamData("windowAdded",{windowId:e.windowId,name:e.name}),this.logger?.trace(`[${t}] workspace window registered successfully with id ${e.windowId} and name ${e.name}`)}async registerWorkspaceWindow(e,t){this.logger?.trace(`[${t}] handling workspace window registration with id: ${e.windowId} and name: ${e.name}`),this.sessionController.removeEjectedWindowId(e.windowId),e.channelId&&this.sessionController.addWindowChannel(e.windowId,e.channelId),this.sessionController.saveWindowData({windowId:e.windowId,name:e.name,initialChannelId:e.channelId}),this.sessionController.saveWorkspaceClient({windowId:e.windowId,frameId:e.frameId,initialTitle:e.title,workspaceId:e.workspaceId}),this.sessionController.saveNonGlue({windowId:e.windowId});const r=await this.glueController.pullHibernatedContext(e.windowId),n=e.context||r;n&&await this.glueController.setStartContext(e.windowId,n,"window"),this.emitStreamData("windowAdded",{windowId:e.windowId,name:e.name}),this.logger?.trace(`[${t}] workspace window registered successfully with id ${e.windowId} and name ${e.name}`)}async handleFocusEvent(e,t){this.logger?.trace(`[${t}] handling focus event from window id: ${e.windowId} and hasFocus: ${e.hasFocus}`),this.emitStreamData("focusChange",e),this.logger?.trace(`[${t}] focus event from window id: ${e.windowId} and hasFocus: ${e.hasFocus} handled`)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("windows",e,t)}async openWindow(e,t){if(this.sessionController.getWindowDataByName(e.name))return ioError.raiseError(`Cannot open a window with name: ${e.name}, because a window with that name already exists.`);if(checkIsOriginBlocked(e.url,this.connectionConfig.blockList))return ioError.raiseError(`Cannot open a window with url: ${e.url}, because its origin is blocked by the Platform`);this.logger?.trace(`[${t}] handling open command with a valid name: ${e.name}, url: ${e.url} and options: ${JSON.stringify(e.options)}`);const r=await this.getStartingBounds(e,t),n=e.options?.windowId??`g42-${nanoid$5(10)}`,i={name:e.name,windowId:n,initialBounds:r,initialUrl:e.url,initialContext:e.options?.context,layoutComponentId:e.options?.layoutComponentId},o=`left=${r.left},top=${r.top},width=${r.width},height=${r.height}`;this.logger?.trace(`[${t}] calling native window open with bounds: ${o}`);const s=window.open(e.url,i.windowId,o);return s?(await this.processNewWindow(i,e.options?.context,s),this.logger?.trace(`[${t}] the new window is opened, saved in session, state and announced, responding to the caller`),i):ioError.raiseError(`Cannot open window with url: ${e.url} and name: ${e.name}. The most likely reason is that the user has not approved popups or has a blocker.`)}async handleWindowHello(e,t){if(this.logger?.trace(`[${t}] handling a hello message from a real windowId: ${e.windowId}`),e.windowId){this.stateController.remove(e.windowId),this.sessionController.removeNonGlue({windowId:e.windowId});const r=this.sessionController.getWorkspaceClientById(e.windowId);if(r&&r.initialTitle){const n=e.windowId,i=r.initialTitle;PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setTitle,{windowId:n,title:i},{windowId:n}),this.clientResponseTimeoutMs).catch(e=>this.logger?.trace(`[${t}] error while setting the workspace window title: ${e.message}`))}}const r=!(!e.windowId||!this.sessionController.getFrameData(e.windowId)),n=this.sessionController.getAllWindowsData().map(e=>({windowId:e.windowId,name:e.name}));this.logger?.trace(`[${t}] a full list of all current windows has been compiled, sending it to the caller`);const i=e.windowId?this.refreshLocks[e.windowId]:void 0;return i&&e.windowId&&(i.open(),delete this.refreshLocks[e.windowId]),{windows:n,isWorkspaceFrame:r}}handleGetUrl(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the url of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get url request for window ${e.windowId}`);const r=`Cannot get the url of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getUrl,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}handleGetTitle(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the title of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get title request for window ${e.windowId}`);const r=`Cannot get the title of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getTitle,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleSetTitle(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot set the title of window: ${e.windowId}, because it does not exist for the platform`);this.sessionController.getWorkspaceClientById(e.windowId)&&await this.ioc.workspacesController.setItemTitle({itemId:e.windowId,title:e.title},t),this.logger?.trace(`[${t}] handling a set title request for window ${e.windowId} and title: ${e.title}`);const r=`Cannot set the title of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setTitle,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleMoveResize(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot move resize window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more control`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot move resize window: ${e.windowId}, because it does not exist for the platform`);if("Platform"===r.name)return ioError.raiseError("Move-resizing the main application is not allowed");this.logger?.trace(`[${t}] handling a move resize request for window ${e.windowId} and data: ${JSON.stringify(e)}`);const n=`Cannot move resize window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.moveResize,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,n),await this.pause(500)}handleGetBounds(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot get bounds of window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more info`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the bounds of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get bounds request for window ${e.windowId}`);const r=`Cannot get the bounds of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getBounds,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleFocus(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot focus window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more control`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot focus window: ${e.windowId}, because it is not known by the platform`);this.logger?.trace(`[${t}] handling a focus request for window ${e.windowId}`),window.open(void 0,r.windowId)}async handleClose(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return this.logger?.trace(`[${t}] this window is detected as a workspace window, closing via the workspaces controller`),void await this.ioc.workspacesController.closeItem({itemId:e.windowId},t);if(this.sessionController.getInstanceData(e.windowId))return this.logger?.trace(`[${t}] this window is detected as an application instance, closing via the appManager controller`),void await this.ioc.applicationsController.handleInstanceStop({id:e.windowId},t);const r=this.sessionController.getWindowDataById(e.windowId);return r?"Platform"===r.name?ioError.raiseError("Closing the main application is not allowed"):r.selfAssigned?ioError.raiseError("Closing self-assigned windows (windows not opened by the Glue API) is not allowed"):(this.logger?.trace(`[${t}] handling a close request for window ${e.windowId}`),window.open(void 0,r.windowId)?.close(),await this.cleanUpWindow(r.windowId),void this.logger?.trace(`[${t}] window ${e.windowId} has been closed, removed from session, state and announced`)):ioError.raiseError(`Cannot close window: ${e.windowId}, because it is not known by the platform`)}async getStartingBounds(e,t){const r={top:e.options?.top??this.defaultBounds.top,left:e.options?.left??this.defaultBounds.left,height:e.options?.height??this.defaultBounds.height,width:e.options?.width??this.defaultBounds.width};if(!e.options?.relativeTo)return r;const n=e.options.relativeTo,i=this.sessionController.getWindowDataById(n);if(!i)return r;try{const n=(await this.handleGetBounds({windowId:i.windowId},t)).bounds,o=e.options.relativeDirection??"right";return getRelativeBounds(r,n,o)}catch(e){return r}}pause(e){return new Promise(t=>setTimeout(t,e))}handleGetChannel(e,t){this.logger?.trace(`[${t}] handling a get channel request for window ${e.windowId}`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the channel of window: ${e.windowId}, because it does not exist for the platform`);const r=`Cannot get the channel of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getChannel,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleSetZoomFactor(e,t){this.logger?.trace(`[${t}] handling a set zoom factor request for window ${e.windowId} and factor: ${ZOOM_FACTORS[e.factorIndex]}`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot set the zoom factor of window: ${e.windowId}, because it does not exist for the platform`);const r=`Cannot set the zoom factor of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setZoomFactor,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r),this.emitStreamData("zoomFactorChange",e)}async handleRefresh(e,t){this.logger?.trace(`[${t}] handling a refresh request for window ${e.windowId}`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot refresh window: ${e.windowId}, because it does not exist for the platform`);if("Platform"===r.name)return ioError.raiseError("Refreshing the main application is not allowed");const n=`Cannot refresh window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`,{isSupported:i}=await this.glueController.checkClientOperationSupport("windows",this.operations.refresh,{instance:e.windowId});if(!i)return ioError.raiseError(`[${t}] Cannot handle refresh request, because the target instance does not support the operation`);await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.refresh,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,n);const o=this.createRefreshLock();this.refreshLocks[e.windowId]=o,await o.lock}createRefreshLock(){let e;const t=PromisePlus(t=>{e=t},3e3,"The refresh lock was not opened in time, this is most likely a bug in the platform");if(!e)throw new Error("The open function for the refresh lock was not initialized properly");return{open:e,lock:t}}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}class SessionStorageController{cache={};sessionStorage;windowsNamespace="g42_core_windows";instancesNamespace="g42_core_instances";bridgeInstancesNamespace="g42_core_bridge";nonGlueNamespace="g42_core_nonglue";workspaceWindowsNamespace="g42_core_workspace_clients";workspaceFramesNamespace="g42_core_workspace_frames";workspaceHibernationNamespace="g42_core_workspace_hibernation";globalLayoutsNamespace="g42_core_layouts_global";workspaceLayoutsNamespace="g42_core_layouts_workspace";appDefsNamespace="g42_core_app_definitions";appDefsInmemoryNamespace="g42_core_app_definitions_inmemory";notificationsNamespace="g42_core_notifications";prefsRestSchedulerNamespace="g42_core_prefs_rest_scheduler";layoutsSystemNamespace="g42_core_layouts_system";systemNamespace="g42_system";workspaceFrameCache="g42_workspace_frame_cache";channelsNamespace="g42_core_channels";ejectedWindowIdsNamespace="g42_core_ejected_windows";allNamespaces=[this.bridgeInstancesNamespace,this.windowsNamespace,this.instancesNamespace,this.nonGlueNamespace,this.workspaceWindowsNamespace,this.workspaceFramesNamespace,this.globalLayoutsNamespace,this.workspaceLayoutsNamespace,this.appDefsNamespace,this.workspaceHibernationNamespace,this.appDefsInmemoryNamespace,this.notificationsNamespace,this.prefsRestSchedulerNamespace,this.workspaceFrameCache,this.channelsNamespace,this.ejectedWindowIdsNamespace];get logger(){return logger.get("session.storage")}start(){this.sessionStorage=window.sessionStorage,this.allNamespaces.forEach(e=>{this.getItem(e)||this.setItem(e,JSON.stringify([]))})}shutdown(){this.allNamespaces.forEach(e=>{this.setItem(e,JSON.stringify([]))}),this.removeItem(this.systemNamespace),this.removeItem(this.layoutsSystemNamespace)}getSystemSettings(){const e=this.getItem(this.systemNamespace);if(e)return JSON.parse(e)}setSystemSettings(e){this.setItem(this.systemNamespace,JSON.stringify(e))}getLayoutsSystemData(){const e=this.getItem(this.layoutsSystemNamespace);return e?JSON.parse(e):{}}setLayoutsSystemData(e){this.setItem(this.layoutsSystemNamespace,JSON.stringify(e))}getTimeout(e){const t=this.getNamespaceData(this.workspaceHibernationNamespace);return t.find(t=>t.workspaceId===e)?.timeout}removeTimeout(e){const t=this.getNamespaceData(this.workspaceHibernationNamespace);t.find(t=>t.workspaceId===e)&&this.setItem(this.workspaceHibernationNamespace,JSON.stringify(t.filter(t=>t.workspaceId!==e)))}saveTimeout(e,t){const r=this.getNamespaceData(this.workspaceHibernationNamespace);r.some(t=>t.workspaceId===e)||(r.push({workspaceId:e,timeout:t}),this.setItem(this.workspaceHibernationNamespace,JSON.stringify(r)))}exportClearTimeouts(){const e=this.getNamespaceData(this.workspaceHibernationNamespace);return this.setItem(this.workspaceHibernationNamespace,JSON.stringify([])),e}getAllApps(e){const t="remote"===e?this.appDefsNamespace:this.appDefsInmemoryNamespace;return this.getNamespaceData(t)}overwriteApps(e,t){const r="remote"===t?this.appDefsNamespace:this.appDefsInmemoryNamespace;this.setItem(r,JSON.stringify(e))}removeApp(e,t){const r="remote"===t?this.appDefsNamespace:this.appDefsInmemoryNamespace,n=this.getAllApps(t),i=n.find(t=>t.name===e);return i&&this.setItem(r,JSON.stringify(n.filter(t=>t.name!==e))),i}getLayoutSnapshot(e){const t="Global"===e?this.globalLayoutsNamespace:this.workspaceLayoutsNamespace;return{layouts:this.getNamespaceData(t)}}saveLayoutSnapshot(e,t){const r="Global"===t?this.globalLayoutsNamespace:this.workspaceLayoutsNamespace;this.setItem(r,JSON.stringify(e.layouts))}saveFrameData(e){const t=this.getNamespaceData(this.workspaceFramesNamespace);t.some(t=>t.windowId===e.windowId)||(t.push(e),this.setItem(this.workspaceFramesNamespace,JSON.stringify(t)))}getPlatformFrame(){return this.getAllFrames().find(e=>e.isPlatform)}getAllFrames(){return this.getNamespaceData(this.workspaceFramesNamespace)}getFrameData(e){return this.getAllFrames().find(t=>t.windowId===e)}setFrameActive(e){const t=this.getAllFrames(),r=t.find(t=>t.windowId===e);r&&!r.active&&(r.active=!0,this.setItem(this.workspaceFramesNamespace,JSON.stringify(t)))}removeFrameData(e){return!!e&&this.doRemove(e,this.workspaceFramesNamespace)}saveWorkspaceClient(e){const t=this.getNamespaceData(this.workspaceWindowsNamespace);t.some(t=>t.windowId===e.windowId)||(t.push(e),this.setItem(this.workspaceWindowsNamespace,JSON.stringify(t)))}getWorkspaceClientById(e){return this.getNamespaceData(this.workspaceWindowsNamespace).find(t=>t.windowId===e)}pickWorkspaceClients(e){return this.getNamespaceData(this.workspaceWindowsNamespace).filter(e)}removeWorkspaceClient(e){return!!e&&this.doRemove(e,this.workspaceWindowsNamespace)}getAllNonGlue(){return this.getNamespaceData(this.nonGlueNamespace)}saveNonGlue(e){const t=this.getNamespaceData(this.nonGlueNamespace);return t.some(t=>t.windowId===e.windowId)?(this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`),!1):(this.logger?.trace(`saving non glue window with id: ${e.windowId}`),t.push(e),this.setItem(this.nonGlueNamespace,JSON.stringify(t)),!0)}removeNonGlue(e){return!(!e||!e.windowId)&&(this.logger?.trace(`removing non glue window with id: ${e.windowId}`),this.doRemove(e.windowId,this.nonGlueNamespace))}saveBridgeInstanceData(e){const t=this.getNamespaceData(this.bridgeInstancesNamespace);t.some(t=>t.windowId===e.windowId)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`):(this.logger?.trace(`saving new instance with id: ${e.windowId} and app name: ${e.appName}`),t.push(e),this.setItem(this.bridgeInstancesNamespace,JSON.stringify(t)))}getBridgeInstanceData(e){return this.getNamespaceData(this.bridgeInstancesNamespace).find(t=>t.windowId===e)}removeBridgeInstanceData(e){const t=this.getNamespaceData(this.bridgeInstancesNamespace);this.setItem(this.bridgeInstancesNamespace,JSON.stringify(t.filter(t=>t.windowId!==e)))}saveInstanceData(e){const t=this.getNamespaceData(this.instancesNamespace);t.some(t=>t.id===e.id)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`):(this.logger?.trace(`saving new instance with id: ${e.id} and app name: ${e.applicationName}`),t.push(e),this.setItem(this.instancesNamespace,JSON.stringify(t)))}removeInstance(e){this.logger?.trace(`removing instance with id: ${e}`);const t=this.getAllInstancesData();this.setItem(this.instancesNamespace,JSON.stringify(t.filter(t=>t.id!==e))),this.removeBridgeInstanceData(e)}getInstanceData(e){return this.getAllInstancesData().find(t=>t.id===e)}getAllInstancesData(){return this.getNamespaceData(this.instancesNamespace)}removeNotification(e){const t=this.getNamespaceData(this.notificationsNamespace);t.find(t=>t.id===e)&&this.setItem(this.notificationsNamespace,JSON.stringify(t.filter(t=>t.id!==e)))}saveNewNotification(e){const t=this.getAllNotifications();if(t.some(t=>t.id===e.id))return ioError.raiseError(`Notification with id ${e.id} already exists`);this.logger?.trace(`saving notification with id: ${e.id}`),t.push(e),this.setItem(this.notificationsNamespace,JSON.stringify(t))}updateNotification(e){const t=this.getAllNotifications(),r=t.findIndex(t=>t.id===e.id);if(-1===r)return ioError.raiseError(`Notification with id ${e.id} does not exist`);this.logger?.trace(`updating notification with id: ${e.id}`),t[r]=e,this.setItem(this.notificationsNamespace,JSON.stringify(t))}getNotification(e){return this.getAllNotifications().find(t=>t.id===e)}getAllNotifications(){return this.getNamespaceData(this.notificationsNamespace)}savePrefsRestSchedulerCache(e){const t=this.getAllPrefsRestSchedulerCache();t.some(t=>t.app===e.app)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this app already exists`):(this.logger?.trace(`saving prefs rest scheduler cache for app: ${e.app}`),t.push(e),this.setItem(this.prefsRestSchedulerNamespace,JSON.stringify(t)))}getAllPrefsRestSchedulerCache(){return this.getNamespaceData(this.prefsRestSchedulerNamespace)}clearAllPrefsRestSchedulerCache(){this.setItem(this.prefsRestSchedulerNamespace,JSON.stringify([]))}saveWindowData(e){const t=this.getAllWindowsData();t.some(t=>t.name===e.name)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this name already exists`):(this.logger?.trace(`saving window with id: ${e.windowId} and name: ${e.name}`),t.push(e),this.setItem(this.windowsNamespace,JSON.stringify(t)))}getAllWindowsData(){return this.getNamespaceData(this.windowsNamespace)}getWindowDataById(e){return this.getAllWindowsData().find(t=>t.windowId===e)}getWindowDataByName(e){return this.getAllWindowsData().find(t=>t.name===e)}removeWindowData(e){return!!e&&(this.logger?.trace(`removing window with id: ${e}`),this.doRemove(e,this.windowsNamespace))}fullWindowClean(e){const t=this.removeWindowData(e),r=this.removeNonGlue({windowId:e}),n=this.removeWorkspaceClient(e);return t||r||n}addWindowChannel(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`adding channel data for window with id: ${e}`),r[n].channels=Array.from(new Set([...r[n].channels||[],t])),this.setItem(this.channelsNamespace,JSON.stringify(r))}setChannelsForWindow(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:t}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`adding channels data for window with id: ${e}`),r[n].channels=Array.from(new Set(t)),this.setItem(this.channelsNamespace,JSON.stringify(r))}setAdditionalChannelForWindow(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`add additional channel data for window with id: ${e}`),r[n].channels=Array.from(new Set([...r[n].channels??[],t])),this.setItem(this.channelsNamespace,JSON.stringify(r))}addChannelRestrictionsByWindowId(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry with restrictions`),r.push({windowId:e,restrictions:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`channel data found for window with id: ${e}, updating restrictions`);const i=r[n].restrictions?.some(e=>e.name===t.name);r[n].restrictions=i?[t]:[...r[n].restrictions||[],t],this.setItem(this.channelsNamespace,JSON.stringify(r))}addAllChannelsRestrictionsByWindowId(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry with restrictions`),r.push({windowId:e,restrictions:t}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`channel data found for window with id: ${e}, updating restrictions`),r[n].restrictions=t,this.setItem(this.channelsNamespace,JSON.stringify(r))}addEjectedWindowId(e){const t=this.getNamespaceData(this.ejectedWindowIdsNamespace),r=Array.from(new Set([...t,e]));this.setItem(this.ejectedWindowIdsNamespace,JSON.stringify(r))}removeEjectedWindowId(e){const t=this.getNamespaceData(this.ejectedWindowIdsNamespace).filter(t=>t!==e);this.setItem(this.ejectedWindowIdsNamespace,JSON.stringify(t))}getEjectedWindowIds(){return this.getNamespaceData(this.ejectedWindowIdsNamespace)}getWindowChannelData(e){return this.getNamespaceData(this.channelsNamespace).find(t=>t.windowId===e)}getAllWindowsChannelData(){return this.getNamespaceData(this.channelsNamespace)}removeWindowChannelData(e){return!!e&&this.doRemove(e,this.channelsNamespace)}handlePlatformUnloadCleanup(){const e=this.getNamespaceData(this.workspaceWindowsNamespace);if(!e.length)return;this.getAllWindowsData().forEach(t=>{const r=e.find(e=>e.windowId===t.windowId);if(!r)return;const n=this.getFrameData(r.frameId);n?.isPlatform&&(this.fullWindowClean(t.windowId),this.removeWindowChannelData(t.windowId),this.removeInstance(t.windowId))})}doRemove(e,t){const r=this.getNamespaceData(t).reduce((t,r)=>(r.windowId===e?t.removed=!0:t.newData.push(r),t),{removed:!1,newData:[]});return this.setItem(t,JSON.stringify(r.newData)),r.removed}getNamespaceData(e){const t=this.getItem(e);return t?JSON.parse(t):[]}getItem(e){const t=this.sessionStorage.getItem(e);return t?(this.cache[e]=t,t):(this.doFullRecovery(),this.cache[e])}setItem(e,t){this.cache[e]=t,this.sessionStorage.setItem(e,t)}removeItem(e){delete this.cache[e],this.sessionStorage.removeItem(e)}doFullRecovery(){this.logger?.warn("Session storage is empty or corrupted, performing full recovery from in-memory cache");this.allNamespaces.filter(e=>e!==this.systemNamespace&&e!==this.layoutsSystemNamespace).forEach(e=>{const t=this.cache[e]??JSON.stringify([]);this.setItem(e,t)}),this.setItem(this.systemNamespace,this.cache[this.systemNamespace]??JSON.stringify({})),this.setItem(this.layoutsSystemNamespace,this.cache[this.layoutsSystemNamespace]??JSON.stringify({})),this.logger?.info("Full recovery completed, session storage is now restored from in-memory cache")}}class WindowsStateController{sessionStorage;registry=CallbackRegistryFactory$2();checkIntervalMs=500;childrenToCheck=[];checkerCancelled=!1;currentTimeout;constructor(e){this.sessionStorage=e}get logger(){return logger.get("state.controller")}start(){this.checkerCancelled=!1;const e=this.sessionStorage.getAllNonGlue(),t=this.sessionStorage.pickWorkspaceClients(()=>!0);this.logger?.debug(`starting state controller with ${e.length} non-glue windows and ${t.length} workspace clients from previous session`);e.filter(e=>t.every(t=>t.windowId!==e.windowId)).forEach(e=>{this.logger?.trace(`detected non glue window with id ${e.windowId} from previous session, attempting reference refresh`);const t=window.open(void 0,e.windowId);t&&this.childrenToCheck.push({window:t,windowId:e.windowId})}),this.checkWindows(),this.logger?.debug(`state controller startup completed with ${this.childrenToCheck.length} windows to monitor`)}add(e,t){this.logger?.trace(`adding window id: ${t} to non glue state checking`);this.sessionStorage.saveNonGlue({windowId:t})&&this.childrenToCheck.push({window:e,windowId:t})}getAll(){return this.logger?.trace("getting all non glue windows"),this.childrenToCheck}remove(e){this.logger?.trace(`removing window id: ${e} from non glue state checking`),this.sessionStorage.removeNonGlue({windowId:e}),this.childrenToCheck=this.childrenToCheck.filter(t=>t.windowId!==e)}cancel(){this.logger?.debug("cancelling state controller"),this.currentTimeout&&clearTimeout(this.currentTimeout),this.checkerCancelled=!0,this.registry.clear()}onWindowDisappeared(e){return this.registry.add("window-disappear",e)}checkWindows(){this.checkerCancelled||(this.childrenToCheck.forEach(e=>{if(!e.window||e.window.closed)return this.logger?.trace(`non glue window ${e.windowId} has disappeared, removing from collections and announcing.`),this.remove(e.windowId),void this.registry.execute("window-disappear",e.windowId)}),this.currentTimeout=setTimeout(this.checkWindows.bind(this),this.checkIntervalMs))}}const intentsOperationTypesDecoder=oneOf$1(constant$2("findIntent"),constant$2("getIntents"),constant$2("raise"),constant$2("operationCheck"),constant$2("filterHandlers"),constant$2("getIntentsByHandler")),intentHandlerDecoder=object$3({applicationName:nonEmptyStringDecoder$2,applicationTitle:optional$3(string$5()),applicationDescription:optional$3(string$5()),applicationIcon:optional$3(string$5()),type:oneOf$1(constant$2("app"),constant$2("instance")),displayName:optional$3(string$5()),contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),instanceId:optional$3(string$5()),instanceTitle:optional$3(string$5()),resultType:optional$3(nonEmptyStringDecoder$2),customConfig:optional$3(object$3())}),intentDecoder=object$3({name:nonEmptyStringDecoder$2,handlers:array$3(intentHandlerDecoder)}),intentTargetDecoder=oneOf$1(constant$2("startNew"),constant$2("reuse"),object$3({app:optional$3(nonEmptyStringDecoder$2),instance:optional$3(nonEmptyStringDecoder$2)})),intentContextDecoder=object$3({type:optional$3(nonEmptyStringDecoder$2),data:optional$3(object$3())}),intentsDecoder=array$3(intentDecoder),wrappedIntentsDecoder=object$3({intents:intentsDecoder}),wrappedIntentFilterDecoder=object$3({filter:optional$3(object$3({name:optional$3(nonEmptyStringDecoder$2),contextType:optional$3(nonEmptyStringDecoder$2),resultType:optional$3(nonEmptyStringDecoder$2)}))});object$3({applicationName:nonEmptyStringDecoder$2,applicationIcon:optional$3(string$5()),instanceId:optional$3(string$5())});const applicationStartOptionsDecoder=object$3({top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(windowRelativeDirectionDecoder),waitForAGMReady:optional$3(boolean$4()),channelId:optional$3(nonEmptyStringDecoder$2)}),intentRequestDecoder=object$3({intent:nonEmptyStringDecoder$2,target:optional$3(intentTargetDecoder),context:optional$3(intentContextDecoder),options:optional$3(applicationStartOptionsDecoder),handlers:optional$3(array$3(intentHandlerDecoder)),timeout:optional$3(nonNegativeNumberDecoder$2),waitUserResponseIndefinitely:optional$3(boolean$4()),clearSavedHandler:optional$3(boolean$4())}),resolverConfigDecoder=object$3({enabled:optional$3(boolean$4()),appName:string$5(),waitResponseTimeout:number$5()}),intentResultDecoder=object$3({request:intentRequestDecoder,handler:intentHandlerDecoder,result:anyJson$2()}),resolverResponseDecoder=object$3({intent:nonEmptyStringDecoder$2,handler:intentHandlerDecoder,correlationId:optional$3(string$5()),userSettings:object$3({preserveChoice:optional$3(boolean$4())})}),handlerExclusionCriteriaApplicationNameDecoder=object$3({applicationName:nonEmptyStringDecoder$2}),handlerExclusionCriteriaInstanceIdDecoder=object$3({instanceId:nonEmptyStringDecoder$2}),handlerExclusionCriteriaDecoder=oneOf$1(handlerExclusionCriteriaApplicationNameDecoder,handlerExclusionCriteriaInstanceIdDecoder),handlerFilterDecoder=object$3({title:optional$3(nonEmptyStringDecoder$2),openResolver:optional$3(boolean$4()),timeout:optional$3(nonNegativeNumberDecoder$2),intent:optional$3(nonEmptyStringDecoder$2),contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),resultType:optional$3(nonEmptyStringDecoder$2),applicationNames:optional$3(array$3(nonEmptyStringDecoder$2)),excludeList:optional$3(array$3(handlerExclusionCriteriaDecoder))}),filterHandlersResultDecoder=object$3({handlers:array$3(intentHandlerDecoder)}),embeddedResolverConfigDecoder=object$3({enabled:boolean$4(),initialCaller:object$3({instanceId:nonEmptyStringDecoder$2})}),filterHandlersWithResolverConfigDecoder=object$3({filterHandlersRequest:handlerFilterDecoder,resolverConfig:resolverConfigDecoder,embeddedResolverConfig:optional$3(embeddedResolverConfigDecoder)}),intentInfoDecoder=object$3({intent:nonEmptyStringDecoder$2,contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),description:optional$3(nonEmptyStringDecoder$2),displayName:optional$3(nonEmptyStringDecoder$2),icon:optional$3(nonEmptyStringDecoder$2),resultType:optional$3(nonEmptyStringDecoder$2)}),getIntentsResultDecoder=object$3({intents:array$3(intentInfoDecoder)}),raiseIntentRequestDecoder=object$3({intentRequest:intentRequestDecoder,resolverConfig:resolverConfigDecoder,embeddedResolverConfig:optional$3(embeddedResolverConfigDecoder)}),appManagerOperationTypesDecoder=oneOf$1(constant$2("appHello"),constant$2("applicationStart"),constant$2("instanceStop"),constant$2("registerWorkspaceApp"),constant$2("unregisterWorkspaceApp"),constant$2("export"),constant$2("import"),constant$2("remove"),constant$2("clear"),constant$2("registerRemoteApps"),constant$2("operationCheck")),basicInstanceDataDecoder=object$3({id:nonEmptyStringDecoder$2}),instanceDataDecoder=object$3({id:nonEmptyStringDecoder$2,applicationName:nonEmptyStringDecoder$2}),applicationDataDecoder=object$3({name:nonEmptyStringDecoder$2,type:nonEmptyStringDecoder$2.where(e=>"window"===e,"Expected a value of window"),createOptions:applicationDetailsDecoder,instances:array$3(instanceDataDecoder),userProperties:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),version:optional$3(nonEmptyStringDecoder$2),icon:optional$3(string$5()),caption:optional$3(nonEmptyStringDecoder$2)});object$3({name:nonEmptyStringDecoder$2,type:nonEmptyStringDecoder$2.where(e=>"window"===e,"Expected a value of window"),createOptions:applicationDetailsDecoder,userProperties:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),version:optional$3(nonEmptyStringDecoder$2),icon:optional$3(string$5()),caption:optional$3(nonEmptyStringDecoder$2)});const appHelloSuccessDecoder$1=object$3({apps:array$3(applicationDataDecoder),initialChannelId:optional$3(nonEmptyStringDecoder$2)}),appHelloDecoder=object$3({windowId:optional$3(nonEmptyStringDecoder$2)}),originAppDecoder=object$3({interopInstance:nonEmptyStringDecoder$2,name:optional$3(nonEmptyStringDecoder$2)}),startReasonDecoder=object$3({originApp:originAppDecoder,intentRequest:optional$3(intentRequestDecoder)}),applicationStartConfigDecoder=object$3({name:nonEmptyStringDecoder$2,id:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(oneOf$1(constant$2("top"),constant$2("left"),constant$2("right"),constant$2("bottom"))),waitForAGMReady:optional$3(boolean$4()),forceChromeTab:optional$3(boolean$4()),layoutComponentId:optional$3(nonEmptyStringDecoder$2),channelId:optional$3(nonEmptyStringDecoder$2),startReason:optional$3(startReasonDecoder)}),appsImportOperationDecoder=object$3({definitions:array$3(allApplicationDefinitionsDecoder),mode:oneOf$1(constant$2("replace"),constant$2("merge"))}),appRemoveConfigDecoder=object$3({name:nonEmptyStringDecoder$2}),appsExportOperationDecoder=object$3({definitions:array$3(glueCoreAppDefinitionDecoder)}),appsRemoteRegistrationDecoder=object$3({definitions:array$3(allApplicationDefinitionsDecoder)});class ApplicationsController{glueController;sessionStorage;stateController;appDirectory;managerController;ioc;registry=CallbackRegistryFactory$2();config;connectionConfig;applicationStartTimeoutMs=15e3;managerAppsCheckCount=0;started=!1;defaultBounds;explicitClosingInstanceIds={};isManagerConfigured;locks={};operations={appHello:{name:"appHello",dataDecoder:appHelloDecoder,resultDecoder:appHelloSuccessDecoder$1,execute:this.handleAppHello.bind(this)},applicationStart:{name:"applicationStart",dataDecoder:applicationStartConfigDecoder,resultDecoder:instanceDataDecoder,execute:this.handleApplicationStart.bind(this)},instanceStop:{name:"instanceStop",dataDecoder:basicInstanceDataDecoder,execute:this.handleInstanceStop.bind(this)},registerWorkspaceApp:{name:"registerWorkspaceApp",dataDecoder:workspaceWindowDataDecoder,execute:this.registerWorkspaceApp.bind(this)},unregisterWorkspaceApp:{name:"unregisterWorkspaceApp",dataDecoder:simpleWindowDecoder,execute:this.unregisterWorkspaceApp.bind(this)},import:{name:"import",dataDecoder:appsImportOperationDecoder,execute:this.handleImport.bind(this)},remove:{name:"remove",dataDecoder:appRemoveConfigDecoder,execute:this.handleRemove.bind(this)},export:{name:"export",resultDecoder:appsExportOperationDecoder,execute:this.handleExport.bind(this)},clear:{name:"clear",execute:this.handleClear.bind(this)},registerRemoteApps:{name:"registerRemoteApps",dataDecoder:appsRemoteRegistrationDecoder,execute:this.handleRegisterRemoteApps.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i,o){this.glueController=e,this.sessionStorage=t,this.stateController=r,this.appDirectory=n,this.managerController=i,this.ioc=o}get logger(){return logger.get("applications.controller")}handlePlatformShutdown(){this.managerAppsCheckCount=0,this.locks={},this.started=!1,this.appDirectory.stop()}async start(e){this.defaultBounds=e.windows.defaultWindowOpenBounds,this.logger?.trace("initializing applications"),this.config=e.applications,this.connectionConfig=e.connection,this.isManagerConfigured=!!e.manager?.url,await this.appDirectory.start({config:e.applications,appsStateChange:e=>this.emitStreamData("appDirectoryStateChange",e),sequelizer:this.ioc.createSequelizer(),isManagerConfigured:this.isManagerConfigured}),this.started=!0,this.stateController.onWindowDisappeared(e=>this.processInstanceClosed(e).catch(e=>this.logger?.warn(`error while processing instance closed: ${e?.message}`))),this.logger?.trace("initialization is completed")}async ready(){if(!this.isManagerConfigured)return;const e=this.managerController.getAllApps();await this.confirmApps(e)}async confirmApps(e){const t=this.glueController.clientGlue,r=e.every(e=>{const r=e.appId??e.name;return!!t.appManager.application(r)});return++this.managerAppsCheckCount,r?this.logger?.trace("all manager applications are loaded, proceeding"):this.managerAppsCheckCount>10?ioError.raiseError("not all manager applications are loaded after 10 checks, stopping the process"):(this.logger?.trace("not all manager applications are loaded, waiting for them to be loaded"),await wait(500),this.confirmApps(e))}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=appManagerOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This appManager request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`AppManager request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`AppManager request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(e,t){if(this.logger?.trace(`handling unloading of ${e}`),e&&!this.explicitClosingInstanceIds[e])return!t||t.closed?(this.logger?.trace(`${e} detected as closed, processing instance closed`),void this.processInstanceClosed(e).catch(e=>this.logger?.warn(`error while processing instance closed: ${e.message}`))):void this.logger?.trace(`${e} detected as not closed, skipping instance closed procedure`)}async unregisterWorkspaceApp(e){this.sessionStorage.removeEjectedWindowId(e.windowId),this.ioc.windowsController.setExplicitClosingWindowId(e.windowId),this.explicitClosingInstanceIds[e.windowId]=!0,await this.processInstanceClosed(e.windowId),await this.ioc.windowsController.cleanUpWindow(e.windowId),this.ioc.portsBridge.removeGwClient(e.windowId)}async handleApplicationStart(e,t){this.logger?.trace(`[${t}] handling application start command for application: ${e.name}`);const r=new Date,n=(await this.appDirectory.getAll()).find(t=>t.name===e.name);if(!n)return ioError.raiseError(`Cannot start an instance of application: ${e.name}, because it is not found.`);if(checkIsOriginBlocked(n.createOptions.url,this.connectionConfig.blockList))return ioError.raiseError(`Cannot start an instance of application: ${e.name}, because its origin is blocked by the Platform`);const i={id:e.id??`g42-${nanoid$5(10)}`,applicationName:e.name},o=await this.getStartingBounds(n.createOptions,e,t),s=e.forceChromeTab?void 0:`left=${o.left},top=${o.top},width=${o.width},height=${o.height}`;this.logger?.trace(`[${t}] open arguments are valid, opening to bounds: ${s}`);const a=window.open(n.createOptions.url,i.id,s);if(!a)return ioError.raiseError(`Cannot start an instance with url: ${n.createOptions.url} for application: ${e.name}. The most likely reason is that the user has not approved popups or has a blocker.`);this.sessionStorage.saveBridgeInstanceData({windowId:i.id,appName:i.applicationName});const c={data:i,context:e.context};if(await this.processNewInstance(c),this.logger?.trace(`[${t}] the new window has been opened successfully with id: ${i.id}, checking for AGM ready and notifying windows`),e.waitForAGMReady&&(this.logger?.trace(`[${t}] wait for AGM is set, configuring the lock`),this.setLock(i.id)),await this.notifyWindows(n.createOptions.url,i,o,a,e.context,e.layoutComponentId,e.channelId),e.channelId&&this.sessionStorage.addWindowChannel(i.id,e.channelId),this.locks[i.id])try{await PromiseWrap(()=>this.locks[i.id]?.keyOne,this.applicationStartTimeoutMs)}catch(t){return delete this.locks[i.id],ioError.raiseError(`Application start for ${e.name} timed out waiting for client to initialize Glue`)}this.logger?.trace(`[${t}] the windows controller has been successfully notified`),this.logger?.trace(`[${t}] the new instance with id ${i.id} has been saved, announced and context set, lifting key two and responding to caller`),this.locks[i.id]?.openKeyTwo();const l=this.glueController.getLocalServers().find(({instance:e})=>i.id===e),u={start:r,end:new Date};return this.registry.execute("instance-started",{id:i.id,api:l?.api,applicationName:i.applicationName,startup:u}),i}onInstanceStarted(e){return"function"!=typeof e?ioError.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e)}async processInstanceClosed(e){if(!e)return;const t=this.sessionStorage.getInstanceData(e);if(t){delete this.locks[t.id],this.sessionStorage.removeInstance(t.id);try{await this.glueController.clearContext(e,"instance")}catch(t){this.logger?.warn(`error while clearing the context of instance ${e}: ${t?.message}`)}this.emitStreamData("instanceStopped",t),await this.waitEventFlush(),delete this.explicitClosingInstanceIds[t.id]}}async notifyWindows(e,t,r,n,i,o,s){const a={windowId:t.id,name:`${t.applicationName}_${t.id}`,initialUrl:e,initialContext:i,initialBounds:r,layoutComponentId:o,initialChannelId:s};await this.ioc.windowsController.processNewWindow(a,i,n)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleAppHello(e,t){this.logger?.trace(`[${t}] handling hello message for id: ${e.windowId}`),e.windowId&&this.locks[e.windowId]&&(this.logger?.trace(`[${t}] found an app lock, unlocking key one and waiting for the second one`),this.locks[e.windowId].openKeyOne(),await this.locks[e.windowId].keyTwo,delete this.locks[e.windowId],this.logger?.trace(`[${t}] the lock is lifted, proceeding`));const r=this.sessionStorage.getAllInstancesData(),n=(await this.appDirectory.getAll()).map(e=>{const t=r.filter(t=>t.applicationName===e.name);return{...e,instances:t}});if(e.windowId){this.logger?.trace(`[${t}] there is a valid windowId, removing ${e.windowId} from the state controller`),this.stateController.remove(e.windowId);const r=n.find(t=>t.instances.some(t=>t.id===e.windowId));if(r?.title){const n=e.windowId,i=r.title;PromiseWrap(()=>this.glueController.callWindow("windows",this.ioc.windowsController.setTitleOperation,{windowId:n,title:i},{windowId:n}),2e4).catch(e=>this.logger?.trace(`[${t}] error while setting the application instance title: ${e.message}`))}}if(!e.windowId){this.logger?.trace(`[${t}] no windowId was provided, returning all apps without initialChannelId`);return{apps:n}}const i=this.sessionStorage.getWindowDataById(e.windowId),o=this.sessionStorage.getWindowChannelData(e.windowId),s=o?o.channels?.[0]:i?.initialChannelId,a={apps:n,initialChannelId:s};return this.logger?.trace(`[${t}] compiled a list of all active applications and instances and returning it to the caller with initialChannelId: ${s}`),a}async handleInstanceStop(e,t){this.logger?.trace(`[${t}] handling stop command for instance: ${e.id}`);if(this.sessionStorage.getWorkspaceClientById(e.id))return this.logger?.trace(`[${t}] this instance is detected as a workspace window, closing via the workspaces controller`),void await this.ioc.workspacesController.closeItem({itemId:e.id},t);if(!this.sessionStorage.getInstanceData(e.id))return ioError.raiseError(`Cannot close instance: ${e.id}, because it is not known by the platform`);const r=this.sessionStorage.getWindowDataById(e.id);if(!r)return ioError.raiseError(`Cannot close instance: ${e.id}, because it's window is not known by the platform`);this.ioc.windowsController.setExplicitClosingWindowId(e.id),this.explicitClosingInstanceIds[e.id]=!0,window.open(void 0,r.windowId)?.close(),await this.processInstanceClosed(e.id),await this.ioc.windowsController.cleanUpWindow(e.id),this.logger?.trace(`[${t}] instance ${e.id} has been closed, removed from store, announced stopped and notified windows, responding to caller`)}async handleRegisterRemoteApps(e,t){if(this.logger?.trace(`[${t}] handling remote bypass command`),this.config.remote)return ioError.raiseError(`[${t}] cannot accept remote apps from the protocol, because there is an active remote configuration.`);await this.appDirectory.processAppDefinitions(e.definitions,{mode:"replace",type:"remote"}),this.logger?.trace(`[${t}] remote bypass command completed`)}async handleImport(e,t){this.logger?.trace(`[${t}] handling import command`),await this.appDirectory.processAppDefinitions(e.definitions,{type:"inmemory",mode:e.mode}),this.logger?.trace(`[${t}] import command completed`)}async handleRemove(e,t){this.logger?.trace(`[${t}] handling remove command for ${e.name}`);const r=await this.appDirectory.removeInMemory(e.name);r&&(this.logger?.trace(`definition ${r.name} removed successfully`),this.emitStreamData("appDirectoryStateChange",{appsRemoved:[r],appsAdded:[],appsChanged:[]}))}async handleExport(e,t){this.logger?.trace(`[${t}] handling export command`);const r=await this.appDirectory.exportInMemory();return this.logger?.trace(`[${t}] export command successful`),{definitions:r}}async handleClear(e,t){this.logger?.trace(`[${t}] handling clear command`),await this.appDirectory.processAppDefinitions([],{type:"inmemory",mode:"replace"}),this.logger?.trace(`[${t}] all in-memory apps are cleared`)}setLock(e){const t={},r=new Promise(e=>{t.openKeyOne=e}),n=new Promise(e=>{t.openKeyTwo=e});t.keyOne=r,t.keyTwo=n,this.locks[e]=t}async registerWorkspaceApp(e,t){if(!e.appName)return ioError.raiseError(`Cannot register application with config: ${JSON.stringify(e)}, because no app name was found`);const r=await this.appDirectory.getAll();if(e.appName===defaultNoAppWindowComponentAppName$1)return await this.ioc.windowsController.registerWorkspaceWindow(e,t);if(!r.some(t=>t.name===e.appName))return ioError.raiseError(`Cannot register application with config: ${JSON.stringify(e)}, because no app with this name name was found`);this.sessionStorage.removeEjectedWindowId(e.windowId),e.channelId&&this.sessionStorage.addWindowChannel(e.windowId,e.channelId),this.sessionStorage.saveBridgeInstanceData({windowId:e.windowId,appName:e.appName}),this.logger?.trace(`[${t}] processing valid workspace application registration with id ${e.windowId}, app name ${e.appName} and frame ${e.frameId}`),e.context&&await this.glueController.setStartContext(e.windowId,e.context,"instance");const n={id:e.windowId,applicationName:e.appName};this.sessionStorage.saveInstanceData(n),this.emitStreamData("instanceStarted",n),this.logger?.trace(`[${t}] instance registration is completed and announced, calling windows registration`),await this.ioc.windowsController.registerWorkspaceWindow(e,t)}async processNewInstance(e){e.context&&await this.glueController.setStartContext(e.data.id,e.context,"instance"),this.sessionStorage.saveInstanceData(e.data),this.emitStreamData("instanceStarted",e.data)}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("appManager",e,t)}async getStartingBounds(e,t,r){const n={top:t.top??e.top??this.defaultBounds.top,left:t.left??e.left??this.defaultBounds.left,width:t.width??e.width??this.defaultBounds.width,height:t.height??e.height??this.defaultBounds.height};if(!t.relativeTo)return n;try{const e=await this.ioc.windowsController.getWindowBounds(t.relativeTo,r),i=t.relativeDirection??"right";return getRelativeBounds(n,e,i)}catch(e){return n}}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}const layoutsOperationTypesDecoder=oneOf$1(constant$2("get"),constant$2("getAll"),constant$2("export"),constant$2("import"),constant$2("remove"),constant$2("save"),constant$2("restore"),constant$2("rename"),constant$2("getGlobalPermissionState"),constant$2("checkGlobalActivated"),constant$2("requestGlobalPermission"),constant$2("operationCheck"),constant$2("getDefaultGlobal"),constant$2("setDefaultGlobal"),constant$2("clearDefaultGlobal"),constant$2("updateMetadata"),constant$2("getCurrent")),newLayoutOptionsDecoder=object$3({name:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),metadata:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2)),setAsCurrent:optional$3(boolean$4()),ignoreContexts:optional$3(boolean$4())}),restoreOptionsDecoder=object$3({name:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),closeRunningInstance:optional$3(boolean$4()),closeMe:optional$3(boolean$4()),timeout:optional$3(nonNegativeNumberDecoder$2)}),simpleLayoutConfigDecoder=object$3({name:nonEmptyStringDecoder$2,type:layoutTypeDecoder}),getAllLayoutsConfigDecoder=object$3({type:layoutTypeDecoder}),saveLayoutConfigDecoder=object$3({layout:newLayoutOptionsDecoder}),renameLayoutConfigDecoder=object$3({layout:glueLayoutDecoder,newName:nonEmptyStringDecoder$2}),layoutResultDecoder=object$3({status:nonEmptyStringDecoder$2}),updateLayoutMetadataConfigDecoder=object$3({layout:glueLayoutDecoder}),restoreLayoutConfigDecoder=object$3({layout:restoreOptionsDecoder}),allLayoutsFullConfigDecoder=object$3({layouts:array$3(glueLayoutDecoder)}),importModeDecoder=oneOf$1(constant$2("replace"),constant$2("merge")),layoutsImportConfigDecoder=object$3({layouts:array$3(glueLayoutDecoder),mode:importModeDecoder,skipManagerRequest:optional$3(boolean$4())}),allLayoutsSummariesResultDecoder=object$3({summaries:array$3(layoutSummaryDecoder$1)});object$3({layout:glueLayoutDecoder});const optionalSimpleLayoutResult=object$3({layout:optional$3(glueLayoutDecoder)}),setDefaultGlobalConfigDecoder=object$3({name:nonEmptyStringDecoder$2});object$3({layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),layoutName:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2))}),object$3({windowContext:optional$3(anyJson$2())});const fullSaveRequestResponseDecoder=object$3({bounds:windowBoundsDecoder,windowContext:optional$3(anyJson$2()),url:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2,application:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2,initialContext:optional$3(anyJson$2())});object$3({windowContext:optional$3(anyJson$2()),windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2}),object$3({windows:array$3(fullSaveRequestResponseDecoder)});const permissionStateResultDecoder=object$3({state:oneOf$1(constant$2("prompt"),constant$2("denied"),constant$2("granted"))}),simpleAvailabilityResultDecoder=object$3({isAvailable:boolean$4()}),defaultNoAppWindowComponentAppName="no-app-window",defaultPermissionTimeoutMS=25e3,defaultRestHeaders$1={"Content-Type":"application/json",Accept:"application/json"},defaultRestRequestTimeoutMS$1=3e4,layoutEventOperations={added:"layoutAdded",changed:"layoutChanged",removed:"layoutRemoved",renamed:"layoutRenamed"},getWindowManagementPermissionStatus=async e=>{try{return await navigator.permissions.query({name:"window-management"})}catch(t){e?.warn(extractErrorMsg$1(t));return await navigator.permissions.query({name:"window-placement"})}};class LayoutsController{glueController;globalBuilder;globalRestorer;localStore;managerStore;restStore;sessionStore;registry=CallbackRegistryFactory$2();unsubFuncs=[];started=!1;store;operations={get:{name:"get",dataDecoder:simpleLayoutConfigDecoder,resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetLayout.bind(this)},getAll:{name:"getAll",dataDecoder:getAllLayoutsConfigDecoder,resultDecoder:allLayoutsSummariesResultDecoder,execute:this.handleGetAll.bind(this)},getCurrent:{name:"getCurrent",resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetCurrentLayout.bind(this)},export:{name:"export",dataDecoder:getAllLayoutsConfigDecoder,resultDecoder:allLayoutsFullConfigDecoder,execute:this.handleExport.bind(this)},import:{name:"import",dataDecoder:layoutsImportConfigDecoder,execute:this.handleImport.bind(this)},remove:{name:"remove",dataDecoder:simpleLayoutConfigDecoder,execute:this.handleRemove.bind(this)},rename:{name:"rename",dataDecoder:renameLayoutConfigDecoder,resultDecoder:layoutResultDecoder,execute:this.handleRename.bind(this)},save:{name:"save",dataDecoder:saveLayoutConfigDecoder,execute:this.handleSave.bind(this)},restore:{name:"restore",dataDecoder:restoreLayoutConfigDecoder,execute:this.handleRestore.bind(this)},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:permissionStateResultDecoder,execute:this.handleGetGlobalPermissionState.bind(this)},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:simpleAvailabilityResultDecoder,execute:this.handleRequestGlobalPermission.bind(this)},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:simpleAvailabilityResultDecoder,execute:this.handleCheckGlobalActivated.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetDefaultGlobal.bind(this)},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:setDefaultGlobalConfigDecoder,execute:this.handleSetDefaultGlobal.bind(this)},clearDefaultGlobal:{name:"clearDefaultGlobal",execute:this.handleClearDefaultGlobal.bind(this)},updateMetadata:{name:"updateMetadata",dataDecoder:updateLayoutMetadataConfigDecoder,execute:this.handleUpdateMetadata.bind(this)}};constructor(e,t,r,n,i,o,s){this.glueController=e,this.globalBuilder=t,this.globalRestorer=r,this.localStore=n,this.managerStore=i,this.restStore=o,this.sessionStore=s}get logger(){return logger.get("layouts.controller")}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.store.stop()}async start(e){this.store=this.getStore(e),this.setupStoreListeners(),await this.store.start(e),this.started=!0,this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=layoutsOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This layouts request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Layouts request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r,e.callerId,e.callerType),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Layouts request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleSave(e,t){this.logger?.trace(`[${t}] handling save layout with config: ${JSON.stringify(e)}`),await this.checkRequestPermission("save"),this.logger?.trace(`[${t}] the required permissions are granted, proceeding.`);const r=await this.globalBuilder.saveGlobalLayout(e,t);return(e.layout.setAsCurrent??!0)&&this.sessionStore.setLayoutsSystemData({currentLayoutName:r.name}),this.logger?.trace(`[${t}] layout ${e.layout.name} was saved successfully`),{layout:r}}async handleRestore(e,t,r,n){this.logger?.trace(`[${t}] handling restore layout with config: ${JSON.stringify(e)}`),await this.checkRequestPermission("restore",e.layout.timeout);const i=new Date,o=await this.get("Global",e.layout.name,t);if(!o)return ioError.raiseError(`Layout with name "${e.layout.name}" and type: "Global" cannot be found`);await this.globalRestorer.restoreGlobalLayout(e,t,r,n);const s=new Date;this.registry.execute("layout-restored",{layoutName:e.layout.name,startTime:i,endTime:s}),await this.emitData({operation:"layoutRestored",layout:o}),this.logger?.trace(`[${t}] layout ${e.layout.name} was restored successfully`)}onLayoutRestored(e){return"function"!=typeof e?ioError.raiseError("onLayoutRestored requires a single argument of type function"):this.registry.add("layout-restored",e)}async handleGetAll(e,t){this.logger?.trace(`[${t}] handling get all layout summaries request for type: ${e.type}`);const r=(await this.store.getAllLayouts(e.type,t)).map(e=>({name:e.name,type:e.type,context:e.context,metadata:e.metadata}));return this.logger?.trace(`[${t}] all summaries have been compiled, responding to caller`),{summaries:r}}async handleGetCurrentLayout(e,t){this.logger?.trace(`[${t}] handling get current layout request`);const{currentLayoutName:r}=this.sessionStore.getLayoutsSystemData(),n=r?await this.get("Global",r,t):void 0;return this.logger?.trace(`[${t}] request completed, responding to the caller with layout with name: ${r}`),{layout:n}}async handleExport(e,t){this.logger?.trace(`[${t}] handling get all layout full request for type: ${e.type}`);const r=await this.store.getAllLayouts(e.type,t);return this.logger?.trace(`[${t}] full layouts collection have been compiled, responding to caller`),{layouts:r}}async handleImport(e,t){this.logger?.trace(`[${t}] handling mass import request for layout names: ${e.layouts.map(e=>e.name).join(", ")}`);const r=e.layouts.filter(e=>"Workspace"===e.type),n=e.layouts.filter(e=>"Global"===e.type).map(e=>({...e,token:e.token??generateLayoutToken()}));await this.store.saveLayouts(r,n,e.mode,t),this.logger?.trace(`[${t}] mass import completed, responding to caller`)}async handleRemove(e,t){this.logger?.trace(`[${t}] handling remove request for ${JSON.stringify(e)}`);const r=await this.get(e.type,e.name,t);r?(await this.store.deleteLayout(r,t),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed`)):this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" cannot be found and therefore cannot be removed`)}async handleRename(e,t){this.logger?.trace(`[${t}] handling rename request for ${JSON.stringify(e)}`);const r=e.layout.name;if(e.newName===r)return this.logger?.trace(`[${t}] The provided new layout name ${e.newName} is the same as the current one.`),{status:"Success"};const n=await this.get(e.layout.type,r,t);if(!n){const n=`layout with name "${r}" and type: "${e.layout.type}" cannot be found`;return this.logger?.trace(`[${t}] ${n}`),{status:n}}return await this.store.renameLayout(n,e.newName,t)}async handleUpdateMetadata(e,t){this.logger?.trace(`[${t}] handling update metadata request for ${JSON.stringify(e)}`);const r=await this.get(e.layout.type,e.layout.name,t);if(!r)return ioError.raiseError(`Layout with name "${e.layout.name}" and type: "${e.layout.type}" cannot be found`);const n={...r,metadata:e.layout.metadata};return"Global"===r.type?await this.store.saveLayouts([],[n],"merge",t):await this.store.saveLayouts([n],[],"merge",t)}async handleGetLayout(e,t){this.logger?.trace(`[${t}] handling get layout request for name: ${e.name} and type: ${e.type}`);const r=(await this.store.getAllLayouts(e.type,t)).find(t=>t.name===e.name);return this.logger?.trace(`[${t}] request completed, responding to the caller`),{layout:r}}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleGetGlobalPermissionState(e,t){this.logger?.trace(`[${t}] handling Get Global Permission State request`);const{state:r}=await getWindowManagementPermissionStatus(this.logger);return this.logger?.trace(`[${t}] request completed with state: ${r}, responding to the caller`),{state:r}}async handleRequestGlobalPermission(e,t){this.logger?.trace(`[${t}] handling Request Global Permission command`);const{state:r}=await getWindowManagementPermissionStatus(this.logger);if("granted"===r)return{isAvailable:!0};if("denied"===r)return{isAvailable:!1};try{return await window.getScreenDetails(),this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!0}}catch(e){return this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!1}}}async handleCheckGlobalActivated(e,t){return this.logger?.trace(`[${t}] handling Check Global Activated request`),this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!0}}async handleGetDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Get Default Global request`);return{layout:await this.store.getDefaultLayout(t)}}async handleSetDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Set Default Global request for name: ${e.name}`);const r=(await this.store.getAllLayouts("Global",t)).find(t=>t.name===e.name);if(!r)return ioError.raiseError(`Layout ${e.name} does not exist`);await this.store.setDefaultLayout(e.name,t),await this.emitData({operation:"defaultLayoutChanged",layout:{name:r.name}})}async handleClearDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Clear Default Global request`),await this.store.clearDefaultLayout(t),await this.emitData({operation:"defaultLayoutChanged"}),this.logger?.trace(`[${t}] request completed, responding to the caller`)}updateCurrentLayoutIfNeeded(e){if("Global"!==e.layout.type)return;const t=this.sessionStore.getLayoutsSystemData(),r=e.operation===layoutEventOperations.renamed&&t.currentLayoutName===e.layout.prevName,n=e.operation===layoutEventOperations.removed&&t.currentLayoutName===e.layout.name;(r||n)&&(r&&(t.currentLayoutName=e.layout.name),n&&(t.currentLayoutName=void 0),this.sessionStore.setLayoutsSystemData(t))}async emitData(e){this.logger?.trace(`sending notification of event: ${e.operation} with data: ${JSON.stringify(e)}`),this.glueController.pushSystemMessage("layouts",e.operation,e.layout)}async announceEvents(e){let t=0;for(const r of e)++t,t%10==0&&await this.waitEventFlush(),await this.emitData(r)}async get(e,t,r){return(await this.store.getAllLayouts(e,r)).find(r=>r.name===t&&r.type===e)}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}async checkRequestPermission(e,t=defaultPermissionTimeoutMS){if(window.gtf)return;const{state:r}=await getWindowManagementPermissionStatus(this.logger);switch(r){case"granted":return;case"prompt":try{return void await PromiseWrap(()=>window.getScreenDetails(),t,"Timeout waiting for user permission for Multi-Screen Window Placement")}catch(t){return ioError.raiseError(`Cannot complete operation ${e} for Global Layouts, because the user has not granted the Multi-Screen Window Placement permission`)}case"denied":return ioError.raiseError(`Cannot complete operation ${e} for Global Layouts, because the user has denied the Multi-Screen Window Placement permission`)}}setupStoreListeners(){const e=this.store.onLayoutsAdded(e=>{this.announceEvents(e.map(e=>({operation:layoutEventOperations.added,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),t=this.store.onLayoutsChanged(e=>{this.announceEvents(e.map(e=>({operation:layoutEventOperations.changed,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),r=this.store.onLayoutsRemoved(e=>{const t=layoutEventOperations.removed;this.announceEvents(e.map(e=>({operation:t,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e))),e.forEach(e=>this.updateCurrentLayoutIfNeeded({operation:t,layout:e}))}),n=this.store.onLayoutsRenamed(e=>{const t=layoutEventOperations.renamed;this.announceEvents(e.map(e=>({operation:t,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e))),e.forEach(e=>this.updateCurrentLayoutIfNeeded({operation:t,layout:e}))});this.unsubFuncs.push(e,t,r,n)}getStore(e){const t=e.layouts?.mode,r=!(!e?.manager?.url||!e?.manager?.features?.layoutsStore),n=!!e?.layouts?.rest?.url;return!t&&r?this.managerStore:!t&&n?this.restStore:t||r?"idb"===t||"session"===t?(this.checkForConflictingLocalSettings(n),this.localStore):"rest"===t&&n?this.restStore:"rest"!==t||n?"manager"===t&&r?this.managerStore:"manager"!==t||r?ioError.raiseError("Cannot set layouts store."):ioError.raiseError("The layouts store is configured to be managed, but the manager is not configured."):ioError.raiseError("The layouts store is configured to be rest, but the rest url is not configured."):this.localStore}checkForConflictingLocalSettings(e){if(e)return ioError.raiseError("Layouts store is configured to be local, but the rest url is also configured. Please either remove de-config rest or set the layouts store to be rest.")}}const instanceOfAny=(e,t)=>t.some(t=>e instanceof t);let idbProxyableTypes,cursorAdvanceMethods;function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const cursorRequestMap=new WeakMap,transactionDoneMap=new WeakMap,transactionStoreNamesMap=new WeakMap,transformCache=new WeakMap,reverseTransformCache=new WeakMap;function promisifyRequest(e){const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(wrap(e.result)),n()},o=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",o)});return t.then(t=>{t instanceof IDBCursor&&cursorRequestMap.set(t,e)}).catch(()=>{}),reverseTransformCache.set(t,e),t}function cacheDonePromiseForTransaction(e){if(transactionDoneMap.has(e))return;const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),n()},o=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});transactionDoneMap.set(e,t)}let idbProxyTraps={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return transactionDoneMap.get(e);if("objectStoreNames"===t)return e.objectStoreNames||transactionStoreNamesMap.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return wrap(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function replaceTraps(e){idbProxyTraps=e(idbProxyTraps)}function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?getCursorAdvanceMethods().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(cursorRequestMap.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...r){const n=e.call(unwrap(this),t,...r);return transactionStoreNamesMap.set(n,t.sort?t.sort():[t]),wrap(n)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&cacheDonePromiseForTransaction(e),instanceOfAny(e,getIdbProxyableTypes())?new Proxy(e,idbProxyTraps):e)}function wrap(e){if(e instanceof IDBRequest)return promisifyRequest(e);if(transformCache.has(e))return transformCache.get(e);const t=transformCachableValue(e);return t!==e&&(transformCache.set(e,t),reverseTransformCache.set(t,e)),t}const unwrap=e=>reverseTransformCache.get(e);function openDB(e,t,{blocked:r,upgrade:n,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=wrap(s);return n&&s.addEventListener("upgradeneeded",e=>{n(wrap(s.result),e.oldVersion,e.newVersion,wrap(s.transaction),e)}),r&&s.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}function deleteDB(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),wrap(r).then(()=>{})}const readMethods=["get","getKey","getAll","getAllKeys","count"],writeMethods=["put","add","delete","clear"],cachedMethods=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(cachedMethods.get(t))return cachedMethods.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,i=writeMethods.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!readMethods.includes(r))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return n&&(s=s.index(t.shift())),(await Promise.all([s[r](...t),i&&o.done]))[0]};return cachedMethods.set(t,o),o}replaceTraps(e=>({...e,get:(t,r,n)=>getMethod(t,r)||e.get(t,r,n),has:(t,r)=>!!getMethod(t,r)||e.has(t,r)}));class IDBController{_database;defaultDBName="glue42core";dbName=this.defaultDBName;dbVersion=3;globalLayoutsObjectStoreName="globalLayouts";prefsObjectStoreName="prefs";serviceWorkerObjectStoreName="serviceWorker";workspaceLayoutsObjectStoreName="workspaceLayouts";constructor(){"indexedDB"in window||ioError.raiseError("Cannot initialize the local storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open database")}async start(e){e?.id&&(this.dbName=e?.id);const t=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=t}stop(){this.database.close(),delete this._database,this.dbName=this.defaultDBName}getAllLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.getAll(t)}deleteLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.delete(r,e)}clearLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.clear(t)}getLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.get(r,e)}storeLayout(e){runDecoderWithIOError(glueLayoutDecoder,e);const t=this.getLayoutsObjectStoreName(e.type);return this.database.put(t,e,e.name)}async renameLayout(e,t){runDecoderWithIOError(glueLayoutDecoder,e);const r=this.getLayoutsObjectStoreName(e.type),n=this.database.transaction(r,"readwrite");return await Promise.all([n.store.delete(t),n.store.put(e,e.name),n.done]),e}getLayoutsObjectStoreName(e){switch(e){case"Workspace":return this.workspaceLayoutsObjectStoreName;case"Global":return this.globalLayoutsObjectStoreName;default:return ioError.raiseError(`The provided layout type is not recognized: ${e}`)}}clearServiceWorker(){return this.database.clear(this.serviceWorkerObjectStoreName)}storeServiceWorker(e){return this.database.put(this.serviceWorkerObjectStoreName,e,"workerData")}async clearAllPrefs(e){const t=(await this.getAllPrefs()).map(({app:t})=>({app:t,data:{},lastUpdate:e})),r=this.database.transaction(this.prefsObjectStoreName,"readwrite");return await Promise.all([...t.map(e=>r.store.put(e,e.app)),r.done]),t}getAllPrefs(){return this.database.getAll(this.prefsObjectStoreName)}getPrefs(e){return this.database.get(this.prefsObjectStoreName,e)}deletePrefs(e){return this.database.delete(this.prefsObjectStoreName,e)}async replaceAllPrefs(e){const t=this.database.transaction(this.prefsObjectStoreName,"readwrite");return await t.store.clear(),await Promise.all([...e.map(e=>t.store.put(e,e.app)),t.done]),e}async setPrefs(e){return await this.database.put(this.prefsObjectStoreName,e,e.app),e}async updatePrefs(e){const t=await this.database.get(this.prefsObjectStoreName,e.app),r=t?{app:e.app,data:{...t.data,...e.data},lastUpdate:e.lastUpdate}:e;return this.setPrefs(r)}setUpDB(e){e.objectStoreNames.contains(this.workspaceLayoutsObjectStoreName)||e.createObjectStore(this.workspaceLayoutsObjectStoreName),e.objectStoreNames.contains(this.globalLayoutsObjectStoreName)||e.createObjectStore(this.globalLayoutsObjectStoreName),e.objectStoreNames.contains(this.serviceWorkerObjectStoreName)||e.createObjectStore(this.serviceWorkerObjectStoreName),e.objectStoreNames.contains(this.prefsObjectStoreName)||e.createObjectStore(this.prefsObjectStoreName)}}const defaultLoadingConfig={defaultStrategy:"direct",delayed:{batch:1,initialOffsetInterval:1e3,interval:5e3},showDelayedIndicator:!1};class WorkspacesController{framesController;glueController;stateController;hibernationWatcher;sequelizer;sessionStorageController;ioc;registry=CallbackRegistryFactory$2();_started=!1;settings;defaultWindowOpenBounds;connectionConfig;operations={frameHello:{name:"frameHello",dataDecoder:frameHelloDecoder,execute:this.handleFrameHello.bind(this)},isWindowInWorkspace:{name:"isWindowInWorkspace",dataDecoder:simpleItemConfigDecoder,resultDecoder:isWindowInSwimlaneResultDecoder,execute:this.isWindowInWorkspace.bind(this)},createWorkspace:{name:"createWorkspace",dataDecoder:workspaceCreateConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.createWorkspace.bind(this)},createFrame:{name:"createFrame",resultDecoder:frameSummaryResultDecoder,execute:this.createFrame.bind(this)},initFrame:{name:"initFrame",resultDecoder:voidResultDecoder,execute:this.initFrame.bind(this)},getAllFramesSummaries:{name:"getAllFramesSummaries",resultDecoder:frameSummariesResultDecoder,execute:this.getAllFramesSummaries.bind(this)},getFrameSummary:{name:"getFrameSummary",dataDecoder:getFrameSummaryConfigDecoder,resultDecoder:frameSummaryDecoder,execute:this.getFrameSummary.bind(this)},getAllWorkspacesSummaries:{name:"getAllWorkspacesSummaries",resultDecoder:workspaceSummariesResultDecoder,execute:this.getAllWorkspacesSummaries.bind(this)},getWorkspaceSnapshot:{name:"getWorkspaceSnapshot",dataDecoder:simpleItemConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.getWorkspaceSnapshot.bind(this)},getAllLayoutsSummaries:{name:"getAllLayoutsSummaries",resultDecoder:layoutSummariesDecoder,execute:this.getAllLayoutsSummaries.bind(this)},openWorkspace:{name:"openWorkspace",dataDecoder:openWorkspaceConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.openWorkspace.bind(this)},deleteLayout:{name:"deleteLayout",dataDecoder:deleteLayoutConfigDecoder,resultDecoder:voidResultDecoder,execute:this.deleteLayout.bind(this)},saveLayout:{name:"saveLayout",dataDecoder:workspaceLayoutSaveConfigDecoder,resultDecoder:workspaceLayoutDecoder,execute:this.saveLayout.bind(this)},importLayout:{name:"importLayout",dataDecoder:workspacesLayoutImportConfigDecoder,resultDecoder:voidResultDecoder,execute:this.importLayout.bind(this)},exportAllLayouts:{name:"exportAllLayouts",resultDecoder:exportedLayoutsResultDecoder,execute:this.exportAllLayouts.bind(this)},restoreItem:{name:"restoreItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.restoreItem.bind(this)},maximizeItem:{name:"maximizeItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.maximizeItem.bind(this)},focusItem:{name:"focusItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.focusItem.bind(this)},closeItem:{name:"closeItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.closeItem.bind(this)},closeWorkspace:{name:"closeWorkspace",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.closeWorkspace.bind(this)},resizeItem:{name:"resizeItem",dataDecoder:resizeItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.resizeItem.bind(this)},changeFrameState:{name:"changeFrameState",dataDecoder:frameStateConfigDecoder,resultDecoder:voidResultDecoder,execute:this.changeFrameState.bind(this)},getFrameState:{name:"getFrameState",dataDecoder:simpleItemConfigDecoder,resultDecoder:frameStateResultDecoder,execute:this.getFrameState.bind(this)},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleItemConfigDecoder,resultDecoder:frameBoundsResultDecoder,execute:this.getFrameBounds.bind(this)},moveFrame:{name:"moveFrame",dataDecoder:moveFrameConfigDecoder,resultDecoder:voidResultDecoder,execute:this.moveFrame.bind(this)},getFrameSnapshot:{name:"getFrameSnapshot",dataDecoder:frameSnapshotConfigDecoder,resultDecoder:frameSnapshotResultDecoder,execute:this.getFrameSnapshot.bind(this)},forceLoadWindow:{name:"forceLoadWindow",dataDecoder:simpleItemConfigDecoder,resultDecoder:simpleWindowOperationSuccessResultDecoder,execute:this.forceLoadWindow.bind(this)},ejectWindow:{name:"ejectWindow",dataDecoder:ejectWindowDataDecoder,resultDecoder:simpleWindowOperationSuccessResultDecoder,execute:this.ejectWindow.bind(this)},setItemTitle:{name:"setItemTitle",dataDecoder:setItemTitleConfigDecoder,resultDecoder:voidResultDecoder,execute:this.setItemTitle.bind(this)},moveWindowTo:{name:"moveWindowTo",dataDecoder:moveWindowConfigDecoder,resultDecoder:voidResultDecoder,execute:this.moveWindowTo.bind(this)},addWindow:{name:"addWindow",dataDecoder:addWindowConfigDecoder,resultDecoder:addItemResultDecoder,execute:this.addWindow.bind(this)},addContainer:{name:"addContainer",dataDecoder:addContainerConfigDecoder,resultDecoder:addItemResultDecoder,execute:this.addContainer.bind(this)},bundleWorkspace:{name:"bundleWorkspace",dataDecoder:bundleWorkspaceConfigDecoder,resultDecoder:voidResultDecoder,execute:this.bundleWorkspace.bind(this)},bundleItem:{name:"bundleItem",dataDecoder:bundleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.bundleItem.bind(this)},hibernateWorkspace:{name:"hibernateWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.hibernateWorkspace.bind(this)},resumeWorkspace:{name:"resumeWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.resumeWorkspace.bind(this)},getWorkspacesConfig:{name:"getWorkspacesConfig",resultDecoder:workspacesConfigDecoder,execute:this.getWorkspacesConfiguration.bind(this)},lockWorkspace:{name:"lockWorkspace",dataDecoder:lockWorkspaceDecoder,resultDecoder:voidResultDecoder,execute:this.lockWorkspace.bind(this)},lockWindow:{name:"lockWindow",dataDecoder:lockWindowDecoder,resultDecoder:voidResultDecoder,execute:this.lockWindow.bind(this)},lockContainer:{name:"lockContainer",dataDecoder:lockContainerDecoder,resultDecoder:voidResultDecoder,execute:this.lockContainer.bind(this)},pinWorkspace:{name:"pinWorkspace",dataDecoder:pinWorkspaceDecoder,resultDecoder:voidResultDecoder,execute:this.pinWorkspace.bind(this)},unpinWorkspace:{name:"unpinWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.unpinWorkspace.bind(this)},getWorkspaceIcon:{name:"getWorkspaceIcon",dataDecoder:workspaceSelectorDecoder,resultDecoder:workspaceIconDecoder,execute:this.getWorkspaceIcon.bind(this)},setWorkspaceIcon:{name:"setWorkspaceIcon",dataDecoder:setWorkspaceIconDecoder,resultDecoder:voidResultDecoder,execute:this.setWorkspaceIcon.bind(this)},checkStarted:{name:"checkStarted",execute:this.handleCheckStarted.bind(this)},getPlatformFrameId:{name:"getPlatformFrameId",execute:this.handleGetPlatformFrameId.bind(this)},getWorkspacesLayouts:{name:"getWorkspacesLayouts",dataDecoder:getWorkspacesLayoutsConfigDecoder,resultDecoder:getWorkspacesLayoutsResponseDecoder,execute:this.handleGetWorkspacesLayouts.bind(this)},getWorkspaceWindowsOnLayoutSaveContext:{name:"getWorkspaceWindowsOnLayoutSaveContext",dataDecoder:getWorkspaceWindowsOnLayoutSaveContextConfigDecoder,resultDecoder:getWorkspaceWindowsOnLayoutSaveContextResult,execute:this.handleGetWorkspaceWindowsOnLayoutSaveContext.bind(this)},setMaximizationBoundary:{name:"setMaximizationBoundary",dataDecoder:setMaximizationBoundaryConfigDecoder,resultDecoder:voidResultDecoder,execute:this.handleSetMaximizationBoundary.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:frameBoundsResultDecoder,dataDecoder:simpleItemConfigDecoder,execute:this.getWorkspaceWindowFrameBounds.bind(this)},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder,execute:this.handleFocusEvent.bind(this)},bringBackToWorkspace:{name:"bringBackToWorkspace",dataDecoder:bringBackToWorkspaceDataDecoder,execute:this.handleBringBackToWorkspace.bind(this)},showChannelsLink:{name:"showChannelsLink",dataDecoder:showChannelsLinkDecoder,resultDecoder:voidResultDecoder,execute:this.showChannelsLink.bind(this)}};constructor(e,t,r,n,i,o,s){this.framesController=e,this.glueController=t,this.stateController=r,this.hibernationWatcher=n,this.sequelizer=i,this.sessionStorageController=o,this.ioc=s}get started(){return this._started}set started(e){this._started=e}handlePlatformShutdown(){this.started=!1,this.hibernationWatcher.stop(),this.framesController.stop()}async start(e){e.workspaces?(this.connectionConfig=e.connection,this.settings=this.applyDefaults(e.workspaces),this.defaultWindowOpenBounds=e.windows.defaultWindowOpenBounds,this.settings.hibernation&&this.hibernationWatcher.start(this,this.settings.hibernation),await Promise.all([this.glueController.createWorkspacesStream(),this.glueController.createWorkspacesEventsReceiver(this.bridgeWorkspaceEvent.bind(this))]),this.started=!0):this.started=!1}async configurePostStart(){await this.framesController.start(this.settings,this.defaultWindowOpenBounds,this.operations.getFrameSummary),this.stateController.onWindowDisappeared(e=>this.framesController.handleFrameDisappeared(e))}get logger(){return logger.get("workspaces.controller")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this workspaces control message, because the controller has not been started");const t=e.data,r=e.commandId,n=workspacesOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This workspace request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Workspace request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Workspace request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(e,t){this.logger?.trace(`handling unloading of ${e}`),t&&!t.closed||(this.logger?.trace(`${e} detected as closed, checking if frame and processing close`),this.framesController.handleFrameDisappeared(e))}bridgeWorkspaceEvent(e){if(this.glueController.pushWorkspacesMessage(e),"closed"===e.action&&"workspace"===e.type){const{workspaceSummary:t}=e.payload;this.glueController.clearContext(t.id,"workspace"),this.registry.execute("workspace-closed",{layoutName:t.config.name})}this.settings.hibernation&&this.hibernationWatcher.notifyEvent(e)}onWorkspaceClosed(e){return"function"!=typeof e?ioError.raiseError("onWorkspaceClosed requires a single argument of type function"):this.registry.add("workspace-closed",e)}async closeWorkspace(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] handling closeWorkspace request with config ${JSON.stringify(e)}`);const r=e.itemId,n=(await this.getAllWorkspacesSummaries({},t)).summaries,i=n.find(e=>e.id===r);if(!i)return ioError.raiseError(`Cannot close workspace with id: ${r}, because it is unknown to the platform`);const o=i.config.frameId,s=1===n.filter(e=>e.config.frameId===o).length,a=this.glueController.platformWindowId;if(s&&o===a&&this.logger?.info(`[${t}] this is the last workspace in the platform frame, cannot close the platform frame.`),s&&o!==a)return this.logger?.trace(`[${t}] this is the last workspace in frame ${o}, closing the frame`),await this.framesController.closeFrame(o),void this.logger?.trace(`[${t}] the frame window is closed`);this.logger?.trace(`[${t}] targeting frame ${o} for closing workspace ${r}`),await this.glueController.callFrame(this.operations.closeItem,e,o),this.logger?.trace(`[${t}] frame ${o} gave a success signal, responding to caller`)})}async closeFrame(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] handling closeFrame request with config ${JSON.stringify(e)}`),await this.framesController.closeFrame(e.itemId),this.logger?.trace(`[${t}] the frame window is closed`)})}async closeItem(e,t){this.logger?.trace(`[${t}] handling closeItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r)return await this.closeFrame(e,t);const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${n.windowId}`),await this.glueController.callFrame(this.operations.closeItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async setItemTitle(e,t){this.logger?.trace(`[${t}] handling setItemTitle request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setItemTitle,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async hibernateWorkspace(e,t){this.logger?.trace(`[${t}] handling hibernateWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.preserveAllWorkspaceWindowsContext(e.workspaceId),await this.glueController.callFrame(this.operations.hibernateWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async getWorkspacesConfiguration(e,t){return this.logger?.trace(`[${t}] handling getWorkspacesConfiguration request`),this.settings}async getWorkspaceWindowFrameBounds(e,t){this.logger?.trace(`[${t}] handling getWorkspaceWindowFrameBounds request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId}),n=await this.glueController.callWindow("windows",this.ioc.windowsController.getFrameBoundsOperation,{windowId:r.windowId},{windowId:r.windowId});return this.logger?.trace(`[${t}] getWorkspaceWindowFrameBounds completed`),{bounds:n.bounds}}async getAllFramesSummaries(e,t){if(this.logger?.trace(`[${t}] handling getAllFramesSummaries request`),!this.started)return{summaries:[]};const r=await this.framesController.getAll();this.logger?.trace(`[${t}] sending getFrameSummary to all known frames: ${r.join(", ")}`);const n=(await Promise.all(r.map(e=>this.glueController.callFrame(this.operations.getFrameSummary,{itemId:e.windowId},e.windowId)))).filter(e=>"none"!==e.id);return this.logger?.trace(`[${t}] all frames responded, returning to caller`),{summaries:n}}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleFrameHello(e,t){this.logger?.trace(`[${t}] handling handleFrameHello command with config: ${JSON.stringify(e)}`),e.windowId&&this.framesController.processNewHello(e.windowId)}async isWindowInWorkspace(e,t){this.logger?.trace(`[${t}] handling isWindowInWorkspace command with config: ${JSON.stringify(e)}`);const r=this.framesController.getAll();this.logger?.trace(`[${t}] sending isWindowInWorkspace to all known frames: ${JSON.stringify(r.join(", "))}`);const n=(await Promise.all(r.map(t=>this.glueController.callFrame(this.operations.isWindowInWorkspace,e,t.windowId)))).some(e=>e.inWorkspace);return this.logger?.trace(`[${t}] all frames responded, returning ${n} to the caller`),{inWorkspace:n}}async createWorkspace(e,t){this.logger?.trace(`[${t}] handling createWorkspace command`);const r=this.getBlockedAppNames(e.children??[],t);if(r.length)return ioError.raiseError(`Cannot complete 'createWorkspace' operation because there're app origins blocked by the Platform. Blocked names: ${JSON.stringify(r)}`);const n={frameId:e.frame?.reuseFrameId,newFrame:e.frame?.newFrame,itemId:e.config?.reuseWorkspaceId},i=await this.framesController.getFrameInstance(n);this.logger?.trace(`[${t}] calling frame: ${i.windowId}, based on selection config: ${JSON.stringify(n)}`);const o=await this.glueController.callFrame(this.operations.createWorkspace,e,i.windowId);return this.logger?.trace(`[${t}] frame ${i.windowId} responded with a valid snapshot, returning to caller`),o}async createFrame(e,t){this.logger?.trace(`[${t}] handling createFrame command`);const r=await this.framesController.openFrame(e.frameConfig,e.layoutComponentId);this.logger?.trace(`[${t}] calling frame: ${r.windowId}}`);const n=await this.glueController.callFrame(this.operations.createFrame,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded returning to caller`),n}async initFrame(e,t){this.logger?.trace(`[${t}] handling initFrame command`);const r={frameId:e.frameId},n=await this.framesController.getFrameInstance(r);this.logger?.trace(`[${t}] calling frame: ${n.windowId}, based on selection config: ${JSON.stringify(r)}`);const i=await this.filterWorkspacesWithInstanceRestrictions(e.workspaces,t),o={...e,workspaces:i};await this.glueController.callFrame(this.operations.initFrame,o,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} responded returning to caller`)}async getFrameSummary(e,t){this.logger?.trace(`[${t}] handling getFrameSummary request for config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] forwarding getFrameSummary to frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getFrameSummary,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid summary, returning to caller`),n}async getAllWorkspacesSummaries(e,t){this.logger?.trace(`[${t}] handling getAllWorkspacesSummaries request`);const r=this.framesController.getAll();this.logger?.trace(`[${t}] sending getAllWorkspacesSummaries to all known frames: ${r.join(", ")}`);const n=(await Promise.all(r.map(e=>this.glueController.callFrame(this.operations.getAllWorkspacesSummaries,{},e.windowId)))).reduce((e,t)=>(e.push(...t.summaries),e),[]);return this.logger?.trace(`[${t}] all frames responded, results were aggregated, returning to caller`),{summaries:n}}async getWorkspaceSnapshot(e,t){this.logger?.trace(`[${t}] handling getWorkspaceSnapshot for config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getWorkspaceSnapshot,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid snapshot, retuning to caller`),n}async handleCheckStarted(e,t){return this.logger?.trace(`[${t}] handling handleCheckStarted request`),this.logger?.trace(`[${t}] the controller has been started, responding to caller`),{started:!0}}async handleGetPlatformFrameId(e,t){this.logger?.trace(`[${t}] handling GetPlatformFrameId request`);const r=this.framesController.getPlatformFrameSessionData();return this.logger?.trace(`[${t}] GetPlatformFrameId completed, responding to caller`),{id:r?.windowId}}async getFrameSessionData(e,t){this.logger?.trace(`[${t}] handling getFrameSessionData request`);const r=this.framesController.getFrameConfig(e.frameId);return this.logger?.trace(`[${t}] getFrameSessionData completed, responding to caller`),r}async handleGetWorkspacesLayouts(e,t){this.logger?.trace(`[${t}] handling handleGetWorkspacesLayouts request for frame: ${e.frameId} for layout: ${e.layoutName} of type: ${e.layoutType} and config: ${JSON.stringify(e)}`);const r=await this.glueController.callFrame(this.operations.getWorkspacesLayouts,e,e.frameId);if(this.logger?.trace(`[${t}] handleGetWorkspacesLayouts request completed for frame: ${e.frameId} for layout: ${e.layoutName} of type: ${e.layoutType} and config: ${JSON.stringify(e)}`),!e.ignoreContexts)return this.logger?.info(`[${t}] 'ignoreContexts' flag not set on layout save request, returning workspace and window contexts as received from frame ${e.frameId}`),r;return await this.checkIsIgnoreContextsOnLayoutSaveSupported(e.frameId,t)?(this.logger?.info(`[${t}] Returning workspaces layouts response as received from frame ${e.frameId}.`),r):(this.clearWorkspaceAndWindowsContexts(r.workspaces),this.logger?.info(`[${t}] Returning workspaces layouts response after clearing workspace and window contexts in the Platform`),r)}async getFrameBounds(e,t){this.logger?.trace(`[${t}] handling getFrameBounds request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({frameId:e.itemId}),n=await this.glueController.callWindow("windows",this.ioc.windowsController.getFrameBoundsOperation,{windowId:r.windowId},{windowId:r.windowId});return this.logger?.trace(`[${t}] getFrameBounds completed`),{bounds:n.bounds}}async showChannelsLink(e,t){this.logger?.trace(`[${t}] - received 'showChannelsLink' signal for windowId ${e.windowId}`);const r=await this.framesController.getFrameInstance({frameId:e.frameId});if(!r)return ioError.raiseError(`[${t}] - frame ${e.frameId} not found, cannot show channels link`);await this.glueController.callFrame(this.operations.showChannelsLink,e,r.windowId),this.logger?.trace(`[${t}] - frame ${r.windowId} gave a success signal, responding to caller`)}async getAllLayoutsSummaries(e,t){this.logger?.trace(`[${t}] handling getAllLayoutsSummaries command`);const r=(await this.ioc.layoutsController.handleGetAll({type:"Workspace"},t)).summaries.map(e=>({name:e.name}));return this.logger?.trace(`[${t}] all layouts retrieved and mapped, returning to caller`),{summaries:r}}async openWorkspace(e,t){this.logger?.trace(`[${t}] handling openWorkspace command for name: ${e.name}`);const r={frameId:e.restoreOptions?.frameId,newFrame:e.restoreOptions?.newFrame,itemId:e.restoreOptions?.reuseWorkspaceId},n=new Date,i=await this.tryFocusExistingWorkspace(e.name,t),o=await this.framesController.getFrameInstance(r),s=i?await this.getWorkspaceSnapshot({itemId:i},t):await this.glueController.callFrame(this.operations.openWorkspace,e,o.windowId),a=new Date;return this.registry.execute("workspace-restored",{layoutName:e.name,startTime:n,endTime:a}),s}onWorkspaceRestored(e){return this.registry.add("workspace-restored",e)}async deleteLayout(e,t){this.logger?.trace(`[${t}] handling deleteLayout request for name: ${e.name}`),await this.ioc.layoutsController.handleRemove({name:e.name,type:"Workspace"},t),this.logger?.trace(`[${t}] layouts reported this layout as deleted, responding to caller`)}async saveLayout(e,t){this.logger?.trace(`[${t}] handling saveLayout request for workspace ${e.workspaceId} and name ${e.name}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] forwarding request to frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.saveLayout,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid layout, returning to caller`),n}async importLayout(e,t){this.logger?.trace(`[${t}] handling importLayout command for layout ${e.layout.name}`),await this.ioc.layoutsController.handleImport({layouts:[e.layout],mode:e.mode},t),this.logger?.trace(`[${t}] the layouts controller successfully imported the layout, responding to caller`)}async exportAllLayouts(e,t){this.logger?.trace(`[${t}] handling exportAllLayouts request`);return await this.ioc.layoutsController.handleExport({type:"Workspace"},t)}async restoreItem(e,t){this.logger?.trace(`[${t}] handling restoreItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.restoreItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async maximizeItem(e,t){this.logger?.trace(`[${t}] handling maximizeItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.maximizeItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async focusItem(e,t){this.logger?.trace(`[${t}] handling focusItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r)return this.logger?.trace(`[${t}] this is targeted at a frame, focusing the frame`),void window.open(void 0,r.windowId);const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${n.windowId}`),await this.glueController.callFrame(this.operations.focusItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async resizeItem(e,t){this.logger?.trace(`[${t}] handling resizeItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r){this.logger?.trace(`[${t}] detected targeted item is frame, building window resize config`);const n={windowId:e.itemId,width:e.width,height:e.height,relative:e.relative};return await this.glueController.callWindow("windows",this.ioc.windowsController.moveResizeOperation,n,{windowId:r.windowId}),void this.logger?.trace(`[${t}] window resize responded with success, returning to caller`)}const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeted item is not a frame, it is located in frame ${n.windowId}`),await this.glueController.callFrame(this.operations.resizeItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async getFrameSnapshot(e,t){this.logger?.trace(`[${t}] handling getFrameSnapshot request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getFrameSnapshot,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async forceLoadWindow(e,t){this.logger?.trace(`[${t}] handling forceLoadWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.forceLoadWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async ejectWindow(e,t){this.logger?.trace(`[${t}] handling ejectWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);e.windowId&&this.sessionStorageController.addEjectedWindowId(e.windowId),this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.ejectWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async moveWindowTo(e,t){this.logger?.trace(`[${t}] handling moveWindowTo request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.moveWindowTo,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async addWindow(e,t){if(this.logger?.trace(`[${t}] handling addWindow request with config ${JSON.stringify(e)}`),e.definition.appName&&this.checkIfOriginBlockedByAppName(e.definition.appName))return ioError.raiseError(`Cannot complete 'addWindow' operation - origin of app '${e.definition.appName}' is blocked by the Platform`);const r=await this.framesController.getFrameInstance({itemId:e.parentId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.addWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal: ${JSON.stringify(n)}, responding to caller`),n}checkIfOriginBlockedByAppName(e){const t=this.glueController.getAllApplications().find(t=>t.name===e);return t?checkIsOriginBlocked(t.userProperties.details.url,this.connectionConfig.blockList):ioError.raiseError(`Application with name: ${e} does not exist`)}extractAppNamesFromConfig(e,t=[]){if("window"===e.type&&e.appName)return t.push(e.appName),t;for(const r of e.children||[])this.extractAppNamesFromConfig(r,t);return t}getBlockedAppNames(e,t){const r=[];for(const t of e)this.extractAppNamesFromConfig(t,r);this.logger?.trace(`[${t}] filtering blocked apps from all gathered appNames: ${JSON.stringify(r)}`);const n=r.filter(e=>this.checkIfOriginBlockedByAppName(e));return this.logger?.trace(`[${t}] blocked app names: ${JSON.stringify(n)}`),n}async addContainer(e,t){this.logger?.trace(`[${t}] handling addContainer request with config ${JSON.stringify(e)}`);const r=this.getBlockedAppNames(e.definition.children??[],t);if(r.length)return ioError.raiseError(`Cannot complete 'addContainer' operation because there're app origins blocked by the Platform. Blocked names: ${JSON.stringify(r)}`);const n=await this.framesController.getFrameInstance({itemId:e.parentId});this.logger?.trace(`[${t}] targeting frame ${n.windowId}`);const i=await this.glueController.callFrame(this.operations.addContainer,e,n.windowId);return this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal: ${JSON.stringify(i)}, responding to caller`),i}async bundleWorkspace(e,t){this.logger?.trace(`[${t}] handling bundleWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.bundleWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async bundleItem(e,t){this.logger?.trace(`[${t}] handling bundleItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.bundleItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async resumeWorkspace(e,t){this.logger?.trace(`[${t}] handling resumeWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.resumeWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockWorkspace(e,t){this.logger?.trace(`[${t}] handling lockWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockContainer(e,t){this.logger?.trace(`[${t}] handling lockContainer request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockContainer,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockWindow(e,t){this.logger?.trace(`[${t}] handling lockWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.windowPlacementId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockWindow,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async pinWorkspace(e,t){this.logger?.trace(`[${t}] handling pinWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.pinWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async unpinWorkspace(e,t){this.logger?.trace(`[${t}] handling unpinWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.unpinWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async getWorkspaceIcon(e,t){this.logger?.trace(`[${t}] handling getWorkspaceIcon request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getWorkspaceIcon,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async setWorkspaceIcon(e,t){this.logger?.trace(`[${t}] handling setWorkspaceIcon request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setWorkspaceIcon,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async handleGetWorkspaceWindowsOnLayoutSaveContext(e,t){this.logger?.trace(`[${t}] handling GetWorkspaceWindowsOnLayoutSaveContext request with config: ${JSON.stringify(e)}`);const r=await Promise.all(e.windowIds.map(async t=>({windowId:t,windowContext:await this.getWorkspaceWindowOnLayoutSaveData(t,e)})));return this.logger?.trace(`[${t}] operation GetWorkspaceWindowsOnLayoutSaveContext completed responding`),{windowsOnSaveData:r}}async handleSetMaximizationBoundary(e,t){this.logger?.trace(`[${t}] handling setMaximizationBoundary request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setMaximizationBoundary,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async changeFrameState(e,t){return ioError.raiseError("Frame states are not supported in Glue42 Core")}async getFrameState(e,t){return ioError.raiseError("Frame states are not supported in Glue42 Core")}async handleFocusEvent(e,t){this.logger?.trace(`[${t}] handling focus event from frame id: ${e.windowId} and hasFocus: ${e.hasFocus}`);try{await this.framesController.getFrameInstance({frameId:e.windowId})}catch(r){return void this.logger?.trace(`[${t}] ignoring focus event for unrecognized frame with id: ${e.windowId}`)}const r={type:"frame",action:"focus",payload:{frameSummary:{id:e.windowId,isFocused:e.hasFocus}}};this.bridgeWorkspaceEvent(r),this.logger?.trace(`[${t}] focus event from frame id: ${e.windowId} and hasFocus: ${e.hasFocus} handled`)}async moveFrame(e,t){this.logger?.trace(`[${t}] handling moveFrame command with config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({frameId:e.itemId}),n={windowId:e.itemId,top:e.top,left:e.left,relative:e.relative};await this.glueController.callWindow("windows",this.ioc.windowsController.moveResizeOperation,n,{windowId:r.windowId}),this.logger?.trace(`[${t}] frame with id ${r.windowId} was successfully moved, responding to caller`)}applyDefaults(e){const t=e?.hibernation||{},r=deepMerge(defaultLoadingConfig,e?.loadingStrategy||{});return{...e,loadingStrategy:r,hibernation:t}}async getWorkspaceWindowOnLayoutSaveData(e,t){if(this.ioc.sessionController.getAllNonGlue().some(t=>t.windowId===e))return{};if(!this.ioc.sessionController.getWorkspaceClientById(e))return ioError.raiseError(`Cannot ask window: ${e} for on layout save request, because it is not a known workspace window`);const r=`Cannot fetch the on layout save context from: ${e}, because of timeout`,n=await PromiseWrap(async()=>{try{return await this.glueController.callWindow("layouts",{name:"clientSaveRequest",execute:async()=>{}},t,{windowId:e})}catch(e){return{}}},15e3,r);return n?.windowContext??{}}async handleBringBackToWorkspace({windowId:e},t){this.logger?.trace(`[${t}] - received 'bringBackToWorkspace' signal for windowId ${e}`);if(!this.glueController.getWindowById(e))return ioError.raiseError(`Cannot bring back window with id ${e} to workspace because it is not known by the platform`);this.sessionStorageController.addEjectedWindowId(e);const r=await this.glueController.clientGlue.contexts.get(`___window___${e}`);if(!r||!Object.keys(r).length||!r.___io___?.ejectedWindow)return ioError.raiseError(`Cannot bring back window with id ${e} to workspace because it was never a part from one`);const{___io___:{ejectedWindow:n}}=r,i=await this.framesController.getFrameInstance({itemId:n.frameId}),o={definition:{type:"group",children:[{windowId:e,type:"window"}]},parentType:"workspace",parentId:n.workspaceId},s=await this.glueController.callFrame(this.operations.addContainer,o,i.windowId);this.logger?.trace(`[${t}] - frame ${i.windowId} gave a success signal: ${JSON.stringify(s)}`)}async tryFocusExistingWorkspace(e,t){const r=await this.ioc.layoutsController.handleGetLayout({name:e,type:"Workspace"},t);if(!this.hasInstanceRestriction(r.layout))return;const n=(await this.getAllWorkspacesSummaries({},t)).summaries.find(t=>t.config.layoutName===e);return n?(await this.focusItem({itemId:n.id},t),n.id):void 0}hasInstanceRestriction(e){if(!e)return!1;const t=e.components[0];return!1===t.state?.config?.allowMultiple}async filterWorkspacesWithInstanceRestrictions(e,t){const r=await this.getAllWorkspacesSummaries({},t),n=await Promise.all(e.map(e=>e).filter(e=>e.name).map(e=>this.ioc.layoutsController.handleGetLayout({name:e.name,type:"Workspace"},t))),i=e.filter((e,t,i)=>{if(!this.isRestoreWorkspaceDefinition(e))return!0;const o=n.find(t=>t.layout?.name===e.name)?.layout;if(!this.hasInstanceRestriction(o))return!0;const s=r.summaries.find(t=>t.config.layoutName===e.name),a=e!==i.find(t=>this.isRestoreWorkspaceDefinition(t)&&t.name===e.name);return!s&&!a},[]);return i}isRestoreWorkspaceDefinition(e){return!!e.name}async checkIsIgnoreContextsOnLayoutSaveSupported(e,t){const r=await this.glueController.isFrameOperationSupported("isIgnoreContextsOnLayoutSaveSupported",e);return this.logger?.info(`[${t}] Frame ${e} ${r?"supports":"does NOT support"} 'ignoreContexts' flag on layout save requests`),r}clearWorkspaceAndWindowsContexts(e){e.forEach(e=>{e.context={},this.clearWorkspaceChildrenContexts(e.children)})}clearWorkspaceChildrenContexts(e){e.forEach(e=>{"window"!==e.type?this.clearWorkspaceChildrenContexts(e.children):e.config.context={}})}}const INTENTS_RESOLVER_INTEROP_PREFIX="T42.Intents.Resolver.Control.",INTENTS_RESOLVER_WIDTH=400,INTENTS_RESOLVER_HEIGHT=400,DEFAULT_METHOD_RESPONSE_TIMEOUT_MS=6e4,DEFAULT_RAISE_TIMEOUT_MS=9e4,DEFAULT_PICK_HANDLER_BY_TIMEOUT_MS=9e4,ERRORS=errors.intents;class IntentsController{glueController;legacyResolverController;appDirectory;windowsController;prefsController;uiController;operations={getIntents:{name:"getIntents",resultDecoder:wrappedIntentsDecoder,execute:this.getWrappedIntents.bind(this)},findIntent:{name:"findIntent",dataDecoder:wrappedIntentFilterDecoder,resultDecoder:wrappedIntentsDecoder,execute:this.findIntent.bind(this)},raise:{name:"raise",dataDecoder:raiseIntentRequestDecoder,resultDecoder:intentResultDecoder,execute:this.raise.bind(this)},filterHandlers:{name:"filterHandlers",dataDecoder:filterHandlersWithResolverConfigDecoder,resultDecoder:filterHandlersResultDecoder,execute:this.filterHandlers.bind(this)},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:intentHandlerDecoder,resultDecoder:getIntentsResultDecoder,execute:this.getIntentsByHandler.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};started=!1;isIntentsSharingEnabledViaBridge=!1;constructor(e,t,r,n,i,o){this.glueController=e,this.legacyResolverController=t,this.appDirectory=r,this.windowsController=n,this.prefsController=i,this.uiController=o}get logger(){return logger.get("intents.controller")}handlePlatformShutdown(){this.started=!1}async start(e){this.started=!0;const t=e.gateway?.bridge;this.isIntentsSharingEnabledViaBridge=!!t?.url&&!1!==t.intents?.enabled}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this intents control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=e.callerType,o=intentsOperationTypesDecoder.run(e.operation);if(!o.ok)return ioError.raiseError(`This intents request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(o.error)}`);const s=o.result,a=this.operations[s].dataDecoder?.run(t);if(a&&!a.ok)return ioError.raiseError(`Intents request for ${s} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(a.error)}`);this.logger?.debug(`[${r}] ${s} command is valid with data: ${JSON.stringify(t)}`);const c=await this.operations[s].execute(t,r,n,i),l=this.operations[s].resultDecoder?.run(c);return l&&!l.ok?ioError.raiseError(`Intents request for ${s} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(l.error)}`):(this.logger?.trace(`[${r}] ${s} command was executed successfully`),c)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}extractAppIntents(e){const t={},r=e.filter(e=>e.intents.length>0);for(const e of r)for(const r of e.intents){t[r.name]||(t[r.name]=[]);const n={applicationName:e.name,applicationTitle:e.title,applicationDescription:e.caption,displayName:r.displayName,contextTypes:r.contexts,applicationIcon:e.icon,type:"app",resultType:r.resultType,customConfig:r.customConfig};t[r.name].push(n)}return t}async getInstanceIntents(e,t){const r={},n=this.isIntentsSharingEnabledViaBridge?this.glueController.getServers():this.glueController.getLocalServers();for(const i of n){const n=(i.getMethods?.()||[]).filter(e=>e.name.startsWith(GlueWebIntentsPrefix));await Promise.all(n.map(async n=>{const o=n.name.replace(GlueWebIntentsPrefix,"");r[o]=r[o]??[];const s={apps:e,server:i,method:n,commandId:t,intentName:o},a=this.glueController.isValidWindowId(s.server.windowId)?await this.getInstanceIntentHandler(s):this.getInstanceIntentHandlerWithInvalidWindowId(s);r[o].push(a)}))}return r}getInstanceIntentHandlerWithInvalidWindowId({server:e,method:t,apps:r,intentName:n}){const i=this.glueController.clientGlue.appManager.instances().find(t=>t.id===e.instance),o=t.flags.intent;if(!i)return{instanceId:e.instance,applicationName:e.application??e.applicationName??"",applicationIcon:o.icon,applicationTitle:"",applicationDescription:o.description,displayName:o.displayName,contextTypes:o.contextTypes,instanceTitle:e.instance,type:"instance",resultType:o.resultType,customConfig:o.customConfig};const{application:s}=i,a=r.find(e=>e.name===s.name)?.intents?.find(e=>e.name===n);return{instanceId:e.instance,applicationName:s.name,applicationIcon:o.icon??s.icon,applicationTitle:s.title??"",applicationDescription:o.description??s.caption,displayName:o.displayName??a?.displayName,contextTypes:o.contextTypes??a?.contexts,instanceTitle:"",type:"instance",resultType:o.resultType??a?.resultType}}async getInstanceIntentHandler({apps:e,intentName:t,server:r,method:n,commandId:i}){const o=e.find(e=>e.name===r.application),s=o?.intents?.find(e=>e.name===t)||void 0,a=n.flags.intent,c=await this.windowsController.getWindowTitle(r.windowId??"",i);return{instanceId:r.windowId||r.instance,applicationName:r.application||"",applicationIcon:a.icon||o?.icon,applicationTitle:o?.title||"",applicationDescription:a.description||o?.caption,displayName:a.displayName||s?.displayName,contextTypes:a.contextTypes||s?.contexts,instanceTitle:c,type:"instance",resultType:s?.resultType||a.resultType,customConfig:a.customConfig}}mergeIntentStores(e,t){const r={};for(const n of new Set([...Object.keys(e),...Object.keys(t)]))r[n]=[...e[n]||[],...t[n]||[]];return r}wrapIntents(e){return{intents:e}}async getIntents(e){const t=(await this.appDirectory.getAll()).map(e=>({name:e.name,title:e.title||"",icon:e.icon,caption:e.caption,intents:e.userProperties.intents??[]})),r=this.extractAppIntents(t);this.logger?.trace(`[${e}] got app intents`);const n=await this.getInstanceIntents(t,e);this.logger?.trace(`[${e}] got instance intents`);const i=this.mergeIntentStores(r,n);return Object.keys(i).map(e=>({name:e,handlers:i[e]}))}async getWrappedIntents(e){this.logger?.trace(`[${e}] handling getIntents command`);const t=await this.getIntents(e);return this.logger?.trace(`[${e}] getIntents command completed`),this.wrapIntents(t)}async findIntent(e,t){this.logger?.trace(`[${t}] handling findIntent command`);const r=e.filter;let n=await this.getIntents(t);if(!r)return this.wrapIntents(n);if("string"==typeof r)return this.wrapIntents(n.filter(e=>e.name===r));if(r.contextType){const e=r.contextType.toLowerCase();n=n.filter(t=>t.handlers.some(t=>t.contextTypes?.some(t=>t.toLowerCase()===e)))}if(r.name&&(n=n.filter(e=>e.name===r.name)),r.resultType){const e=r.resultType.toLowerCase();n=n.filter(t=>t.handlers.some(t=>t.resultType?.toLowerCase()===e))}return this.logger?.trace(`[${t}] findIntent command completed`),this.wrapIntents(n)}async getIntent(e,t){return(await this.getIntents(t)).find(t=>t.name===e)}async startApp(e,t){const r={...t.options??{},originIntentRequest:t};return(await this.glueController.clientGlue.appManager.application(e).start(t.context,r)).id}async raiseIntent(e,t,r,n){this.logger?.trace(`[${t}] handling raiseIntent command with intentRequest: ${JSON.stringify(e)}`);const i=e.intent,o=await this.getIntent(i,t);if(!o)return ioError.raiseError(`Intent ${i} not found!`);this.logger?.trace(`Raised intent definition: ${JSON.stringify(o)}`);const s=e.handlers?this.findHandlerByFilter(e.handlers,{type:"app"}):this.findHandlerByFilter(o.handlers,{type:"app"}),a=e.handlers?this.findHandlerByFilter(e.handlers,{type:"instance"}):this.findHandlerByFilter(o.handlers,{type:"instance"});let c;if(e.target&&"reuse"!==e.target||(c=a||s),"startNew"===e.target&&(c=s),"object"==typeof e.target&&e.target.app&&(c=this.findHandlerByFilter(o.handlers,{app:e.target.app})),"object"==typeof e.target&&e.target.instance&&(c=this.findHandlerByFilter(o.handlers,{instance:e.target.instance,app:e.target.app})),!c)return ioError.raiseError(`Can not raise intent for request ${JSON.stringify(e)} - can not find intent handler!`);return await this.raiseIntentToTargetHandler({request:e,handler:c,commandId:t,callerId:r,timeout:n})}findHandlerByFilter(e,t){return t.type?e.find(e=>e.type===t.type):t.instance?e.find(e=>t.app?e.applicationName===t.app&&e.instanceId===t.instance:e.instanceId===t.instance):t.app?e.find(e=>e.applicationName===t.app):void 0}async raiseIntentToTargetHandler({handler:e,request:t,callerId:r,commandId:n,timeout:i}){this.logger?.trace(`Raising intent to target handler:${JSON.stringify(e)}`);const o=e.instanceId?Promise.resolve(e.instanceId):this.startApp(e.applicationName,t).catch(e=>{const t=e instanceof Error||"string"==typeof e?e:JSON.stringify(e);return ioError.raiseError(`${ERRORS.TARGET_INSTANCE_UNAVAILABLE}. Reason: ${t}`)}),s=await o,a=`${GlueWebIntentsPrefix}${t.intent}`;this.logger?.trace(`Searching for interop server offering method ${a}`);const c={methodResponseTimeoutMs:i?i+1e3:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS,waitTimeoutMs:i?i+1e3:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS},l=this.glueController.invokeMethod(a,{...t.context,_initialCallerId:r},{instance:s},c).catch(e=>ioError.raiseError(`${ERRORS.INTENT_HANDLER_REJECTION}. Reason: ${e instanceof Error?e:JSON.stringify(e)}`)),u=await l;return this.logger?.trace(`[${n}] raiseIntent command completed. Returning result: ${JSON.stringify(u)}`),{request:t,handler:{...e,instanceId:s,type:"instance"},result:u.returned}}async raise(e,t,r,n){if(this.logger?.trace(`[${t}] Receive raise command with config: ${JSON.stringify(e)}`),!r)return ioError.raiseError(`${ERRORS.CALLER_NOT_DEFINED} for 'raise' command with request ${JSON.stringify(e)}`);const i=e.intentRequest.timeout||DEFAULT_RAISE_TIMEOUT_MS,o={instanceId:void 0},s=this.coreRaiseIntent.bind(this,{request:e,resolverInstance:o,timeout:i,commandId:t,callerId:this.getCallerIdByCallerType(r,n)});return e.intentRequest.waitUserResponseIndefinitely?s():PromiseWrap(s,i,`${ERRORS.TIMEOUT_HIT} - waited ${i}ms for 'raise' to resolve`)}async handleRaiseWithEmbeddedResolver({intentRequest:e,initialCaller:t,timeout:r,commandId:n}){this.logger?.trace(`[${n}] handling raise command with embedded resolver`);const i=e.waitUserResponseIndefinitely?MAX_SET_TIMEOUT_DELAY:r,o={commandId:n,config:{intentRequest:e,timeout:i},methodResponseTimeoutMs:i,initialCaller:t},s=await this.uiController.openResolver(o);s.isClosed&&ioError.raiseError(`${ERRORS.USER_CANCELLED}`),s.isExpired&&ioError.raiseError(`${ERRORS.TIMEOUT_HIT} - waited ${r}ms for user to choose an intent handler`);const a=s.userChoice?.handler;if(!a)return ioError.raiseError(`${ERRORS.HANDLER_NOT_FOUND}`);if(!!s.userChoice?.userSettings.preserveChoice)try{this.logger?.trace(`[${n}] - User wants to preserve the chosen of handler: ${JSON.stringify(a)}`),await this.preserveUserChoice({initialCaller:t,commandId:n,handler:a,intentName:e.intent})}catch(e){this.logger?.warn(`[${n}] - Prefs API threw the following error: ${e}. Handler won't be preserved`)}return this.handleRaiseToTargetHandler(e,a,n,t.instanceId,r)}async coreRaiseIntent({request:e,resolverInstance:t,timeout:r,commandId:n,callerId:i}){const{resolverConfig:o,intentRequest:s,embeddedResolverConfig:a}=e,c=(await this.findIntent({filter:{name:s.intent}},n)).intents.find(e=>e.name===s.intent);if(!c)return ioError.raiseError(`${ERRORS.INTENT_NOT_FOUND} with name ${s.intent}`);this.logger?.trace(`[${n}] Intent to be handled: ${JSON.stringify(c)}`);const{open:l,reason:u}=this.checkIfResolverShouldBeOpenedForRaise(c,s,o,a);if(!l)return this.logger?.trace(`[${n}] Intent Resolver UI won't be used. Reason: ${u}`),this.handleRaiseWithoutResolver({request:e,commandId:n,callerId:i,timeout:r});if(this.logger?.trace(`[${n}] Starting Intent Resolver app for intent request: ${JSON.stringify(e)}`),a?.enabled)return this.logger?.trace(`[${n}] Handling 'raise' with embedded intent resolver`),this.handleRaiseWithEmbeddedResolver({intentRequest:s,initialCaller:a.initialCaller,timeout:r,commandId:n});if(o){this.logger?.trace(`[${n}] Handling 'raise' with legacy intent resolver`);const o=this.handleRaiseWithLegacyResolver({request:e,commandId:n,resolverInstance:t,callerId:i,timeout:r});return o.catch(()=>t.instanceId&&this.legacyResolverController.stopResolverInstance(t.instanceId)),o}return ioError.raiseError(`Couldn't complete 'raise' operation with request: ${JSON.stringify(s)}`)}async handleRaiseToTargetHandler(e,t,r,n,i){const o=`with timeout of ${e.timeout??DEFAULT_RAISE_TIMEOUT_MS}ms`;if(this.logger?.trace(`Raising intent to target handler: ${JSON.stringify(t)} ${o}`),e.waitUserResponseIndefinitely)return PromiseWrap(()=>this.raiseIntentToTargetHandler({request:e,handler:{...t,type:t.instanceId?"instance":"app"},commandId:r,timeout:i,callerId:n}),i,`${ERRORS.INTENT_DELIVERY_FAILED} - waited ${i}ms for client to handle the raised intent`);const s=await this.raiseIntentToTargetHandler({request:e,handler:{...t,type:t.instanceId?"instance":"app"},commandId:r,callerId:n,timeout:i});return this.logger?.trace(`Result from raise() method for intent ${JSON.stringify(e.intent)}: ${JSON.stringify(s)}`),s}async handleRaiseWithoutResolver({request:e,commandId:t,callerId:r,timeout:n}){const{intentRequest:i}=e;return i.waitUserResponseIndefinitely?PromiseWrap(()=>this.raiseIntent(i,t,r,n),n,`${ERRORS.TIMEOUT_HIT} - waited ${n}ms for 'raise' to resolve`):this.raiseIntent(i,t,r,n)}async handleRaiseWithLegacyResolver(e){const{request:t,callerId:r,commandId:n,resolverInstance:i,timeout:o}=e,s=await this.legacyResolverController.startResolverApp({request:t.intentRequest,resolverConfig:t.resolverConfig,callerId:r,commandId:n,resolverInstance:i,method:"raise"});return this.handleRaiseToTargetHandler(t.intentRequest,s,n,r,o)}async preserveUserChoice({initialCaller:e,commandId:t,filter:r,intentName:n,handler:i}){const o=e.instanceId===this.glueController.me.instance?this.prefsController.platformAppName:this.glueController.getAppNameByInstanceId(e.instanceId);if(!o)return;this.logger?.info(`[${t}] - Saving user's choice of handler for '${o}' app`);const s=await this.prefsController.get({app:o},t),a=s.prefs.data?.intents??{},c={...s.prefs.data,intents:{...a,[n]:{handler:i,filter:r}}};await this.prefsController.update({app:o,data:c},t)}checkIfIntentHasMoreThanOneHandler(e,t){const r=t.handlers||e.handlers;if(!t.target)return r.length>1;if("reuse"===t.target)return r.filter(e=>"instance"===e.type&&e.instanceId).length>1||e.handlers.filter(e=>"app"===e.type).length>1;if("startNew"===t.target)return r.filter(e=>"app"===e.type).length>1;if(t.target.instance)return!1;if(t.target.app){const e=t.target.app;return r.filter(t=>t.applicationName===e&&t.instanceId).length>1}return!1}checkIfResolverShouldBeOpenedForRaise(e,t,r,n){if(!this.checkIfIntentHasMoreThanOneHandler(e,t))return{open:!1,reason:"Raised intent has only one handler"};if(n?.enabled)return{open:!0};const i=this.checkIfResolverShouldBeOpenByResolverConfig(r);return i.open?{open:!0}:i}checkIfResolverShouldBeOpenedForFilterHandlers(e,t,r,n){return 1===e.length?{open:!1,reason:`There's only one valid intent handler for filter ${JSON.stringify(t)}`}:!1===t.openResolver?{open:!1,reason:"Intents resolver is disabled by IntentHandler filter"}:n?.enabled?{open:!0}:this.checkIfResolverShouldBeOpenByResolverConfig(r)}checkIfResolverShouldBeOpenByResolverConfig(e){if(!e.enabled)return{open:!1,reason:"Intent Resolver is disabled. Raising intent to first found handler"};return this.glueController.clientGlue.appManager.application(e.appName)?{open:!0}:{open:!1,reason:`Application with name ${e.appName} not found`}}async filterHandlers(e,t,r,n){if(this.logger?.trace(`[${t}] Receive 'filterHandlers' command with request: ${JSON.stringify(e)}`),!r)return ioError.raiseError("Cannot preform 'filterHandlers' - callerId is not defined");const{filterHandlersRequest:i,resolverConfig:o,embeddedResolverConfig:s}=e,a=await this.getIntents(t),c=this.filterHandlersBy(a,i);if(!c?.length)return{handlers:[]};const{open:l,reason:u}=this.checkIfResolverShouldBeOpenedForFilterHandlers(c,i,o,s);if(!l)return this.logger?.trace(`[${t}] Intent Resolver UI won't be used. Reason: ${u}`),{handlers:c};const d=i.timeout||DEFAULT_PICK_HANDLER_BY_TIMEOUT_MS;if(s?.enabled)return this.logger?.trace(`[${t}] Handling 'filterHandlers' with embedded intent resolver`),PromiseWrap(()=>this.handleFilterHandlersWithEmbeddedResolver({commandId:t,handlerFilter:i,initialCaller:s.initialCaller,timeout:d}),d,`${ERRORS.TIMEOUT_HIT} - waited ${d}ms for 'filterHandlers' to resolve`);const h={instanceId:void 0};return{handlers:[await PromiseWrap(()=>this.legacyResolverController.startResolverApp({request:i,resolverConfig:o,commandId:t,callerId:this.getCallerIdByCallerType(r,n),resolverInstance:h,method:"filterHandlers"}),d,`Timeout of ${d}ms hit for 'filterHandlers' request with filter: ${JSON.stringify(e.filterHandlersRequest)}`)]}}async handleFilterHandlersWithEmbeddedResolver({commandId:e,handlerFilter:t,initialCaller:r,timeout:n}){const i={commandId:e,config:{handlerFilter:t,timeout:n},methodResponseTimeoutMs:n,initialCaller:r},o=await this.uiController.openResolver(i);o.isClosed&&ioError.raiseError(`${ERRORS.USER_CANCELLED}`),o.isExpired&&ioError.raiseError(`${ERRORS.TIMEOUT_HIT} - waited ${n}ms for user to choose an intent handler`);const{handler:s,intent:a}=o.userChoice??{};if(!s)return ioError.raiseError(`${ERRORS.HANDLER_NOT_FOUND}`);if(!a)return ioError.raiseError(`${ERRORS.INTENT_NOT_FOUND} for handlerFilter: ${JSON.stringify(t)}`);if(!!o.userChoice?.userSettings.preserveChoice)try{this.logger?.trace(`[${e}] - User wants to preserve the chosen of handler: ${JSON.stringify(s)}`);const n={applicationNames:t.applicationNames,contextTypes:t.contextTypes,resultType:t.resultType};await this.preserveUserChoice({initialCaller:r,commandId:e,handler:s,intentName:a,filter:n})}catch(t){this.logger?.warn(`[${e}] - Prefs API threw the following error: ${t}. Handler won't be preserved`)}return{handlers:[s]}}filterHandlersBy(e,t){const r=e.filter(e=>{if(!t.intent||t.intent===e.name){if(t.excludeList&&(e.handlers=this.excludeIntentHandlers(e,t.excludeList)),t.resultType){const r=e.handlers.filter(e=>e.resultType&&e.resultType===t.resultType);if(!r.length)return;e.handlers=r}if(t.contextTypes){const r=e.handlers.filter(e=>t.contextTypes?.every(t=>e.contextTypes?.includes(t)));if(!r.length)return;e.handlers=r}if(t.applicationNames){const r=e.handlers.filter(e=>t.applicationNames?.includes(e.applicationName));if(!r.length)return;e.handlers=r}return e}}),n=r.map(e=>e.handlers).flat(1);return n.filter((e,t)=>t===n.findIndex(t=>e.instanceId?e.instanceId===t.instanceId:!t.instanceId&&t.applicationName===e.applicationName))}excludeIntentHandlers(e,t){return e.handlers.filter(e=>!t.some(t=>"applicationName"in t?t.applicationName===e.applicationName:"instanceId"in t&&t.instanceId===e.instanceId))}async getIntentsByHandler(e,t){this.logger?.log(`[${t}] - Receive 'getIntents' command with request: ${JSON.stringify(e)}`);const r=runDecoderWithIOError(intentHandlerDecoder,e),n=await this.getIntents(t);clearNullUndefined(r),this.logger?.info(`[${t}] - extracting valid intents for the passed handler`);const i=this.extractIntentsWithInfoByHandler(n,r);return this.logger?.info(`[${t}] - returning intents for handler ${JSON.stringify(e)}`),{intents:i}}isHandlerValid(e,t){return Object.keys(e).every(r=>"contextTypes"===r?e.contextTypes?.every(e=>t.contextTypes?.includes(e)):t[r]===e[r])}extractIntentsWithInfoByHandler(e,t){return e.reduce((e,r)=>(r.handlers.forEach(n=>{if(!this.isHandlerValid(t,n))return;const i={intent:r.name,contextTypes:n.contextTypes,description:n.applicationDescription,displayName:n.displayName,icon:n.applicationIcon,resultType:n.resultType};e.push(i)}),e),[])}getCallerIdByCallerType(e,t){return"plugin"===t?this.glueController.me.instance??"":e}}const channelOperationDecoder=oneOf$1(constant$2("appHello"),constant$2("addChannel"),constant$2("removeChannel"),constant$2("operationCheck"),constant$2("getMyChannel"),constant$2("getWindowIdsOnChannel"),constant$2("getWindowIdsWithChannels"),constant$2("joinChannel"),constant$2("restrict"),constant$2("getRestrictions"),constant$2("restrictAll"),constant$2("notifyChannelsChanged"),constant$2("leaveChannel"),constant$2("requestChannelSelector"),constant$2("getMode")),leaveChannelDecoder=object$3({windowId:nonEmptyStringDecoder$2,channelName:optional$3(nonEmptyStringDecoder$2)}),channelsChangedDecoder=object$3({windowId:nonEmptyStringDecoder$2,channelNames:array$3(nonEmptyStringDecoder$2)}),modeDecoder=oneOf$1(constant$2("single"),constant$2("multi")),getChannelsModeDecoder=object$3({mode:modeDecoder}),channelFDC3DisplayMetadataDecoder=object$3({color:optional$3(nonEmptyStringDecoder$2),icon:optional$3(nonEmptyStringDecoder$2),name:optional$3(nonEmptyStringDecoder$2),glyph:optional$3(nonEmptyStringDecoder$2)}),channelFdc3MetaDecoder=object$3({id:nonEmptyStringDecoder$2,displayMetadata:optional$3(channelFDC3DisplayMetadataDecoder)}),channelMetaDecoder=object$3({color:nonEmptyStringDecoder$2,fdc3:optional$3(channelFdc3MetaDecoder)}),channelDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,meta:channelMetaDecoder,data:optional$3(anyJson$2())}),removeChannelDataDecoder=object$3({name:nonEmptyStringDecoder$2}),getMyChanelResultDecoder=object$3({channel:optional$3(nonEmptyStringDecoder$2)}),getWindowIdsOnChannelDataDecoder=object$3({channel:nonEmptyStringDecoder$2}),getWindowIdsOnChannelResultDecoder=object$3({windowIds:array$3(nonEmptyStringDecoder$2)}),getWindowIdsWithChannelsResultDecoder=object$3({windowIdsWithChannels:array$3(object$3({application:nonEmptyStringDecoder$2,channel:optional$3(nonEmptyStringDecoder$2),windowId:nonEmptyStringDecoder$2}))}),windowWithChannelFilterDecoder=object$3({application:optional$3(nonEmptyStringDecoder$2),channels:optional$3(array$3(nonEmptyStringDecoder$2)),windowIds:optional$3(array$3(nonEmptyStringDecoder$2))}),wrappedWindowWithChannelFilterDecoder=object$3({filter:optional$3(windowWithChannelFilterDecoder)}),joinChannelDataDecoder=object$3({channel:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2}),channelRestrictionConfigWithWindowIdDecoder=object$3({name:nonEmptyStringDecoder$2,read:boolean$4(),write:boolean$4(),windowId:nonEmptyStringDecoder$2}),restrictionConfigDataDecoder=object$3({config:channelRestrictionConfigWithWindowIdDecoder}),getRestrictionsDataDecoder=object$3({windowId:nonEmptyStringDecoder$2}),restrictionsConfigDecoder=object$3({read:boolean$4(),write:boolean$4(),windowId:nonEmptyStringDecoder$2}),restrictAllDataDecoder=object$3({restrictions:restrictionsConfigDecoder}),channelRestrictionsDecoder=object$3({name:nonEmptyStringDecoder$2,read:boolean$4(),write:boolean$4(),windowId:optional$3(nonEmptyStringDecoder$2)}),restrictionsDecoder=object$3({channels:array$3(channelRestrictionsDecoder)}),requestChannelSelectorConfigDecoder=object$3({windowId:nonEmptyStringDecoder$2,channelsNames:array$3(nonEmptyStringDecoder$2)}),appHelloDataDecoder=object$3({windowId:nonEmptyStringDecoder$2}),appHelloSuccessDecoder=object$3({mode:modeDecoder,channels:array$3(nonEmptyStringDecoder$2),restrictions:array$3(channelRestrictionsDecoder)});class ChannelsController{glueController;sessionController;workspacesController;mode;operations={appHello:{name:"appHello",dataDecoder:appHelloDataDecoder,execute:this.handleAppHello.bind(this),resultDecoder:appHelloSuccessDecoder},addChannel:{name:"addChannel",execute:this.addChannel.bind(this),dataDecoder:channelDefinitionDecoder},removeChannel:{name:"removeChannel",execute:this.removeChannel.bind(this),dataDecoder:removeChannelDataDecoder},getMyChannel:{name:"getMyChannel",execute:async()=>{},resultDecoder:getMyChanelResultDecoder},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",execute:this.handleGetWindowIdsOnChannel.bind(this),dataDecoder:getWindowIdsOnChannelDataDecoder,resultDecoder:getWindowIdsOnChannelResultDecoder},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",execute:this.handleGetWindowIdsWithChannels.bind(this),dataDecoder:wrappedWindowWithChannelFilterDecoder,resultDecoder:getWindowIdsWithChannelsResultDecoder},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},joinChannel:{name:"joinChannel",dataDecoder:joinChannelDataDecoder,execute:this.handleJoinChannel.bind(this)},restrict:{name:"restrict",dataDecoder:restrictionConfigDataDecoder,execute:this.restrict.bind(this)},getRestrictions:{name:"getRestrictions",dataDecoder:getRestrictionsDataDecoder,execute:this.getRestrictions.bind(this),resultDecoder:restrictionsDecoder},restrictAll:{name:"restrictAll",dataDecoder:restrictAllDataDecoder,execute:this.restrictAll.bind(this)},notifyChannelsChanged:{name:"notifyChannelsChanged",execute:this.handleChannelsChanged.bind(this),dataDecoder:channelsChangedDecoder},leaveChannel:{name:"leaveChannel",dataDecoder:leaveChannelDecoder,execute:this.handleLeaveChannel.bind(this)},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:requestChannelSelectorConfigDecoder,execute:this.handleRequestChannelSelector.bind(this)},getMode:{name:"getMode",resultDecoder:getChannelsModeDecoder,execute:this.handleGetMode.bind(this)}};constructor(e,t,r){this.glueController=e,this.sessionController=t,this.workspacesController=r}get logger(){return logger.get("channels.controller")}async start(e){const t=e.channels.definitions;this.logger?.trace("initializing channels"),this.mode=e.channels.mode,this.logger?.trace(`initializing channels with mode: ${this.mode}`),await this.setupChannels(t),this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){const t=e.data,r=e.commandId,n=e.callerId,i=channelOperationDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This channels request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`Channels request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`Channels request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}handleClientUnloaded(e,t){this.logger?.trace(`[${e}] - Received client unloaded event for windowId: ${e}`);this.sessionController.getEjectedWindowIds().includes(e)?this.logger?.trace(`[${e}] - A workspace window with ID ${e} is being ejected or brought back to workspace. Keeping track of it.`):t&&!t.closed||(this.sessionController.removeEjectedWindowId(e),this.sessionController.removeWindowChannelData(e),this.logger?.trace(`[${e}] - Client unloaded event processed. Removed from Session Storage successfully`))}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleAppHello({windowId:e},t){this.logger?.trace(`[${t}] - Received 'appHello' message for window with ID: ${e}`);this.checkIfValidWindowOrInteropInstanceId(e)||ioError.raiseError(`[${t}] - Cannot complete 'appHello' operation - received invalid window ID: ${e}`);const r=this.sessionController.getWindowChannelData(e);return this.logger?.trace(`[${t}] - Session data for window with ID ${e}: ${JSON.stringify(r)}`),{mode:this.mode,channels:r?.channels||[],restrictions:r?.restrictions||[]}}async handleLeaveChannel(e,t){this.trace(`[${t}] handling leaveChannel command with windowId: ${e.windowId}`,t);this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'leaveChannel' operation - received invalid window ID: ${e.windowId}`),this.removeChannelsFromSessionStorage(e.windowId,e.channelName),await this.glueController.callWindow("channels",this.operations.leaveChannel,e,{instance:e.windowId}),this.trace(`[${t}] successfully left the channel on window with ID "${e.windowId}"`,t)}removeChannelsFromSessionStorage(e,t){const r=this.sessionController.getWindowChannelData(e);if(!r?.channels?.length)return void this.logger?.trace(`No channels data found for window with id: ${e}, nothing to remove`);const n=t?r.channels.filter(e=>e!==t):[];this.sessionController.setChannelsForWindow(e,n)}async setupChannels(e){await Promise.all(e.map(e=>this.addChannel(e)))}async addChannel(e,t){this.trace(`[${t}] handling addChannel command with a valid name: ${e.name}, color: ${e.meta.color} and data: ${JSON.stringify(e.data)}`,t);const r={name:e.name,meta:e.meta,data:e.data||{}},n=this.createContextName(r.name);this.trace(`[${t}] setting a new channel context with name: ${n}`,t),await this.glueController.setContext(n,r),this.trace(`[${t}] channel context with name: ${n} created successfully`,t)}async removeChannel({name:e},t){this.trace(`[${t}] handling removeChannel command with a valid name: ${e}`,t);const r=this.createContextName(e);await this.glueController.destroyContext(r),this.trace(`[${t}] channel context with name: ${r} destroyed successfully`,t)}async getWindowChannel(e,t){if(!await this.checkIfAppHelloSupported(e))return this.trace(`[${t}] client is outdated and does not support platform session storage, falling back to window call`,t),this.glueController.callWindow("channels",this.operations.getMyChannel,{},{instance:e});const r=this.sessionController.getWindowChannelData(e),n=r?.channels?.[0];return{channel:n}}async handleGetWindowIdsOnChannel({channel:e},t){this.trace(`[${t}] handling getWindowIdsOnChannel command with channel: ${e}`,t);const r=this.glueController.getLocalServers().reduce((e,{windowId:t})=>t?[...e,t]:e,[]);this.trace(`[${t}] compiled a list of the IDs of all the windows that will be called: [${r.join(", ")}]`,t);const n=await Promise.all(r.map(async e=>{const{channel:r}=await this.getWindowChannel(e,t);return{channel:r,windowId:e}})),i=n.filter(t=>t.channel===e).map(({windowId:e})=>e);return this.trace(`[${t}] compiled a list of all windowIds that are on the "${e}" channel and returning it to the caller: [${i.join(", ")}]`,t),{windowIds:i}}async handleGetWindowIdsWithChannels({filter:e},t){this.trace(`[${t}] handling getWindowIdsWithChannels command with filter: ${JSON.stringify(e)}`,t);const r=this.glueController.getLocalServers(),n=this.glueController.getAllApplicationNames(),i=r.filter(({windowId:e})=>e);this.trace(`[${t}] compiled a list of the IDs of all the windows that will be called: [${i.map(({windowId:e})=>e).join(", ")}]`,t);const o=await Promise.all(i.map(async({applicationName:e,windowId:r})=>{const{channel:i}=await this.getWindowChannel(r,t);return{application:e&&n.includes(e)?e:"no-app-window",...i?{channel:i}:{},windowId:r}}));let s=o;return e?(e.application&&(this.trace(`[${t}] filtering windows by application: ${e.application}`,t),s=s.filter(({application:t})=>t===e.application)),e.channels&&(this.trace(`[${t}] filtering windows by channels: [${e.channels.join(", ")}]`,t),s=s.filter(({channel:t})=>t&&e.channels?.includes(t))),e.windowIds&&(this.trace(`[${t}] filtering windows by windowIds: [${e.windowIds.join(", ")}]`,t),s=s.filter(({windowId:t})=>e.windowIds?.includes(t))),this.trace(`[${t}] compiled a list of all windowIds with channels and returning it to the caller: ${JSON.stringify(s)}`,t),{windowIdsWithChannels:s}):(this.trace(`[${t}] compiled a list of all windowIds with channels and returning it to the caller: ${JSON.stringify(s)}`,t),{windowIdsWithChannels:s})}async handleChannelsChanged(e,t){this.trace(`[${t}] handling notifyChannelsChanged command with data: ${JSON.stringify(e)}`,t),this.glueController.pushSystemMessage("windows","notifyChannelsChanged",e),this.trace(`[${t}] successfully notified all windows about the channel change`,t)}async handleRequestChannelSelector(e,t){this.trace(`[${t}] handling requestChannelSelector command with windowId: ${e.windowId} and initial channels: ${e.channelsNames?.join(", ")}`,t);const r=this.sessionController.getWorkspaceClientById(e.windowId);if(!r)return ioError.raiseError(`Failed to display channel selector on window with ID "${e.windowId}", because the provided windowId is not a workspace window.`);await this.workspacesController.showChannelsLink({windowId:r.windowId,frameId:r.frameId,channelsNames:e.channelsNames},t),this.trace(`[${t}] successfully notified all windows about the channel change`,t)}async handleGetMode(){return{mode:this.mode}}async handleJoinChannel({channel:e,windowId:t},r){this.trace(`[${r}] handling joinChannel command with channel: ${e} and windowId: ${t}`,r);this.checkIfValidWindowOrInteropInstanceId(t)||ioError.raiseError(`[${r}] - Cannot complete 'joinChannel' operation - received invalid window ID: ${t}`),"single"===this.mode?this.sessionController.setChannelsForWindow(t,[e]):this.sessionController.setAdditionalChannelForWindow(t,e),await this.glueController.callWindow("channels",this.operations.joinChannel,{channel:e,windowId:t},{instance:t}),this.trace(`[${r}] successfully joined "${e}" channel on window with ID "${t}"`,r)}createContextName(e){return`${ChannelContextPrefix}${e}`}trace(e,t){t&&this.logger?.trace(e)}async restrict({config:e},t,r){this.trace(`[${t}] received restrict command with config ${JSON.stringify(e)} from callerId: ${r}`,t);this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'restrict' operation - received invalid window ID: ${e.windowId}`),this.sessionController.addChannelRestrictionsByWindowId(e.windowId,e),await this.glueController.callWindow("channels",this.operations.restrict,{config:e},{instance:e.windowId})}async getRestrictions({windowId:e},t,r){this.trace(`[${t}] received getRestrictions command for window with id ${e} from callerId: ${r}`,t);this.checkIfValidWindowOrInteropInstanceId(e)||ioError.raiseError(`[${t}] - Cannot complete 'getRestrictions' operation - received invalid window ID: ${e}`);if(!await this.checkIfAppHelloSupported(e))return this.logger?.trace(`[${t}] - Client's restrictions are saved in its own session storage. Calling it to get restrictions.`),this.glueController.callWindow("channels",this.operations.getRestrictions,{windowId:e},{instance:e});const n=this.sessionController.getWindowChannelData(e);return{channels:n?.restrictions||[]}}async restrictAll({restrictions:e},t,r){this.trace(`[${t}] received restrictAll command with config ${JSON.stringify(e)} from callerId: ${r}`,t);return this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'restrictAll' operation - received invalid window ID: ${e.windowId}`),this.addAllChannelRestrictionsInSessionStorage(e.windowId,e),this.glueController.callWindow("channels",this.operations.restrictAll,{restrictions:e},{instance:e.windowId})}addAllChannelRestrictionsInSessionStorage(e,t){const r=this.glueController.getAllContexts().filter(e=>e.startsWith(ChannelContextPrefix)).map(e=>e.replace(ChannelContextPrefix,"")),n=r.map(e=>({name:e,...t}));this.sessionController.addAllChannelsRestrictionsByWindowId(e,n)}checkIfValidWindowOrInteropInstanceId(e){if(this.glueController.isValidWindowId(e))return!0;if(this.glueController.platformWindowId===e)return!0;return!!this.glueController.getLocalServers().some(t=>t.instance===e)}async checkIfAppHelloSupported(e){try{return(await this.glueController.checkClientOperationSupport("channels",this.operations.appHello,{instance:e})).isSupported}catch(t){return this.logger?.trace(`Client with windowId: ${e} does NOT support 'appHello' message.`),!1}}}class FramesController{sessionController;glueController;ioc;config;defaultBounds;frameSummaryOperation;locks={};defaultFrameHelloTimeoutMs=15e3;_handleUnload;constructor(e,t,r){this.sessionController=e,this.glueController=t,this.ioc=r}get myFrameId(){return this.glueController.platformWindowId}stop(){this._handleUnload&&window.removeEventListener("pagehide",this._handleUnload)}async start(e,t,r){this.config=e,this.defaultBounds=t,this.frameSummaryOperation=r}async openFrame(e,t){const r="object"==typeof e?e.bounds??{}:{},n=r.top??this.defaultBounds.top,i=r.left??this.defaultBounds.left,o=r.width??this.defaultBounds.width,s=r.height??this.defaultBounds.height,a="object"==typeof e&&e?.frameId?e.frameId:`g42-${nanoid$5(10)}`;if(this.sessionController.getAllFrames().some(e=>e.windowId===a))return ioError.raiseError(`Cannot open a frame with id: ${a}, because a frame with this id already exists`);const c={windowId:a,active:!1,isPlatform:!1,layoutComponentId:t},l=`left=${i},top=${n},width=${o},height=${s}`,u=(await this.getWorkspacesUrls()).workspacesUrl.current,d=u.includes("?")?`${u}&emptyFrame=true`:`${u}?emptyFrame=true`;if(!window.open(d,c.windowId,l))return ioError.raiseError("Cannot open a new workspace frame, because the user has not allowed popups or uses a blocker");this.sessionController.saveFrameData(c);try{return await this.waitHello(c.windowId),{windowId:c.windowId}}catch(e){return delete this.locks[c.windowId],ioError.raiseError("Cannot open a new frame, because the workspace frame app did not send a hello in time")}}async closeFrame(e){if(this.myFrameId===e)return ioError.raiseError("Cannot close the platform frame, because it is the current frame");this.sessionController.getFrameData(e)&&(this.handleFrameDisappeared(e),window.open(void 0,e)?.close())}processNewHello(e){this.sessionController.getFrameData(e)&&(this.sessionController.setFrameActive(e),this.locks[e]?.lift())}handleFrameDisappeared(e){this.sessionController.getFrameData(e)&&(this.sessionController.removeFrameData(e),this.clearAllWorkspaceWindows(e))}getAll(){return this.sessionController.getAllFrames().filter(e=>e.active).map(e=>({windowId:e.windowId}))}async getFrameInstance(e){if(e){if(["frameId","itemId","newFrame"].reduce((t,r)=>(e[r]&&t.push(r),t),[]).length>1)return ioError.raiseError(`Cannot retrieve the frame, because of over-specification: the provided selection object must have either 1 or none of the possible properties: ${JSON.stringify(e)}`)}const t=this.getAll();if(e?.frameId){const r=t.find(t=>t.windowId===e.frameId);return r||ioError.raiseError(`Cannot retrieve a frame with Id: ${e.frameId}, because it is not known by the platform`)}return e?.itemId?this.getFrameByItemId(e.itemId,t):e?.newFrame?this.openFrame(e.newFrame):t.length?this.getLastOpenedFrame():this.openFrame()}getPlatformFrameSessionData(){return this.sessionController.getAllFrames().find(e=>e.isPlatform)}getFrameConfig(e){return this.sessionController.getAllFrames().find(t=>t.windowId===e)}clearAllWorkspaceWindows(e){this.sessionController.pickWorkspaceClients(t=>t.frameId===e).forEach(e=>{this.ioc.applicationsController.unregisterWorkspaceApp({windowId:e.windowId})})}async waitHello(e){return PromisePlus(t=>{this.locks[e]={lift:t}},this.defaultFrameHelloTimeoutMs,"Frame hello timed out")}getLastOpenedFrame(){const e=this.sessionController.getAllFrames().filter(e=>e.active);return e[e.length-1]}async getFrameByItemId(e,t){if(!t.length)return ioError.raiseError(`Cannot get frame by item id for: ${e}, because not frames were found`);for(const r of t){if("none"!==(await this.glueController.callFrame(this.frameSummaryOperation,{itemId:e},r.windowId)).id)return r}return ioError.raiseError(`Cannot find frame for item: ${e}`)}getWorkspacesUrls(){return new URL(window.location.href).protocol.includes("extension")?new Promise(e=>{chrome.storage.local.get("workspacesUrl",t=>{e(t)})}):Promise.resolve({workspacesUrl:{current:this.config.src,default:this.config.src}})}}class WorkspaceHibernationWatcher{session;sequelizer;workspacesController;settings;running;constructor(e,t){this.session=e,this.sequelizer=t}get logger(){return logger.get("workspaces.hibernation")}stop(){this.running=!1}start(e,t){this.logger?.trace(`starting the hibernation watcher with following settings: ${JSON.stringify(this.settings)}`),this.running=!0,this.workspacesController=e,this.settings=t;const r=this.session.exportClearTimeouts();this.settings?.idleWorkspaces?.idleMSThreshold&&r.forEach(e=>this.buildTimer(e.workspaceId)),this.logger?.trace("The hibernation watcher has started successfully")}notifyEvent(e){"window"===e.type&&this.handleWorkspaceWindowEvent(e),"workspace"===e.type&&this.handleWorkspaceEvent(e)}handleWorkspaceWindowEvent(e){("opened"===e.action||"added"===e.action)&&(this.sequelizer.enqueue(()=>this.checkMaximumAmountCore()),this.addTimersForWorkspacesInFrame(e.payload.windowSummary.config.frameId))}handleWorkspaceEvent(e){const t="selected"===e.action,r="lock-configuration-changed"===e.action,n=e.payload;if(!("selected"===e.action||"opened"===e.action||"lock-configuration-changed"===e.action))return;this.sequelizer.enqueue(()=>this.checkMaximumAmountCore());const i=n.workspaceSummary.config.allowSystemHibernation;if(!(t||r&&i))return;const o=this.session.getTimeout(n.workspaceSummary.id);o&&(clearTimeout(o),this.session.removeTimeout(n.workspaceSummary.id)),this.addTimersForWorkspacesInFrame(n.frameSummary.id)}compare(e,t){return e.config.lastActive>t.config.lastActive?1:e.config.lastActivethis.workspacesController.getWorkspaceSnapshot({itemId:e.id},t)),n=(await Promise.all(r)).filter(e=>!this.isWorkspaceHibernated(e.config)&&!this.isWorkspaceEmpty(e)),i=n.filter(e=>this.isSystemHibernationAllowed(e));if(n.length<=e)return;this.logger?.trace(`Found ${i.length} eligible for hibernation workspaces`);const o=i.sort(this.compare).slice(0,n.length-e).map(e=>this.tryHibernateWorkspace(e.id));await Promise.all(o)}async tryHibernateWorkspace(e){try{const t=await this.workspacesController.getWorkspaceSnapshot({itemId:e},nanoid$5(10));if(!this.canBeHibernated(t))return;this.logger?.trace(`trying to hibernate workspace ${e}`),await this.workspacesController.hibernateWorkspace({workspaceId:e},nanoid$5(10)),this.logger?.trace(`workspace ${e} was hibernated successfully`)}catch(e){this.logger?.trace(e)}}canBeHibernated(e){const t=this.isWorkspaceHibernated(e.config),r=this.isWorkspaceSelected(e.config),n=this.isWorkspaceEmpty(e),i=this.isSystemHibernationAllowed(e);return!t&&!r&&!n&&i}isWorkspaceHibernated(e){return e.isHibernated}isWorkspaceSelected(e){return e.isSelected}isWorkspaceEmpty(e){return!e.children.length}isSystemHibernationAllowed(e){const{allowSystemHibernation:t}=e.config;return"boolean"!=typeof t||t}async getWorkspacesInFrame(e){const t=(await this.workspacesController.getAllWorkspacesSummaries({},nanoid$5(10))).summaries.reduce((t,r)=>(r.config.frameId===e&&t.push(this.workspacesController.getWorkspaceSnapshot({itemId:r.id},nanoid$5(10))),t),[]);return await Promise.all(t)}async addTimersForWorkspacesInFrame(e){if(!this.settings?.idleWorkspaces?.idleMSThreshold)return;(await this.getWorkspacesInFrame(e)).forEach(e=>{this.canBeHibernated(e)&&!this.session.getTimeout(e.id)&&(this.buildTimer(e.id),this.logger?.trace(`Starting workspace idle timer ( ${this.settings?.idleWorkspaces?.idleMSThreshold}ms ) for workspace ${e.id}`))})}buildTimer(e){const t=window.setTimeout(()=>{this.running&&(this.logger?.trace(`Timer triggered will try to hibernated ${e}`),this.tryHibernateWorkspace(e),this.session.removeTimeout(e))},this.settings?.idleWorkspaces?.idleMSThreshold);this.session.saveTimeout(e,t)}}class SystemController{session;workspacesController;glueController;pluginsController;profileData;environment;base={};started=!1;errorPort=errorChannel.port2;registry=CallbackRegistryFactory$2();platformOperations=["cleanupClientsOnWorkspaceFrameUnregister"];operations={getEnvironment:{name:"getEnvironment",resultDecoder:anyDecoder,execute:this.handleGetEnvironment.bind(this)},getBase:{name:"getBase",resultDecoder:anyDecoder,execute:this.handleGetBase.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},workspacesInitCheck:{name:"workspacesInitCheck",resultDecoder:workspacesInitCheckResultDecoder,execute:this.handleWorkspacesInitCheck.bind(this)},clientError:{name:"clientError",dataDecoder:clientErrorDataDecoder,execute:this.handleClientError.bind(this)},systemHello:{name:"systemHello",resultDecoder:systemHelloSuccessDecoder,execute:this.handleSystemHello.bind(this)},getProfileData:{name:"getProfileData",execute:this.handleGetProfileData.bind(this)}};constructor(e,t,r,n){this.session=e,this.workspacesController=t,this.glueController=r,this.pluginsController=n}get logger(){return logger.get("system.controller")}handlePlatformShutdown(){this.started=!1,this.registry.clear()}async start(e){this.environment=e.environment,this.base={workspaces:{frameCache:e.workspacesFrameCache},workspacesFrameCache:e.workspacesFrameCache,communicationId:this.session.getSystemSettings()?.systemInstanceId,platformVersion:version$1,connectionProtocolVersion:connectionProtocolVersion,fdc3:{webProxyUrl:FDC3ProxyUrl}},this.profileData=e.profileData,this.errorPort.onmessage=e=>{this.registry.execute("platform-error",{message:e.data})},this.started=!0}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this system control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=systemOperationTypesDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This system request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`System request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`System request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}onPlatformError(e){return this.registry.add("platform-error",e)}onClientError(e){return this.registry.add("client-error",e)}setProfileData(e){this.profileData=e}async handleOperationCheck(e){const t=Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase()),r=this.platformOperations.some(t=>t.toLowerCase()===e.operation.toLowerCase());return{isSupported:t||r}}async handleGetEnvironment(){return this.environment}async handleGetProfileData(){if(!this.profileData)return;return{...this.profileData,plugins:this.pluginsController.registeredPlugins.map(e=>({name:e.name,version:e.version}))}}async handleGetBase(){return this.base}async handleWorkspacesInitCheck(){return{initialized:this.workspacesController.started}}async handleClientError({message:e},t,r){this.logger?.trace(`[${t}] received clientError command with message ${e} from callerId: ${r}`),this.glueController.clientGlue?r&&r===this.glueController.me.instance?this.registry.execute("platform-error",{message:e}):this.registry.execute("client-error",{message:e,callerId:r}):this.registry.execute("platform-error",{message:e})}async handleSystemHello(){return{isClientErrorOperationSupported:!0}}}class AppDirectory{remoteWatcher;manager;cache;unsubFuncs=[];maxAllowedApplicationsInStore=1e4;baseEventFlushDurationMs=10;appsStateChange;sequelizer;isManagerConfigured;constructor(e,t,r){this.remoteWatcher=e,this.manager=t,this.cache=r}stop(){this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[]}async start(e){if(this.logger?.trace("Starting the application directory"),this.appsStateChange=e.appsStateChange,this.sequelizer=e.sequelizer,await this.cache.start(e.config.remote),e.config.local?.length&&(this.logger?.trace("Detected local applications, parsing..."),await this.processAppDefinitions(e.config.local,{type:"inmemory",mode:"merge"})),e.isManagerConfigured&&(this.isManagerConfigured=e.isManagerConfigured,this.setupManagerListeners(),this.logger?.trace("Detected manager configuration, starting the watcher...")),e.config.remote){this.logger?.trace("Detected remote app store configuration, starting the watcher...");try{await this.remoteWatcher.start(e.config.remote,e=>this.processAppDefinitions(e,{type:"remote",mode:"replace"}))}catch(e){return this.handleRemoteConnectionFailure(e)}}}processAppDefinitions(e,t){return this.sequelizer.enqueue(async()=>{const r=e.map(e=>this.parseDefinition(e)),n=[...await this.cache.getAllRemoteApps(),...await this.cache.getAllMemoryApps()],i=this[t.mode](n,r);if(i.readyApps.length>this.maxAllowedApplicationsInStore)return ioError.raiseError("Cannot save the app definitions, because the total number exceeds 10000, which is the limit.");const o="remote"===t.type?this.cache.saveRemoteApps.bind(this.cache):this.cache.saveMemoryApps.bind(this.cache);await o(i.readyApps),await this.announceApps(i)})}getAll(){return this.sequelizer.enqueue(async()=>{const e=new Map,t=await this.cache.getAllMemoryApps(),r=await this.cache.getAllRemoteApps(),n=this.isManagerConfigured?this.manager.getAllApps().map(this.parseDefinition):[];return r.forEach(t=>e.set(t.name,t)),n.forEach(t=>e.set(t.name,t)),t.forEach(t=>e.set(t.name,t)),Array.from(e.values())})}exportInMemory(){return this.sequelizer.enqueue(async()=>(await this.cache.getAllMemoryApps()).map(this.reverseParseDefinition))}removeInMemory(e){return this.sequelizer.enqueue(async()=>this.cache.removeMemoryApp(e))}merge(e,t){const r={readyApps:[],addedApps:[],changedApps:[],removedApps:[]},n=e.reduce((e,t)=>(e[t.name]=t,e),{});return t.forEach(e=>n[e.name]&&!objEqualFast(e,n[e.name])?(n[e.name]=e,void r.changedApps.push(e)):n[e.name]?void 0:(n[e.name]=e,void r.addedApps.push(e))),r.readyApps=Object.values(n),r}replace(e,t){const r={readyApps:[],addedApps:[],changedApps:[],removedApps:[]},n=e.reduce((e,t)=>(e[t.name]=t,e),{});return t.forEach(e=>{n[e.name]||r.addedApps.push(e),n[e.name]&&!objEqualFast(e,n[e.name])&&r.changedApps.push(e),n[e.name]&&(n[e.name].isChecked=!0)}),r.removedApps=e.filter(e=>!e.isChecked),r.readyApps=t,r}reverseParseDefinition(e){const t=e.userProperties.details,{details:r,...n}=e.userProperties,i={name:e.name,type:e.type||"window",title:e.title,version:e.version,icon:e.icon,caption:e.caption,details:t,customProperties:n};return e.fdc3&&(i.fdc3=e.fdc3),i}parseDefinition(e){const t=["name","title","version","customProperties","icon","caption","type"],r=Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))),{isFdc3:n}=fdc3.isFdc3Definition(e);let i;if(n)i=fdc3.parseToBrowserBaseAppData(e);else{const t=e.details;i={createOptions:t,type:e.type||"window",name:e.name,title:e.title,version:e.version,icon:e.icon,caption:e.caption,userProperties:{...r,...e.customProperties}},i.userProperties.details||(i.userProperties.details=t)}return Object.keys(i).forEach(e=>void 0===i[e]&&delete i[e]),i}get logger(){return logger.get("applications.remote.directory")}async announceApps(e){const t={appsAdded:e.addedApps,appsChanged:e.changedApps,appsRemoved:e.removedApps};this.logger?.trace(`announcing a change in the app directory state: ${JSON.stringify(t)}`),this.appsStateChange(t),await this.waitEventFlush()}setupManagerListeners(){const e=this.manager.onAppsAdded(e=>{this.announceApps({addedApps:e.map(this.parseDefinition),changedApps:[],removedApps:[],readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),t=this.manager.onAppsDeleted(e=>{this.announceApps({addedApps:[],changedApps:[],removedApps:e.map(this.parseDefinition),readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),r=this.manager.onAppsChanged(e=>{this.announceApps({addedApps:[],changedApps:e.map(this.parseDefinition),removedApps:[],readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))});this.unsubFuncs.push(e,t,r)}waitEventFlush(){return new Promise(e=>setTimeout(e,this.baseEventFlushDurationMs))}async handleRemoteConnectionFailure(e){const t=await this.cache.getAllRemoteApps();if(!t?.length)return ioError.raiseError(`The connection to the remote app store failed and there are no cached entries, cannot continue. Error: ${extractErrorMsg$1(e)}`);this.logger?.warn(`The connection to the remote app store failed, but there are cached entries, continuing with the cached apps. Error: ${extractErrorMsg$1(e)}`)}}const defaultRemoteWatcherHeaders={"Content-Type":"application/json",Accept:"application/json"},defaultRemoteWatcherRequestTimeoutMS=3e3,fetchTimeout=(e,t=defaultFetchTimeoutMs,r=new AbortController)=>new Promise((n,i)=>{const o={signal:r.signal};let s=!1;const a=setTimeout(()=>{s=!0,i(new Error(`Fetch request for: ${JSON.stringify(e)} timed out at: ${t} milliseconds`)),r.abort()},t);fetch(e,o).then(e=>{s||(clearTimeout(a),n(e))}).catch(e=>{s||(clearTimeout(a),i(e))})});class RemoteWatcher{scheduler;handleApps;config;constructor(e){this.scheduler=e}async start(e,t){this.handleApps=t,this.config=this.prepareConfig(e);const r=this.doInitialRequest();if(this.configureScheduler(),this.config.waitInitialResponse)return this.logger?.info("Waiting for the initial response from the remote app store before proceeding"),void await r;r.catch(e=>this.logger?.error("The initial request to the remote app store failed",e))}getRequest(){const e=new Headers;for(const t in defaultRemoteWatcherHeaders)e.append(t,defaultRemoteWatcherHeaders[t]);for(const t in this.config.customHeaders)this.logger?.trace("Custom headers detected and set"),e.append(t,this.config.customHeaders[t]);const t={method:"GET",headers:e,mode:"cors",cache:"default"},r=this.config.getRequestInit?.({url:this.config.url,requestInit:t});return new Request(this.config.url,{...t,...r})}get logger(){return logger.get("applications.remote.directory")}prepareConfig(e){const t={...e,requestTimeout:e.requestTimeout??defaultRemoteWatcherRequestTimeoutMS,customHeaders:e.customHeaders??{},getRequestInit:e.getRequestInit??(()=>({})),waitInitialResponse:e.waitInitialResponse??!0};return t.cache?.enabled&&!t.pollingInterval?ioError.raiseError("Polling interval is required when cache is enabled"):t.pollingInterval&&t.pollingInterval<5e3?ioError.raiseError("Polling interval must be at least 5000ms"):t}configureScheduler(){if(!this.config.pollingInterval)return void this.logger?.info("Polling interval is not set, skipping scheduler setup");const e="applications:get:all";if(this.scheduler.checkEntryExists(e))return;const t={key:e,getRequest:()=>this.getRequest(),timeout:this.config.requestTimeout,refreshIntervalMS:this.config.pollingInterval,onData:this.processGetAllAppsUpdate.bind(this),onError:e=>this.logger?.error("Error during get all application definitions from scheduler",e)};this.scheduler.register(t)}async processGetAllAppsUpdate(e){if(!e||!Array.isArray(e.applications))return this.logger?.warn("The remote response was either empty or did not contain an applications collection");this.logger?.trace("There is a valid response from the app store, processing definitions...");const t=e.applications.reduce((e,t)=>{const r=allApplicationDefinitionsDecoder.run(t);return r.ok?e.push(t):this.logger?.warn(`Removing applications definition with name: ${t.name} from the remote response, because of validation error: ${JSON.stringify(r.error)}`),e},[]);await this.handleApps(t)}async doInitialRequest(){try{const e=this.getRequest(),t=await fetchTimeout(e,this.config.requestTimeout),r=await t.json();await this.processGetAllAppsUpdate(r)}catch(e){return ioError.raiseError("Error during initial request to get all applications",e)}}}class ServiceWorkerController{idbController;registry=CallbackRegistryFactory$2();_serviceWorkerRegistration;channel;_broadcastMessageHandler;constructor(e){this.idbController=e}get logger(){return logger.get("service.worker.web.platform")}get serviceWorkerRegistration(){return this._serviceWorkerRegistration?this._serviceWorkerRegistration:ioError.raiseError("Accessing missing service worker registration object. This is caused because the application is trying to raise a persistent notification, which requires a service worker. Please provide a service worker config when initializing GlueWebPlatform.")}shutdown(){this.channel?.removeEventListener("message",this._broadcastMessageHandler),this.registry.clear()}async connect(e){if(e.serviceWorker){if(this.logger?.info("Detected service worker definition, connecting..."),!e.serviceWorker.url&&void 0===e.serviceWorker.registrationPromise)return ioError.raiseError("The service worker config is defined, but it is missing a url or a registration promise, please provide one or the other");if(e.serviceWorker.url&&void 0!==e.serviceWorker.registrationPromise)return ioError.raiseError("The service worker is over-specified, there is both defined url and a registration promise, please provide one or the other");await this.prepareSwDb(),this._serviceWorkerRegistration=e.serviceWorker.url?await this.registerWorker(e.serviceWorker.url):await this.waitRegistration(e.serviceWorker.registrationPromise),this._serviceWorkerRegistration&&this.setUpBroadcastChannelConnection(),this.logger?.info("Service worker connection completed.")}}async showNotification(e,t){const r=Object.assign({},e,{title:void 0,clickInterop:void 0,actions:void 0});r.actions=e.actions?.map(e=>({action:e.action,title:e.title,icon:e.icon}));const n={focusPlatformOnDefaultClick:e.focusPlatformOnDefaultClick,clickInterop:e.clickInterop,actions:e.actions,id:t};r.data?r.data.glueData=n:r.data={glueData:n},await this.serviceWorkerRegistration.showNotification(e.title,r)}notifyReady(){this._serviceWorkerRegistration&&this.channel.postMessage({platformStarted:!0})}onNotificationClick(e){return this.registry.add("notification-click",e)}onNotificationClose(e){return this.registry.add("notification-close",e)}setUpBroadcastChannelConnection(){this.channel=new BroadcastChannel(serviceWorkerBroadcastChannelName),this._broadcastMessageHandler=this.broadcastMessageHandler.bind(this),this.channel.addEventListener("message",this._broadcastMessageHandler)}broadcastMessageHandler(e){const t=e.data,r=t?.messageType;if(r)if("ping"!==r){if("notificationClick"===r){const e=t.action,r=t.glueData;return void this.registry.execute("notification-click",{action:e,glueData:r})}if("notificationClose"===r){const e=t.action,r=t.glueData;return void this.registry.execute("notification-close",{action:e,glueData:r})}"notificationError"!==r||this.logger?.error(`Service worker error when raising notification: ${t.error}`)}else this.channel.postMessage({pong:!0})}async registerWorker(e){if("serviceWorker"in navigator)try{return await navigator.serviceWorker.register(e)}catch(e){const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(t)}else this.logger?.warn(`A defined service worker has not been registered at ${e} because this browser does not support it.`)}async waitRegistration(e){if("function"!=typeof e.then||"function"!=typeof e.catch)return ioError.raiseError("The provided service worker registration promise is not a promise");const t=await e;return"function"!=typeof t.showNotification?ioError.raiseError("The provided registration promise is a promise, but it resolved with an object which does not appear to be a ServiceWorkerRegistration"):t}async prepareSwDb(){await this.idbController.clearServiceWorker(),await this.idbController.storeServiceWorker({platformUrl:window.location.href})}}const setNotificationDefaults=e=>{e.showToast="boolean"!=typeof e.showToast||e.showToast,e.showInPanel="boolean"!=typeof e.showInPanel||e.showInPanel,e.timestamp=void 0===e.timestamp?Date.now():e.timestamp,e.state=void 0===e.state?"Active":e.state},notificationsOperationDecoder=oneOf$1(constant$2("raiseNotification"),constant$2("requestPermission"),constant$2("getPermission"),constant$2("operationCheck"),constant$2("list"),constant$2("clear"),constant$2("click"),constant$2("clearAll"),constant$2("configure"),constant$2("getConfiguration"),constant$2("setState"),constant$2("clearOld"),constant$2("getActiveCount")),interopActionSettingsDecoder=object$3({method:nonEmptyStringDecoder$2,arguments:optional$3(anyJson$2()),target:optional$3(oneOf$1(constant$2("all"),constant$2("best")))}),glue42NotificationActionDecoder=object$3({action:string$5(),title:nonEmptyStringDecoder$2,icon:optional$3(string$5()),interop:optional$3(interopActionSettingsDecoder)}),notificationStateDecoder=oneOf$1(constant$2("Active"),constant$2("Acknowledged"),constant$2("Seen"),constant$2("Closed"),constant$2("Stale"),constant$2("Snoozed"),constant$2("Processing")),glue42NotificationOptionsDecoder=object$3({title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$4()),badge:optional$3(string$5()),body:optional$3(string$5()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$5()),image:optional$3(string$5()),lang:optional$3(string$5()),renotify:optional$3(boolean$4()),requireInteraction:optional$3(boolean$4()),silent:optional$3(boolean$4()),tag:optional$3(string$5()),timestamp:optional$3(nonNegativeNumberDecoder$2),vibrate:optional$3(array$3(number$5())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:optional$3(boolean$4()),showInPanel:optional$3(boolean$4()),state:optional$3(notificationStateDecoder)}),glue42NotificationOptionsWithDefaultsDecoder=object$3({title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$4()),badge:optional$3(string$5()),body:optional$3(string$5()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$5()),image:optional$3(string$5()),lang:optional$3(string$5()),renotify:optional$3(boolean$4()),requireInteraction:optional$3(boolean$4()),silent:optional$3(boolean$4()),tag:optional$3(string$5()),timestamp:nonNegativeNumberDecoder$2,vibrate:optional$3(array$3(number$5())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:boolean$4(),showInPanel:boolean$4(),state:optional$3(notificationStateDecoder)}),raiseNotificationDecoder=object$3({settings:glue42NotificationOptionsDecoder,id:nonEmptyStringDecoder$2}),raiseNotificationResultDecoder=object$3({settings:glue42NotificationOptionsWithDefaultsDecoder}),permissionRequestResultDecoder=object$3({permissionGranted:boolean$4()}),permissionQueryResultDecoder=object$3({permission:oneOf$1(constant$2("default"),constant$2("granted"),constant$2("denied"))}),simpleNotificationSelectDecoder=object$3({id:nonEmptyStringDecoder$2}),notificationClickConfigDecoder=object$3({id:nonEmptyStringDecoder$2,action:optional$3(nonEmptyStringDecoder$2)}),notificationsDataDecoder=object$3({id:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$4()),badge:optional$3(string$5()),body:optional$3(string$5()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$5()),image:optional$3(string$5()),lang:optional$3(string$5()),renotify:optional$3(boolean$4()),requireInteraction:optional$3(boolean$4()),silent:optional$3(boolean$4()),tag:optional$3(string$5()),timestamp:optional$3(nonNegativeNumberDecoder$2),vibrate:optional$3(array$3(number$5())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:optional$3(boolean$4()),showInPanel:optional$3(boolean$4()),state:optional$3(notificationStateDecoder)}),allNotificationsDataDecoder=object$3({notifications:array$3(notificationsDataDecoder)}),notificationsConfigurationDecoder=object$3({enable:optional$3(boolean$4()),enableToasts:optional$3(boolean$4()),sourceFilter:optional$3(notificationFilterDecoder),showNotificationBadge:optional$3(boolean$4())}),notificationsConfigurationProtocolDecoder=object$3({configuration:notificationsConfigurationDecoder}),notificationsActiveCountDecoder=object$3({count:number$5()}),notificationSetStateRequestDecoder=object$3({id:nonEmptyStringDecoder$2,state:notificationStateDecoder}),prefsNotificationsDecoder=object$3({config:notificationsConfigurationDecoder});class NotificationsController{glueController;serviceWorkerController;session;localStorage;prefsController;started=!1;isInExtension=!1;clearNotificationOnClick;extNotificationConfig;systemUnsubFuncs=[];_chromeClickedHandler;_chromeButtonClickedHandler;_chromeClosedHandler;operations={raiseNotification:{name:"raiseNotification",execute:this.handleRaiseNotification.bind(this),dataDecoder:raiseNotificationDecoder,resultDecoder:raiseNotificationResultDecoder},requestPermission:{name:"requestPermission",resultDecoder:permissionRequestResultDecoder,execute:this.handleRequestPermission.bind(this)},getPermission:{name:"getPermission",resultDecoder:permissionQueryResultDecoder,execute:this.handleGetPermission.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},list:{name:"list",resultDecoder:allNotificationsDataDecoder,execute:this.handleList.bind(this)},click:{name:"click",dataDecoder:notificationClickConfigDecoder,execute:this.handleClick.bind(this)},clear:{name:"clear",dataDecoder:simpleNotificationSelectDecoder,execute:this.handleClear.bind(this)},clearAll:{name:"clearAll",execute:this.handleClearAll.bind(this)},configure:{name:"configure",dataDecoder:notificationsConfigurationProtocolDecoder,execute:this.handleConfigure.bind(this)},getActiveCount:{name:"getActiveCount",resultDecoder:notificationsActiveCountDecoder,execute:this.handleGetActiveCount.bind(this)},getConfiguration:{name:"getConfiguration",resultDecoder:notificationsConfigurationProtocolDecoder,execute:this.handleGetConfiguration.bind(this)},setState:{name:"setState",dataDecoder:notificationSetStateRequestDecoder,execute:this.handleSetState.bind(this)},clearOld:{name:"clearOld",execute:this.handleClearOld.bind(this)}};constructor(e,t,r,n,i){this.glueController=e,this.serviceWorkerController=t,this.session=r,this.localStorage=n,this.prefsController=i}get logger(){return logger.get("notifications.controller")}get config(){const e=this.localStorage.getNotificationsConfig();return e||ioError.raiseError("The notifications configuration has not been set.")}get currentActiveCount(){return this.session.getAllNotifications().reduce((e,t)=>"Active"===t.state?e+1:e,0)}handlePlatformShutdown(){this.started=!1;new URL(window.location.href).protocol.includes("extension")&&this.removeExtensionNotificationsListeners(),this.systemUnsubFuncs.forEach(e=>e()),this.systemUnsubFuncs=[]}async start(){this.clearNotificationOnClick=this.config.clearNotificationOnClick;new URL(window.location.href).protocol.includes("extension")&&await this.setupExtensionNotifications(),this.listenForServiceWorkerNotificationEvents(),this.started=!0}async setupInitialConfig(){const e=this.prefsController.storeType;if(!e||"local"===e)return void this.logger?.info("The notifications service will use the local storage for the notifications configuration");let t;try{t=await this.glueController.clientGlue.prefs.get(systemPrefsAppName)}catch(e){return void this.logger?.warn(`Failed to get the system preferences for the notifications service: ${e}, falling back to local storage`)}const r=t?.data[notificationsPrefsKey];if(!r)return void this.logger?.info("The system preferences for the notifications service are not set in prefs, falling back to local storage");const n=prefsNotificationsDecoder.run(r);if(!n.ok)return void this.logger?.error(`The system preferences from Prefs for the notifications service did not pass validation: ${JSON.stringify(n.error)}, falling back to local storage`);const i=n.result.config;this.localStorage.updateNotificationsConfig(i)}ready(){return Promise.resolve()}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this notifications control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=notificationsOperationDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This notifications request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`Notifications request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`Notifications request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}async handleConfigure({configuration:e},t,r=""){if(this.logger?.trace(`[${t}] handling a notification configure message with data: ${JSON.stringify(e)}`),this.validateServiceAccess(r,!0),this.localStorage.updateNotificationsConfig(e),this.glueController.pushSystemMessage("notifications","configurationChanged",{configuration:this.config}),"local"!==this.prefsController.storeType){const e={config:this.config};this.glueController.clientGlue.prefs.update({[notificationsPrefsKey]:e},{app:systemPrefsAppName}).catch(e=>{this.logger?.warn(`Failed to update the notifications configuration in prefs: ${e} - the settings are only updated in the local storage`)})}this.logger?.trace(`[${t}] handling a notification configure message completed`)}async handleGetActiveCount(e,t){return this.logger?.trace(`[${t}] handling a get active count message`),{count:this.currentActiveCount}}async handleGetConfiguration(e,t){this.logger?.trace(`[${t}] handling a get notification configure message`);const r={...this.config};return this.logger?.trace(`[${t}] handling a get notification configure message completed`),{configuration:r}}async handleList(e,t){this.logger?.trace(`[${t}] handling a list notification message`);const r=this.session.getAllNotifications();return this.logger?.trace(`[${t}] list notification message completed`),{notifications:r}}async handleSetState({id:e,state:t},r){this.logger?.trace(`[${r}] handling a set state notification message with data: ${JSON.stringify({id:e,state:t})}`);const n=this.session.getNotification(e);if(!n)return ioError.raiseError(`Cannot set state of a notification: ${e}, because it doesn't exist`);const i=this.currentActiveCount;n.state=t,this.session.updateNotification(n),this.glueController.pushSystemMessage("notifications","stateChange",{id:e,state:t}),this.syncActiveCount(i)}async handleClick(e,t){this.logger?.trace(`[${t}] handling a click notification message with data: ${JSON.stringify(e)}`);const r=this.session.getNotification(e.id);return r?e.action&&r.actions?.every(t=>t.action!==e.action)?ioError.raiseError(`Cannot click action ${e.action} of ${e.id}, because that notification does not have that action`):(this.handleNotificationClick({notification:r,action:e.action}),void this.logger?.trace(`[${t}] handling a click notification message completed`)):ioError.raiseError(`Cannot click a notification: ${e.id}, because it doesn't exist`)}async handleClear(e,t){this.logger?.trace(`[${t}] handling a clear notification message with data: ${JSON.stringify(e)}`);const r=this.currentActiveCount;this.removeNotification(e.id),this.syncActiveCount(r),this.logger?.trace(`[${t}] handling a clear notification message completed`)}async handleClearAll(e,t){this.logger?.trace(`[${t}] handling a clearAll notifications message`);const r=this.session.getAllNotifications(),n=r.reduce((e,t)=>"Active"===t.state?e+1:e,0);r.forEach(e=>this.removeNotification(e.id)),this.syncActiveCount(n),this.logger?.trace(`[${t}] handling a clearAll notification message completed`)}async handleClearOld(e,t){this.logger?.trace(`[${t}] handling a clearOld notifications message`);const r=this.session.getAllNotifications(),n=r.reduce((e,t)=>"Active"===t.state?e+1:e,0);r.filter(e=>"Active"!==e.state).forEach(e=>this.removeNotification(e.id)),this.syncActiveCount(n),this.logger?.trace(`[${t}] handling a clearOld notification message completed`)}async handleRaiseNotification({settings:e,id:t},r,n=""){if(this.logger?.trace(`[${r}] handling a raise notification message with a title: ${e.title}`),!this.config.enable)return ioError.raiseError("Cannot raise a notification, because the notifications service is disabled");this.validateServiceAccess(n);const i=this.currentActiveCount;setNotificationDefaults(e),this.processNewNotification(e,t);const o=this.config.enableToasts?!!e.showToast:this.config.enableToasts;await this.showToast({settings:e,id:t},o,r);const s={definition:Object.assign({},e,{title:void 0,clickInterop:void 0,actions:void 0}),id:t};return setTimeout(()=>this.glueController.pushSystemMessage("notifications","notificationShow",s),0),this.logger?.trace(`[${r}] notification with a title: ${e.title} was successfully raised`),this.syncActiveCount(i),{settings:e}}async showToast({settings:e,id:t},r,n){if(!r)return;if(this.isInExtension)return void await this.raiseExtensionToast(e,t,n);e.actions&&e.actions.length?await this.raiseActionsToast(e,t,n):this.raiseSimpleToast(e,t,n)}async handleGetPermission(e,t){this.logger?.trace(`[${t}] handling a get permission message`);const r=Notification.permission;return this.logger?.trace(`[${t}] permission for raising notifications is: ${r}`),{permission:r}}async handleRequestPermission(e,t){this.logger?.trace(`[${t}] handling a request permission message`);let r=Notification.permission;"granted"!==r&&(r=await Notification.requestPermission());const n="granted"===r;return this.logger?.trace(`[${t}] permission for raising notifications is: ${r}`),{permissionGranted:n}}validateServiceAccess(e,t){const r=this.glueController.getAppNameByInstanceId(e)||"";if(t&&e===this.glueController.me.instance)return;if(this.config.sourceFilter.blocked.includes(r))return ioError.raiseError(`Cannot complete the notifications operation, because the caller app: ${r} is blocked from the notifications service`);const n=this.config.sourceFilter.allowed.includes("*"),i=this.config.sourceFilter.allowed.includes(r);return n||i?void 0:ioError.raiseError(`Cannot complete the notifications operation, because the caller app: ${r} is not present in the allowed list of the notifications service`)}async raiseSimpleToast(e,t,r){this.logger?.trace(`[${r}] notification with a title: ${e.title} was found to be non-persistent and therefore will be raised with the native notifications API`);const n=Object.assign({},e,{title:void 0,clickInterop:void 0}),i=new Notification(e.title,n);i.onclick=()=>{e.focusPlatformOnDefaultClick&&window.focus();const r=this.session.getNotification(t);r&&this.handleNotificationClick({action:"",notification:r})},i.onclose=()=>{const e=this.currentActiveCount;this.removeNotification(t),this.syncActiveCount(e)}}async raiseActionsToast(e,t,r){this.logger?.trace(`[${r}] notification with a title: ${e.title} was found to be persistent and therefore the service worker will be instructed to raise it.`),await this.serviceWorkerController.showNotification(e,t)}raiseExtensionToast(e,t,r){return new Promise((n,i)=>{if(this.logger?.trace(`[${r}] notification with a title: ${e.title} will be raised with the native extension notifications API, because the platform is running in extension mode`),!this.extNotificationConfig)return i("Cannot raise a notification, because the environment settings for the extension mode are missing.");const o=e.actions?e.actions.map(e=>({title:e.title,iconUrl:e.icon})):void 0,s={type:"basic",iconUrl:e.icon||this.extNotificationConfig.defaultIcon,title:e.title,message:e.body||this.extNotificationConfig.defaultMessage,silent:e.silent,requireInteraction:e.requireInteraction,imageUrl:e.image,buttons:o};chrome.notifications.create(t,s,()=>n())})}async setupExtensionNotifications(){this.isInExtension=!0,this.extNotificationConfig=(await this.getExtNotificationsConfig()).notifications,this.listenForExtensionNotificationsEvents()}listenForExtensionNotificationsEvents(){this._chromeClickedHandler=this.chromeClickedHandler.bind(this),chrome.notifications.onClicked.addListener(this._chromeClickedHandler),this._chromeButtonClickedHandler=this.chromeButtonClickedHandler.bind(this),chrome.notifications.onButtonClicked.addListener(this._chromeButtonClickedHandler),this._chromeClosedHandler=this.chromeClosedHandler.bind(this),chrome.notifications.onClosed.addListener(this._chromeClosedHandler)}removeExtensionNotificationsListeners(){chrome.notifications.onClicked.removeListener(this._chromeClickedHandler),chrome.notifications.onButtonClicked.removeListener(this._chromeButtonClickedHandler),chrome.notifications.onClosed.removeListener(this._chromeClosedHandler)}chromeClickedHandler(e){const t=this.session.getNotification(e);t&&this.handleNotificationClick({notification:t})}chromeButtonClickedHandler(e,t){const r=this.session.getNotification(e);if(!r)return;if(!r.actions)return;const n=r.actions[t].action;this.handleNotificationClick({action:n,notification:r})}chromeClosedHandler(e){const t=this.currentActiveCount;this.removeNotification(e),this.syncActiveCount(t)}listenForServiceWorkerNotificationEvents(){const e=this.serviceWorkerController.onNotificationClick(e=>{const t=this.session.getNotification(e.glueData.id);t&&this.handleNotificationClick({action:e.action,notification:t})}),t=this.serviceWorkerController.onNotificationClose(e=>{const t=this.currentActiveCount;this.removeNotification(e.glueData.id),this.syncActiveCount(t)});this.systemUnsubFuncs.push(e),this.systemUnsubFuncs.push(t)}getExtNotificationsConfig(){return new Promise(e=>{chrome.storage.local.get("notifications",t=>{e(t)})})}handleNotificationClick(e){!e.action&&e.notification.clickInterop&&this.callDefinedInterop(e.notification.clickInterop);const t=e.action?e.notification.actions?.find(t=>t.action===e.action):null;t&&t.interop&&this.callDefinedInterop(t.interop),e.notification.data?.glueData&&delete e.notification.data.glueData;const r={definition:e.notification,action:e.action,id:e.notification.id};if(this.clearNotificationOnClick){const t=this.currentActiveCount;this.removeNotification(e.notification.id),this.syncActiveCount(t)}this.glueController.pushSystemMessage("notifications","notificationClick",r)}callDefinedInterop(e){const t=e.method,r=e.arguments,n=e.target;this.glueController.invokeMethod(t,r,n).catch(e=>{const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(`The interop invocation defined in the clickInterop was rejected, reason: ${t}`)})}processNewNotification(e,t){const r={id:t,...e};this.session.saveNewNotification(r),this.glueController.pushSystemMessage("notifications","notificationRaised",{notification:r})}removeNotification(e){this.session.removeNotification(e),this.glueController.pushSystemMessage("notifications","notificationClosed",{id:e})}syncActiveCount(e){const t=this.currentActiveCount;e!==t&&this.glueController.pushSystemMessage("notifications","activeCountChange",{count:t})}}const extensionOperationTypesDecoder=oneOf$1(constant$2("clientHello"),constant$2("operationCheck")),clientHelloResponseDecoder=object$3({widget:object$3({inject:boolean$4()})}),clientHelloDecoder=object$3({windowId:optional$3(nonEmptyStringDecoder$2)});class ExtensionController{session;started=!1;operations={clientHello:{name:"appHello",resultDecoder:clientHelloResponseDecoder,dataDecoder:clientHelloDecoder,execute:this.handleClientHello.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e){this.session=e}get logger(){return logger.get("extension.controller")}handlePlatformShutdown(){this.started=!1}async start(){this.started=!0,this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this extension control message, because the controller has not been started");const t=e.data,r=e.commandId,n=extensionOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This extension request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Extension request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Extension request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleClientHello(e,t){this.logger?.trace(`[${t}] handling client hello command`);const r=(await this.getWidgetConfig()).widget,n={widget:{inject:!(!!e.windowId&&!!this.session.getFrameData(e.windowId))&&(!!r&&r.enable)}};return this.logger?.trace(`[${t}] responding to client hello command with: ${JSON.stringify(n)}`),n}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}getWidgetConfig(){return new URL(window.location.href).protocol.includes("extension")?new Promise(e=>{chrome.storage.local.get("widget",t=>{e(t)})}):Promise.resolve({widget:{enable:!1}})}}class AsyncSequelizer{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}}class PreferredConnectionController{glueController;portsBridge;sequelizer;registry=CallbackRegistryFactory$2();unsub;discoveryInterval;shouldForceTransfer;preferredUrl;preferredAuth;stopped=!1;constructor(e,t,r){this.glueController=e,this.portsBridge=t,this.sequelizer=r}get logger(){return logger.get("preferred.connection.controller")}shutdown(){this.stopped=!0,this.registry.clear()}async start(e){this.logger?.trace(`Starting the preferred connection with config: ${JSON.stringify(e)}`),this.stopped=!1,this.portsBridge.setPreferredActivated(),e.preferred&&(this.preferredUrl=e.preferred.url,this.preferredAuth=Object.assign({},{provider:"core"},e.preferred.auth),this.shouldForceTransfer="boolean"==typeof e.preferred.forceIncompleteSwitch&&e.preferred.forceIncompleteSwitch,this.discoveryInterval="number"==typeof e.preferred.discoveryIntervalMS?e.preferred.discoveryIntervalMS:defaultPreferredDiscoveryIntervalMS,this.logger?.trace("Starting the initial preferred connection check"),await this.connectPreferred(),this.logger?.trace("The preferred connection controller initiated."))}onReconnect(e){return this.registry.add("system-reconnect",e)}async connectPreferred(e,t,r){if(this.stopped&&!e)return;const n=await this.checkPreFlight(t);if(!n.ready&&e)return ioError.raiseError("The provided preferred connection is not ready.");if(!n.ready)return this.logger?.trace("The preflight is not ready, restarting the preferred tracking."),void wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r));const i={type:"secondary",transportConfig:Object.assign({url:t||this.preferredUrl},{auth:r||this.preferredAuth})};if(this.logger?.trace("Switching the system glue."),this.stopped)return;if(!(await this.glueController.switchTransport(i,"system")).success)return this.logger?.trace("The switch attempt was not successful, revered to default."),void wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r));this.portsBridge.setActivePreferredTransportConfig(i),this.logger?.trace("The switch to the preferred connection was successful, transferring all children.");try{await this.changeClientsConnection(i)}catch(n){return this.logger?.warn(`Some platform clients could not connect to the preferred connection, reverting all to the default connection. Reason: ${JSON.stringify(n)}`),void this.fullDefaultRevert().then(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r))).catch(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r)))}this.logger?.trace("The platform is now fully connected to the preferred connection, hooking up disconnection logic."),this.registry.execute("system-reconnect");const o=this.glueController.onDisconnected(()=>this.handleDisconnected(o,e));this.unsub=o}async revertToDefault(){this.unsub&&(this.unsub(),delete this.unsub),await this.fullDefaultRevert()}async fullDefaultRevert(){await this.glueController.switchTransport({type:"default"},"system"),this.portsBridge.setActivePreferredTransportConfig({type:"default"}),await this.changeClientsConnection({type:"default"})}handleDisconnected(e,t){this.logger?.trace("The platform has been disconnected from the preferred transport, reverting all to the default one."),e(),this.fullDefaultRevert().then(()=>{this.registry.execute("system-reconnect"),this.logger?.trace("The platform reversion to default completed, restarting the preferred tracking."),t||wait(this.discoveryInterval).then(()=>this.connectPreferred())}).catch(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred()))}changeClientsConnection(e){return this.sequelizer.enqueue(async()=>{try{await Promise.all([this.glueController.switchTransport(e,"client"),this.portsBridge.switchAllClientsTransport(e)])}catch(e){if(this.logger?.trace(`Some clients could not connect to the preferred transport with error: ${JSON.stringify(e)}`),!this.shouldForceTransfer)return this.logger?.trace("The platform is not forcing a transfer in cases of errors, re-throwing."),ioError.raiseError(e);this.logger?.trace("The platform is forcing a transfer regardless of the errors.")}await this.glueController.switchTransport(e,"contextsTrack")})}checkPreferredConnection(e){return new Promise(t=>{const r=new WebSocket(e);r.onerror=()=>t({live:!1}),r.onopen=()=>{r.close(),t({live:!0})}})}async checkPreFlight(e){this.logger?.trace("Starting the preflight check");if(!(await this.checkPreferredConnection(e||this.preferredUrl)).live)return this.logger?.trace("The preferred connection is not live."),{ready:!1};this.logger?.trace(`Found a live preferred connection at: ${e||this.preferredUrl}, testing the availability of transport switching logic in all current clients`);const t=await this.portsBridge.checkClientsPreferredLogic();if(this.logger?.trace(`The logic check returned: ${JSON.stringify(t)}`),!t.success&&!this.shouldForceTransfer)return this.logger?.trace("The preflight check is marked as not ready"),{ready:!1};this.logger?.trace("Checking the possibility of all clients to connect to the preferred connection");const r=await this.portsBridge.checkClientsPreferredConnection(e||this.preferredUrl);return this.logger?.trace(`The connection check returned: ${JSON.stringify(r)}`),r.success||this.shouldForceTransfer?(this.logger?.trace("The preflight check is marked as ready"),{ready:!0}):(this.logger?.trace("The preflight check is marked as not ready"),{ready:!1})}}class TransactionsController{transactionLocks={};get logger(){return logger.get("transactions.controller")}completeTransaction(e,t){if("string"!=typeof e)return ioError.raiseError(`Cannot complete the transaction, because the provided id is not a string: ${JSON.stringify(e)}`);const r=this.transactionLocks[e];r?r.lift(t):this.logger?.warn(`Cannot mark a transaction as complete, because there is not lock with id ${e}`)}failTransaction(e,t){const r=this.transactionLocks[e];r?r.fail(t):this.logger?.warn(`Cannot mark a transaction as failed, because there is not lock with id ${e}`)}createTransaction(e,t){const r={},n=nanoid$5(10),i=new Promise((i,o)=>{let s=!0;r.lift=e=>{s=!1,delete this.transactionLocks[n],i(e)},r.fail=e=>{s=!1,delete this.transactionLocks[n],o(e)},setTimeout(()=>{s&&(s=!1,this.logger?.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],o(`Transaction for operation: ${e} timed out.`))},t)});return r.lock=i,r.id=n,this.transactionLocks[n]=r,r}}class InterceptionController{interceptions=[];shutdown(){this.interceptions=[]}async registerInterceptor(e,t){runDecoderWithIOError(interceptorRegistrationRequestDecoder,e),runDecoderWithIOError(nonEmptyStringDecoder$2,t);const r=e.interceptions.reduce((e,t)=>(this.interceptions.some(e=>e.domain===t.domain&&e.operation===t.operation)&&e.push({domain:t.domain,operation:t.operation}),e),[]);if(r.length){const e=r.map(e=>`${e.domain} - ${e.operation}`).join(", ");return ioError.raiseError(`Interception registration is rejected, because the following collisions where found: ${e}`)}e.interceptions.forEach(r=>{this.interceptions.push({domain:r.domain,operation:r.operation,callInterceptor:e.callInterceptor,registrantName:t})})}getOperationInterceptor(e){const t=this.interceptions.find(t=>t.domain===e.domain&&t.operation===e.operation);if(t)return{name:t.registrantName,intercept:t.callInterceptor}}}class PluginsController{interceptionController;glueController;handlePluginMessage;platformApi;allPlugins;registeredPlugins=[];constructor(e,t){this.interceptionController=e,this.glueController=t}get logger(){return logger.get("plugins.controller")}async shutdown(){this.logger?.debug(`starting plugins shutdown for all plugins: [${this.allPlugins.map(e=>e.name).join(", ")}]`),this.allPlugins.forEach(e=>{if(e.stop)try{e.stop()}catch(t){this.logger?.warn(`Plugin: ${e.name} threw while onPlatformShutdown -> ${extractErrorMsg$1(t)}`)}}),this.allPlugins=[],this.registeredPlugins=[],this.logger?.debug("plugins shutdown completed")}async start(e){if(this.logger?.debug(`initializing plugins with ${JSON.stringify((e.plugins??[]).map(e=>e.name))} plugins`),!e.plugins)return;if(this.allPlugins=e.plugins,this.handlePluginMessage=e.handlePluginMessage,this.platformApi=e.api,!e.plugins||!e.plugins.length)return;const t=[],r=[];for(const n of e.plugins){const e=this.startPlugin(n);n.critical&&(t.push(e),r.push(n.name))}this.logger?.debug(`waiting for ${t.length} critical plugins to start: [${r.join(", ")}]`),await Promise.all(t),this.logger?.debug(`all critical plugins started successfully [${r.join(", ")}]`)}async startPlugin(e){this.logger?.debug(`starting plugin with definition: ${JSON.stringify(e)}`);try{const t=this.buildPlatformControls(e.name,this.platformApi);this.validatePlugin(e.name),await e.start(this.glueController.clientGlue,e.config,t),this.registerPlugin(e.name,e.version??"N/A"),this.logger?.debug(`plugin '${e.name}' started successfully`)}catch(t){this.logger?.error(`plugin '${e.name}' failed to start with error: ${extractErrorMsg$1(t)}`);const r="string"==typeof t?t:JSON.stringify(t.message),n=`Plugin: ${e.name} threw while initiating: ${r}`;if(e.critical)return ioError.raiseError(n);this.logger?.warn(n)}}buildPlatformControls(e,t){return{control:t=>this.handlePluginMessage(t,e),logger:logger.get(e),platformApi:t,interception:{register:t=>this.interceptionController.registerInterceptor(t,e)},system:{sendControl:t=>this.handlePluginMessage(t,e)}}}validatePlugin(e){if(this.registeredPlugins.some(t=>t.name===e))throw new Error(`Plugin: ${e} is already registered`)}registerPlugin(e,t){this.registeredPlugins.push({name:e,version:t})}}class DomainsController{systemController;windowsController;applicationsController;layoutsController;workspacesController;intentsController;channelsController;notificationsController;extensionController;searchController;themesController;managerController;prefsController;otelController;uiController;defaultDomainNames=["system","windows","appManager","layouts","workspaces","intents","channels","notifications","extension","search","themes","prefs","otel","ui"];domains;constructor(e,t,r,n,i,o,s,a,c,l,u,d,h,p,g){this.systemController=e,this.windowsController=t,this.applicationsController=r,this.layoutsController=n,this.workspacesController=i,this.intentsController=o,this.channelsController=s,this.notificationsController=a,this.extensionController=c,this.searchController=l,this.themesController=u,this.managerController=d,this.prefsController=h,this.otelController=p,this.uiController=g,this.setDomains()}setDomains(){this.domains={system:{name:"system",libController:this.systemController},windows:{name:"windows",libController:this.windowsController},appManager:{name:"appManager",libController:this.applicationsController},layouts:{name:"layouts",libController:this.layoutsController},workspaces:{name:"workspaces",libController:this.workspacesController},intents:{name:"intents",libController:this.intentsController},channels:{name:"channels",libController:this.channelsController},notifications:{name:"notifications",libController:this.notificationsController},extension:{name:"extension",libController:this.extensionController},search:{name:"search",libController:this.searchController},themes:{name:"themes",libController:this.themesController},manager:{name:"manager",libController:this.managerController},prefs:{name:"prefs",libController:this.prefsController},otel:{name:"otel",libController:this.otelController},ui:{name:"ui",libController:this.uiController}}}get logger(){return logger.get("domains.controller")}shutdown(){Object.values(this.domains).forEach(e=>e.libController.handlePlatformShutdown?e.libController.handlePlatformShutdown():null),this.domains={system:{name:"system",libController:this.systemController},windows:{name:"windows",libController:this.windowsController},appManager:{name:"appManager",libController:this.applicationsController},layouts:{name:"layouts",libController:this.layoutsController},workspaces:{name:"workspaces",libController:this.workspacesController},intents:{name:"intents",libController:this.intentsController},channels:{name:"channels",libController:this.channelsController},notifications:{name:"notifications",libController:this.notificationsController},extension:{name:"extension",libController:this.extensionController},search:{name:"search",libController:this.searchController},themes:{name:"themes",libController:this.themesController},prefs:{name:"prefs",libController:this.prefsController},otel:{name:"otel",libController:this.otelController},ui:{name:"ui",libController:this.uiController}}}setProfileData(e){this.systemController.setProfileData(e)}async setNotificationsData(){await this.notificationsController.setupInitialConfig()}validateDomain(e){const t=this.domains[e];if(!t)return ioError.raiseError(`Accessing a missing domain: ${e}.`);const r=t.domainNameDecoder?t.domainNameDecoder:libDomainDecoder;runDecoderWithIOError(r,e)}async startAllDomains(e){this.logger?.trace("Starting all domains lib controllers"),await Promise.all(Object.values(this.domains).map(t=>t.libController.start(e))),this.logger?.trace("All domains have been initialized")}async configurePostStartAllDomains(){this.logger?.trace("Starting all domains lib controllers"),await Promise.all(Object.values(this.domains).filter(e=>!!e.libController.configurePostStart).map(e=>e.libController.configurePostStart&&e.libController.configurePostStart())),this.logger?.trace("All domains have been initialized")}notifyDomainsClientUnloaded(e){this.logger?.trace(`detected unloading of client: ${e.windowId}, notifying all controllers`),Object.values(this.domains).forEach(t=>{try{t.libController.handleClientUnloaded?.(e.windowId,e.win)}catch(r){const n="string"==typeof r?r:JSON.stringify(r.message),i=t.name;this.logger?.error(`${i} controller threw when handling unloaded client ${e.windowId} with error message: ${n}`)}})}executeControlMessage(e){const t=this.domains[e.domain];return t?t.libController.handleControl(e):ioError.raiseError(`Cannot process message for domain: ${e.domain} and operation ${e.operation}, because no domain can service it.`)}registerDynamicDomain(e){return Object.values(this.domains).map(e=>e.name).some(t=>t===e.name)?ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it is already registered`):e.libController&&e.libController.start&&e.libController.handleControl&&e.libController.handleClientUnloaded?e.domainNameDecoder?void(this.domains[e.name]=e):ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it does not have a domain decoder`):ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it does not have a valid libController`)}unregisterDynamicDomain(e){if(this.defaultDomainNames.some(t=>t===e))return ioError.raiseError(`Cannot unregister a domain: ${e}, because it is a reserved default domain`);delete this.domains[e]}async domainsReady(){this.logger?.trace("Verifying all domains lib controllers ready"),await Promise.all(Object.values(this.domains).map(e=>e.libController.ready())),this.logger?.trace("All domains have signaled ready")}}class LegacyResolverController{glueController;workspacesController;windowsController;prefsController;intentsResolverResponsePromises={};constructor(e,t,r,n){this.glueController=e,this.workspacesController=t,this.windowsController=r,this.prefsController=n}get logger(){return logger.get("intents.resolver.controller")}async startResolverApp({request:e,resolverConfig:t,commandId:r,callerId:n,resolverInstance:i,method:o}){this.logger?.trace(`[${r}] Intents Resolver UI with app name ${t.appName} will be used for request: ${JSON.stringify(e)}`);const s=await this.registerResponseMethod();this.logger?.trace(`[${r}] Registered interop method ${s}`);const a=this.buildStartContext(o,e,s,n),c=await this.buildStartOptions(n,r);this.logger?.trace(`[${r}] Starting Intents Resolver UI with context: ${JSON.stringify(a)} and options: ${c}`);const l=this.glueController.clientGlue.appManager.application(t.appName).start(a,c).catch(e=>ioError.raiseError(`${ERRORS.RESOLVER_UNAVAILABLE}. Reason: ${e instanceof Error||"string"==typeof e?e:JSON.stringify(e)}`)),u=await l;i.instanceId=u.id,this.logger?.trace(`[${r}] Intents Resolver instance with id ${u.id} opened`),this.subscribeOnInstanceStopped(u,o);const d="raise"===o?`for intent request ${JSON.stringify(e)}`:`for '${o}' method with filter ${JSON.stringify(e)}`,h=`${ERRORS.RESOLVER_TIMEOUT} - waited ${t.waitResponseTimeout}ms for the user the choose a handler ${d}`;this.createResponsePromise({intent:"raise"===o?e.intent:void 0,instanceId:u.id,responseMethodName:s,timeout:t.waitResponseTimeout,errorMsg:h});try{return await this.handleInstanceResponse({request:e,instanceId:u.id,method:o,commandId:r,caller:a.initialCaller})}catch(e){return this.stopResolverInstance(i.instanceId),ioError.raiseError(e)}}stopResolverInstance(e){const t=this.glueController.clientGlue.appManager.instances().find(t=>t.id===e);t&&t.stop().catch(e=>this.logger?.warn(e))}async handleInstanceResponse({method:e,caller:t,commandId:r,instanceId:n,request:i}){const o=await this.intentsResolverResponsePromises[n].promise,s="raise"===e?`for intent ${o.intent} `:"";if(this.logger?.trace(`[${r}] Intent handler chosen ${s}: ${JSON.stringify(o.handler)}. Stopping resolver instance with id ${n}`),this.stopResolverInstance(n),this.logger?.trace(`[${r}] Instance with id ${n} successfully stopped`),!o?.userSettings?.preserveChoice)return o.handler;try{await this.saveUserChoice({intent:o.intent,handler:o.handler,filter:"filterHandlers"===e?{applicationNames:i.applicationNames,contextTypes:i.contextTypes,resultType:i.resultType}:void 0,caller:t},r)}catch(e){this.logger?.warn(`[${r}] - Prefs API threw the following error: ${e}`)}return o.handler}async registerResponseMethod(){const e=INTENTS_RESOLVER_INTEROP_PREFIX+nanoid$5(10);return await this.glueController.clientGlue.interop.register(e,(e,t)=>this.responseHandler(e,t)),e}createResponsePromise({instanceId:e,intent:t,responseMethodName:r,timeout:n,errorMsg:i}){let o=()=>{},s=()=>{};const a=PromisePlus((e,t)=>{o=e,s=t},n,i);this.intentsResolverResponsePromises[e]={intent:t,resolve:o,reject:s,promise:a,methodName:r}}buildStartContext(e,t,r,n){const i={callerId:this.glueController.clientGlue.interop.instance.instance,methodName:r,resolverApi:"1.0"},o=this.glueController.getLocalServers().find(e=>e.instance===n);if(!o)throw new Error(`Cannot find window with id: ${n} - the client which sent the "raise" command is no longer opened`);const s=o.application??o.applicationName,a={applicationName:s,applicationTitle:s?this.glueController.clientGlue.appManager.application(s)?.title:"",id:n};return"raise"===e?{...i,initialCaller:a,intent:t}:{...i,initialCaller:a,handlerFilter:t}}async buildStartOptions(e,t){const r=await this.getTargetBounds(e,t);return r?{top:(r.height-INTENTS_RESOLVER_HEIGHT)/2+r.top,left:(r.width-INTENTS_RESOLVER_WIDTH)/2+r.left,width:INTENTS_RESOLVER_WIDTH,height:INTENTS_RESOLVER_HEIGHT}:ioError.raiseError(`[${t}] Cannot find window with id: ${e} - the client which sent the "raise" command is no longer opened`)}async getTargetBounds(e,t){const r=await this.tryGetWindowBasedBounds(e,t)??await this.tryGetWorkspaceBasedBounds(e,t);if(r)return this.logger?.trace(`[${t}] Opening Intents Resolver UI with bounds: ${JSON.stringify(r)}`),r;const n={top:window.screen.availTop??0,left:window.screen.availLeft??0,width:window.screen.width,height:window.screen.height};return this.logger?.trace(`[${t}] Opening Intents Resolver UI relative to my screen bounds: ${JSON.stringify(n)}`),n}async tryGetWindowBasedBounds(e,t){const r=this.glueController.clientGlue.windows.findById(e),n=this.getServerInstanceByWindowId(e);if(!r&&!n)return ioError.raiseError(`Client with id "${e}" does not exist`);if(!r&&n)return this.getWindowBoundsByServerInstance(n,e,t);if(!r)return ioError.raiseError(`Client with id "${e}" does not exist`);try{const n=await r.getBounds();return this.logger?.trace(`[${t}] Opening the resolver UI with bounds: ${JSON.stringify(n)}, relative to a window with id: ${e}`),n}catch(r){return void this.logger?.trace(`[${t}] Failure to get bounds of a window with id ${e}. Error: ${JSON.stringify(r)}`)}}getServerInstanceByWindowId(e){return this.glueController.getLocalServers().find(t=>t.instance===e)}async getWindowBoundsByServerInstance(e,t,r){try{const{bounds:r}=await this.glueController.callWindow("windows",this.windowsController.getBoundsOperation,{windowId:t},{instance:e.instance});return r}catch(t){this.logger?.trace(`[${r}] Failure to get bounds of a window with instance ${e.instance}. Error: ${JSON.stringify(t)}`)}}async tryGetWorkspaceBasedBounds(e,t){try{const{bounds:r}=await this.workspacesController.getWorkspaceWindowFrameBounds({itemId:e},t);return this.logger?.trace(`[${t}] Opening the resolver UI relative to my workspace frame window bounds: ${JSON.stringify(r)}`),r}catch(e){this.logger?.trace(`[${t}] Failure to get my workspace frame window bounds. Error: ${JSON.stringify(e)}`)}}responseHandler(e,t){const r=resolverResponseDecoder.run(e),n=t.instance;return n?r.ok?(this.logger?.trace(`Intent Resolver instance with id ${n} send a valid response: ${JSON.stringify(r.result)}`),this.intentsResolverResponsePromises[n].resolve(e)):(this.logger?.trace(`Intent Resolver instance with id ${n} sent an invalid response. Error: ${JSON.stringify(r.error)}`),this.intentsResolverResponsePromises[n].reject(r.error.message),void this.stopResolverInstance(n)):ioError.raiseError("Cannot find instance id for the response of the intent resolver")}subscribeOnInstanceStopped(e,t){const{application:r}=e,n=r.onInstanceStopped(r=>{if(r.id!==e.id)return;const i=this.intentsResolverResponsePromises[r.id];if(!i)return n();const o="raise"===t?`raised intent ${i.intent}`:`'${t}' method`,s=`${ERRORS.USER_CANCELLED} for ${o}`;i.reject(s),this.cleanUpIntentResolverPromise(r.id),n()})}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.glueController.clientGlue.interop.unregister(t.methodName).catch(e=>this.logger?.warn(e)),delete this.intentsResolverResponsePromises[e]}async saveUserChoice({intent:e,handler:t,filter:r,caller:n},i){const o="Platform"===n.applicationName?this.prefsController.platformAppName:n.applicationName;this.logger?.info(`[${i}] - Saving user's choice of handler for '${o}' app`);const s=await this.prefsController.get({app:o},i),a=s.prefs.data?.intents??{},c={...s.prefs.data,intents:{...a,[e]:{handler:t,filter:r}}};await this.prefsController.update({app:o,data:c},i)}}class LicenseController{verifyLicense(e){if(!e||"string"!=typeof e)return{valid:!1};const t=KEYUTIL_1.getKey(publicLicKey);return{valid:KJUR_1.jws.JWS.verifyJWT(e,t,{alg:["RS256"]})}}getLicensePayload(e){if(!e)return ioError.raiseError("No license key was provided");const t=KJUR_1.jws.JWS.readSafeJSONString(b64utoutf8_1(e.split(".")[1]));return t&&"string"==typeof t.type&&"number"==typeof t.expiration?(t.type=t.type.toLowerCase(),t):ioError.raiseError("The license key payload is invalid")}isPlatformOriginAllowed(e,t=[]){if(!t.length||t.includes("*"))return!0;if("localhost"===e.hostname)return!0;return t.some(t=>pm(t)(e.origin))}checkExpired(e){return!(!e||"number"!=typeof e)&&e<=Date.now()}}class Builder{glueController;sessionStore;windowsController;workspacesController;constructor(e,t,r,n){this.glueController=e,this.sessionStore=t,this.windowsController=r,this.workspacesController=n}get logger(){return logger.get("layouts.builder")}async saveGlobalLayout(e,t){const r=await this.getRawWindowsLayoutData({layoutType:"Global",layoutName:e.layout.name,context:e.layout.context,instances:e.layout.instances,ignoreInstances:e.layout.ignoreInstances,ignoreContexts:e.layout.ignoreContexts},t);this.logger?.trace(`[${t}] received valid data for the eligible windows`);const n=await this.glueController.getLayout(e.layout.name),i=n?await this.updateLayout(n,e.layout,r.windows,t):await this.buildNewLayout(e.layout,r.windows,t);return this.logger?.trace(`[${t}] the layout object was constructed, importing.`),await this.glueController.importLayout(i),this.logger?.trace(`[${t}] the import for layout: ${i.name} was completed, responding.`),i}async updateLayout(e,t,r,n){this.logger?.trace(`[${n}] updating an existing layout with name ${t.name}`),e.context=t.context??{},e.metadata=t.metadata??{},e.token=e.token??generateLayoutToken();const i=r.filter(e=>!!e.layoutComponentId).map(e=>e.layoutComponentId),o=this.getLayoutIdOccurrenceMap(i),s=r.map(t=>this.generateWindowComponent(e,t,o,n));this.logger?.trace(`[${n}] the window components are completed, we have ${s.length} windows for the layout`);const a={layoutName:t.name,layoutType:"Global",context:t.context,ignoreContexts:t.ignoreContexts},c=e.components.filter(e=>"workspaceFrame"===e.type),l=await this.compileWorkspacesFrameComponents(c,a,n);return this.logger?.trace(`[${n}] the workspaces frame components are completed, we have ${l.length} frames for the layout`),e.components=[],e.components.push(...s),e.components.push(...l),e}async buildNewLayout(e,t,r){this.logger?.trace(`[${r}] build a brand new layout with name ${e.name}`);const n={name:e.name,type:"Global",context:e.context??{},metadata:e.metadata??{},components:[],token:generateLayoutToken(),version:2},i=t.map(e=>this.buildNewWindowComponent(e,r));this.logger?.trace(`[${r}] the window components are completed, we have ${i.length} windows for the layout`);const o={layoutName:e.name,layoutType:"Global",context:e.context,ignoreContexts:e.ignoreContexts},s=await this.compileWorkspacesFrameComponents([],o,r);return this.logger?.trace(`[${r}] the workspaces frame components are completed, we have ${s.length} frames for the layout`),n.components.push(...i),n.components.push(...s),n}async getRawWindowsLayoutData(e,t){this.logger?.trace(`[${t}] handling send save requests for layout: ${e.layoutName} to instances: ${e.instances?.join(", ")}`);const r={windows:[...await Promise.all(this.getEligibleGlueWindows(e.instances,e.ignoreInstances).map(r=>this.buildRawGlueWindowData(r,e,t))),...await Promise.all(this.getEligibleNonGlueWindows(e.instances,e.ignoreInstances).map(t=>this.buildRawNonGlueWindowData(t,e)))]};return this.logger?.trace(`[${t}] request completed, responding to the caller`),r}async buildRawGlueWindowData(e,t,r){if(!e.initialUrl)return ioError.raiseError(`Missing URL for client: ${e.name}`);const n=await this.getClientWindowContextOnSaveRequest(t,e),i=this.sessionStore.getAllInstancesData().find(t=>t.id===e.windowId),o=await this.windowsController.getWindowBounds(e.windowId,r),s=await this.glueController.callWindow("channels",{name:"getMyChannel",execute:async()=>{}},{},{windowId:e.windowId});return{bounds:o,windowContext:n,url:e.initialUrl,name:e.name,application:i?i.applicationName:defaultNoAppWindowComponentAppName,initialContext:t.ignoreContexts?{}:e.initialContext,windowId:e.windowId,layoutComponentId:e.layoutComponentId,channelId:s.channel}}async getClientWindowContextOnSaveRequest(e,t){if(e.ignoreContexts)return{};const r=`Cannot fetch the layout save data from: ${t.name} with id: ${t.windowId}`;return(await PromiseWrap(async()=>{try{return await this.glueController.callWindow("layouts",{name:"clientSaveRequest",execute:async()=>{}},e,{windowId:t.windowId})}catch(e){return{}}},15e3,r)).windowContext??{}}async buildRawNonGlueWindowData(e,t){if(!e.initialUrl)return ioError.raiseError(`Missing URL for client: ${e.name}`);const r=this.sessionStore.getAllInstancesData().find(t=>t.id===e.windowId);return{bounds:e.initialBounds??defaultPlatformConfig.windows.defaultWindowOpenBounds,windowContext:{},url:e.initialUrl,name:e.name,application:r?r.applicationName:defaultNoAppWindowComponentAppName,initialContext:t.ignoreContexts?{}:e.initialContext,windowId:e.windowId,layoutComponentId:e.layoutComponentId}}getEligibleNonGlueWindows(e,t){const r=this.getAllEligibleWindows(e,t),n=this.sessionStore.getAllNonGlue(),i=this.sessionStore.pickWorkspaceClients(()=>!0);return r.filter(e=>n.some(t=>t.windowId===e.windowId)&&i.every(t=>t.windowId!==e.windowId))}getEligibleGlueWindows(e,t){const r=this.getAllEligibleWindows(e,t),n=this.sessionStore.getAllNonGlue(),i=this.sessionStore.pickWorkspaceClients(()=>!0);return r.filter(e=>i.every(t=>t.windowId!==e.windowId)&&n.every(t=>t.windowId!==e.windowId))}getAllEligibleWindows(e,t){let r=this.sessionStore.getAllWindowsData().filter(e=>"Platform"!==e.name);if(e&&e.length){const t=this.glueController.getLocalServers().filter(t=>e.some(e=>t.instance===e));r=r.filter(e=>t.some(t=>t.windowId===e.windowId))}if(t&&t.length){const e=this.glueController.getLocalServers().filter(e=>t.some(t=>e.instance===t));r=r.filter(t=>e.every(e=>e.windowId!==t.windowId))}return r}updateExistingWindowComponent(e,t,r){return this.logger?.trace(`[${r}] performing a soft update on am existing component ${e.application} with id ${e.state.instanceId}`),e.state.context=t.windowContext?t.windowContext:e.state.context,e.state.bounds=t.bounds,e.state.createArgs.context=t.initialContext?t.initialContext:e.state.createArgs?.context,e.state.instanceId=e.state.instanceId?e.state.instanceId:t.windowId,e.state.channelId=t.channelId,e}buildNewWindowComponent(e,t){return this.logger?.trace(`[${t}] building a brand new component ${e.application} with id ${e.windowId}`),{type:"window",componentType:"application",application:e.application,state:{context:e.windowContext??{},bounds:e.bounds,createArgs:{name:e.name,url:e.url,context:e.initialContext??{}},windowState:"Normal",restoreState:"Normal",restoreSettings:{groupId:"glue_42_core",groupZOrder:0},instanceId:e.windowId,isSticky:!0,isCollapsed:!1,channelId:e.channelId}}}async compileWorkspacesFrameComponents(e,t,r){this.logger?.trace(`[${r}] requesting information about all running workspaces frames`);const n=await this.getAllFramesSnapshotsWithBounds(t,r);this.logger?.trace(`[${r}] got information on ${n.length} frames, composing the frame components`);const i=n.filter(e=>!!e.config?.layoutComponentId).map(e=>e.config.layoutComponentId),o=this.getLayoutIdOccurrenceMap(i);return n.map(t=>this.generateFrameComponent(t,e,o,r))}getLayoutIdOccurrenceMap(e){const t={};return e.forEach(e=>{t[e]?t[e]=1+t[e]:t[e]=1}),t}softUpdateFrameComponent(e,t,r,n){return this.logger?.trace(`[${n}] performing a soft update on am existing frame component ${e.state.instanceId}`),e.state.bounds=t.bounds,e.state.selectedWorkspace=-1===r?0:r,e.state.workspaces=t.snapshot.workspaces,e.state.context=Object.assign({},e.state.context,{isPlatform:t.config.isPlatform}),e}createNewFrameComponent(e,t,r){return this.logger?.trace(`[${r}] building a new frame component ${e.snapshot.id}`),{type:"workspaceFrame",application:"workspaces-demo",componentType:"application",state:{context:{isPlatform:e.config.isPlatform},bounds:e.bounds,instanceId:e.snapshot.id,selectedWorkspace:-1===t?0:t,workspaces:e.snapshot.workspaces,restoreState:"Normal",windowState:"Normal"}}}generateWindowComponent(e,t,r,n){const i=e.components.find(e=>"window"===e.type&&e.state.instanceId===t.layoutComponentId),o=t.layoutComponentId?r[t.layoutComponentId]:0;return i&&o<2?this.updateExistingWindowComponent(i,t,n):this.buildNewWindowComponent(t,n)}generateFrameComponent(e,t,r,n){const i=e.snapshot.workspaces.findIndex(e=>e?.config?.isSelected),o=t.find(t=>t.state.instanceId===e.config.layoutComponentId),s=e.config.layoutComponentId?r[e.config.layoutComponentId]:0;return o&&s<2?this.softUpdateFrameComponent(o,e,i,n):this.createNewFrameComponent(e,i,n)}async getAllFramesSnapshotsWithBounds(e,t){const r=(await this.workspacesController.getAllFramesSummaries(void 0,t)).summaries||[];return await Promise.all(r.map(async r=>{const n=await this.workspacesController.handleGetWorkspacesLayouts({frameId:r.id,...e},t),i=await this.workspacesController.getFrameSessionData({frameId:r.id},t);return{bounds:(await this.workspacesController.getFrameBounds({itemId:r.id},t)).bounds,snapshot:{id:r.id,workspaces:n.workspaces,config:{}},config:{isPlatform:i?.isPlatform,layoutComponentId:i?.layoutComponentId}}}))}}class Restorer{glueController;validator;resetter;workspacesController;sessionStore;constructor(e,t,r,n,i){this.glueController=e,this.validator=t,this.resetter=r,this.workspacesController=n,this.sessionStore=i}get logger(){return logger.get("layouts.restorer")}async restoreGlobalLayout(e,t,r,n){const i=await this.glueController.getLayout(e.layout.name);if(!i)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because it was not found in this platform`);if("Global"!==i.type)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because it is not a Global Layout`);if(!r||!n)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because the callerId or callerType are missing`);await this.validator.doInitialValidation(i,t),this.logger?.trace(`[${t}] the initial validation of the compliancy of the layout was completed`),await this.closeInstances(n,r,t,e.layout.closeMe,e.layout.closeRunningInstances),this.logger?.trace(`[${t}] closed all necessary running instances`),await this.restore(i,e,t);const o=this.sessionStore.getLayoutsSystemData();o.currentLayoutName=i.name,this.sessionStore.setLayoutsSystemData(o),this.logger?.trace(`[${t}] the layout ${i.name} was restored`)}async closeInstances(e,t,r,n,i){(void 0===i||i)&&await this.resetter.closeAllExceptCaller(t,r);(n||void 0===n&&void 0===i||void 0===n&&i)&&await this.resetter.closeCaller(e,t,r)}async restore(e,t,r){this.logger?.trace(`[${r}] starting the restore process of ${e.name}`);const n=await this.canPlatformFrameAcceptComponent(r)?this.pickComponentForPlatformFrame(e.components.filter(e=>"workspaceFrame"===e.type)):null,i=Promise.all(e.components.map(i=>{if("window"===i.type)return this.restoreWindowComponent(i,r,e.context,t.layout.context);if("workspaceFrame"===i.type){const o=n===i;return this.restoreWorkspaceFrameComponent(i,r,e.context,t.layout.context,o)}}));await i}async restoreWindowComponent(e,t,r,n){this.logger?.trace(`[${t}] restoring window component ${e.application} with id ${e.state.instanceId} and bounds: ${JSON.stringify(e.state.bounds)}`);const i=Object.assign({},r,e.state.context,e.state.createArgs.context,n),o=e.state.channelId,s=e.state.bounds,a=await this.checkTargetBoundsPossible(s);a.isPossible||this.logger?.warn(`Restoring ${e.application} not possible with the saved bounds, falling back to default bounds`);const c=a.isPossible?s:void 0;this.logger?.trace(`[${t}] calling the respective glue open/start method`);const l=e.application===defaultNoAppWindowComponentAppName?this.glueController.openWindow({name:e.state.createArgs.name,url:e.state.createArgs.url,layoutComponentId:e.state.instanceId,context:i,bounds:c}):this.glueController.startApp({name:e.application,layoutComponentId:e.state.instanceId,context:i,bounds:c});this.logger?.trace(`[${t}] the component was started`);const u=await l;o&&await this.glueController.callWindow("channels",{name:"joinChannel",execute:async()=>{}},{windowId:u.id,channel:o},{instance:u.id}).catch(console.error)}async restoreWorkspaceFrameComponent(e,t,r,n,i){this.logger?.trace(`[${t}] restoring workspace frame component $with id ${e.state.instanceId} and bounds: ${JSON.stringify(e.state.bounds)}`);const o=i?(await this.getPlatformFrame(t))?.id:void 0,s=await this.createFrameWithWorkspaceComponents(e,o);this.logger?.trace(`[${t}] the frame was restored, selecting the correct workspace`);const a=await s.workspaces();await(a[e.state.selectedWorkspace]?.focus()),this.logger?.trace(`[${t}] the correct workspace was selected, restoring the workspaces context`);const c=Object.assign({},r,n);await Promise.all(a.map(e=>e.updateContext(c))),this.logger?.trace(`[${t}] the frame component ${e.state.instanceId} is restored`)}async canPlatformFrameAcceptComponent(e){const t=await this.getPlatformFrame(e);if(!t)return!1;const r=await t.workspaces();return 1===r.length&&0===r[0].getAllWindows().length}pickComponentForPlatformFrame(e){if(0===e.length)return;return e.find(e=>e.state.context?.isPlatform)||e[0]}async checkTargetBoundsPossible(e){if(window.gtf)return{isPossible:!0};return(await window.getScreenDetails()).screens.find(t=>{const r=e.left>=t.left&&e.left<=t.left+t.width,n=e.top>=t.top&&e.top<=t.top+t.height;return r&&n})?{isPossible:!0}:{isPossible:!1}}async getPlatformFrame(e){if(!this.glueController.isWorkspacesEnabled)return;if(!await this.workspacesController.handleCheckStarted(void 0,e))return;const t=(await this.workspacesController.handleGetPlatformFrameId({},e)).id;return t?this.glueController.getOrCreateWorkspaceFrame({frameId:t}):void 0}async createFrameWithWorkspaceComponents(e,t){const r=await this.glueController.getOrCreateWorkspaceFrame({frameId:t,bounds:e.state.bounds,layoutComponentId:e.state.instanceId});return await this.glueController.invokeMethod(GlueWorkspaceFrameClientControlName,{operation:"initFrameFromSnapshot",operationArguments:{workspaces:e.state.workspaces,keepWorkspaces:[]}},{windowId:r.id}),r}}class LayoutValidator{glueController;workspacesController;constructor(e,t){this.glueController=e,this.workspacesController=t}async doInitialValidation(e,t){this.validateRequiredApplicationsExistence(e),await this.validateWorkspaceConfigurationInPlatform(e,t),this.validateNoAppNameAndUrl(e)}async doFinalValidation(e){this.validateWindowNamesCollision(e),this.validateInstanceIdCollision(e),await this.validateWorkspaceFramesIdCollisions(e)}validateWindowNamesCollision(e){const t=e.components.filter(e=>"window"===e.type&&e.application===defaultNoAppWindowComponentAppName&&!!e.state.createArgs.name).map(e=>e.state.createArgs.name),r=this.glueController.getAllWindowNames(),n=t.filter(e=>r.some(t=>e===t));if(n.length)return ioError.raiseError(`Cannot restore layout: ${e.name}, because there are window names collisions: ${n.join(", ")}`)}validateInstanceIdCollision(e){const t=e.components.filter(e=>"window"===e.type&&!!e.state.instanceId).map(e=>e.state.instanceId),r=this.glueController.getAllOpenedIds(),n=t.filter(e=>r.some(t=>e===t));if(n.length)return ioError.raiseError(`Cannot restore layout: ${e.name}, because there are instances ids collisions: ${n.join(", ")}`)}async validateWorkspaceFramesIdCollisions(e){if(e.components.every(e=>"workspaceFrame"!==e.type))return;const t=await this.glueController.getAllOpenedFrameIds(),r=e.components.filter(e=>"workspaceFrame"===e.type).map(e=>e.state.instanceId).filter(e=>t.some(t=>e===t));return r.length?ioError.raiseError(`Cannot restore layout: ${e.name}, because there are frame ids collisions: ${r.join(", ")}`):void 0}validateNoAppNameAndUrl(e){const t=e.components.filter(e=>"window"===e.type&&e.application===defaultNoAppWindowComponentAppName).filter(e=>!("window"!==e.type||e.state.createArgs.name&&e.state.createArgs.url));if(!t.length)return;const r=t.map(e=>JSON.stringify(e.state.createArgs)).join(", ");return ioError.raiseError(`Cannot restore layout: ${e.name}, because it has window components, which are not defined applications and are missing name or url, provided insufficient createArgs are: ${r}`)}validateRequiredApplicationsExistence(e){const t=this.glueController.getAllApplicationNames(),r=e.components.filter(e=>"window"===e.type&&e.application!==defaultNoAppWindowComponentAppName).map(e=>e.application);if(r.push(...this.getRequiredAppNamesFromWorkspaceFrameComponents(e)),!r.length)return;const n=r.filter(e=>t.every(t=>t!==e));return n.length?ioError.raiseError(`Cannot restore layout: ${e.name}, because some required applications are not registered with this platform: ${n.join(", ")}`):void 0}async validateWorkspaceConfigurationInPlatform(e,t){if(e.components.every(e=>"Workspace"!==e.type||"workspaceFrame"!==e.type))return;const r=(await this.workspacesController.handleCheckStarted({},t))?.started;return r?void 0:ioError.raiseError(`Cannot restore layout: ${e.name}, because this platform does not have a valid Workspaces configuration`)}getRequiredAppNamesFromWorkspaceFrameComponents(e){const t=[];for(const r of e.components)if("workspaceFrame"===r.type){const e=r.state.workspaces.reduce((e,t)=>(e.push(...this.getAllAppNamesFromChildren(t.children)),e),[]);t.push(...e)}return t}getAllAppNamesFromChildren(e){const t=e.filter(e=>"window"===e.type&&!!e.config.appName&&e.config.appName!==defaultNoAppWindowComponentAppName).map(e=>e.config.appName);for(const r of e)"window"!==r.type&&t.push(...this.getAllAppNamesFromChildren(r.children));return t}}class Resetter{glueController;workspacesController;constructor(e,t){this.glueController=e,this.workspacesController=t}get logger(){return logger.get("layouts.resetter")}async closeAllExceptCaller(e,t){const r=this.glueController.getAllOtherNonPlatformWindows(e);await Promise.all(r.map(async e=>{if(this.glueController.isWorkspacesEnabled){if(await this.glueController.getWorkspaceWindowById(e.id))return}return e.close()})),this.glueController.isWorkspacesEnabled&&await this.closeNecessaryWorkspacesFrames(e,t)}async closeCaller(e,t,r){if("plugin"===e)return;if(await this.glueController.getWorkspaceWindowById(t))return void await this.cleanupWorkspaceCaller(t,r);const n=this.glueController.getWindowById(t);n&&"Platform"!==n.name?await n.close():this.logger?.warn("The close caller was missing, is an iframe or is a platform")}async closeNecessaryWorkspacesFrames(e,t){const r=(await this.workspacesController.handleGetPlatformFrameId({},t)).id;let n=await this.glueController.getAllWorkspacesFrames();r&&(n=n.filter(e=>e.id!==r),await this.cleanUpFrameExceptCaller(r,e));const i=await this.glueController.getWorkspaceWindowById(e);i&&(n=n.filter(e=>e.id!==i.frameId),await this.cleanUpFrameExceptCaller(i.frameId,e)),await Promise.all(n.map(e=>e.close()))}async cleanUpFrameExceptCaller(e,t){const r=await this.glueController.getWorkspacesByFrameId(e),n=r.filter(e=>!e.getWindow(e=>e.id===t)),i=r.find(e=>e.getWindow(e=>e.id===t));await Promise.all(n.map(e=>e.close()));const o=i?i.getAllWindows(e=>e.id!==t):[];await Promise.all(o.map(e=>e.close()))}async cleanupWorkspaceCaller(e,t){const r=(await this.workspacesController.handleGetPlatformFrameId({},t)).id,n=await this.glueController.getWorkspaceWindowById(e);n&&(n.frameId!==r?await n.frame.close():await n.workspace.close())}}const searchOperationDecoder=oneOf$1(constant$2("operationCheck"));class SearchController{glueController;appsRepo;layoutsRepo;workspacesRepo;started=!1;repos=[];provider;activeQueries={};unsubFuncs=[];operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n){this.glueController=e,this.appsRepo=t,this.layoutsRepo=r,this.workspacesRepo=n}get logger(){return logger.get("notifications.controller")}get providerName(){return`io.Connect Browser Platform ${this.glueController.me.instance}`}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.repos=[],this.activeQueries={},this.provider?.unregister()}async configurePostStart(){if(this.repos.push(this.appsRepo),this.repos.push(this.layoutsRepo),!this.glueController.isWorkspacesEnabled)return;this.repos.push(this.workspacesRepo);const e=this.repos.map(e=>({name:e.type,displayName:e.displayType})),t={name:this.providerName,types:e};if(this.logger?.trace(`Registering the platform as a provider with name: ${t.name} and types: ${JSON.stringify(t.types?.join(", "))}.`),this.provider=await this.glueController.registerProvider(t),!this.provider)return ioError.raiseError("The platform was not registered successfully as a provider.");this.logger?.trace("The platform was registered successfully as a provider.");const r=this.provider.onQuery(e=>{this.processQuery(e).then(()=>this.markQueryDone(e)).catch(t=>this.markQueryError(e,t))}),n=this.provider.onQueryCancel(this.processQueryCancel.bind(this));this.unsubFuncs.push(r),this.unsubFuncs.push(n),this.started=!0,this.logger?.info("The module started successfully.")}async start(){this.logger?.info("Starting the Global Search provider.")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this search control message, because the controller has not been started");const t=e.data,r=e.commandId,n=searchOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This search request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Search request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Search request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async processQuery(e){this.logger?.info(`Processing a new query for: ${e.search}`),this.activeQueries[e.id]={allowedResultsCount:e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER};const t=e.types?this.repos.filter(t=>e.types?.some(e=>e.name===t.type)):this.repos;await Promise.all(t.map(t=>this.callRepo(t,e)))}async callRepo(e,t){const r=await this.getRepoResults(e,t);this.activeQueries[t.id]&&r&&this.sendResults(r,t)}async getRepoResults(e,t){try{return await e.getResults(t)}catch(e){return void this.markQueryError(t,e)}}sendResults(e,t){try{e.forEach(e=>{this.activeQueries[t.id]&&(this.activeQueries[t.id].allowedResultsCount?(--this.activeQueries[t.id].allowedResultsCount,t.sendResult(e)):this.markQueryDone(t))})}catch(e){this.logger?.warn(`Failed sending results for query: ${t.search} with an error: ${extractErrorMsg$1(e)}`)}}markQueryDone(e){this.activeQueries[e.id]&&(this.logger?.info(`The query for: ${e.search} is completed`),delete this.activeQueries[e.id],e.done())}markQueryError(e,t){this.activeQueries[e.id]&&(this.logger?.warn(`The query for: ${e.search} ended with an error: ${extractErrorMsg$1(t)}`),delete this.activeQueries[e.id],e.error(extractErrorMsg$1(t)))}processQueryCancel(e){delete this.activeQueries[e.id]}}class ApplicationsRepository{glueController;type="application";displayType="Applications";constructor(e){this.glueController=e}getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)},n=this.glueController.getAllApplications();if(n.filter(t=>checkMatch(r,()=>!!t.title?.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),!r.count)return Promise.resolve(this.transformApps(t));if(n.filter(t=>checkMatch(r,()=>!!t.caption?.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),!r.count)return Promise.resolve(this.transformApps(t));return n.filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),Promise.resolve(this.transformApps(t))}transformApps(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.title,description:r.caption,iconURL:r.icon});return t}}class LayoutsRepository{glueController;type="layout";displayType="Layouts";constructor(e){this.glueController=e}async getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)};return(await this.glueController.getAllLayoutsSummaries()).filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),this.transformLayouts(t)}transformLayouts(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.name});return t}}class WorkspacesRepository{glueController;type="workspace";displayType="Workspaces";constructor(e){this.glueController=e}async getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)};return(await this.glueController.getAllWorkspacesSummaries()).filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),this.transformWorkspaces(t)}transformWorkspaces(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.name});return t}}class LocalStoreController{localStorage;defaultGlobalLayoutNamespace="g42_core_plus_default_global_layout";themesNamespace="g42_core_plus_themes";notificationsNamespace="g42_core_notifications_config";restSchedulerNamespace="g42_core_rest_scheduler";username="g42_public";constructor(){this.localStorage=window.localStorage}start(e){e?.id&&(this.username=e.id);if(!this.localStorage.getItem(this.username)){const e={[this.defaultGlobalLayoutNamespace]:{},[this.themesNamespace]:[],[this.restSchedulerNamespace]:{}};this.localStorage.setItem(this.username,JSON.stringify(e))}}stop(){this.username="g42_public"}saveThemeIfMissing(e){const t=this.getData(this.themesNamespace)||[];t.some(t=>t.theme.name===e.theme.name)||(t.push(e),this.saveData(this.themesNamespace,t))}getAllThemes(){return this.getData(this.themesNamespace)||[]}markThemeSelected(e,t){const r=this.getData(this.themesNamespace)||[],n=r.find(t=>t.theme.name===e);if(!n)return ioError.raiseError(`Cannot mark theme: ${e} as selected, because it doesn't exist`);r.forEach(e=>{e.selected=!1,e.isUserSelected=!1}),n.selected=!0,n.isUserSelected=!!t,this.saveData(this.themesNamespace,r)}getRestSchedulerEntry(e){return this.getAllRestSchedulerEntries()[e]}getAllRestSchedulerEntries(){return this.getData(this.restSchedulerNamespace)||{}}saveRestSchedulerEntry(e){const t=this.getAllRestSchedulerEntries();t[e.key]=e,this.saveData(this.restSchedulerNamespace,t)}clearRestSchedulerEntries(){this.saveData(this.restSchedulerNamespace,{})}deleteRestSchedulerEntry(e){const t=this.getAllRestSchedulerEntries();delete t[e],this.saveData(this.restSchedulerNamespace,t)}getDefaultGlobalLayoutName(){const e=this.getData(this.defaultGlobalLayoutNamespace);return e?.name}saveDefaultGlobalLayout(e){this.saveData(this.defaultGlobalLayoutNamespace,{name:e})}clearDefaultGlobalLayout(){this.saveData(this.defaultGlobalLayoutNamespace,{})}getNotificationsConfig(){return this.getData(this.notificationsNamespace)}setNotificationsConfig(e){this.saveData(this.notificationsNamespace,e)}updateNotificationsConfig(e){const t=this.getNotificationsConfig();if(!t)return ioError.raiseError("Cannot update notifications config, because it doesn't exist");this.setNotificationsConfig(deepMerge(t,e,{arrayMerge:(e,t)=>t}))}getData(e){const t=this.localStorage.getItem(this.username);return t?JSON.parse(t)[e]:ioError.raiseError(`Cannot get data for namespace: ${e}, because the user data is missing`)}saveData(e,t){const r=this.localStorage.getItem(this.username);if(!r)return ioError.raiseError(`Cannot set data for namespace: ${e}, because the user data is missing`);const n=JSON.parse(r);n[e]=t,this.localStorage.setItem(this.username,JSON.stringify(n))}}const themesOperationDecoder=oneOf$1(constant$2("getCurrent"),constant$2("list"),constant$2("select"),constant$2("operationCheck")),themeDecoder=object$3({displayName:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2}),simpleThemeResponseDecoder=object$3({theme:themeDecoder}),allThemesResponseDecoder=object$3({themes:array$3(themeDecoder)}),selectThemeConfigDecoder=object$3({name:nonEmptyStringDecoder$2}),GlueCorePlusThemesStream="T42.Core.Plus.Themes.Stream",lightTheme={name:"light",displayName:"Light"},darkTheme={name:"dark",displayName:"Dark"};class ThemesController{glueController;localStore;started=!1;themesStream;operations={getCurrent:{name:"getCurrent",resultDecoder:simpleThemeResponseDecoder,execute:this.handleGetCurrent.bind(this)},list:{name:"list",resultDecoder:allThemesResponseDecoder,execute:this.handleList.bind(this)},select:{name:"select",dataDecoder:selectThemeConfigDecoder,execute:this.handleSelect.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t){this.glueController=e,this.localStore=t}get logger(){return logger.get("themes.controller")}async start(e){this.started=!0,this.localStore.saveThemeIfMissing({theme:lightTheme,selected:!1,isUserSelected:!1}),this.localStore.saveThemeIfMissing({theme:darkTheme,selected:!1,isUserSelected:!1}),this.themesStream=await this.glueController.createSystemStream(GlueCorePlusThemesStream);if(this.localStore.getAllThemes().some(e=>e.isUserSelected))return;const t="os"===e.themes?.defaultTheme?this.getOsTheme():"light"===e.themes?.defaultTheme?"light":"dark";this.localStore.markThemeSelected(t,!1);const r=this.localStore.getAllThemes().find(e=>e.selected)?.theme;this.themesStream.push({theme:r})}handlePlatformShutdown(){this.started=!1,this.themesStream.close()}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this themes control message, because the controller has not been started");const t=e.data,r=e.commandId,n=themesOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This themes request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Themes request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Themes request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(){}async handleGetCurrent(e,t){this.logger?.trace(`[${t}] handling a getCurrent message`);const r=this.localStore.getAllThemes().find(e=>e.selected);return r?{theme:r.theme}:ioError.raiseError("No selected theme found!")}async handleList(e,t){this.logger?.trace(`[${t}] handling a list message`);return{themes:this.localStore.getAllThemes().map(e=>e.theme)}}async handleSelect(e,t){this.logger?.trace(`[${t}] handling a select message`),this.localStore.markThemeSelected(e.name,!0);const r=this.localStore.getAllThemes().find(e=>e.selected)?.theme;if(!r)return ioError.raiseError("No selected theme found!");this.themesStream.push({theme:r})}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}getOsTheme(){return window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}}function bind(e,t){return function(){return e.apply(t,arguments)}}const{toString:toString}=Object.prototype,{getPrototypeOf:getPrototypeOf}=Object,{iterator:iterator,toStringTag:toStringTag}=Symbol,kindOf=(e=>t=>{const r=toString.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=e=>(e=e.toLowerCase(),t=>kindOf(t)===e),typeOfTest=e=>t=>typeof t===e,{isArray:isArray}=Array,isUndefined=typeOfTest("undefined");function isBuffer(e){return null!==e&&!isUndefined(e)&&null!==e.constructor&&!isUndefined(e.constructor)&&isFunction$1(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&isArrayBuffer(e.buffer),t}const isString=typeOfTest("string"),isFunction$1=typeOfTest("function"),isNumber=typeOfTest("number"),isObject$1=e=>null!==e&&"object"==typeof e,isBoolean=e=>!0===e||!1===e,isPlainObject$1=e=>{if("object"!==kindOf(e))return!1;const t=getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||toStringTag in e||iterator in e)},isEmptyObject=e=>{if(!isObject$1(e)||isBuffer(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=e=>isObject$1(e)&&isFunction$1(e.pipe),isFormData=e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||isFunction$1(e.append)&&("formdata"===(t=kindOf(e))||"object"===t&&isFunction$1(e.toString)&&"[object FormData]"===e.toString()))},isURLSearchParams=kindOfTest("URLSearchParams"),[isReadableStream,isRequest,isResponse,isHeaders]=["ReadableStream","Request","Response","Headers"].map(kindOfTest),trim=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),isArray(e))for(n=0,i=e.length;n0;)if(n=r[i],t===n.toLowerCase())return n;return null}const _global="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,isContextDefined=e=>!isUndefined(e)&&e!==_global;function merge$1(){const{caseless:e,skipUndefined:t}=isContextDefined(this)&&this||{},r={},n=(n,i)=>{const o=e&&findKey(r,i)||i;isPlainObject$1(r[o])&&isPlainObject$1(n)?r[o]=merge$1(r[o],n):isPlainObject$1(n)?r[o]=merge$1({},n):isArray(n)?r[o]=n.slice():t&&isUndefined(n)||(r[o]=n)};for(let e=0,t=arguments.length;e(forEach(t,(t,n)=>{r&&isFunction$1(t)?Object.defineProperty(e,n,{value:bind(t,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),stripBOM=e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject=(e,t,r,n)=>{let i,o,s;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)s=i[o],n&&!n(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&getPrototypeOf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},endsWith=(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray=e=>{if(!e)return null;if(isArray(e))return e;let t=e.length;if(!isNumber(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},isTypedArray=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&getPrototypeOf(Uint8Array)),forEachEntry=(e,t)=>{const r=(e&&e[iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll=(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),hasOwnProperty=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),isRegExp=kindOfTest("RegExp"),reduceDescriptors=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};forEach(r,(r,i)=>{let o;!1!==(o=t(r,i,e))&&(n[i]=o||r)}),Object.defineProperties(e,n)},freezeMethods=e=>{reduceDescriptors(e,(t,r)=>{if(isFunction$1(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];isFunction$1(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet=(e,t)=>{const r={},n=e=>{e.forEach(e=>{r[e]=!0})};return isArray(e)?n(e):n(String(e).split(t)),r},noop=()=>{},toFiniteNumber=(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t;function isSpecCompliantForm(e){return!!(e&&isFunction$1(e.append)&&"FormData"===e[toStringTag]&&e[iterator])}const toJSONObject=e=>{const t=new Array(10),r=(e,n)=>{if(isObject$1(e)){if(t.indexOf(e)>=0)return;if(isBuffer(e))return e;if(!("toJSON"in e)){t[n]=e;const i=isArray(e)?[]:{};return forEach(e,(e,t)=>{const o=r(e,n+1);!isUndefined(o)&&(i[t]=o)}),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=e=>e&&(isObject$1(e)||isFunction$1(e))&&isFunction$1(e.then)&&isFunction$1(e.catch),_setImmediate=(setImmediateSupported="function"==typeof setImmediate,postMessageSupported=isFunction$1(_global.postMessage),setImmediateSupported?setImmediate:postMessageSupported?(token=`axios@${Math.random()}`,callbacks=[],_global.addEventListener("message",({source:e,data:t})=>{e===_global&&t===token&&callbacks.length&&callbacks.shift()()},!1),e=>{callbacks.push(e),_global.postMessage(token,"*")}):e=>setTimeout(e));var setImmediateSupported,postMessageSupported,token,callbacks;const asap="undefined"!=typeof queueMicrotask?queueMicrotask.bind(_global):_setImmediate,isIterable=e=>null!=e&&isFunction$1(e[iterator]);var utils$1={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isBoolean:isBoolean,isObject:isObject$1,isPlainObject:isPlainObject$1,isEmptyObject:isEmptyObject,isReadableStream:isReadableStream,isRequest:isRequest,isResponse:isResponse,isHeaders:isHeaders,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isRegExp:isRegExp,isFunction:isFunction$1,isStream:isStream,isURLSearchParams:isURLSearchParams,isTypedArray:isTypedArray,isFileList:isFileList,forEach:forEach,merge:merge$1,extend:extend$1,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,forEachEntry:forEachEntry,matchAll:matchAll,isHTMLForm:isHTMLForm,hasOwnProperty:hasOwnProperty,hasOwnProp:hasOwnProperty,reduceDescriptors:reduceDescriptors,freezeMethods:freezeMethods,toObjectSet:toObjectSet,toCamelCase:toCamelCase,noop:noop,toFiniteNumber:toFiniteNumber,findKey:findKey,global:_global,isContextDefined:isContextDefined,isSpecCompliantForm:isSpecCompliantForm,toJSONObject:toJSONObject,isAsyncFn:isAsyncFn,isThenable:isThenable,setImmediate:_setImmediate,asap:asap,isIterable:isIterable};let AxiosError$1=class e extends Error{static from(t,r,n,i,o,s){const a=new e(t.message,r||t.code,n,i,o);return a.cause=t,a.name=t.name,s&&Object.assign(a,s),a}constructor(e,t,r,n,i){super(e),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:utils$1.toJSONObject(this.config),code:this.code,status:this.status}}};AxiosError$1.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",AxiosError$1.ERR_BAD_OPTION="ERR_BAD_OPTION",AxiosError$1.ECONNABORTED="ECONNABORTED",AxiosError$1.ETIMEDOUT="ETIMEDOUT",AxiosError$1.ERR_NETWORK="ERR_NETWORK",AxiosError$1.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",AxiosError$1.ERR_DEPRECATED="ERR_DEPRECATED",AxiosError$1.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",AxiosError$1.ERR_BAD_REQUEST="ERR_BAD_REQUEST",AxiosError$1.ERR_CANCELED="ERR_CANCELED",AxiosError$1.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",AxiosError$1.ERR_INVALID_URL="ERR_INVALID_URL";var httpAdapter=null;function isVisitable(e){return utils$1.isPlainObject(e)||utils$1.isArray(e)}function removeBrackets(e){return utils$1.endsWith(e,"[]")?e.slice(0,-2):e}function renderKey(e,t,r){return e?e.concat(t).map(function(e,t){return e=removeBrackets(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}function isFlatArray(e){return utils$1.isArray(e)&&!e.some(isVisitable)}const predicates=utils$1.toFlatObject(utils$1,{},null,function(e){return/^is[A-Z]/.test(e)});function toFormData$1(e,t,r){if(!utils$1.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=utils$1.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!utils$1.isUndefined(t[e])})).metaTokens,i=r.visitor||l,o=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&utils$1.isSpecCompliantForm(t);if(!utils$1.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(utils$1.isDate(e))return e.toISOString();if(utils$1.isBoolean(e))return e.toString();if(!a&&utils$1.isBlob(e))throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");return utils$1.isArrayBuffer(e)||utils$1.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(utils$1.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(utils$1.isArray(e)&&isFlatArray(e)||(utils$1.isFileList(e)||utils$1.endsWith(r,"[]"))&&(a=utils$1.toArray(e)))return r=removeBrackets(r),a.forEach(function(e,n){!utils$1.isUndefined(e)&&null!==e&&t.append(!0===s?renderKey([r],n,o):null===s?r:r+"[]",c(e))}),!1;return!!isVisitable(e)||(t.append(renderKey(i,r,o),c(e)),!1)}const u=[],d=Object.assign(predicates,{defaultVisitor:l,convertValue:c,isVisitable:isVisitable});if(!utils$1.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!utils$1.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),utils$1.forEach(r,function(r,o){!0===(!(utils$1.isUndefined(r)||null===r)&&i.call(t,r,utils$1.isString(o)?o.trim():o,n,d))&&e(r,n?n.concat(o):[o])}),u.pop()}}(e),t}function encode$1(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function AxiosURLSearchParams(e,t){this._pairs=[],e&&toFormData$1(e,this,t)}const prototype=AxiosURLSearchParams.prototype;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function buildURL(e,t,r){if(!t)return e;const n=r&&r.encode||encode,i=utils$1.isFunction(r)?{serialize:r}:r,o=i&&i.serialize;let s;if(s=o?o(t,i):utils$1.isURLSearchParams(t)?t.toString():new AxiosURLSearchParams(t,i).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}prototype.append=function(e,t){this._pairs.push([e,t])},prototype.toString=function(e){const t=e?function(t){return e.call(this,t,encode$1)}:encode$1;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class InterceptorManager{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){utils$1.forEach(this.handlers,function(t){null!==t&&e(t)})}}var transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},URLSearchParams$1="undefined"!=typeof URLSearchParams?URLSearchParams:AxiosURLSearchParams,FormData$2="undefined"!=typeof FormData?FormData:null,Blob$1="undefined"!=typeof Blob?Blob:null,platform$1={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$1,FormData:FormData$2,Blob:Blob$1},protocols:["http","https","file","blob","url","data"]};const hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost";var utils=Object.freeze({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,navigator:_navigator,origin:origin}),platform={...utils,...platform$1};function toURLEncodedForm(e,t){return toFormData$1(e,new platform.classes.URLSearchParams,{visitor:function(e,t,r,n){return platform.isNode&&utils$1.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...t})}function parsePropPath(e){return utils$1.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}function arrayToObject(e){const t={},r=Object.keys(e);let n;const i=r.length;let o;for(n=0;n=e.length;if(o=!o&&utils$1.isArray(n)?n.length:o,a)return utils$1.hasOwnProp(n,o)?n[o]=[n[o],r]:n[o]=r,!s;n[o]&&utils$1.isObject(n[o])||(n[o]=[]);return t(e,r,n[o],i)&&utils$1.isArray(n[o])&&(n[o]=arrayToObject(n[o])),!s}if(utils$1.isFormData(e)&&utils$1.isFunction(e.entries)){const r={};return utils$1.forEachEntry(e,(e,n)=>{t(parsePropPath(e),n,r,0)}),r}return null}function stringifySafely(e,t,r){if(utils$1.isString(e))try{return(t||JSON.parse)(e),utils$1.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}const defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=utils$1.isObject(e);i&&utils$1.isHTMLForm(e)&&(e=new FormData(e));if(utils$1.isFormData(e))return n?JSON.stringify(formDataToJSON(e)):e;if(utils$1.isArrayBuffer(e)||utils$1.isBuffer(e)||utils$1.isStream(e)||utils$1.isFile(e)||utils$1.isBlob(e)||utils$1.isReadableStream(e))return e;if(utils$1.isArrayBufferView(e))return e.buffer;if(utils$1.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(e,this.formSerializer).toString();if((o=utils$1.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return toFormData$1(o?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),stringifySafely(e)):e}],transformResponse:[function(e){const t=this.transitional||defaults.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(utils$1.isResponse(e)||utils$1.isReadableStream(e))return e;if(e&&utils$1.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e,this.parseReviver)}catch(e){if(r){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$1.forEach(["delete","get","head","post","put","patch"],e=>{defaults.headers[e]={}});const ignoreDuplicateOf=utils$1.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);var parseHeaders=e=>{const t={};let r,n,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&ignoreDuplicateOf[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};const $internals=Symbol("internals");function normalizeHeader(e){return e&&String(e).trim().toLowerCase()}function normalizeValue(e){return!1===e||null==e?e:utils$1.isArray(e)?e.map(normalizeValue):String(e)}function parseTokens(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}const isValidHeaderName=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function matchHeaderValue(e,t,r,n,i){return utils$1.isFunction(n)?n.call(this,t,r):(i&&(t=r),utils$1.isString(t)?utils$1.isString(n)?-1!==t.indexOf(n):utils$1.isRegExp(n)?n.test(t):void 0:void 0)}function formatHeader(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}function buildAccessors(e,t){const r=utils$1.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})})}let AxiosHeaders$1=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=normalizeHeader(t);if(!i)throw new Error("header name must be a non-empty string");const o=utils$1.findKey(n,i);(!o||void 0===n[o]||!0===r||void 0===r&&!1!==n[o])&&(n[o||t]=normalizeValue(e))}const o=(e,t)=>utils$1.forEach(e,(e,r)=>i(e,r,t));if(utils$1.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(utils$1.isString(e)&&(e=e.trim())&&!isValidHeaderName(e))o(parseHeaders(e),t);else if(utils$1.isObject(e)&&utils$1.isIterable(e)){let r,n,i={};for(const t of e){if(!utils$1.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?utils$1.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}o(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=normalizeHeader(e)){const r=utils$1.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return parseTokens(e);if(utils$1.isFunction(t))return t.call(this,e,r);if(utils$1.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=normalizeHeader(e)){const r=utils$1.findKey(this,e);return!(!r||void 0===this[r]||t&&!matchHeaderValue(this,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=normalizeHeader(e)){const i=utils$1.findKey(r,e);!i||t&&!matchHeaderValue(r,r[i],i,t)||(delete r[i],n=!0)}}return utils$1.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!matchHeaderValue(this,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return utils$1.forEach(this,(n,i)=>{const o=utils$1.findKey(r,i);if(o)return t[o]=normalizeValue(n),void delete t[i];const s=e?formatHeader(i):String(i).trim();s!==i&&delete t[i],t[s]=normalizeValue(n),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return utils$1.forEach(this,(r,n)=>{null!=r&&!1!==r&&(t[n]=e&&utils$1.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[$internals]=this[$internals]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=normalizeHeader(e);t[n]||(buildAccessors(r,e),t[n]=!0)}return utils$1.isArray(e)?e.forEach(n):n(e),this}};function transformData(e,t){const r=this||defaults,n=t||r,i=AxiosHeaders$1.from(n.headers);let o=n.data;return utils$1.forEach(e,function(e){o=e.call(r,o,i.normalize(),t?t.status:void 0)}),i.normalize(),o}function isCancel$1(e){return!(!e||!e.__CANCEL__)}AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$1.reduceDescriptors(AxiosHeaders$1.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),utils$1.freezeMethods(AxiosHeaders$1);let CanceledError$1=class extends AxiosError$1{constructor(e,t,r){super(null==e?"canceled":e,AxiosError$1.ERR_CANCELED,t,r),this.name="CanceledError",this.__CANCEL__=!0}};function settle(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new AxiosError$1("Request failed with status code "+r.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}function parseProtocol(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function speedometer(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[s];i||(i=c),r[o]=a,n[o]=c;let u=s,d=0;for(;u!==o;)d+=r[u++],u%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i{i=o,r=null,n&&(clearTimeout(n),n=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=o?s(e,t):(r=e,n||(n=setTimeout(()=>{n=null,s(r)},o-a)))},()=>r&&s(r)]}const progressEventReducer=(e,t,r=3)=>{let n=0;const i=speedometer(50,250);return throttle(r=>{const o=r.loaded,s=r.lengthComputable?r.total:void 0,a=o-n,c=i(a);n=o;e({loaded:o,total:s,progress:s?o/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&o<=s?(s-o)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},progressEventDecorator=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},asyncDecorator=e=>(...t)=>utils$1.asap(()=>e(...t));var isURLSameOrigin=platform.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,platform.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(e,t,r,n,i,o,s){if("undefined"==typeof document)return;const a=[`${e}=${encodeURIComponent(t)}`];utils$1.isNumber(r)&&a.push(`expires=${new Date(r).toUTCString()}`),utils$1.isString(n)&&a.push(`path=${n}`),utils$1.isString(i)&&a.push(`domain=${i}`),!0===o&&a.push("secure"),utils$1.isString(s)&&a.push(`SameSite=${s}`),document.cookie=a.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function isAbsoluteURL(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function combineURLs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function buildFullPath(e,t,r){let n=!isAbsoluteURL(t);return e&&(n||0==r)?combineURLs(e,t):t}const headersToObject=e=>e instanceof AxiosHeaders$1?{...e}:e;function mergeConfig$1(e,t){t=t||{};const r={};function n(e,t,r,n){return utils$1.isPlainObject(e)&&utils$1.isPlainObject(t)?utils$1.merge.call({caseless:n},e,t):utils$1.isPlainObject(t)?utils$1.merge({},t):utils$1.isArray(t)?t.slice():t}function i(e,t,r,i){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function o(e,t){if(!utils$1.isUndefined(t))return n(void 0,t)}function s(e,t){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,o){return o in t?n(r,i):o in e?n(void 0,r):void 0}const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(e,t,r)=>i(headersToObject(e),headersToObject(t),0,!0)};return utils$1.forEach(Object.keys({...e,...t}),function(n){const o=c[n]||i,s=o(e[n],t[n],n);utils$1.isUndefined(s)&&o!==a||(r[n]=s)}),r}var resolveConfig=e=>{const t=mergeConfig$1({},e);let{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:o,headers:s,auth:a}=t;if(t.headers=s=AxiosHeaders$1.from(s),t.url=buildURL(buildFullPath(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),utils$1.isFormData(r))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(utils$1.isFunction(r.getHeaders)){const e=r.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(([e,r])=>{t.includes(e.toLowerCase())&&s.set(e,r)})}if(platform.hasStandardBrowserEnv&&(n&&utils$1.isFunction(n)&&(n=n(t)),n||!1!==n&&isURLSameOrigin(t.url))){const e=i&&o&&cookies.read(o);e&&s.set(i,e)}return t};const isXHRAdapterSupported="undefined"!=typeof XMLHttpRequest;var xhrAdapter=isXHRAdapterSupported&&function(e){return new Promise(function(t,r){const n=resolveConfig(e);let i=n.data;const o=AxiosHeaders$1.from(n.headers).normalize();let s,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function g(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(s),n.signal&&n.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const n=AxiosHeaders$1.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());settle(function(e){t(e),g()},function(e){r(e),g()},{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(f)},m.onabort=function(){m&&(r(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,e,m)),m=null)},m.onerror=function(t){const n=t&&t.message?t.message:"Network Error",i=new AxiosError$1(n,AxiosError$1.ERR_NETWORK,e,m);i.event=t||null,r(i),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||transitionalDefaults;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new AxiosError$1(t,i.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,e,m)),m=null},void 0===i&&o.setContentType(null),"setRequestHeader"in m&&utils$1.forEach(o.toJSON(),function(e,t){m.setRequestHeader(t,e)}),utils$1.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),d&&"json"!==d&&(m.responseType=n.responseType),p&&([c,u]=progressEventReducer(p,!0),m.addEventListener("progress",c)),h&&m.upload&&([a,l]=progressEventReducer(h),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(s=t=>{m&&(r(!t||t.type?new CanceledError$1(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(s),n.signal&&(n.signal.aborted?s():n.signal.addEventListener("abort",s)));const y=parseProtocol(n.url);y&&-1===platform.protocols.indexOf(y)?r(new AxiosError$1("Unsupported protocol "+y+":",AxiosError$1.ERR_BAD_REQUEST,e)):m.send(i||null)})};const composeSignals=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;n.abort(t instanceof AxiosError$1?t:new CanceledError$1(t instanceof Error?t.message:t))}};let o=t&&setTimeout(()=>{o=null,i(new AxiosError$1(`timeout of ${t}ms exceeded`,AxiosError$1.ETIMEDOUT))},t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:a}=n;return a.unsubscribe=()=>utils$1.asap(s),a}},streamChunk=function*(e,t){let r=e.byteLength;if(r{const i=readBytes(e,t);let o,s=0,a=e=>{o||(o=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let o=n.byteLength;if(r){let e=s+=o;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},DEFAULT_CHUNK_SIZE=65536,{isFunction:isFunction}=utils$1,globalFetchAPI=(({Request:e,Response:t})=>({Request:e,Response:t}))(utils$1.global),{ReadableStream:ReadableStream$1,TextEncoder:TextEncoder$1}=utils$1.global,test=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},factory=e=>{e=utils$1.merge.call({skipUndefined:!0},globalFetchAPI,e);const{fetch:t,Request:r,Response:n}=e,i=t?isFunction(t):"function"==typeof fetch,o=isFunction(r),s=isFunction(n);if(!i)return!1;const a=i&&isFunction(ReadableStream$1),c=i&&("function"==typeof TextEncoder$1?(l=new TextEncoder$1,e=>l.encode(e)):async e=>new Uint8Array(await new r(e).arrayBuffer()));var l;const u=o&&a&&test(()=>{let e=!1;const t=new r(platform.origin,{body:new ReadableStream$1,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),d=s&&a&&test(()=>utils$1.isReadableStream(new n("").body)),h={stream:d&&(e=>e.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!h[e]&&(h[e]=(t,r)=>{let n=t&&t[e];if(n)return n.call(t);throw new AxiosError$1(`Response type '${e}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,r)})});const p=async(e,t)=>{const n=utils$1.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(utils$1.isBlob(e))return e.size;if(utils$1.isSpecCompliantForm(e)){const t=new r(platform.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return utils$1.isArrayBufferView(e)||utils$1.isArrayBuffer(e)?e.byteLength:(utils$1.isURLSearchParams(e)&&(e+=""),utils$1.isString(e)?(await c(e)).byteLength:void 0)})(t):n};return async e=>{let{url:i,method:s,data:a,signal:c,cancelToken:l,timeout:g,onDownloadProgress:m,onUploadProgress:f,responseType:y,headers:$,withCredentials:b="same-origin",fetchOptions:v}=resolveConfig(e),w=t||fetch;y=y?(y+"").toLowerCase():"text";let S=composeSignals([c,l&&l.toAbortSignal()],g),_=null;const E=S&&S.unsubscribe&&(()=>{S.unsubscribe()});let C;try{if(f&&u&&"get"!==s&&"head"!==s&&0!==(C=await p($,a))){let e,t=new r(i,{method:"POST",body:a,duplex:"half"});if(utils$1.isFormData(a)&&(e=t.headers.get("content-type"))&&$.setContentType(e),t.body){const[e,r]=progressEventDecorator(C,progressEventReducer(asyncDecorator(f)));a=trackStream(t.body,DEFAULT_CHUNK_SIZE,e,r)}}utils$1.isString(b)||(b=b?"include":"omit");const t=o&&"credentials"in r.prototype,c={...v,signal:S,method:s.toUpperCase(),headers:$.normalize().toJSON(),body:a,duplex:"half",credentials:t?b:void 0};_=o&&new r(i,c);let l=await(o?w(_,v):w(i,c));const g=d&&("stream"===y||"response"===y);if(d&&(m||g&&E)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=l[t]});const t=utils$1.toFiniteNumber(l.headers.get("content-length")),[r,i]=m&&progressEventDecorator(t,progressEventReducer(asyncDecorator(m),!0))||[];l=new n(trackStream(l.body,DEFAULT_CHUNK_SIZE,r,()=>{i&&i(),E&&E()}),e)}y=y||"text";let I=await h[utils$1.findKey(h,y)||"text"](l,e);return!g&&E&&E(),await new Promise((t,r)=>{settle(t,r,{data:I,headers:AxiosHeaders$1.from(l.headers),status:l.status,statusText:l.statusText,config:e,request:_})})}catch(t){if(E&&E(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,e,_),{cause:t.cause||t});throw AxiosError$1.from(t,t&&t.code,e,_)}}},seedCache=new Map,getFetch=e=>{let t=e&&e.env||{};const{fetch:r,Request:n,Response:i}=t,o=[n,i,r];let s,a,c=o.length,l=seedCache;for(;c--;)s=o[c],a=l.get(s),void 0===a&&l.set(s,a=c?new Map:factory(t)),l=a;return a};getFetch();const knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:{get:getFetch}};utils$1.forEach(knownAdapters,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const renderReason=e=>`- ${e}`,isResolvedHandle=e=>utils$1.isFunction(e)||null===e||!1===e;function getAdapter$1(e,t){e=utils$1.isArray(e)?e:[e];const{length:r}=e;let n,i;const o={};for(let s=0;s`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));let t=r?e.length>1?"since :\n"+e.map(renderReason).join("\n"):" "+renderReason(e[0]):"as no adapter specified";throw new AxiosError$1("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return i}var adapters={getAdapter:getAdapter$1,adapters:knownAdapters};function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError$1(null,e)}function dispatchRequest(e){throwIfCancellationRequested(e),e.headers=AxiosHeaders$1.from(e.headers),e.data=transformData.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return adapters.getAdapter(e.adapter||defaults.adapter,e)(e).then(function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,e.transformResponse,t),t.headers=AxiosHeaders$1.from(t.headers),t},function(t){return isCancel$1(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,e.transformResponse,t.response),t.response.headers=AxiosHeaders$1.from(t.response.headers))),Promise.reject(t)})}const VERSION$1="1.13.4",validators$1={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{validators$1[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const deprecatedWarnings={};function assertOptions(e,t,r){if("object"!=typeof e)throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const o=n[i],s=t[o];if(s){const t=e[o],r=void 0===t||s(t,o,e);if(!0!==r)throw new AxiosError$1("option "+o+" must be "+r,AxiosError$1.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new AxiosError$1("Unknown option "+o,AxiosError$1.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,r){function n(e,t){return"[Axios v"+VERSION$1+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,o)=>{if(!1===e)throw new AxiosError$1(n(i," has been removed"+(t?" in "+t:"")),AxiosError$1.ERR_DEPRECATED);return t&&!deprecatedWarnings[i]&&(deprecatedWarnings[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,o)}},validators$1.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var validator={assertOptions:assertOptions,validators:validators$1};const validators=validator.validators;let Axios$1=class{constructor(e){this.defaults=e||{},this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=mergeConfig$1(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&validator.assertOptions(r,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),null!=n&&(utils$1.isFunction(n)?t.paramsSerializer={serialize:n}:validator.assertOptions(n,{encode:validators.function,serialize:validators.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),validator.assertOptions(t,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=i&&utils$1.merge(i.common,i[t.method]);i&&utils$1.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=AxiosHeaders$1.concat(o,i);const s=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))});const c=[];let l;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let u,d=0;if(!a){const e=[dispatchRequest.bind(this),void 0];for(e.unshift(...s),e.push(...c),u=e.length,l=Promise.resolve(t);d{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const n=new Promise(e=>{r.subscribe(e),t=e}).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e(function(e,n,i){r.reason||(r.reason=new CanceledError$1(e,n,i),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;const r=new e(function(e){t=e});return{token:r,cancel:t}}};function spread$1(e){return function(t){return e.apply(null,t)}}function isAxiosError$1(e){return utils$1.isObject(e)&&!0===e.isAxiosError}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};function createInstance(e){const t=new Axios$1(e),r=bind(Axios$1.prototype.request,t);return utils$1.extend(r,Axios$1.prototype,t,{allOwnKeys:!0}),utils$1.extend(r,t,null,{allOwnKeys:!0}),r.create=function(t){return createInstance(mergeConfig$1(e,t))},r}Object.entries(HttpStatusCode$1).forEach(([e,t])=>{HttpStatusCode$1[t]=e});const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$1,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function(e){return Promise.all(e)},axios.spread=spread$1,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=e=>formDataToJSON(utils$1.isHTMLForm(e)?new FormData(e):e),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios:Axios,AxiosError:AxiosError,CanceledError:CanceledError,isCancel:isCancel,CancelToken:CancelToken,VERSION:VERSION,all:all,Cancel:Cancel,isAxiosError:isAxiosError,spread:spread,toFormData:toFormData,AxiosHeaders:AxiosHeaders,HttpStatusCode:HttpStatusCode,formToJSON:formToJSON,getAdapter:getAdapter,mergeConfig:mergeConfig}=axios;class InvalidTokenError extends Error{}function b64DecodeUnicode(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function base64UrlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return b64DecodeUnicode(t)}catch(e){return atob(t)}}function jwtDecode(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${r+1}`);let i;try{i=base64UrlDecode(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}InvalidTokenError.prototype.name="InvalidTokenError";var browser="object"==typeof self?self.FormData:window.FormData,FormData$1=getDefaultExportFromCjs$2(browser);const NEVER=Object.freeze({status:"aborted"});function $constructor(e,t,r){function n(r,n){var i;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(i=r._zod).traits??(i.traits=new Set),r._zod.traits.add(e),t(r,n);for(const e in s.prototype)e in r||Object.defineProperty(r,e,{value:s.prototype[e].bind(r)});r._zod.constr=s,r._zod.def=n}const i=r?.Parent??Object;class o extends i{}function s(e){var t;const i=r?.Parent?new o:this;n(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}const $brand=Symbol("zod_brand");class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const globalConfig={};function config(e){return e&&Object.assign(globalConfig,e),globalConfig}function assertEqual(e){return e}function assertNotEqual(e){return e}function assertIs(e){}function assertNever(e){throw new Error}function assert(e){}function getEnumValues(e){const t=Object.values(e).filter(e=>"number"==typeof e),r=Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t);return r}function joinValues(e,t="|"){return e.map(e=>stringifyPrimitive(e)).join(t)}function jsonStringifyReplacer(e,t){return"bigint"==typeof t?t.toString():t}function cached(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function nullish$1(e){return null==e}function cleanRegex(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function floatSafeRemainder(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let i=(n.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(n)){const e=n.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}const o=r>i?r:i;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}const EVALUATING=Symbol("evaluating");function defineLazy(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==EVALUATING)return void 0===n&&(n=EVALUATING,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function objectClone(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function assignProp(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...e){const t={};for(const r of e){const e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}function cloneDef(e){return mergeDefs(e._zod.def)}function getElementAtPath(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function promiseAllObject(e){const t=Object.keys(e),r=t.map(t=>e[t]);return Promise.all(r).then(e=>{const r={};for(let n=0;n{};function isObject(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const allowsEval=cached(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function isPlainObject(e){if(!1===isObject(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==isObject(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function shallowClone(e){return isPlainObject(e)?{...e}:e}function numKeys(e){let t=0;for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}const getParsedType=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":"undefined"!=typeof Map&&e instanceof Map?"map":"undefined"!=typeof Set&&e instanceof Set?"set":"undefined"!=typeof Date&&e instanceof Date?"date":"undefined"!=typeof File&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function normalizeParams(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function createTransparentProxy(e){let t;return new Proxy({},{get:(r,n,i)=>(t??(t=e()),Reflect.get(t,n,i)),set:(r,n,i,o)=>(t??(t=e()),Reflect.set(t,n,i,o)),has:(r,n)=>(t??(t=e()),Reflect.has(t,n)),deleteProperty:(r,n)=>(t??(t=e()),Reflect.deleteProperty(t,n)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,n)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)),defineProperty:(r,n,i)=>(t??(t=e()),Reflect.defineProperty(t,n,i))})}function stringifyPrimitive(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function optionalKeys(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}const NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pick(e,t){const r=e._zod.def;return clone(e,mergeDefs(e._zod.def,{get shape(){const e={};for(const n in t){if(!(n in r.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(e[n]=r.shape[n])}return assignProp(this,"shape",e),e},checks:[]}))}function omit(e,t){const r=e._zod.def,n=mergeDefs(e._zod.def,{get shape(){const n={...e._zod.def.shape};for(const e in t){if(!(e in r.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return assignProp(this,"shape",n),n},checks:[]});return clone(e,n)}function extend(e,t){if(!isPlainObject(t))throw new Error("Invalid input to extend: expected a plain object");const r=mergeDefs(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return assignProp(this,"shape",r),r},checks:[]});return clone(e,r)}function merge(e,t){const r=mergeDefs(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return assignProp(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return clone(e,r)}function partial(e,t,r){const n=mergeDefs(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(const t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return assignProp(this,"shape",i),i},checks:[]});return clone(t,n)}function required(e,t,r){const n=mergeDefs(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(const t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return assignProp(this,"shape",i),i},checks:[]});return clone(t,n)}function aborted(e,t=0){for(let r=t;r{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return"string"==typeof e?e:e?.message}function finalizeIssue(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const i=unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(r.customError?.(e))??unwrapMessage(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function getSizableOrigin(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function getLengthableOrigin(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function issue(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}function cleanEnum(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}class Class{constructor(...e){}}var util=Object.freeze({__proto__:null,BIGINT_FORMAT_RANGES:BIGINT_FORMAT_RANGES,Class:Class,NUMBER_FORMAT_RANGES:NUMBER_FORMAT_RANGES,aborted:aborted,allowsEval:allowsEval,assert:assert,assertEqual:assertEqual,assertIs:assertIs,assertNever:assertNever,assertNotEqual:assertNotEqual,assignProp:assignProp,cached:cached,captureStackTrace:captureStackTrace,cleanEnum:cleanEnum,cleanRegex:cleanRegex,clone:clone,cloneDef:cloneDef,createTransparentProxy:createTransparentProxy,defineLazy:defineLazy,esc:esc,escapeRegex:escapeRegex,extend:extend,finalizeIssue:finalizeIssue,floatSafeRemainder:floatSafeRemainder,getElementAtPath:getElementAtPath,getEnumValues:getEnumValues,getLengthableOrigin:getLengthableOrigin,getParsedType:getParsedType,getSizableOrigin:getSizableOrigin,isObject:isObject,isPlainObject:isPlainObject,issue:issue,joinValues:joinValues,jsonStringifyReplacer:jsonStringifyReplacer,merge:merge,mergeDefs:mergeDefs,normalizeParams:normalizeParams,nullish:nullish$1,numKeys:numKeys,objectClone:objectClone,omit:omit,optionalKeys:optionalKeys,partial:partial,pick:pick,prefixIssues:prefixIssues,primitiveTypes:primitiveTypes,promiseAllObject:promiseAllObject,propertyKeyTypes:propertyKeyTypes,randomString:randomString,required:required,shallowClone:shallowClone,stringifyPrimitive:stringifyPrimitive,unwrapMessage:unwrapMessage});const initializer$1=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jsonStringifyReplacer,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer$1),$ZodRealError=$constructor("$ZodError",initializer$1,{Parent:Error});function flattenError(e,t=e=>e.message){const r={},n=[];for(const i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function formatError(e,t){const r=t||function(e){return e.message},n={_errors:[]},i=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>i({issues:e}));else if("invalid_key"===t.code)i({issues:t.issues});else if("invalid_element"===t.code)i({issues:t.issues});else if(0===t.path.length)n._errors.push(r(t));else{let e=n,i=0;for(;i{var o,s;for(const a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map(e=>i({issues:e},a.path));else if("invalid_key"===a.code)i({issues:a.issues},a.path);else if("invalid_element"===a.code)i({issues:a.issues},a.path);else{const e=[...t,...a.path];if(0===e.length){n.errors.push(r(a));continue}let i=n,c=0;for(;c"object"==typeof e?e.key:e);for(const e of r)"number"==typeof e?t.push(`[${e}]`):"symbol"==typeof e?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push("."),t.push(e));return t.join("")}function prettifyError(e){const t=[],r=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(const e of r)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${toDotPath(e.path)}`);return t.join("\n")}const _parse=e=>(t,r,n,i)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new $ZodAsyncError;if(s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(t,i?.callee),t}return s.value},parse$1=_parse($ZodRealError),_parseAsync=e=>async(t,r,n,i)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(t,i?.callee),t}return s.value},parseAsync$1=_parseAsync($ZodRealError),_safeParse=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new $ZodAsyncError;return o.issues.length?{success:!1,error:new(e??$ZodError)(o.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:o.value}},safeParse$1=_safeParse($ZodRealError),_safeParseAsync=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:o.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),cuid$1=/^[cC][^\s-]{8,}$/,cuid2$1=/^[0-9a-z]+$/,ulid$1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid$1=/^[0-9a-vA-V]{20}$/,ksuid$1=/^[A-Za-z0-9]{27}$/,nanoid$2=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid$1=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid$1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,uuid4=uuid$1(4),uuid6=uuid$1(6),uuid7=uuid$1(7),email$1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,_emoji$1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function emoji$1(){return new RegExp(_emoji$1,"u")}const ipv4$1=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6$1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,cidrv4$1=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6$1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64$1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url$1=/^[A-Za-z0-9_-]*$/,hostname$1=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,e164$1=/^\+(?:[0-9]){6,14}[0-9]$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date$3=new RegExp(`^${dateSource}$`);function timeSource(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time$1(e){return new RegExp(`^${timeSource(e)}$`)}function datetime$1(e){const t=timeSource({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${dateSource}T(?:${n})$`)}const string$2=e=>new RegExp(`^${e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*"}$`),bigint$2=/^\d+n?$/,integer=/^\d+$/,number$2=/^-?\d+(?:\.\d+)?/i,boolean$2=/true|false/i,_null$2=/null/i,_undefined$2=/undefined/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/;var regexes=Object.freeze({__proto__:null,base64:base64$1,base64url:base64url$1,bigint:bigint$2,boolean:boolean$2,browserEmail:browserEmail,cidrv4:cidrv4$1,cidrv6:cidrv6$1,cuid:cuid$1,cuid2:cuid2$1,date:date$3,datetime:datetime$1,domain:domain,duration:duration$1,e164:e164$1,email:email$1,emoji:emoji$1,extendedDuration:extendedDuration,guid:guid$1,hostname:hostname$1,html5Email:html5Email,idnEmail:idnEmail,integer:integer,ipv4:ipv4$1,ipv6:ipv6$1,ksuid:ksuid$1,lowercase:lowercase,nanoid:nanoid$2,null:_null$2,number:number$2,rfc5322Email:rfc5322Email,string:string$2,time:time$1,ulid:ulid$1,undefined:_undefined$2,unicodeEmail:unicodeEmail,uppercase:uppercase,uuid:uuid$1,uuid4:uuid4,uuid6:uuid6,uuid7:uuid7,xid:xid$1});const $ZodCheck=$constructor("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(e,t)=>{$ZodCheck.init(e,t);const r=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?n.value<=t.value:n.value{$ZodCheck.init(e,t);const r=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(e,t)=>{$ZodCheck.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===floatSafeRemainder(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(e,t)=>{$ZodCheck.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,o]=NUMBER_FORMAT_RANGES[t.format];e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=o,r&&(n.pattern=integer)}),e._zod.check=s=>{const a=s.value;if(r){if(!Number.isInteger(a))return void s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}))}ao&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:e})}}),$ZodCheckBigIntFormat=$constructor("$ZodCheckBigIntFormat",(e,t)=>{$ZodCheck.init(e,t);const[r,n]=BIGINT_FORMAT_RANGES[t.format];e._zod.onattach.push(e=>{const i=e._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=i=>{const o=i.value;on&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:n,inst:e})}}),$ZodCheckMaxSize=$constructor("$ZodCheckMaxSize",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const n=r.value;n.size<=t.maximum||r.issues.push({origin:getSizableOrigin(n),code:"too_big",maximum:t.maximum,input:n,inst:e,continue:!t.abort})}}),$ZodCheckMinSize=$constructor("$ZodCheckMinSize",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;n.size>=t.minimum||r.issues.push({origin:getSizableOrigin(n),code:"too_small",minimum:t.minimum,input:n,inst:e,continue:!t.abort})}}),$ZodCheckSizeEquals=$constructor("$ZodCheckSizeEquals",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=r=>{const n=r.value,i=n.size;if(i===t.size)return;const o=i>t.size;r.issues.push({origin:getSizableOrigin(n),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const n=r.value;if(n.length<=t.maximum)return;const i=getLengthableOrigin(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const i=getLengthableOrigin(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const n=r.value,i=n.length;if(i===t.length)return;const o=getLengthableOrigin(n),s=i>t.length;r.issues.push({origin:o,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(e,t)=>{var r,n;$ZodCheck.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(e,t)=>{$ZodCheckStringFormat.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=lowercase),$ZodCheckStringFormat.init(e,t)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=uppercase),$ZodCheckStringFormat.init(e,t)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(e,t)=>{$ZodCheck.init(e,t);const r=escapeRegex(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(e,t)=>{$ZodCheck.init(e,t);const r=new RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(e,t)=>{$ZodCheck.init(e,t);const r=new RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});function handleCheckPropertyResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues))}const $ZodCheckProperty=$constructor("$ZodCheckProperty",(e,t)=>{$ZodCheck.init(e,t),e._zod.check=e=>{const r=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(r instanceof Promise)return r.then(r=>handleCheckPropertyResult(r,e,t.property));handleCheckPropertyResult(r,e,t.property)}}),$ZodCheckMimeType=$constructor("$ZodCheckMimeType",(e,t)=>{$ZodCheck.init(e,t);const r=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(e,t)=>{$ZodCheck.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Doc{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),n=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args,r=[...(this?.content??[""]).map(e=>` ${e}`)];return new e(...t,r.join("\n"))}}const version={major:4,minor:0,patch:17},$ZodType=$constructor("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,i=aborted(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===r?.async)throw new $ZodAsyncError;if(n||s instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await s;e.issues.length!==t&&(i||(i=aborted(e,t)))});else{if(e.issues.length===t)continue;i||(i=aborted(e,t))}}return n?n.then(()=>e):e};e._zod.run=(r,i)=>{const o=e._zod.parse(r,i);if(o instanceof Promise){if(!1===i.async)throw new $ZodAsyncError;return o.then(e=>t(e,n,i))}return t(o,n,i)}}e["~standard"]={validate:t=>{try{const r=safeParse$1(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return safeParseAsync$1(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),$ZodString=$constructor("$ZodString",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$2(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),$ZodStringFormat=$constructor("$ZodStringFormat",(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodGUID=$constructor("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=guid$1),$ZodStringFormat.init(e,t)}),$ZodUUID=$constructor("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=uuid$1(e))}else t.pattern??(t.pattern=uuid$1());$ZodStringFormat.init(e,t)}),$ZodEmail=$constructor("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=email$1),$ZodStringFormat.init(e,t)}),$ZodURL=$constructor("$ZodURL",(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=r=>{try{const n=r.value.trim(),i=new URL(n);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:hostname$1.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(t.normalize?r.value=i.href:r.value=n)}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=emoji$1()),$ZodStringFormat.init(e,t)}),$ZodNanoID=$constructor("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=nanoid$2),$ZodStringFormat.init(e,t)}),$ZodCUID=$constructor("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=cuid$1),$ZodStringFormat.init(e,t)}),$ZodCUID2=$constructor("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=cuid2$1),$ZodStringFormat.init(e,t)}),$ZodULID=$constructor("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ulid$1),$ZodStringFormat.init(e,t)}),$ZodXID=$constructor("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xid$1),$ZodStringFormat.init(e,t)}),$ZodKSUID=$constructor("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ksuid$1),$ZodStringFormat.init(e,t)}),$ZodISODateTime=$constructor("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=datetime$1(t)),$ZodStringFormat.init(e,t)}),$ZodISODate=$constructor("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=date$3),$ZodStringFormat.init(e,t)}),$ZodISOTime=$constructor("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=time$1(t)),$ZodStringFormat.init(e,t)}),$ZodISODuration=$constructor("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=duration$1),$ZodStringFormat.init(e,t)}),$ZodIPv4=$constructor("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ipv4$1),$ZodStringFormat.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),$ZodIPv6=$constructor("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ipv6$1),$ZodStringFormat.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=cidrv4$1),$ZodStringFormat.init(e,t)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=cidrv6$1),$ZodStringFormat.init(e,t),e._zod.check=r=>{const[n,i]=r.value.split("/");try{if(!i)throw new Error;const e=Number(i);if(`${e}`!==i)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function isValidBase64(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const $ZodBase64=$constructor("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=base64$1),$ZodStringFormat.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{isValidBase64(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function isValidBase64URL(e){if(!base64url$1.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return isValidBase64(t.padEnd(4*Math.ceil(t.length/4),"="))}const $ZodBase64URL=$constructor("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=base64url$1),$ZodStringFormat.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{isValidBase64URL(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),$ZodE164=$constructor("$ZodE164",(e,t)=>{t.pattern??(t.pattern=e164$1),$ZodStringFormat.init(e,t)});function isValidJWT(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[n]=r;if(!n)return!1;const i=JSON.parse(atob(n));return(!("typ"in i)||"JWT"===i?.typ)&&(!!i.alg&&(!t||"alg"in i&&i.alg===t))}catch{return!1}}const $ZodJWT=$constructor("$ZodJWT",(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=r=>{isValidJWT(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),$ZodCustomStringFormat=$constructor("$ZodCustomStringFormat",(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),$ZodNumber=$constructor("$ZodNumber",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$2,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),$ZodNumberFormat=$constructor("$ZodNumber",(e,t)=>{$ZodCheckNumberFormat.init(e,t),$ZodNumber.init(e,t)}),$ZodBoolean=$constructor("$ZodBoolean",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$2,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),$ZodBigInt=$constructor("$ZodBigInt",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=bigint$2,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),$ZodBigIntFormat=$constructor("$ZodBigInt",(e,t)=>{$ZodCheckBigIntFormat.init(e,t),$ZodBigInt.init(e,t)}),$ZodSymbol=$constructor("$ZodSymbol",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>{const n=t.value;return"symbol"==typeof n||t.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:e}),t}}),$ZodUndefined=$constructor("$ZodUndefined",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_undefined$2,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,r)=>{const n=t.value;return void 0===n||t.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),t}}),$ZodNull=$constructor("$ZodNull",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_null$2,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const n=t.value;return null===n||t.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),t}}),$ZodAny=$constructor("$ZodAny",(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e}),$ZodUnknown=$constructor("$ZodUnknown",(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e}),$ZodNever=$constructor("$ZodNever",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),$ZodVoid=$constructor("$ZodVoid",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>{const n=t.value;return void 0===n||t.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),t}}),$ZodDate=$constructor("$ZodDate",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(e){}const i=r.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),r}});function handleArrayResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),t.value[r]=e.value}const $ZodArray=$constructor("$ZodArray",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let e=0;ehandleArrayResult(t,r,e))):handleArrayResult(a,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function handlePropertyResult(e,t,r,n){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const $ZodObject=$constructor("$ZodObject",(e,t)=>{$ZodType.init(e,t);const r=cached(()=>{const e=Object.keys(t.shape);for(const r of e)if(!t.shape[r]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=optionalKeys(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});defineLazy(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r});let n;const i=isObject,o=!globalConfig.jitless,s=o&&allowsEval.value,a=t.catchall;let c;e._zod.parse=(l,u)=>{c??(c=r.value);const d=l.value;if(!i(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;const h=[];if(o&&s&&!1===u?.async&&!0!==u.jitless)n||(n=(e=>{const t=new Doc(["shape","payload","ctx"]),n=r.value,i=e=>{const t=esc(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let s=0;for(const e of n.keys)o[e]="key_"+s++;t.write("const newResult = {}");for(const e of n.keys){const r=o[e],n=esc(e);t.write(`const ${r} = ${i(e)};`),t.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${n}, ...iss.path] : [${n}]\n })));\n }\n \n if (${r}.value === undefined) {\n if (${n} in input) {\n newResult[${n}] = undefined;\n }\n } else {\n newResult[${n}] = ${r}.value;\n }\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,r)=>a(e,t,r)})(t.shape)),l=n(l,u);else{l.value={};const e=c.shape;for(const t of c.keys){const r=e[t]._zod.run({value:d[t],issues:[]},u);r instanceof Promise?h.push(r.then(e=>handlePropertyResult(e,l,t,d))):handlePropertyResult(r,l,t,d)}}if(!a)return h.length?Promise.all(h).then(()=>l):l;const p=[],g=c.keySet,m=a._zod,f=m.def.type;for(const e of Object.keys(d)){if(g.has(e))continue;if("never"===f){p.push(e);continue}const t=m.run({value:d[e],issues:[]},u);t instanceof Promise?h.push(t.then(t=>handlePropertyResult(t,l,e,d))):handlePropertyResult(t,l,e,d)}return p.length&&l.issues.push({code:"unrecognized_keys",keys:p,input:d,inst:e}),h.length?Promise.all(h).then(()=>l):l}});function handleUnionResults(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;const i=e.filter(e=>!aborted(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,n,config())))}),t)}const $ZodUnion=$constructor("$ZodUnion",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),defineLazy(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),defineLazy(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazy(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>cleanRegex(e.source)).join("|")})$`)}});const r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(r)return n(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>handleUnionResults(t,i,e,o)):handleUnionResults(a,i,e,o)}}),$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(e,t)=>{$ZodUnion.init(e,t);const r=e._zod.parse;defineLazy(e._zod,"propValues",()=>{const e={};for(const r of t.options){const n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[t,r]of Object.entries(n)){e[t]||(e[t]=new Set);for(const n of r)e[t].add(n)}}return e});const n=cached(()=>{const e=t.options,r=new Map;for(const n of e){const e=n._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const t of e){if(r.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(i,o)=>{const s=i.value;if(!isObject(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),i)}}),$ZodIntersection=$constructor("$ZodIntersection",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,r)=>{const n=e.value,i=t.left._zod.run({value:n,issues:[]},r),o=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,r])=>handleIntersectionResults(e,t,r)):handleIntersectionResults(e,i,o)}});function mergeValues(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(isPlainObject(e)&&isPlainObject(t)){const r=Object.keys(t),n=Object.keys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of n){const n=mergeValues(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};i[r]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n{$ZodType.init(e,t);const r=t.items,n=r.length-[...r].reverse().findIndex(e=>"optional"!==e._zod.optin);e._zod.parse=(i,o)=>{const s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];const a=[];if(!t.rest){const t=s.length>r.length,o=s.length=s.length&&c>=n)continue;const t=e._zod.run({value:s[c],issues:[]},o);t instanceof Promise?a.push(t.then(e=>handleTupleResult(e,i,c))):handleTupleResult(t,i,c)}if(t.rest){const e=s.slice(r.length);for(const r of e){c++;const e=t.rest._zod.run({value:r,issues:[]},o);e instanceof Promise?a.push(e.then(e=>handleTupleResult(e,i,c))):handleTupleResult(e,i,c)}}return a.length?Promise.all(a).then(()=>i):i}});function handleTupleResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),t.value[r]=e.value}const $ZodRecord=$constructor("$ZodRecord",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!isPlainObject(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;const o=[];if(t.keyType._zod.values){const s=t.keyType._zod.values;r.value={};for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const s=t.valueType._zod.run({value:i[e],issues:[]},n);s instanceof Promise?o.push(s.then(t=>{t.issues.length&&r.issues.push(...prefixIssues(e,t.issues)),r.value[e]=t.value})):(s.issues.length&&r.issues.push(...prefixIssues(e,s.issues)),r.value[e]=s.value)}let a;for(const e in i)s.has(e)||(a=a??[],a.push(e));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:a})}else{r.value={};for(const s of Reflect.ownKeys(i)){if("__proto__"===s)continue;const a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>finalizeIssue(e,n,config())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}const c=t.valueType._zod.run({value:i[s],issues:[]},n);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&r.issues.push(...prefixIssues(s,e.issues)),r.value[a.value]=e.value})):(c.issues.length&&r.issues.push(...prefixIssues(s,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),$ZodMap=$constructor("$ZodMap",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!(i instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),r;const o=[];r.value=new Map;for(const[s,a]of i){const c=t.keyType._zod.run({value:s,issues:[]},n),l=t.valueType._zod.run({value:a,issues:[]},n);c instanceof Promise||l instanceof Promise?o.push(Promise.all([c,l]).then(([t,o])=>{handleMapResult(t,o,r,s,i,e,n)})):handleMapResult(c,l,r,s,i,e,n)}return o.length?Promise.all(o).then(()=>r):r}});function handleMapResult(e,t,r,n,i,o,s){e.issues.length&&(propertyKeyTypes.has(typeof n)?r.issues.push(...prefixIssues(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map(e=>finalizeIssue(e,s,config()))})),t.issues.length&&(propertyKeyTypes.has(typeof n)?r.issues.push(...prefixIssues(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:n,issues:t.issues.map(e=>finalizeIssue(e,s,config()))})),r.value.set(e.value,t.value)}const $ZodSet=$constructor("$ZodSet",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!(i instanceof Set))return r.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),r;const o=[];r.value=new Set;for(const e of i){const i=t.valueType._zod.run({value:e,issues:[]},n);i instanceof Promise?o.push(i.then(e=>handleSetResult(e,r))):handleSetResult(i,r)}return o.length?Promise.all(o).then(()=>r):r}});function handleSetResult(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const $ZodEnum=$constructor("$ZodEnum",(e,t)=>{$ZodType.init(e,t);const r=getEnumValues(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(e=>propertyKeyTypes.has(typeof e)).map(e=>"string"==typeof e?escapeRegex(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const o=t.value;return n.has(o)||t.issues.push({code:"invalid_value",values:r,input:o,inst:e}),t}}),$ZodLiteral=$constructor("$ZodLiteral",(e,t)=>{if($ZodType.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?escapeRegex(e):e?escapeRegex(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,n)=>{const i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),$ZodFile=$constructor("$ZodFile",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>{const n=t.value;return n instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:n,inst:e}),t}}),$ZodTransform=$constructor("$ZodTransform",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,r)=>{const n=t.transform(e.value,e);if(r.async){return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(e.value=t,e))}if(n instanceof Promise)throw new $ZodAsyncError;return e.value=n,e}});function handleOptionalResult(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const $ZodOptional=$constructor("$ZodOptional",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",e._zod.optout="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),defineLazy(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cleanRegex(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>handleOptionalResult(t,e.value)):handleOptionalResult(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}}),$ZodNullable=$constructor("$ZodNullable",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),defineLazy(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cleanRegex(e.source)}|null)$`):void 0}),defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),$ZodDefault=$constructor("$ZodDefault",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>handleDefaultResult(e,t)):handleDefaultResult(n,t)}});function handleDefaultResult(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const $ZodPrefault=$constructor("$ZodPrefault",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),$ZodNonOptional=$constructor("$ZodNonOptional",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(t=>handleNonOptionalResult(t,e)):handleNonOptionalResult(i,e)}});function handleNonOptionalResult(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const $ZodSuccess=$constructor("$ZodSuccess",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===n.issues.length,e)}}),$ZodCatch=$constructor("$ZodCatch",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>finalizeIssue(e,r,config()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>finalizeIssue(e,r,config()))},input:e.value}),e.issues=[]),e)}}),$ZodNaN=$constructor("$ZodNaN",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)}),$ZodPipe=$constructor("$ZodPipe",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"values",()=>t.in._zod.values),defineLazy(e._zod,"optin",()=>t.in._zod.optin),defineLazy(e._zod,"optout",()=>t.out._zod.optout),defineLazy(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{const n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>handlePipeResult(e,t,r)):handlePipeResult(n,t,r)}});function handlePipeResult(e,t,r){return e.issues.length?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const $ZodReadonly=$constructor("$ZodReadonly",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"propValues",()=>t.innerType._zod.propValues),defineLazy(e._zod,"values",()=>t.innerType._zod.values),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(handleReadonlyResult):handleReadonlyResult(n)}});function handleReadonlyResult(e){return e.value=Object.freeze(e.value),e}const $ZodTemplateLiteral=$constructor("$ZodTemplateLiteral",(e,t)=>{$ZodType.init(e,t);const r=[];for(const e of t.parts)if("object"==typeof e&&null!==e){if(!e._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);const t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw new Error(`Invalid template literal part: ${e._zod.traits}`);const n=t.startsWith("^")?1:0,i=t.endsWith("$")?t.length-1:t.length;r.push(t.slice(n,i))}else{if(null!==e&&!primitiveTypes.has(typeof e))throw new Error(`Invalid template literal part: ${e}`);r.push(escapeRegex(`${e}`))}e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(r,n)=>"string"!=typeof r.value?(r.issues.push({input:r.value,inst:e,expected:"template_literal",code:"invalid_type"}),r):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r)}),$ZodPromise=$constructor("$ZodPromise",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,r)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},r))}),$ZodLazy=$constructor("$ZodLazy",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"innerType",()=>t.getter()),defineLazy(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),defineLazy(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),defineLazy(e._zod,"optin",()=>e._zod.innerType._zod.optin??void 0),defineLazy(e._zod,"optout",()=>e._zod.innerType._zod.optout??void 0),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)}),$ZodCustom=$constructor("$ZodCustom",(e,t)=>{$ZodCheck.init(e,t),$ZodType.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(t=>handleRefineResult(t,r,n,e));handleRefineResult(i,r,n,e)}});function handleRefineResult(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(issue(e))}}const error$F=()=>{const e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(t){return e[t]??null}const r={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return e=>{switch(e.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${e.expected}، ولكن تم إدخال ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(e.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?` أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${r} ${e.maximum.toString()} ${n.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${r} ${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${r} ${e.minimum.toString()} ${n.unit}`:`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${r} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`نَص غير مقبول: يجب أن يبدأ بـ "${e.prefix}"`:"ends_with"===t.format?`نَص غير مقبول: يجب أن ينتهي بـ "${t.suffix}"`:"includes"===t.format?`نَص غير مقبول: يجب أن يتضمَّن "${t.includes}"`:"regex"===t.format?`نَص غير مقبول: يجب أن يطابق النمط ${t.pattern}`:`${r[t.format]??e.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${e.divisor}`;case"unrecognized_keys":return`معرف${e.keys.length>1?"ات":""} غريب${e.keys.length>1?"ة":""}: ${joinValues(e.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${e.origin}`;case"invalid_union":default:return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${e.origin}`}}};function ar(){return{localeError:error$F()}}const error$E=()=>{const e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(t){return e[t]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${e.expected}, daxil olan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Yanlış dəyər: gözlənilən ${stringifyPrimitive(e.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${r}${e.maximum.toString()} ${n.unit??"element"}`:`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Çox kiçik: gözlənilən ${e.origin} ${r}${e.minimum.toString()} ${n.unit}`:`Çox kiçik: gözlənilən ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Yanlış mətn: "${t.prefix}" ilə başlamalıdır`:"ends_with"===t.format?`Yanlış mətn: "${t.suffix}" ilə bitməlidir`:"includes"===t.format?`Yanlış mətn: "${t.includes}" daxil olmalıdır`:"regex"===t.format?`Yanlış mətn: ${t.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${r[t.format]??e.format}`}case"not_multiple_of":return`Yanlış ədəd: ${e.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${e.keys.length>1?"lar":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} daxilində yanlış açar`;case"invalid_union":default:return"Yanlış dəyər";case"invalid_element":return`${e.origin} daxilində yanlış dəyər`}}};function az(){return{localeError:error$E()}}function getBelarusianPlural(e,t,r,n){const i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?n:1===o?t:o>=2&&o<=4?r:n}const error$D=()=>{const e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(t){return e[t]??null}const r={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return e=>{switch(e.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${e.expected}, атрымана ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"лік";case"object":if(Array.isArray(e))return"масіў";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Няправільны ўвод: чакалася ${stringifyPrimitive(e.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);if(n){const t=getBelarusianPlural(Number(e.maximum),n.unit.one,n.unit.few,n.unit.many);return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна ${n.verb} ${r}${e.maximum.toString()} ${t}`}return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна быць ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);if(n){const t=getBelarusianPlural(Number(e.minimum),n.unit.one,n.unit.few,n.unit.many);return`Занадта малы: чакалася, што ${e.origin} павінна ${n.verb} ${r}${e.minimum.toString()} ${t}`}return`Занадта малы: чакалася, што ${e.origin} павінна быць ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Няправільны радок: павінен пачынацца з "${t.prefix}"`:"ends_with"===t.format?`Няправільны радок: павінен заканчвацца на "${t.suffix}"`:"includes"===t.format?`Няправільны радок: павінен змяшчаць "${t.includes}"`:"regex"===t.format?`Няправільны радок: павінен адпавядаць шаблону ${t.pattern}`:`Няправільны ${r[t.format]??e.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${e.keys.length>1?"ключы":"ключ"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${e.origin}`;case"invalid_union":default:return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${e.origin}`}}};function be(){return{localeError:error$D()}}const error$C=()=>{const e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(t){return e[t]??null}const r={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipus invàlid: s'esperava ${e.expected}, s'ha rebut ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Valor invàlid: s'esperava ${stringifyPrimitive(e.values[0])}`:`Opció invàlida: s'esperava una de ${joinValues(e.values," o ")}`;case"too_big":{const r=e.inclusive?"com a màxim":"menys de",n=t(e.origin);return n?`Massa gran: s'esperava que ${e.origin??"el valor"} contingués ${r} ${e.maximum.toString()} ${n.unit??"elements"}`:`Massa gran: s'esperava que ${e.origin??"el valor"} fos ${r} ${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?"com a mínim":"més de",n=t(e.origin);return n?`Massa petit: s'esperava que ${e.origin} contingués ${r} ${e.minimum.toString()} ${n.unit}`:`Massa petit: s'esperava que ${e.origin} fos ${r} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Format invàlid: ha de començar amb "${t.prefix}"`:"ends_with"===t.format?`Format invàlid: ha d'acabar amb "${t.suffix}"`:"includes"===t.format?`Format invàlid: ha d'incloure "${t.includes}"`:"regex"===t.format?`Format invàlid: ha de coincidir amb el patró ${t.pattern}`:`Format invàlid per a ${r[t.format]??e.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${e.divisor}`;case"unrecognized_keys":return`Clau${e.keys.length>1?"s":""} no reconeguda${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${e.origin}`;case"invalid_union":default:return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${e.origin}`}}};function ca(){return{localeError:error$C()}}const error$B=()=>{const e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(t){return e[t]??null}const r={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return e=>{switch(e.code){case"invalid_type":return`Neplatný vstup: očekáváno ${e.expected}, obdrženo ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":if(Array.isArray(e))return"pole";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neplatný vstup: očekáváno ${stringifyPrimitive(e.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Hodnota je příliš velká: ${e.origin??"hodnota"} musí mít ${r}${e.maximum.toString()} ${n.unit??"prvků"}`:`Hodnota je příliš velká: ${e.origin??"hodnota"} musí být ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Hodnota je příliš malá: ${e.origin??"hodnota"} musí mít ${r}${e.minimum.toString()} ${n.unit??"prvků"}`:`Hodnota je příliš malá: ${e.origin??"hodnota"} musí být ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neplatný řetězec: musí začínat na "${t.prefix}"`:"ends_with"===t.format?`Neplatný řetězec: musí končit na "${t.suffix}"`:"includes"===t.format?`Neplatný řetězec: musí obsahovat "${t.includes}"`:"regex"===t.format?`Neplatný řetězec: musí odpovídat vzoru ${t.pattern}`:`Neplatný formát ${r[t.format]??e.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${e.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${e.origin}`;case"invalid_union":default:return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${e.origin}`}}};function cs(){return{localeError:error$B()}}const error$A=()=>{const e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function r(t){return e[t]??null}function n(e){return t[e]??e}const i={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldigt input: forventede ${n(e.expected)}, fik ${n((e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tal";case"object":return Array.isArray(e)?"liste":null===e?"null":Object.getPrototypeOf(e)!==Object.prototype&&e.constructor?e.constructor.name:"objekt"}return t})(e.input))}`;case"invalid_value":return 1===e.values.length?`Ugyldig værdi: forventede ${stringifyPrimitive(e.values[0])}`:`Ugyldigt valg: forventede en af følgende ${joinValues(e.values,"|")}`;case"too_big":{const t=e.inclusive?"<=":"<",i=r(e.origin),o=n(e.origin);return i?`For stor: forventede ${o??"value"} ${i.verb} ${t} ${e.maximum.toString()} ${i.unit??"elementer"}`:`For stor: forventede ${o??"value"} havde ${t} ${e.maximum.toString()}`}case"too_small":{const t=e.inclusive?">=":">",i=r(e.origin),o=n(e.origin);return i?`For lille: forventede ${o} ${i.verb} ${t} ${e.minimum.toString()} ${i.unit}`:`For lille: forventede ${o} havde ${t} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: skal starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: skal ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: skal indeholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: skal matche mønsteret ${t.pattern}`:`Ugyldig ${i[t.format]??e.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${e.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${e.origin}`;default:return"Ugyldigt input"}}};function da(){return{localeError:error$A()}}const error$z=()=>{const e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(t){return e[t]??null}const r={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return e=>{switch(e.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${e.expected}, erhalten ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"Zahl";case"object":if(Array.isArray(e))return"Array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ungültige Eingabe: erwartet ${stringifyPrimitive(e.values[0])}`:`Ungültige Option: erwartet eine von ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Zu groß: erwartet, dass ${e.origin??"Wert"} ${r}${e.maximum.toString()} ${n.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${e.origin??"Wert"} ${r}${e.maximum.toString()} ist`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Zu klein: erwartet, dass ${e.origin} ${r}${e.minimum.toString()} ${n.unit} hat`:`Zu klein: erwartet, dass ${e.origin} ${r}${e.minimum.toString()} ist`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ungültiger String: muss mit "${t.prefix}" beginnen`:"ends_with"===t.format?`Ungültiger String: muss mit "${t.suffix}" enden`:"includes"===t.format?`Ungültiger String: muss "${t.includes}" enthalten`:"regex"===t.format?`Ungültiger String: muss dem Muster ${t.pattern} entsprechen`:`Ungültig: ${r[t.format]??e.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${e.divisor} sein`;case"unrecognized_keys":return`${e.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${e.origin}`;case"invalid_union":default:return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${e.origin}`}}};function de(){return{localeError:error$z()}}const parsedType$3=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t},error$y=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(t){return e[t]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${e.expected}, received ${parsedType$3(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${stringifyPrimitive(e.values[0])}`:`Invalid option: expected one of ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Too big: expected ${e.origin??"value"} to have ${r}${e.maximum.toString()} ${n.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Too small: expected ${e.origin} to have ${r}${e.minimum.toString()} ${n.unit}`:`Too small: expected ${e.origin} to be ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}};function en(){return{localeError:error$y()}}const parsedType$2=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":if(Array.isArray(e))return"tabelo";if(null===e)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t},error$x=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(t){return e[t]??null}const r={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return e=>{switch(e.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${e.expected}, riceviĝis ${parsedType$2(e.input)}`;case"invalid_value":return 1===e.values.length?`Nevalida enigo: atendiĝis ${stringifyPrimitive(e.values[0])}`:`Nevalida opcio: atendiĝis unu el ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${r}${e.maximum.toString()} ${n.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Tro malgranda: atendiĝis ke ${e.origin} havu ${r}${e.minimum.toString()} ${n.unit}`:`Tro malgranda: atendiĝis ke ${e.origin} estu ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nevalida karaktraro: devas komenciĝi per "${t.prefix}"`:"ends_with"===t.format?`Nevalida karaktraro: devas finiĝi per "${t.suffix}"`:"includes"===t.format?`Nevalida karaktraro: devas inkluzivi "${t.includes}"`:"regex"===t.format?`Nevalida karaktraro: devas kongrui kun la modelo ${t.pattern}`:`Nevalida ${r[t.format]??e.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${e.divisor}`;case"unrecognized_keys":return`Nekonata${e.keys.length>1?"j":""} ŝlosilo${e.keys.length>1?"j":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${e.origin}`;case"invalid_union":default:return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${e.origin}`}}};function eo(){return{localeError:error$x()}}const error$w=()=>{const e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(t){return e[t]??null}const r={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Entrada inválida: se esperaba ${e.expected}, recibido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"arreglo";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: se esperaba ${stringifyPrimitive(e.values[0])}`:`Opción inválida: se esperaba una de ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Demasiado grande: se esperaba que ${e.origin??"valor"} tuviera ${r}${e.maximum.toString()} ${n.unit??"elementos"}`:`Demasiado grande: se esperaba que ${e.origin??"valor"} fuera ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Demasiado pequeño: se esperaba que ${e.origin} tuviera ${r}${e.minimum.toString()} ${n.unit}`:`Demasiado pequeño: se esperaba que ${e.origin} fuera ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Cadena inválida: debe comenzar con "${t.prefix}"`:"ends_with"===t.format?`Cadena inválida: debe terminar en "${t.suffix}"`:"includes"===t.format?`Cadena inválida: debe incluir "${t.includes}"`:"regex"===t.format?`Cadena inválida: debe coincidir con el patrón ${t.pattern}`:`Inválido ${r[t.format]??e.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Llave${e.keys.length>1?"s":""} desconocida${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Llave inválida en ${e.origin}`;case"invalid_union":default:return"Entrada inválida";case"invalid_element":return`Valor inválido en ${e.origin}`}}};function es(){return{localeError:error$w()}}const error$v=()=>{const e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(t){return e[t]??null}const r={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return e=>{switch(e.code){case"invalid_type":return`ورودی نامعتبر: می‌بایست ${e.expected} می‌بود، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"آرایه";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} دریافت شد`;case"invalid_value":return 1===e.values.length?`ورودی نامعتبر: می‌بایست ${stringifyPrimitive(e.values[0])} می‌بود`:`گزینه نامعتبر: می‌بایست یکی از ${joinValues(e.values,"|")} می‌بود`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`خیلی بزرگ: ${e.origin??"مقدار"} باید ${r}${e.maximum.toString()} ${n.unit??"عنصر"} باشد`:`خیلی بزرگ: ${e.origin??"مقدار"} باید ${r}${e.maximum.toString()} باشد`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`خیلی کوچک: ${e.origin} باید ${r}${e.minimum.toString()} ${n.unit} باشد`:`خیلی کوچک: ${e.origin} باید ${r}${e.minimum.toString()} باشد`}case"invalid_format":{const t=e;return"starts_with"===t.format?`رشته نامعتبر: باید با "${t.prefix}" شروع شود`:"ends_with"===t.format?`رشته نامعتبر: باید با "${t.suffix}" تمام شود`:"includes"===t.format?`رشته نامعتبر: باید شامل "${t.includes}" باشد`:"regex"===t.format?`رشته نامعتبر: باید با الگوی ${t.pattern} مطابقت داشته باشد`:`${r[t.format]??e.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${e.divisor} باشد`;case"unrecognized_keys":return`کلید${e.keys.length>1?"های":""} ناشناس: ${joinValues(e.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${e.origin}`;case"invalid_union":default:return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${e.origin}`}}};function fa(){return{localeError:error$v()}}const error$u=()=>{const e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(t){return e[t]??null}const r={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return e=>{switch(e.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${e.expected}, oli ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Virheellinen syöte: täytyy olla ${stringifyPrimitive(e.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Liian suuri: ${n.subject} täytyy olla ${r}${e.maximum.toString()} ${n.unit}`.trim():`Liian suuri: arvon täytyy olla ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Liian pieni: ${n.subject} täytyy olla ${r}${e.minimum.toString()} ${n.unit}`.trim():`Liian pieni: arvon täytyy olla ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Virheellinen syöte: täytyy alkaa "${t.prefix}"`:"ends_with"===t.format?`Virheellinen syöte: täytyy loppua "${t.suffix}"`:"includes"===t.format?`Virheellinen syöte: täytyy sisältää "${t.includes}"`:"regex"===t.format?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${t.pattern}`:`Virheellinen ${r[t.format]??e.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${e.divisor} monikerta`;case"unrecognized_keys":return`${e.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function fi(){return{localeError:error$u()}}const error$t=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const r={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : ${e.expected} attendu, ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombre";case"object":if(Array.isArray(e))return"tableau";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} reçu`;case"invalid_value":return 1===e.values.length?`Entrée invalide : ${stringifyPrimitive(e.values[0])} attendu`:`Option invalide : une valeur parmi ${joinValues(e.values,"|")} attendue`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Trop grand : ${e.origin??"valeur"} doit ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"élément(s)"}`:`Trop grand : ${e.origin??"valeur"} doit être ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Trop petit : ${e.origin} doit ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Trop petit : ${e.origin} doit être ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au modèle ${t.pattern}`:`${r[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${joinValues(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};function fr(){return{localeError:error$t()}}const error$s=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const r={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : attendu ${e.expected}, reçu ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrée invalide : attendu ${stringifyPrimitive(e.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"≤":"<",n=t(e.origin);return n?`Trop grand : attendu que ${e.origin??"la valeur"} ait ${r}${e.maximum.toString()} ${n.unit}`:`Trop grand : attendu que ${e.origin??"la valeur"} soit ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?"≥":">",n=t(e.origin);return n?`Trop petit : attendu que ${e.origin} ait ${r}${e.minimum.toString()} ${n.unit}`:`Trop petit : attendu que ${e.origin} soit ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au motif ${t.pattern}`:`${r[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${joinValues(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};function frCA(){return{localeError:error$s()}}const error$r=()=>{const e={string:{unit:"אותיות",verb:"לכלול"},file:{unit:"בייטים",verb:"לכלול"},array:{unit:"פריטים",verb:"לכלול"},set:{unit:"פריטים",verb:"לכלול"}};function t(t){return e[t]??null}const r={regex:"קלט",email:"כתובת אימייל",url:"כתובת רשת",emoji:"אימוג'י",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"תאריך וזמן ISO",date:"תאריך ISO",time:"זמן ISO",duration:"משך זמן ISO",ipv4:"כתובת IPv4",ipv6:"כתובת IPv6",cidrv4:"טווח IPv4",cidrv6:"טווח IPv6",base64:"מחרוזת בבסיס 64",base64url:"מחרוזת בבסיס 64 לכתובות רשת",json_string:"מחרוזת JSON",e164:"מספר E.164",jwt:"JWT",template_literal:"קלט"};return e=>{switch(e.code){case"invalid_type":return`קלט לא תקין: צריך ${e.expected}, התקבל ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`קלט לא תקין: צריך ${stringifyPrimitive(e.values[0])}`:`קלט לא תקין: צריך אחת מהאפשרויות ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`גדול מדי: ${e.origin??"value"} צריך להיות ${r}${e.maximum.toString()} ${n.unit??"elements"}`:`גדול מדי: ${e.origin??"value"} צריך להיות ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`קטן מדי: ${e.origin} צריך להיות ${r}${e.minimum.toString()} ${n.unit}`:`קטן מדי: ${e.origin} צריך להיות ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`מחרוזת לא תקינה: חייבת להתחיל ב"${t.prefix}"`:"ends_with"===t.format?`מחרוזת לא תקינה: חייבת להסתיים ב "${t.suffix}"`:"includes"===t.format?`מחרוזת לא תקינה: חייבת לכלול "${t.includes}"`:"regex"===t.format?`מחרוזת לא תקינה: חייבת להתאים לתבנית ${t.pattern}`:`${r[t.format]??e.format} לא תקין`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${e.divisor}`;case"unrecognized_keys":return`מפתח${e.keys.length>1?"ות":""} לא מזוה${e.keys.length>1?"ים":"ה"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`מפתח לא תקין ב${e.origin}`;case"invalid_union":default:return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${e.origin}`}}};function he(){return{localeError:error$r()}}const error$q=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(t){return e[t]??null}const r={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return e=>{switch(e.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${e.expected}, a kapott érték ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"szám";case"object":if(Array.isArray(e))return"tömb";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Érvénytelen bemenet: a várt érték ${stringifyPrimitive(e.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Túl nagy: ${e.origin??"érték"} mérete túl nagy ${r}${e.maximum.toString()} ${n.unit??"elem"}`:`Túl nagy: a bemeneti érték ${e.origin??"érték"} túl nagy: ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Túl kicsi: a bemeneti érték ${e.origin} mérete túl kicsi ${r}${e.minimum.toString()} ${n.unit}`:`Túl kicsi: a bemeneti érték ${e.origin} túl kicsi ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Érvénytelen string: "${t.prefix}" értékkel kell kezdődnie`:"ends_with"===t.format?`Érvénytelen string: "${t.suffix}" értékkel kell végződnie`:"includes"===t.format?`Érvénytelen string: "${t.includes}" értéket kell tartalmaznia`:"regex"===t.format?`Érvénytelen string: ${t.pattern} mintának kell megfelelnie`:`Érvénytelen ${r[t.format]??e.format}`}case"not_multiple_of":return`Érvénytelen szám: ${e.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${e.origin}`;case"invalid_union":default:return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${e.origin}`}}};function hu(){return{localeError:error$q()}}const error$p=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(t){return e[t]??null}const r={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak valid: diharapkan ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak valid: diharapkan ${stringifyPrimitive(e.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Terlalu besar: diharapkan ${e.origin??"value"} memiliki ${r}${e.maximum.toString()} ${n.unit??"elemen"}`:`Terlalu besar: diharapkan ${e.origin??"value"} menjadi ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Terlalu kecil: diharapkan ${e.origin} memiliki ${r}${e.minimum.toString()} ${n.unit}`:`Terlalu kecil: diharapkan ${e.origin} menjadi ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak valid: harus dimulai dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak valid: harus berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak valid: harus menyertakan "${t.includes}"`:"regex"===t.format?`String tidak valid: harus sesuai pola ${t.pattern}`:`${r[t.format]??e.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${e.origin}`;case"invalid_union":default:return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${e.origin}`}}};function id(){return{localeError:error$p()}}const parsedType$1=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"númer";case"object":if(Array.isArray(e))return"fylki";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t},error$o=()=>{const e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(t){return e[t]??null}const r={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return e=>{switch(e.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${parsedType$1(e.input)} þar sem á að vera ${e.expected}`;case"invalid_value":return 1===e.values.length?`Rangt gildi: gert ráð fyrir ${stringifyPrimitive(e.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} hafi ${r}${e.maximum.toString()} ${n.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} sé ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Of lítið: gert er ráð fyrir að ${e.origin} hafi ${r}${e.minimum.toString()} ${n.unit}`:`Of lítið: gert er ráð fyrir að ${e.origin} sé ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ógildur strengur: verður að byrja á "${t.prefix}"`:"ends_with"===t.format?`Ógildur strengur: verður að enda á "${t.suffix}"`:"includes"===t.format?`Ógildur strengur: verður að innihalda "${t.includes}"`:"regex"===t.format?`Ógildur strengur: verður að fylgja mynstri ${t.pattern}`:`Rangt ${r[t.format]??e.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${e.divisor}`;case"unrecognized_keys":return`Óþekkt ${e.keys.length>1?"ir lyklar":"ur lykill"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${e.origin}`;case"invalid_union":default:return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${e.origin}`}}};function is(){return{localeError:error$o()}}const error$n=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(t){return e[t]??null}const r={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input non valido: atteso ${e.expected}, ricevuto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numero";case"object":if(Array.isArray(e))return"vettore";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input non valido: atteso ${stringifyPrimitive(e.values[0])}`:`Opzione non valida: atteso uno tra ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Troppo grande: ${e.origin??"valore"} deve avere ${r}${e.maximum.toString()} ${n.unit??"elementi"}`:`Troppo grande: ${e.origin??"valore"} deve essere ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Troppo piccolo: ${e.origin} deve avere ${r}${e.minimum.toString()} ${n.unit}`:`Troppo piccolo: ${e.origin} deve essere ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Stringa non valida: deve iniziare con "${t.prefix}"`:"ends_with"===t.format?`Stringa non valida: deve terminare con "${t.suffix}"`:"includes"===t.format?`Stringa non valida: deve includere "${t.includes}"`:"regex"===t.format?`Stringa non valida: deve corrispondere al pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${e.divisor}`;case"unrecognized_keys":return`Chiav${e.keys.length>1?"i":"e"} non riconosciut${e.keys.length>1?"e":"a"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${e.origin}`;case"invalid_union":default:return"Input non valido";case"invalid_element":return`Valore non valido in ${e.origin}`}}};function it(){return{localeError:error$n()}}const error$m=()=>{const e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(t){return e[t]??null}const r={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return e=>{switch(e.code){case"invalid_type":return`無効な入力: ${e.expected}が期待されましたが、${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"数値";case"object":if(Array.isArray(e))return"配列";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}が入力されました`;case"invalid_value":return 1===e.values.length?`無効な入力: ${stringifyPrimitive(e.values[0])}が期待されました`:`無効な選択: ${joinValues(e.values,"、")}のいずれかである必要があります`;case"too_big":{const r=e.inclusive?"以下である":"より小さい",n=t(e.origin);return n?`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${n.unit??"要素"}${r}必要があります`:`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${r}必要があります`}case"too_small":{const r=e.inclusive?"以上である":"より大きい",n=t(e.origin);return n?`小さすぎる値: ${e.origin}は${e.minimum.toString()}${n.unit}${r}必要があります`:`小さすぎる値: ${e.origin}は${e.minimum.toString()}${r}必要があります`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無効な文字列: "${t.prefix}"で始まる必要があります`:"ends_with"===t.format?`無効な文字列: "${t.suffix}"で終わる必要があります`:"includes"===t.format?`無効な文字列: "${t.includes}"を含む必要があります`:"regex"===t.format?`無効な文字列: パターン${t.pattern}に一致する必要があります`:`無効な${r[t.format]??e.format}`}case"not_multiple_of":return`無効な数値: ${e.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${e.keys.length>1?"群":""}: ${joinValues(e.keys,"、")}`;case"invalid_key":return`${e.origin}内の無効なキー`;case"invalid_union":default:return"無効な入力";case"invalid_element":return`${e.origin}内の無効な値`}}};function ja(){return{localeError:error$m()}}const error$l=()=>{const e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(t){return e[t]??null}const r={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return e=>{switch(e.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${e.expected} ប៉ុន្តែទទួលបាន ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":if(Array.isArray(e))return"អារេ (Array)";if(null===e)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(e.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${r} ${e.maximum.toString()} ${n.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${r} ${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`តូចពេក៖ ត្រូវការ ${e.origin} ${r} ${e.minimum.toString()} ${n.unit}`:`តូចពេក៖ ត្រូវការ ${e.origin} ${r} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${t.prefix}"`:"ends_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${t.suffix}"`:"includes"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${t.includes}"`:"regex"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${t.pattern}`:`មិនត្រឹមត្រូវ៖ ${r[t.format]??e.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${e.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${joinValues(e.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`;case"invalid_union":default:return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`}}};function kh(){return{localeError:error$l()}}const error$k=()=>{const e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(t){return e[t]??null}const r={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return e=>{switch(e.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${e.expected}, 받은 타입은 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}입니다`;case"invalid_value":return 1===e.values.length?`잘못된 입력: 값은 ${stringifyPrimitive(e.values[0])} 이어야 합니다`:`잘못된 옵션: ${joinValues(e.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const r=e.inclusive?"이하":"미만",n="미만"===r?"이어야 합니다":"여야 합니다",i=t(e.origin),o=i?.unit??"요소";return i?`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()}${o} ${r}${n}`:`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()} ${r}${n}`}case"too_small":{const r=e.inclusive?"이상":"초과",n="이상"===r?"이어야 합니다":"여야 합니다",i=t(e.origin),o=i?.unit??"요소";return i?`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()}${o} ${r}${n}`:`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()} ${r}${n}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`잘못된 문자열: "${t.prefix}"(으)로 시작해야 합니다`:"ends_with"===t.format?`잘못된 문자열: "${t.suffix}"(으)로 끝나야 합니다`:"includes"===t.format?`잘못된 문자열: "${t.includes}"을(를) 포함해야 합니다`:"regex"===t.format?`잘못된 문자열: 정규식 ${t.pattern} 패턴과 일치해야 합니다`:`잘못된 ${r[t.format]??e.format}`}case"not_multiple_of":return`잘못된 숫자: ${e.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${joinValues(e.keys,", ")}`;case"invalid_key":return`잘못된 키: ${e.origin}`;case"invalid_union":default:return"잘못된 입력";case"invalid_element":return`잘못된 값: ${e.origin}`}}};function ko(){return{localeError:error$k()}}const error$j=()=>{const e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(t){return e[t]??null}const r={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return e=>{switch(e.code){case"invalid_type":return`Грешен внес: се очекува ${e.expected}, примено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"број";case"object":if(Array.isArray(e))return"низа";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${stringifyPrimitive(e.values[0])}`:`Грешана опција: се очекува една ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Премногу голем: се очекува ${e.origin??"вредноста"} да има ${r}${e.maximum.toString()} ${n.unit??"елементи"}`:`Премногу голем: се очекува ${e.origin??"вредноста"} да биде ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Премногу мал: се очекува ${e.origin} да има ${r}${e.minimum.toString()} ${n.unit}`:`Премногу мал: се очекува ${e.origin} да биде ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неважечка низа: мора да започнува со "${t.prefix}"`:"ends_with"===t.format?`Неважечка низа: мора да завршува со "${t.suffix}"`:"includes"===t.format?`Неважечка низа: мора да вклучува "${t.includes}"`:"regex"===t.format?`Неважечка низа: мора да одгоара на патернот ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${e.origin}`;case"invalid_union":default:return"Грешен внес";case"invalid_element":return`Грешна вредност во ${e.origin}`}}};function mk(){return{localeError:error$j()}}const error$i=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(t){return e[t]??null}const r={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak sah: dijangka ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombor";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak sah: dijangka ${stringifyPrimitive(e.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Terlalu besar: dijangka ${e.origin??"nilai"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"elemen"}`:`Terlalu besar: dijangka ${e.origin??"nilai"} adalah ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Terlalu kecil: dijangka ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Terlalu kecil: dijangka ${e.origin} adalah ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak sah: mesti bermula dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak sah: mesti berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak sah: mesti mengandungi "${t.includes}"`:"regex"===t.format?`String tidak sah: mesti sepadan dengan corak ${t.pattern}`:`${r[t.format]??e.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${e.origin}`;case"invalid_union":default:return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${e.origin}`}}};function ms(){return{localeError:error$i()}}const error$h=()=>{const e={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function t(t){return e[t]??null}const r={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return e=>{switch(e.code){case"invalid_type":return`Ongeldige invoer: verwacht ${e.expected}, ontving ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"getal";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ongeldige invoer: verwacht ${stringifyPrimitive(e.values[0])}`:`Ongeldige optie: verwacht één van ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Te lang: verwacht dat ${e.origin??"waarde"} ${r}${e.maximum.toString()} ${n.unit??"elementen"} bevat`:`Te lang: verwacht dat ${e.origin??"waarde"} ${r}${e.maximum.toString()} is`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Te kort: verwacht dat ${e.origin} ${r}${e.minimum.toString()} ${n.unit} bevat`:`Te kort: verwacht dat ${e.origin} ${r}${e.minimum.toString()} is`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ongeldige tekst: moet met "${t.prefix}" beginnen`:"ends_with"===t.format?`Ongeldige tekst: moet op "${t.suffix}" eindigen`:"includes"===t.format?`Ongeldige tekst: moet "${t.includes}" bevatten`:"regex"===t.format?`Ongeldige tekst: moet overeenkomen met patroon ${t.pattern}`:`Ongeldig: ${r[t.format]??e.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${e.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${e.origin}`;case"invalid_union":default:return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${e.origin}`}}};function nl(){return{localeError:error$h()}}const error$g=()=>{const e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(t){return e[t]??null}const r={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldig input: forventet ${e.expected}, fikk ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tall";case"object":if(Array.isArray(e))return"liste";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ugyldig verdi: forventet ${stringifyPrimitive(e.values[0])}`:`Ugyldig valg: forventet en av ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`For stor(t): forventet ${e.origin??"value"} til å ha ${r}${e.maximum.toString()} ${n.unit??"elementer"}`:`For stor(t): forventet ${e.origin??"value"} til å ha ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`For lite(n): forventet ${e.origin} til å ha ${r}${e.minimum.toString()} ${n.unit}`:`For lite(n): forventet ${e.origin} til å ha ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: må starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: må ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: må inneholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: må matche mønsteret ${t.pattern}`:`Ugyldig ${r[t.format]??e.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${e.origin}`;case"invalid_union":default:return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${e.origin}`}}};function no(){return{localeError:error$g()}}const error$f=()=>{const e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(t){return e[t]??null}const r={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return e=>{switch(e.code){case"invalid_type":return`Fâsit giren: umulan ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numara";case"object":if(Array.isArray(e))return"saf";if(null===e)return"gayb";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Fâsit giren: umulan ${stringifyPrimitive(e.values[0])}`:`Fâsit tercih: mûteberler ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Fazla büyük: ${e.origin??"value"}, ${r}${e.maximum.toString()} ${n.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${e.origin??"value"}, ${r}${e.maximum.toString()} olmalıydı.`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Fazla küçük: ${e.origin}, ${r}${e.minimum.toString()} ${n.unit} sahip olmalıydı.`:`Fazla küçük: ${e.origin}, ${r}${e.minimum.toString()} olmalıydı.`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Fâsit metin: "${t.prefix}" ile başlamalı.`:"ends_with"===t.format?`Fâsit metin: "${t.suffix}" ile bitmeli.`:"includes"===t.format?`Fâsit metin: "${t.includes}" ihtivâ etmeli.`:"regex"===t.format?`Fâsit metin: ${t.pattern} nakşına uymalı.`:`Fâsit ${r[t.format]??e.format}`}case"not_multiple_of":return`Fâsit sayı: ${e.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${e.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function ota(){return{localeError:error$f()}}const error$e=()=>{const e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(t){return e[t]??null}const r={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return e=>{switch(e.code){case"invalid_type":return`ناسم ورودي: باید ${e.expected} وای, مګر ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"ارې";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} ترلاسه شو`;case"invalid_value":return 1===e.values.length?`ناسم ورودي: باید ${stringifyPrimitive(e.values[0])} وای`:`ناسم انتخاب: باید یو له ${joinValues(e.values,"|")} څخه وای`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`ډیر لوی: ${e.origin??"ارزښت"} باید ${r}${e.maximum.toString()} ${n.unit??"عنصرونه"} ولري`:`ډیر لوی: ${e.origin??"ارزښت"} باید ${r}${e.maximum.toString()} وي`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`ډیر کوچنی: ${e.origin} باید ${r}${e.minimum.toString()} ${n.unit} ولري`:`ډیر کوچنی: ${e.origin} باید ${r}${e.minimum.toString()} وي`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ناسم متن: باید د "${t.prefix}" سره پیل شي`:"ends_with"===t.format?`ناسم متن: باید د "${t.suffix}" سره پای ته ورسيږي`:"includes"===t.format?`ناسم متن: باید "${t.includes}" ولري`:"regex"===t.format?`ناسم متن: باید د ${t.pattern} سره مطابقت ولري`:`${r[t.format]??e.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${e.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${e.keys.length>1?"کلیډونه":"کلیډ"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${e.origin} کې`;case"invalid_union":default:return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${e.origin} کې`}}};function ps(){return{localeError:error$e()}}const error$d=()=>{const e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(t){return e[t]??null}const r={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return e=>{switch(e.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${e.expected}, otrzymano ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"liczba";case"object":if(Array.isArray(e))return"tablica";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(e.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Za duża wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${r}${e.maximum.toString()} ${n.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Za mała wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${r}${e.minimum.toString()} ${n.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${t.prefix}"`:"ends_with"===t.format?`Nieprawidłowy ciąg znaków: musi kończyć się na "${t.suffix}"`:"includes"===t.format?`Nieprawidłowy ciąg znaków: musi zawierać "${t.includes}"`:"regex"===t.format?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${t.pattern}`:`Nieprawidłow(y/a/e) ${r[t.format]??e.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${e.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${e.origin}`;case"invalid_union":default:return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${e.origin}`}}};function pl(){return{localeError:error$d()}}const error$c=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(t){return e[t]??null}const r={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipo inválido: esperado ${e.expected}, recebido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"array";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: esperado ${stringifyPrimitive(e.values[0])}`:`Opção inválida: esperada uma das ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Muito grande: esperado que ${e.origin??"valor"} tivesse ${r}${e.maximum.toString()} ${n.unit??"elementos"}`:`Muito grande: esperado que ${e.origin??"valor"} fosse ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Muito pequeno: esperado que ${e.origin} tivesse ${r}${e.minimum.toString()} ${n.unit}`:`Muito pequeno: esperado que ${e.origin} fosse ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Texto inválido: deve começar com "${t.prefix}"`:"ends_with"===t.format?`Texto inválido: deve terminar com "${t.suffix}"`:"includes"===t.format?`Texto inválido: deve incluir "${t.includes}"`:"regex"===t.format?`Texto inválido: deve corresponder ao padrão ${t.pattern}`:`${r[t.format]??e.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Chave${e.keys.length>1?"s":""} desconhecida${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Chave inválida em ${e.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${e.origin}`;default:return"Campo inválido"}}};function pt(){return{localeError:error$c()}}function getRussianPlural(e,t,r,n){const i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?n:1===o?t:o>=2&&o<=4?r:n}const error$b=()=>{const e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(t){return e[t]??null}const r={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return e=>{switch(e.code){case"invalid_type":return`Неверный ввод: ожидалось ${e.expected}, получено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"массив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неверный ввод: ожидалось ${stringifyPrimitive(e.values[0])}`:`Неверный вариант: ожидалось одно из ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);if(n){const t=getRussianPlural(Number(e.maximum),n.unit.one,n.unit.few,n.unit.many);return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет иметь ${r}${e.maximum.toString()} ${t}`}return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);if(n){const t=getRussianPlural(Number(e.minimum),n.unit.one,n.unit.few,n.unit.many);return`Слишком маленькое значение: ожидалось, что ${e.origin} будет иметь ${r}${e.minimum.toString()} ${t}`}return`Слишком маленькое значение: ожидалось, что ${e.origin} будет ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неверная строка: должна начинаться с "${t.prefix}"`:"ends_with"===t.format?`Неверная строка: должна заканчиваться на "${t.suffix}"`:"includes"===t.format?`Неверная строка: должна содержать "${t.includes}"`:"regex"===t.format?`Неверная строка: должна соответствовать шаблону ${t.pattern}`:`Неверный ${r[t.format]??e.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспознанн${e.keys.length>1?"ые":"ый"} ключ${e.keys.length>1?"и":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${e.origin}`;case"invalid_union":default:return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${e.origin}`}}};function ru(){return{localeError:error$b()}}const error$a=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(t){return e[t]??null}const r={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return e=>{switch(e.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${e.expected}, prejeto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"število";case"object":if(Array.isArray(e))return"tabela";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neveljaven vnos: pričakovano ${stringifyPrimitive(e.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} imelo ${r}${e.maximum.toString()} ${n.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Premajhno: pričakovano, da bo ${e.origin} imelo ${r}${e.minimum.toString()} ${n.unit}`:`Premajhno: pričakovano, da bo ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neveljaven niz: mora se začeti z "${t.prefix}"`:"ends_with"===t.format?`Neveljaven niz: mora se končati z "${t.suffix}"`:"includes"===t.format?`Neveljaven niz: mora vsebovati "${t.includes}"`:"regex"===t.format?`Neveljaven niz: mora ustrezati vzorcu ${t.pattern}`:`Neveljaven ${r[t.format]??e.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${e.divisor}`;case"unrecognized_keys":return`Neprepoznan${e.keys.length>1?"i ključi":" ključ"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${e.origin}`;case"invalid_union":default:return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${e.origin}`}}};function sl(){return{localeError:error$a()}}const error$9=()=>{const e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(t){return e[t]??null}const r={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return e=>{switch(e.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${e.expected}, fick ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"antal";case"object":if(Array.isArray(e))return"lista";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ogiltig inmatning: förväntat ${stringifyPrimitive(e.values[0])}`:`Ogiltigt val: förväntade en av ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`För stor(t): förväntade ${e.origin??"värdet"} att ha ${r}${e.maximum.toString()} ${n.unit??"element"}`:`För stor(t): förväntat ${e.origin??"värdet"} att ha ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`För lite(t): förväntade ${e.origin??"värdet"} att ha ${r}${e.minimum.toString()} ${n.unit}`:`För lite(t): förväntade ${e.origin??"värdet"} att ha ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ogiltig sträng: måste börja med "${t.prefix}"`:"ends_with"===t.format?`Ogiltig sträng: måste sluta med "${t.suffix}"`:"includes"===t.format?`Ogiltig sträng: måste innehålla "${t.includes}"`:"regex"===t.format?`Ogiltig sträng: måste matcha mönstret "${t.pattern}"`:`Ogiltig(t) ${r[t.format]??e.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${e.origin??"värdet"}`;case"invalid_union":default:return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${e.origin??"värdet"}`}}};function sv(){return{localeError:error$9()}}const error$8=()=>{const e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(t){return e[t]??null}const r={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${e.expected}, பெறப்பட்டது ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"எண் அல்லாதது":"எண்";case"object":if(Array.isArray(e))return"அணி";if(null===e)return"வெறுமை";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(e.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(e.values,"|")} இல் ஒன்று`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${r}${e.maximum.toString()} ${n.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${r}${e.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${r}${e.minimum.toString()} ${n.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${r}${e.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const t=e;return"starts_with"===t.format?`தவறான சரம்: "${t.prefix}" இல் தொடங்க வேண்டும்`:"ends_with"===t.format?`தவறான சரம்: "${t.suffix}" இல் முடிவடைய வேண்டும்`:"includes"===t.format?`தவறான சரம்: "${t.includes}" ஐ உள்ளடக்க வேண்டும்`:"regex"===t.format?`தவறான சரம்: ${t.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${r[t.format]??e.format}`}case"not_multiple_of":return`தவறான எண்: ${e.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${e.keys.length>1?"கள்":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} இல் தவறான விசை`;case"invalid_union":default:return"தவறான உள்ளீடு";case"invalid_element":return`${e.origin} இல் தவறான மதிப்பு`}}};function ta(){return{localeError:error$8()}}const error$7=()=>{const e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(t){return e[t]??null}const r={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return e=>{switch(e.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${e.expected} แต่ได้รับ ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":if(Array.isArray(e))return"อาร์เรย์ (Array)";if(null===e)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(e.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"ไม่เกิน":"น้อยกว่า",n=t(e.origin);return n?`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${r} ${e.maximum.toString()} ${n.unit??"รายการ"}`:`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${r} ${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?"อย่างน้อย":"มากกว่า",n=t(e.origin);return n?`น้อยกว่ากำหนด: ${e.origin} ควรมี${r} ${e.minimum.toString()} ${n.unit}`:`น้อยกว่ากำหนด: ${e.origin} ควรมี${r} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${t.prefix}"`:"ends_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${t.suffix}"`:"includes"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${t.includes}" อยู่ในข้อความ`:"regex"===t.format?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${t.pattern}`:`รูปแบบไม่ถูกต้อง: ${r[t.format]??e.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${e.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${joinValues(e.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${e.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${e.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function th(){return{localeError:error$7()}}const parsedType=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t},error$6=()=>{const e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(t){return e[t]??null}const r={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return e=>{switch(e.code){case"invalid_type":return`Geçersiz değer: beklenen ${e.expected}, alınan ${parsedType(e.input)}`;case"invalid_value":return 1===e.values.length?`Geçersiz değer: beklenen ${stringifyPrimitive(e.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Çok büyük: beklenen ${e.origin??"değer"} ${r}${e.maximum.toString()} ${n.unit??"öğe"}`:`Çok büyük: beklenen ${e.origin??"değer"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Çok küçük: beklenen ${e.origin} ${r}${e.minimum.toString()} ${n.unit}`:`Çok küçük: beklenen ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Geçersiz metin: "${t.prefix}" ile başlamalı`:"ends_with"===t.format?`Geçersiz metin: "${t.suffix}" ile bitmeli`:"includes"===t.format?`Geçersiz metin: "${t.includes}" içermeli`:"regex"===t.format?`Geçersiz metin: ${t.pattern} desenine uymalı`:`Geçersiz ${r[t.format]??e.format}`}case"not_multiple_of":return`Geçersiz sayı: ${e.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${e.keys.length>1?"lar":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} içinde geçersiz anahtar`;case"invalid_union":default:return"Geçersiz değer";case"invalid_element":return`${e.origin} içinde geçersiz değer`}}};function tr(){return{localeError:error$6()}}const error$5=()=>{const e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(t){return e[t]??null}const r={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return e=>{switch(e.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${e.expected}, отримано ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"масив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неправильні вхідні дані: очікується ${stringifyPrimitive(e.values[0])}`:`Неправильна опція: очікується одне з ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Занадто велике: очікується, що ${e.origin??"значення"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"елементів"}`:`Занадто велике: очікується, що ${e.origin??"значення"} буде ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Занадто мале: очікується, що ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Занадто мале: очікується, що ${e.origin} буде ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неправильний рядок: повинен починатися з "${t.prefix}"`:"ends_with"===t.format?`Неправильний рядок: повинен закінчуватися на "${t.suffix}"`:"includes"===t.format?`Неправильний рядок: повинен містити "${t.includes}"`:"regex"===t.format?`Неправильний рядок: повинен відповідати шаблону ${t.pattern}`:`Неправильний ${r[t.format]??e.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${e.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${e.keys.length>1?"і":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${e.origin}`;case"invalid_union":default:return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${e.origin}`}}};function ua(){return{localeError:error$5()}}const error$4=()=>{const e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(t){return e[t]??null}const r={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return e=>{switch(e.code){case"invalid_type":return`غلط ان پٹ: ${e.expected} متوقع تھا، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"نمبر";case"object":if(Array.isArray(e))return"آرے";if(null===e)return"نل";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} موصول ہوا`;case"invalid_value":return 1===e.values.length?`غلط ان پٹ: ${stringifyPrimitive(e.values[0])} متوقع تھا`:`غلط آپشن: ${joinValues(e.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`بہت بڑا: ${e.origin??"ویلیو"} کے ${r}${e.maximum.toString()} ${n.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${e.origin??"ویلیو"} کا ${r}${e.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`بہت چھوٹا: ${e.origin} کے ${r}${e.minimum.toString()} ${n.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${e.origin} کا ${r}${e.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const t=e;return"starts_with"===t.format?`غلط سٹرنگ: "${t.prefix}" سے شروع ہونا چاہیے`:"ends_with"===t.format?`غلط سٹرنگ: "${t.suffix}" پر ختم ہونا چاہیے`:"includes"===t.format?`غلط سٹرنگ: "${t.includes}" شامل ہونا چاہیے`:"regex"===t.format?`غلط سٹرنگ: پیٹرن ${t.pattern} سے میچ ہونا چاہیے`:`غلط ${r[t.format]??e.format}`}case"not_multiple_of":return`غلط نمبر: ${e.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${e.keys.length>1?"ز":""}: ${joinValues(e.keys,"، ")}`;case"invalid_key":return`${e.origin} میں غلط کی`;case"invalid_union":default:return"غلط ان پٹ";case"invalid_element":return`${e.origin} میں غلط ویلیو`}}};function ur(){return{localeError:error$4()}}const error$3=()=>{const e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(t){return e[t]??null}const r={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return e=>{switch(e.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${e.expected}, nhận được ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"số";case"object":if(Array.isArray(e))return"mảng";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(e.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Quá lớn: mong đợi ${e.origin??"giá trị"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"phần tử"}`:`Quá lớn: mong đợi ${e.origin??"giá trị"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Quá nhỏ: mong đợi ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Quá nhỏ: mong đợi ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chuỗi không hợp lệ: phải bắt đầu bằng "${t.prefix}"`:"ends_with"===t.format?`Chuỗi không hợp lệ: phải kết thúc bằng "${t.suffix}"`:"includes"===t.format?`Chuỗi không hợp lệ: phải bao gồm "${t.includes}"`:"regex"===t.format?`Chuỗi không hợp lệ: phải khớp với mẫu ${t.pattern}`:`${r[t.format]??e.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${e.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${e.origin}`;case"invalid_union":default:return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${e.origin}`}}};function vi(){return{localeError:error$3()}}const error$2=()=>{const e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(t){return e[t]??null}const r={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return e=>{switch(e.code){case"invalid_type":return`无效输入:期望 ${e.expected},实际接收 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"非数字(NaN)":"数字";case"object":if(Array.isArray(e))return"数组";if(null===e)return"空值(null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`无效输入:期望 ${stringifyPrimitive(e.values[0])}`:`无效选项:期望以下之一 ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`数值过大:期望 ${e.origin??"值"} ${r}${e.maximum.toString()} ${n.unit??"个元素"}`:`数值过大:期望 ${e.origin??"值"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`数值过小:期望 ${e.origin} ${r}${e.minimum.toString()} ${n.unit}`:`数值过小:期望 ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`无效字符串:必须以 "${t.prefix}" 开头`:"ends_with"===t.format?`无效字符串:必须以 "${t.suffix}" 结尾`:"includes"===t.format?`无效字符串:必须包含 "${t.includes}"`:"regex"===t.format?`无效字符串:必须满足正则表达式 ${t.pattern}`:`无效${r[t.format]??e.format}`}case"not_multiple_of":return`无效数字:必须是 ${e.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} 中的键(key)无效`;case"invalid_union":default:return"无效输入";case"invalid_element":return`${e.origin} 中包含无效值(value)`}}};function zhCN(){return{localeError:error$2()}}const error$1=()=>{const e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(t){return e[t]??null}const r={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return e=>{switch(e.code){case"invalid_type":return`無效的輸入值:預期為 ${e.expected},但收到 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`無效的輸入值:預期為 ${stringifyPrimitive(e.values[0])}`:`無效的選項:預期為以下其中之一 ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`數值過大:預期 ${e.origin??"值"} 應為 ${r}${e.maximum.toString()} ${n.unit??"個元素"}`:`數值過大:預期 ${e.origin??"值"} 應為 ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`數值過小:預期 ${e.origin} 應為 ${r}${e.minimum.toString()} ${n.unit}`:`數值過小:預期 ${e.origin} 應為 ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無效的字串:必須以 "${t.prefix}" 開頭`:"ends_with"===t.format?`無效的字串:必須以 "${t.suffix}" 結尾`:"includes"===t.format?`無效的字串:必須包含 "${t.includes}"`:"regex"===t.format?`無效的字串:必須符合格式 ${t.pattern}`:`無效的 ${r[t.format]??e.format}`}case"not_multiple_of":return`無效的數字:必須為 ${e.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${e.keys.length>1?"們":""}:${joinValues(e.keys,"、")}`;case"invalid_key":return`${e.origin} 中有無效的鍵值`;case"invalid_union":default:return"無效的輸入值";case"invalid_element":return`${e.origin} 中有無效的值`}}};function zhTW(){return{localeError:error$1()}}const error=()=>{const e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(t){return e[t]??null}const r={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return e=>{switch(e.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${e.expected}, àmọ̀ a rí ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nọ́mbà";case"object":if(Array.isArray(e))return"akopọ";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(e.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Tó pọ̀ jù: a ní láti jẹ́ pé ${e.origin??"iye"} ${n.verb} ${r}${e.maximum} ${n.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${r}${e.maximum}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Kéré ju: a ní láti jẹ́ pé ${e.origin} ${n.verb} ${r}${e.minimum} ${n.unit}`:`Kéré ju: a ní láti jẹ́ ${r}${e.minimum}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${t.prefix}"`:"ends_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${t.suffix}"`:"includes"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${t.includes}"`:"regex"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${t.pattern}`:`Aṣìṣe: ${r[t.format]??e.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${e.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${e.origin}`;case"invalid_union":default:return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${e.origin}`}}};function yo(){return{localeError:error()}}var index$1=Object.freeze({__proto__:null,ar:ar,az:az,be:be,ca:ca,cs:cs,da:da,de:de,en:en,eo:eo,es:es,fa:fa,fi:fi,fr:fr,frCA:frCA,he:he,hu:hu,id:id,is:is,it:it,ja:ja,kh:kh,ko:ko,mk:mk,ms:ms,nl:nl,no:no,ota:ota,pl:pl,ps:ps,pt:pt,ru:ru,sl:sl,sv:sv,ta:ta,th:th,tr:tr,ua:ua,ur:ur,vi:vi,yo:yo,zhCN:zhCN,zhTW:zhTW});const $output=Symbol("ZodOutput"),$input=Symbol("ZodInput");class $ZodRegistry{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function registry(){return new $ZodRegistry}const globalRegistry=registry();function _string(e,t){return new e({type:"string",...normalizeParams(t)})}function _coercedString(e,t){return new e({type:"string",coerce:!0,...normalizeParams(t)})}function _email(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(t)})}function _guid(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(t)})}function _uuid(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(t)})}function _uuidv4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(t)})}function _uuidv6(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(t)})}function _uuidv7(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(t)})}function _url(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(t)})}function _emoji(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(t)})}function _nanoid(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(t)})}function _cuid(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(t)})}function _cuid2(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(t)})}function _ulid(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(t)})}function _xid(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(t)})}function _ksuid(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(t)})}function _ipv4(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(t)})}function _ipv6(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(t)})}function _cidrv4(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(t)})}function _cidrv6(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(t)})}function _base64(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(t)})}function _base64url(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(t)})}function _e164(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(t)})}function _jwt(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(t)})}const TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:"string",format:"date",check:"string_format",...normalizeParams(t)})}function _isoTime(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(t)})}function _isoDuration(e,t){return new e({type:"string",format:"duration",check:"string_format",...normalizeParams(t)})}function _number(e,t){return new e({type:"number",checks:[],...normalizeParams(t)})}function _coercedNumber(e,t){return new e({type:"number",coerce:!0,checks:[],...normalizeParams(t)})}function _int(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(t)})}function _float32(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams(t)})}function _float64(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams(t)})}function _int32(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams(t)})}function _uint32(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams(t)})}function _boolean(e,t){return new e({type:"boolean",...normalizeParams(t)})}function _coercedBoolean(e,t){return new e({type:"boolean",coerce:!0,...normalizeParams(t)})}function _bigint(e,t){return new e({type:"bigint",...normalizeParams(t)})}function _coercedBigint(e,t){return new e({type:"bigint",coerce:!0,...normalizeParams(t)})}function _int64(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams(t)})}function _uint64(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams(t)})}function _symbol(e,t){return new e({type:"symbol",...normalizeParams(t)})}function _undefined$1(e,t){return new e({type:"undefined",...normalizeParams(t)})}function _null$1(e,t){return new e({type:"null",...normalizeParams(t)})}function _any(e){return new e({type:"any"})}function _unknown(e){return new e({type:"unknown"})}function _never(e,t){return new e({type:"never",...normalizeParams(t)})}function _void$1(e,t){return new e({type:"void",...normalizeParams(t)})}function _date(e,t){return new e({type:"date",...normalizeParams(t)})}function _coercedDate(e,t){return new e({type:"date",coerce:!0,...normalizeParams(t)})}function _nan(e,t){return new e({type:"nan",...normalizeParams(t)})}function _lt(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:!1})}function _lte(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:!0})}function _gt(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:!1})}function _gte(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:!0})}function _positive(e){return _gt(0,e)}function _negative(e){return _lt(0,e)}function _nonpositive(e){return _lte(0,e)}function _nonnegative(e){return _gte(0,e)}function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(t),value:e})}function _maxSize(e,t){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(t),maximum:e})}function _minSize(e,t){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(t),minimum:e})}function _size(e,t){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(t),size:e})}function _maxLength(e,t){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(t),maximum:e})}function _minLength(e,t){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(t),minimum:e})}function _length(e,t){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(t),length:e})}function _regex(e,t){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(t),pattern:e})}function _lowercase(e){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(e)})}function _uppercase(e){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(e)})}function _includes(e,t){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(t),includes:e})}function _startsWith(e,t){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(t),prefix:e})}function _endsWith(e,t){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(t),suffix:e})}function _property(e,t,r){return new $ZodCheckProperty({check:"property",property:e,schema:t,...normalizeParams(r)})}function _mime(e,t){return new $ZodCheckMimeType({check:"mime_type",mime:e,...normalizeParams(t)})}function _overwrite(e){return new $ZodCheckOverwrite({check:"overwrite",tx:e})}function _normalize(e){return _overwrite(t=>t.normalize(e))}function _trim(){return _overwrite(e=>e.trim())}function _toLowerCase(){return _overwrite(e=>e.toLowerCase())}function _toUpperCase(){return _overwrite(e=>e.toUpperCase())}function _array(e,t,r){return new e({type:"array",element:t,...normalizeParams(r)})}function _union(e,t,r){return new e({type:"union",options:t,...normalizeParams(r)})}function _discriminatedUnion(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...normalizeParams(n)})}function _intersection(e,t,r){return new e({type:"intersection",left:t,right:r})}function _tuple(e,t,r,n){const i=r instanceof $ZodType;return new e({type:"tuple",items:t,rest:i?r:null,...normalizeParams(i?n:r)})}function _record(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...normalizeParams(n)})}function _map(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...normalizeParams(n)})}function _set(e,t,r){return new e({type:"set",valueType:t,...normalizeParams(r)})}function _enum$1(e,t,r){const n=Array.isArray(t)?Object.fromEntries(t.map(e=>[e,e])):t;return new e({type:"enum",entries:n,...normalizeParams(r)})}function _nativeEnum(e,t,r){return new e({type:"enum",entries:t,...normalizeParams(r)})}function _literal(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...normalizeParams(r)})}function _file(e,t){return new e({type:"file",...normalizeParams(t)})}function _transform(e,t){return new e({type:"transform",transform:t})}function _optional(e,t){return new e({type:"optional",innerType:t})}function _nullable(e,t){return new e({type:"nullable",innerType:t})}function _default$1(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return"function"==typeof r?r():shallowClone(r)}})}function _nonoptional(e,t,r){return new e({type:"nonoptional",innerType:t,...normalizeParams(r)})}function _success(e,t){return new e({type:"success",innerType:t})}function _catch$1(e,t,r){return new e({type:"catch",innerType:t,catchValue:"function"==typeof r?r:()=>r})}function _pipe(e,t,r){return new e({type:"pipe",in:t,out:r})}function _readonly(e,t){return new e({type:"readonly",innerType:t})}function _templateLiteral(e,t,r){return new e({type:"template_literal",parts:t,...normalizeParams(r)})}function _lazy(e,t){return new e({type:"lazy",getter:t})}function _promise(e,t){return new e({type:"promise",innerType:t})}function _custom(e,t,r){const n=normalizeParams(r);n.abort??(n.abort=!0);return new e({type:"custom",check:"custom",fn:t,...n})}function _refine(e,t,r){return new e({type:"custom",check:"custom",fn:t,...normalizeParams(r)})}function _superRefine(e){const t=_check(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(issue(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(issue(n))}},e(r.value,r)));return t}function _check(e,t){const r=new $ZodCheck({check:"custom",...normalizeParams(t)});return r._zod.check=e,r}function _stringbool(e,t){const r=normalizeParams(t);let n=r.truthy??["true","1","yes","on","y","enabled"],i=r.falsy??["false","0","no","off","n","disabled"];"sensitive"!==r.case&&(n=n.map(e=>"string"==typeof e?e.toLowerCase():e),i=i.map(e=>"string"==typeof e?e.toLowerCase():e));const o=new Set(n),s=new Set(i),a=e.Pipe??$ZodPipe,c=e.Boolean??$ZodBoolean,l=e.String??$ZodString,u=new(e.Transform??$ZodTransform)({type:"transform",transform:(e,t)=>{let n=e;return"sensitive"!==r.case&&(n=n.toLowerCase()),!!o.has(n)||!s.has(n)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:t.value,inst:u,continue:!1}),{})},error:r.error}),d=new a({type:"pipe",in:new l({type:"string",error:r.error}),out:u,error:r.error});return new a({type:"pipe",in:d,out:new c({type:"boolean",error:r.error}),error:r.error})}function _stringFormat(e,t,r,n={}){const i=normalizeParams(n),o={...normalizeParams(n),check:"string_format",type:"string",format:t,fn:"function"==typeof r?r:e=>r.test(e),...i};r instanceof RegExp&&(o.pattern=r);return new e(o)}class $ZodFunction{constructor(e){this._def=e,this.def=e}implement(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=(...r)=>{const n=this._def.input?parse$1(this._def.input,r,void 0,{callee:t}):r;if(!Array.isArray(n))throw new Error("Invalid arguments schema: not an array or tuple schema.");const i=e(...n);return this._def.output?parse$1(this._def.output,i,void 0,{callee:t}):i};return t}implementAsync(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=async(...r)=>{const n=this._def.input?await parseAsync$1(this._def.input,r,void 0,{callee:t}):r;if(!Array.isArray(n))throw new Error("Invalid arguments schema: not an array or tuple schema.");const i=await e(...n);return this._def.output?parseAsync$1(this._def.output,i,void 0,{callee:t}):i};return t}input(...e){const t=this.constructor;return Array.isArray(e[0])?new t({type:"function",input:new $ZodTuple({type:"tuple",items:e[0],rest:e[1]}),output:this._def.output}):new t({type:"function",input:e[0],output:this._def.output})}output(e){return new(0,this.constructor)({type:"function",input:this._def.input,output:e})}}function _function(e){return new $ZodFunction({type:"function",input:Array.isArray(e?.input)?_tuple($ZodTuple,e?.input):e?.input??_array($ZodArray,_unknown($ZodUnknown)),output:e?.output??_unknown($ZodUnknown)})}class JSONSchemaGenerator{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??globalRegistry,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;const n=e._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o){o.count++;return t.schemaPath.includes(e)&&(o.cycle=t.path),o.schema}const s={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const r={...t,schemaPath:[...t.schemaPath,e],path:t.path},o=e._zod.parent;if(o)s.ref=o,this.process(o,r),this.seen.get(o).isParent=!0;else{const t=s.schema;switch(n.type){case"string":{const r=t;r.type="string";const{minimum:n,maximum:o,format:a,patterns:c,contentEncoding:l}=e._zod.bag;if("number"==typeof n&&(r.minLength=n),"number"==typeof o&&(r.maxLength=o),a&&(r.format=i[a]??a,""===r.format&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const e=[...c];1===e.length?r.pattern=e[0].source:e.length>1&&(s.schema.allOf=[...e.map(e=>({..."draft-7"===this.target||"draft-4"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{const r=t,{minimum:n,maximum:i,format:o,multipleOf:s,exclusiveMaximum:a,exclusiveMinimum:c}=e._zod.bag;"string"==typeof o&&o.includes("int")?r.type="integer":r.type="number","number"==typeof c&&("draft-4"===this.target?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),"number"==typeof n&&(r.minimum=n,"number"==typeof c&&"draft-4"!==this.target&&(c>=n?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof a&&("draft-4"===this.target?(r.maximum=a,r.exclusiveMaximum=!0):r.exclusiveMaximum=a),"number"==typeof i&&(r.maximum=i,"number"==typeof a&&"draft-4"!==this.target&&(a<=i?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof s&&(r.multipleOf=s);break}case"boolean":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const i=t,{minimum:o,maximum:s}=e._zod.bag;"number"==typeof o&&(i.minItems=o),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=this.process(n.element,{...r,path:[...r.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const i=n.shape;for(const t in i)e.properties[t]=this.process(i[t],{...r,path:[...r.path,"properties",t]});const o=new Set(Object.keys(i)),s=new Set([...o].filter(e=>{const t=n.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));s.size>0&&(e.required=Array.from(s)),"never"===n.catchall?._zod.def.type?e.additionalProperties=!1:n.catchall?n.catchall&&(e.additionalProperties=this.process(n.catchall,{...r,path:[...r.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=n.options.map((e,t)=>this.process(e,{...r,path:[...r.path,"anyOf",t]}));break;case"intersection":{const e=t,i=this.process(n.left,{...r,path:[...r.path,"allOf",0]}),o=this.process(n.right,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length,a=[...s(i)?i.allOf:[i],...s(o)?o.allOf:[o]];e.allOf=a;break}case"tuple":{const i=t;i.type="array";const o=n.items.map((e,t)=>this.process(e,{...r,path:[...r.path,"prefixItems",t]}));if("draft-2020-12"===this.target?i.prefixItems=o:i.items=o,n.rest){const e=this.process(n.rest,{...r,path:[...r.path,"items"]});"draft-2020-12"===this.target?i.items=e:i.additionalItems=e}n.rest&&(i.items=this.process(n.rest,{...r,path:[...r.path,"items"]}));const{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a);break}case"record":{const e=t;e.type="object","draft-4"!==this.target&&(e.propertyNames=this.process(n.keyType,{...r,path:[...r.path,"propertyNames"]})),e.additionalProperties=this.process(n.valueType,{...r,path:[...r.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,r=getEnumValues(n.entries);r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),e.enum=r;break}case"literal":{const e=t,r=[];for(const e of n.values)if(void 0===e){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(e))}else r.push(e);if(0===r.length);else if(1===r.length){const t=r[0];e.type=null===t?"null":typeof t,"draft-4"===this.target?e.enum=[t]:e.const=t}else r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),r.every(e=>"boolean"==typeof e)&&(e.type="string"),r.every(e=>null===e)&&(e.type="null"),e.enum=r;break}case"file":{const r=t,n={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:o,mime:s}=e._zod.bag;void 0!==i&&(n.minLength=i),void 0!==o&&(n.maxLength=o),s?1===s.length?(n.contentMediaType=s[0],Object.assign(r,n)):r.anyOf=s.map(e=>({...n,contentMediaType:e})):Object.assign(r,n);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(n.innerType,r);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(n.innerType,r),s.ref=n.innerType;break;case"success":t.type="boolean";break;case"default":this.process(n.innerType,r),s.ref=n.innerType,t.default=JSON.parse(JSON.stringify(n.defaultValue));break;case"prefault":this.process(n.innerType,r),s.ref=n.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break;case"catch":{let e;this.process(n.innerType,r),s.ref=n.innerType;try{e=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const r=t,n=e._zod.pattern;if(!n)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=n.source;break}case"pipe":{const e="input"===this.io?"transform"===n.in._zod.def.type?n.out:n.in:n.out;this.process(e,r),s.ref=e;break}case"readonly":this.process(n.innerType,r),s.ref=n.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,r),s.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")}}}const c=this.metadataRegistry.get(e);c&&Object.assign(s.schema,c),"input"===this.io&&isTransforming(e)&&(delete s.schema.examples,delete s.schema.default),"input"===this.io&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault;return this.seen.get(e).schema}emit(e,t){const r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=e=>{const t="draft-2020-12"===this.target?"$defs":"definitions";if(r.external){const n=r.external.registry.get(e[0])?.id,i=r.external.uri??(e=>e);if(n)return{ref:i(n)};const o=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=o,{defId:o,ref:`${i("__shared")}#/${t}/${o}`}}if(e[1]===n)return{ref:"#"};const i=`#/${t}/`,o=e[1].schema.id??"__schema"+this.counter++;return{defId:o,ref:i+o}},o=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:r,defId:n}=i(e);t.def={...t.schema},n&&(t.defId=n);const o=t.schema;for(const e in o)delete o[e];o.$ref=r};if("throw"===r.cycles)for(const e of this.seen.entries()){const t=e[1];if(t.cycle)throw new Error(`Cycle detected: #/${t.cycle?.join("/")}/\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const t of this.seen.entries()){const n=t[1];if(e===t[0]){o(t);continue}if(r.external){const n=r.external.registry.get(t[0])?.id;if(e!==t[0]&&n){o(t);continue}}const i=this.metadataRegistry.get(t[0])?.id;i?o(t):(n.cycle||n.count>1&&"ref"===r.reused)&&o(t)}const s=(e,t)=>{const r=this.seen.get(e),n=r.def??r.schema,i={...n};if(null===r.ref)return;const o=r.ref;if(r.ref=null,o){s(o,t);const e=this.seen.get(o).schema;!e.$ref||"draft-7"!==t.target&&"draft-4"!==t.target?(Object.assign(n,e),Object.assign(n,i)):(n.allOf=n.allOf??[],n.allOf.push(e))}r.isParent||this.override({zodSchema:e,jsonSchema:n,path:r.path??[]})};for(const e of[...this.seen.entries()].reverse())s(e[0],{target:this.target});const a={};if("draft-2020-12"===this.target?a.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?a.$schema="http://json-schema.org/draft-07/schema#":"draft-4"===this.target?a.$schema="http://json-schema.org/draft-04/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const t=r.external.registry.get(e)?.id;if(!t)throw new Error("Schema is missing an `id` property");a.$id=r.external.uri(t)}Object.assign(a,n.def);const c=r.external?.defs??{};for(const e of this.seen.entries()){const t=e[1];t.def&&t.defId&&(c[t.defId]=t.def)}r.external||Object.keys(c).length>0&&("draft-2020-12"===this.target?a.$defs=c:a.definitions=c);try{return JSON.parse(JSON.stringify(a))}catch(e){throw new Error("Error converting schema to JSON.")}}}function toJSONSchema(e,t){if(e instanceof $ZodRegistry){const r=new JSONSchemaGenerator(t),n={};for(const t of e._idmap.entries()){const[e,n]=t;r.process(n)}const i={},o={registry:e,uri:t?.uri,defs:n};for(const n of e._idmap.entries()){const[e,s]=n;i[e]=r.emit(s,{...t,external:o})}if(Object.keys(n).length>0){const e="draft-2020-12"===r.target?"$defs":"definitions";i.__shared={[e]:n}}return{schemas:i}}const r=new JSONSchemaGenerator(t);return r.process(e),r.emit(e,t)}function isTransforming(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;switch(n.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return isTransforming(n.element,r);case"object":for(const e in n.shape)if(isTransforming(n.shape[e],r))return!0;return!1;case"union":for(const e of n.options)if(isTransforming(e,r))return!0;return!1;case"intersection":return isTransforming(n.left,r)||isTransforming(n.right,r);case"tuple":for(const e of n.items)if(isTransforming(e,r))return!0;return!(!n.rest||!isTransforming(n.rest,r));case"record":case"map":return isTransforming(n.keyType,r)||isTransforming(n.valueType,r);case"set":return isTransforming(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return isTransforming(n.innerType,r);case"lazy":return isTransforming(n.getter(),r);case"transform":return!0;case"pipe":return isTransforming(n.in,r)||isTransforming(n.out,r)}throw new Error(`Unknown schema type: ${n.type}`)}var jsonSchema=Object.freeze({__proto__:null}),index=Object.freeze({__proto__:null,$ZodAny:$ZodAny,$ZodArray:$ZodArray,$ZodAsyncError:$ZodAsyncError,$ZodBase64:$ZodBase64,$ZodBase64URL:$ZodBase64URL,$ZodBigInt:$ZodBigInt,$ZodBigIntFormat:$ZodBigIntFormat,$ZodBoolean:$ZodBoolean,$ZodCIDRv4:$ZodCIDRv4,$ZodCIDRv6:$ZodCIDRv6,$ZodCUID:$ZodCUID,$ZodCUID2:$ZodCUID2,$ZodCatch:$ZodCatch,$ZodCheck:$ZodCheck,$ZodCheckBigIntFormat:$ZodCheckBigIntFormat,$ZodCheckEndsWith:$ZodCheckEndsWith,$ZodCheckGreaterThan:$ZodCheckGreaterThan,$ZodCheckIncludes:$ZodCheckIncludes,$ZodCheckLengthEquals:$ZodCheckLengthEquals,$ZodCheckLessThan:$ZodCheckLessThan,$ZodCheckLowerCase:$ZodCheckLowerCase,$ZodCheckMaxLength:$ZodCheckMaxLength,$ZodCheckMaxSize:$ZodCheckMaxSize,$ZodCheckMimeType:$ZodCheckMimeType,$ZodCheckMinLength:$ZodCheckMinLength,$ZodCheckMinSize:$ZodCheckMinSize,$ZodCheckMultipleOf:$ZodCheckMultipleOf,$ZodCheckNumberFormat:$ZodCheckNumberFormat,$ZodCheckOverwrite:$ZodCheckOverwrite,$ZodCheckProperty:$ZodCheckProperty,$ZodCheckRegex:$ZodCheckRegex,$ZodCheckSizeEquals:$ZodCheckSizeEquals,$ZodCheckStartsWith:$ZodCheckStartsWith,$ZodCheckStringFormat:$ZodCheckStringFormat,$ZodCheckUpperCase:$ZodCheckUpperCase,$ZodCustom:$ZodCustom,$ZodCustomStringFormat:$ZodCustomStringFormat,$ZodDate:$ZodDate,$ZodDefault:$ZodDefault,$ZodDiscriminatedUnion:$ZodDiscriminatedUnion,$ZodE164:$ZodE164,$ZodEmail:$ZodEmail,$ZodEmoji:$ZodEmoji,$ZodEnum:$ZodEnum,$ZodError:$ZodError,$ZodFile:$ZodFile,$ZodFunction:$ZodFunction,$ZodGUID:$ZodGUID,$ZodIPv4:$ZodIPv4,$ZodIPv6:$ZodIPv6,$ZodISODate:$ZodISODate,$ZodISODateTime:$ZodISODateTime,$ZodISODuration:$ZodISODuration,$ZodISOTime:$ZodISOTime,$ZodIntersection:$ZodIntersection,$ZodJWT:$ZodJWT,$ZodKSUID:$ZodKSUID,$ZodLazy:$ZodLazy,$ZodLiteral:$ZodLiteral,$ZodMap:$ZodMap,$ZodNaN:$ZodNaN,$ZodNanoID:$ZodNanoID,$ZodNever:$ZodNever,$ZodNonOptional:$ZodNonOptional,$ZodNull:$ZodNull,$ZodNullable:$ZodNullable,$ZodNumber:$ZodNumber,$ZodNumberFormat:$ZodNumberFormat,$ZodObject:$ZodObject,$ZodOptional:$ZodOptional,$ZodPipe:$ZodPipe,$ZodPrefault:$ZodPrefault,$ZodPromise:$ZodPromise,$ZodReadonly:$ZodReadonly,$ZodRealError:$ZodRealError,$ZodRecord:$ZodRecord,$ZodRegistry:$ZodRegistry,$ZodSet:$ZodSet,$ZodString:$ZodString,$ZodStringFormat:$ZodStringFormat,$ZodSuccess:$ZodSuccess,$ZodSymbol:$ZodSymbol,$ZodTemplateLiteral:$ZodTemplateLiteral,$ZodTransform:$ZodTransform,$ZodTuple:$ZodTuple,$ZodType:$ZodType,$ZodULID:$ZodULID,$ZodURL:$ZodURL,$ZodUUID:$ZodUUID,$ZodUndefined:$ZodUndefined,$ZodUnion:$ZodUnion,$ZodUnknown:$ZodUnknown,$ZodVoid:$ZodVoid,$ZodXID:$ZodXID,$brand:$brand,$constructor:$constructor,$input:$input,$output:$output,Doc:Doc,JSONSchema:jsonSchema,JSONSchemaGenerator:JSONSchemaGenerator,NEVER:NEVER,TimePrecision:TimePrecision,_any:_any,_array:_array,_base64:_base64,_base64url:_base64url,_bigint:_bigint,_boolean:_boolean,_catch:_catch$1,_check:_check,_cidrv4:_cidrv4,_cidrv6:_cidrv6,_coercedBigint:_coercedBigint,_coercedBoolean:_coercedBoolean,_coercedDate:_coercedDate,_coercedNumber:_coercedNumber,_coercedString:_coercedString,_cuid:_cuid,_cuid2:_cuid2,_custom:_custom,_date:_date,_default:_default$1,_discriminatedUnion:_discriminatedUnion,_e164:_e164,_email:_email,_emoji:_emoji,_endsWith:_endsWith,_enum:_enum$1,_file:_file,_float32:_float32,_float64:_float64,_gt:_gt,_gte:_gte,_guid:_guid,_includes:_includes,_int:_int,_int32:_int32,_int64:_int64,_intersection:_intersection,_ipv4:_ipv4,_ipv6:_ipv6,_isoDate:_isoDate,_isoDateTime:_isoDateTime,_isoDuration:_isoDuration,_isoTime:_isoTime,_jwt:_jwt,_ksuid:_ksuid,_lazy:_lazy,_length:_length,_literal:_literal,_lowercase:_lowercase,_lt:_lt,_lte:_lte,_map:_map,_max:_lte,_maxLength:_maxLength,_maxSize:_maxSize,_mime:_mime,_min:_gte,_minLength:_minLength,_minSize:_minSize,_multipleOf:_multipleOf,_nan:_nan,_nanoid:_nanoid,_nativeEnum:_nativeEnum,_negative:_negative,_never:_never,_nonnegative:_nonnegative,_nonoptional:_nonoptional,_nonpositive:_nonpositive,_normalize:_normalize,_null:_null$1,_nullable:_nullable,_number:_number,_optional:_optional,_overwrite:_overwrite,_parse:_parse,_parseAsync:_parseAsync,_pipe:_pipe,_positive:_positive,_promise:_promise,_property:_property,_readonly:_readonly,_record:_record,_refine:_refine,_regex:_regex,_safeParse:_safeParse,_safeParseAsync:_safeParseAsync,_set:_set,_size:_size,_startsWith:_startsWith,_string:_string,_stringFormat:_stringFormat,_stringbool:_stringbool,_success:_success,_superRefine:_superRefine,_symbol:_symbol,_templateLiteral:_templateLiteral,_toLowerCase:_toLowerCase,_toUpperCase:_toUpperCase,_transform:_transform,_trim:_trim,_tuple:_tuple,_uint32:_uint32,_uint64:_uint64,_ulid:_ulid,_undefined:_undefined$1,_union:_union,_unknown:_unknown,_uppercase:_uppercase,_url:_url,_uuid:_uuid,_uuidv4:_uuidv4,_uuidv6:_uuidv6,_uuidv7:_uuidv7,_void:_void$1,_xid:_xid,clone:clone,config:config,flattenError:flattenError,formatError:formatError,function:_function,globalConfig:globalConfig,globalRegistry:globalRegistry,isValidBase64:isValidBase64,isValidBase64URL:isValidBase64URL,isValidJWT:isValidJWT,locales:index$1,parse:parse$1,parseAsync:parseAsync$1,prettifyError:prettifyError,regexes:regexes,registry:registry,safeParse:safeParse$1,safeParseAsync:safeParseAsync$1,toDotPath:toDotPath,toJSONSchema:toJSONSchema,treeifyError:treeifyError,util:util,version:version});const ZodISODateTime=$constructor("ZodISODateTime",(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}const ZodISODate=$constructor("ZodISODate",(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date$2(e){return _isoDate(ZodISODate,e)}const ZodISOTime=$constructor("ZodISOTime",(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time(e){return _isoTime(ZodISOTime,e)}const ZodISODuration=$constructor("ZodISODuration",(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}var iso=Object.freeze({__proto__:null,ZodISODate:ZodISODate,ZodISODateTime:ZodISODateTime,ZodISODuration:ZodISODuration,ZodISOTime:ZodISOTime,date:date$2,datetime:datetime,duration:duration,time:time});const initializer=(e,t)=>{$ZodError.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>formatError(e,t)},flatten:{value:t=>flattenError(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},isEmpty:{get:()=>0===e.issues.length}})},ZodError=$constructor("ZodError",initializer),ZodRealError=$constructor("ZodError",initializer,{Parent:Error}),parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),ZodType=$constructor("ZodType",(e,t)=>($ZodType.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>clone(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>parse(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>safeParse(e,t,r),e.parseAsync=async(t,r)=>parseAsync(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>safeParseAsync(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(refine(t,r)),e.superRefine=t=>e.check(superRefine(t)),e.overwrite=t=>e.check(_overwrite(t)),e.optional=()=>optional(e),e.nullable=()=>nullable(e),e.nullish=()=>optional(nullable(e)),e.nonoptional=t=>nonoptional(e,t),e.array=()=>array(e),e.or=t=>union([e,t]),e.and=t=>intersection(e,t),e.transform=t=>pipe(e,transform(t)),e.default=t=>_default(e,t),e.prefault=t=>prefault(e,t),e.catch=t=>_catch(e,t),e.pipe=t=>pipe(e,t),e.readonly=()=>readonly(e),e.describe=t=>{const r=e.clone();return globalRegistry.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>globalRegistry.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return globalRegistry.get(e);const r=e.clone();return globalRegistry.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),_ZodString=$constructor("_ZodString",(e,t)=>{$ZodString.init(e,t),ZodType.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(_regex(...t)),e.includes=(...t)=>e.check(_includes(...t)),e.startsWith=(...t)=>e.check(_startsWith(...t)),e.endsWith=(...t)=>e.check(_endsWith(...t)),e.min=(...t)=>e.check(_minLength(...t)),e.max=(...t)=>e.check(_maxLength(...t)),e.length=(...t)=>e.check(_length(...t)),e.nonempty=(...t)=>e.check(_minLength(1,...t)),e.lowercase=t=>e.check(_lowercase(t)),e.uppercase=t=>e.check(_uppercase(t)),e.trim=()=>e.check(_trim()),e.normalize=(...t)=>e.check(_normalize(...t)),e.toLowerCase=()=>e.check(_toLowerCase()),e.toUpperCase=()=>e.check(_toUpperCase())}),ZodString=$constructor("ZodString",(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=t=>e.check(_email(ZodEmail,t)),e.url=t=>e.check(_url(ZodURL,t)),e.jwt=t=>e.check(_jwt(ZodJWT,t)),e.emoji=t=>e.check(_emoji(ZodEmoji,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.uuid=t=>e.check(_uuid(ZodUUID,t)),e.uuidv4=t=>e.check(_uuidv4(ZodUUID,t)),e.uuidv6=t=>e.check(_uuidv6(ZodUUID,t)),e.uuidv7=t=>e.check(_uuidv7(ZodUUID,t)),e.nanoid=t=>e.check(_nanoid(ZodNanoID,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.cuid=t=>e.check(_cuid(ZodCUID,t)),e.cuid2=t=>e.check(_cuid2(ZodCUID2,t)),e.ulid=t=>e.check(_ulid(ZodULID,t)),e.base64=t=>e.check(_base64(ZodBase64,t)),e.base64url=t=>e.check(_base64url(ZodBase64URL,t)),e.xid=t=>e.check(_xid(ZodXID,t)),e.ksuid=t=>e.check(_ksuid(ZodKSUID,t)),e.ipv4=t=>e.check(_ipv4(ZodIPv4,t)),e.ipv6=t=>e.check(_ipv6(ZodIPv6,t)),e.cidrv4=t=>e.check(_cidrv4(ZodCIDRv4,t)),e.cidrv6=t=>e.check(_cidrv6(ZodCIDRv6,t)),e.e164=t=>e.check(_e164(ZodE164,t)),e.datetime=t=>e.check(datetime(t)),e.date=t=>e.check(date$2(t)),e.time=t=>e.check(time(t)),e.duration=t=>e.check(duration(t))});function string$1(e){return _string(ZodString,e)}const ZodStringFormat=$constructor("ZodStringFormat",(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor("ZodEmail",(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)});function email(e){return _email(ZodEmail,e)}const ZodGUID=$constructor("ZodGUID",(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)});function guid(e){return _guid(ZodGUID,e)}const ZodUUID=$constructor("ZodUUID",(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)});function uuid(e){return _uuid(ZodUUID,e)}function uuidv4(e){return _uuidv4(ZodUUID,e)}function uuidv6(e){return _uuidv6(ZodUUID,e)}function uuidv7(e){return _uuidv7(ZodUUID,e)}const ZodURL=$constructor("ZodURL",(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)});function url(e){return _url(ZodURL,e)}const ZodEmoji=$constructor("ZodEmoji",(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)});function emoji(e){return _emoji(ZodEmoji,e)}const ZodNanoID=$constructor("ZodNanoID",(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)});function nanoid$1(e){return _nanoid(ZodNanoID,e)}const ZodCUID=$constructor("ZodCUID",(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)});function cuid(e){return _cuid(ZodCUID,e)}const ZodCUID2=$constructor("ZodCUID2",(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)});function cuid2(e){return _cuid2(ZodCUID2,e)}const ZodULID=$constructor("ZodULID",(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)});function ulid(e){return _ulid(ZodULID,e)}const ZodXID=$constructor("ZodXID",(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)});function xid(e){return _xid(ZodXID,e)}const ZodKSUID=$constructor("ZodKSUID",(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)});function ksuid(e){return _ksuid(ZodKSUID,e)}const ZodIPv4=$constructor("ZodIPv4",(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)});function ipv4(e){return _ipv4(ZodIPv4,e)}const ZodIPv6=$constructor("ZodIPv6",(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)});function ipv6(e){return _ipv6(ZodIPv6,e)}const ZodCIDRv4=$constructor("ZodCIDRv4",(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)});function cidrv4(e){return _cidrv4(ZodCIDRv4,e)}const ZodCIDRv6=$constructor("ZodCIDRv6",(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)});function cidrv6(e){return _cidrv6(ZodCIDRv6,e)}const ZodBase64=$constructor("ZodBase64",(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)});function base64(e){return _base64(ZodBase64,e)}const ZodBase64URL=$constructor("ZodBase64URL",(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)});function base64url(e){return _base64url(ZodBase64URL,e)}const ZodE164=$constructor("ZodE164",(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)});function e164(e){return _e164(ZodE164,e)}const ZodJWT=$constructor("ZodJWT",(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)});function jwt(e){return _jwt(ZodJWT,e)}const ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(e,t)=>{$ZodCustomStringFormat.init(e,t),ZodStringFormat.init(e,t)});function stringFormat(e,t,r={}){return _stringFormat(ZodCustomStringFormat,e,t,r)}function hostname(e){return _stringFormat(ZodCustomStringFormat,"hostname",hostname$1,e)}const ZodNumber=$constructor("ZodNumber",(e,t)=>{$ZodNumber.init(e,t),ZodType.init(e,t),e.gt=(t,r)=>e.check(_gt(t,r)),e.gte=(t,r)=>e.check(_gte(t,r)),e.min=(t,r)=>e.check(_gte(t,r)),e.lt=(t,r)=>e.check(_lt(t,r)),e.lte=(t,r)=>e.check(_lte(t,r)),e.max=(t,r)=>e.check(_lte(t,r)),e.int=t=>e.check(int(t)),e.safe=t=>e.check(int(t)),e.positive=t=>e.check(_gt(0,t)),e.nonnegative=t=>e.check(_gte(0,t)),e.negative=t=>e.check(_lt(0,t)),e.nonpositive=t=>e.check(_lte(0,t)),e.multipleOf=(t,r)=>e.check(_multipleOf(t,r)),e.step=(t,r)=>e.check(_multipleOf(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function number$1(e){return _number(ZodNumber,e)}const ZodNumberFormat=$constructor("ZodNumberFormat",(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}function float32(e){return _float32(ZodNumberFormat,e)}function float64(e){return _float64(ZodNumberFormat,e)}function int32(e){return _int32(ZodNumberFormat,e)}function uint32(e){return _uint32(ZodNumberFormat,e)}const ZodBoolean=$constructor("ZodBoolean",(e,t)=>{$ZodBoolean.init(e,t),ZodType.init(e,t)});function boolean$1(e){return _boolean(ZodBoolean,e)}const ZodBigInt=$constructor("ZodBigInt",(e,t)=>{$ZodBigInt.init(e,t),ZodType.init(e,t),e.gte=(t,r)=>e.check(_gte(t,r)),e.min=(t,r)=>e.check(_gte(t,r)),e.gt=(t,r)=>e.check(_gt(t,r)),e.gte=(t,r)=>e.check(_gte(t,r)),e.min=(t,r)=>e.check(_gte(t,r)),e.lt=(t,r)=>e.check(_lt(t,r)),e.lte=(t,r)=>e.check(_lte(t,r)),e.max=(t,r)=>e.check(_lte(t,r)),e.positive=t=>e.check(_gt(BigInt(0),t)),e.negative=t=>e.check(_lt(BigInt(0),t)),e.nonpositive=t=>e.check(_lte(BigInt(0),t)),e.nonnegative=t=>e.check(_gte(BigInt(0),t)),e.multipleOf=(t,r)=>e.check(_multipleOf(t,r));const r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function bigint$1(e){return _bigint(ZodBigInt,e)}const ZodBigIntFormat=$constructor("ZodBigIntFormat",(e,t)=>{$ZodBigIntFormat.init(e,t),ZodBigInt.init(e,t)});function int64(e){return _int64(ZodBigIntFormat,e)}function uint64(e){return _uint64(ZodBigIntFormat,e)}const ZodSymbol=$constructor("ZodSymbol",(e,t)=>{$ZodSymbol.init(e,t),ZodType.init(e,t)});function symbol(e){return _symbol(ZodSymbol,e)}const ZodUndefined=$constructor("ZodUndefined",(e,t)=>{$ZodUndefined.init(e,t),ZodType.init(e,t)});function _undefined(e){return _undefined$1(ZodUndefined,e)}const ZodNull=$constructor("ZodNull",(e,t)=>{$ZodNull.init(e,t),ZodType.init(e,t)});function _null(e){return _null$1(ZodNull,e)}const ZodAny=$constructor("ZodAny",(e,t)=>{$ZodAny.init(e,t),ZodType.init(e,t)});function any(){return _any(ZodAny)}const ZodUnknown=$constructor("ZodUnknown",(e,t)=>{$ZodUnknown.init(e,t),ZodType.init(e,t)});function unknown(){return _unknown(ZodUnknown)}const ZodNever=$constructor("ZodNever",(e,t)=>{$ZodNever.init(e,t),ZodType.init(e,t)});function never(e){return _never(ZodNever,e)}const ZodVoid=$constructor("ZodVoid",(e,t)=>{$ZodVoid.init(e,t),ZodType.init(e,t)});function _void(e){return _void$1(ZodVoid,e)}const ZodDate=$constructor("ZodDate",(e,t)=>{$ZodDate.init(e,t),ZodType.init(e,t),e.min=(t,r)=>e.check(_gte(t,r)),e.max=(t,r)=>e.check(_lte(t,r));const r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function date$1(e){return _date(ZodDate,e)}const ZodArray=$constructor("ZodArray",(e,t)=>{$ZodArray.init(e,t),ZodType.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(_minLength(t,r)),e.nonempty=t=>e.check(_minLength(1,t)),e.max=(t,r)=>e.check(_maxLength(t,r)),e.length=(t,r)=>e.check(_length(t,r)),e.unwrap=()=>e.element});function array(e,t){return _array(ZodArray,e,t)}function keyof(e){const t=e._zod.def.shape;return _enum(Object.keys(t))}const ZodObject=$constructor("ZodObject",(e,t)=>{$ZodObject.init(e,t),ZodType.init(e,t),defineLazy(e,"shape",()=>t.shape),e.keyof=()=>_enum(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:unknown()}),e.loose=()=>e.clone({...e._zod.def,catchall:unknown()}),e.strict=()=>e.clone({...e._zod.def,catchall:never()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>extend(e,t),e.merge=t=>merge(e,t),e.pick=t=>pick(e,t),e.omit=t=>omit(e,t),e.partial=(...t)=>partial(ZodOptional,e,t[0]),e.required=(...t)=>required(ZodNonOptional,e,t[0])});function object(e,t){const r={type:"object",get shape(){return assignProp(this,"shape",e?objectClone(e):{}),this.shape},...normalizeParams(t)};return new ZodObject(r)}function strictObject(e,t){return new ZodObject({type:"object",get shape(){return assignProp(this,"shape",objectClone(e)),this.shape},catchall:never(),...normalizeParams(t)})}function looseObject(e,t){return new ZodObject({type:"object",get shape(){return assignProp(this,"shape",objectClone(e)),this.shape},catchall:unknown(),...normalizeParams(t)})}const ZodUnion=$constructor("ZodUnion",(e,t)=>{$ZodUnion.init(e,t),ZodType.init(e,t),e.options=t.options});function union(e,t){return new ZodUnion({type:"union",options:e,...normalizeParams(t)})}const ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(e,t)=>{ZodUnion.init(e,t),$ZodDiscriminatedUnion.init(e,t)});function discriminatedUnion(e,t,r){return new ZodDiscriminatedUnion({type:"union",options:t,discriminator:e,...normalizeParams(r)})}const ZodIntersection=$constructor("ZodIntersection",(e,t)=>{$ZodIntersection.init(e,t),ZodType.init(e,t)});function intersection(e,t){return new ZodIntersection({type:"intersection",left:e,right:t})}const ZodTuple=$constructor("ZodTuple",(e,t)=>{$ZodTuple.init(e,t),ZodType.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})});function tuple(e,t,r){const n=t instanceof $ZodType;return new ZodTuple({type:"tuple",items:e,rest:n?t:null,...normalizeParams(n?r:t)})}const ZodRecord=$constructor("ZodRecord",(e,t)=>{$ZodRecord.init(e,t),ZodType.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,r){return new ZodRecord({type:"record",keyType:e,valueType:t,...normalizeParams(r)})}function partialRecord(e,t,r){const n=clone(e);return n._zod.values=void 0,new ZodRecord({type:"record",keyType:n,valueType:t,...normalizeParams(r)})}const ZodMap=$constructor("ZodMap",(e,t)=>{$ZodMap.init(e,t),ZodType.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function map(e,t,r){return new ZodMap({type:"map",keyType:e,valueType:t,...normalizeParams(r)})}const ZodSet=$constructor("ZodSet",(e,t)=>{$ZodSet.init(e,t),ZodType.init(e,t),e.min=(...t)=>e.check(_minSize(...t)),e.nonempty=t=>e.check(_minSize(1,t)),e.max=(...t)=>e.check(_maxSize(...t)),e.size=(...t)=>e.check(_size(...t))});function set(e,t){return new ZodSet({type:"set",valueType:e,...normalizeParams(t)})}const ZodEnum=$constructor("ZodEnum",(e,t)=>{$ZodEnum.init(e,t),ZodType.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{const i={};for(const n of e){if(!r.has(n))throw new Error(`Key ${n} not found in enum`);i[n]=t.entries[n]}return new ZodEnum({...t,checks:[],...normalizeParams(n),entries:i})},e.exclude=(e,n)=>{const i={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new ZodEnum({...t,checks:[],...normalizeParams(n),entries:i})}});function _enum(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ZodEnum({type:"enum",entries:r,...normalizeParams(t)})}function nativeEnum(e,t){return new ZodEnum({type:"enum",entries:e,...normalizeParams(t)})}const ZodLiteral=$constructor("ZodLiteral",(e,t)=>{$ZodLiteral.init(e,t),ZodType.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new ZodLiteral({type:"literal",values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ZodFile=$constructor("ZodFile",(e,t)=>{$ZodFile.init(e,t),ZodType.init(e,t),e.min=(t,r)=>e.check(_minSize(t,r)),e.max=(t,r)=>e.check(_maxSize(t,r)),e.mime=(t,r)=>e.check(_mime(Array.isArray(t)?t:[t],r))});function file(e){return _file(ZodFile,e)}const ZodTransform=$constructor("ZodTransform",(e,t)=>{$ZodTransform.init(e,t),ZodType.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=n=>{if("string"==typeof n)r.issues.push(issue(n,r.value,t));else{const t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),r.issues.push(issue(t))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then(e=>(r.value=e,r)):(r.value=i,r)}});function transform(e){return new ZodTransform({type:"transform",transform:e})}const ZodOptional=$constructor("ZodOptional",(e,t)=>{$ZodOptional.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional({type:"optional",innerType:e})}const ZodNullable=$constructor("ZodNullable",(e,t)=>{$ZodNullable.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable({type:"nullable",innerType:e})}function nullish(e){return optional(nullable(e))}const ZodDefault=$constructor("ZodDefault",(e,t)=>{$ZodDefault.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():shallowClone(t)}})}const ZodPrefault=$constructor("ZodPrefault",(e,t)=>{$ZodPrefault.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():shallowClone(t)}})}const ZodNonOptional=$constructor("ZodNonOptional",(e,t)=>{$ZodNonOptional.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:"nonoptional",innerType:e,...normalizeParams(t)})}const ZodSuccess=$constructor("ZodSuccess",(e,t)=>{$ZodSuccess.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function success(e){return new ZodSuccess({type:"success",innerType:e})}const ZodCatch=$constructor("ZodCatch",(e,t)=>{$ZodCatch.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const ZodNaN=$constructor("ZodNaN",(e,t)=>{$ZodNaN.init(e,t),ZodType.init(e,t)});function nan(e){return _nan(ZodNaN,e)}const ZodPipe=$constructor("ZodPipe",(e,t)=>{$ZodPipe.init(e,t),ZodType.init(e,t),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:"pipe",in:e,out:t})}const ZodReadonly=$constructor("ZodReadonly",(e,t)=>{$ZodReadonly.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly({type:"readonly",innerType:e})}const ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(e,t)=>{$ZodTemplateLiteral.init(e,t),ZodType.init(e,t)});function templateLiteral(e,t){return new ZodTemplateLiteral({type:"template_literal",parts:e,...normalizeParams(t)})}const ZodLazy=$constructor("ZodLazy",(e,t)=>{$ZodLazy.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.getter()});function lazy(e){return new ZodLazy({type:"lazy",getter:e})}const ZodPromise=$constructor("ZodPromise",(e,t)=>{$ZodPromise.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function promise(e){return new ZodPromise({type:"promise",innerType:e})}const ZodCustom=$constructor("ZodCustom",(e,t)=>{$ZodCustom.init(e,t),ZodType.init(e,t)});function check(e){const t=new $ZodCheck({check:"custom"});return t._zod.check=e,t}function custom(e,t){return _custom(ZodCustom,e??(()=>!0),t)}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e){return _superRefine(e)}function _instanceof(e,t={error:`Input not instance of ${e.name}`}){const r=new ZodCustom({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...normalizeParams(t)});return r._zod.bag.Class=e,r}const stringbool=(...e)=>_stringbool({Pipe:ZodPipe,Boolean:ZodBoolean,String:ZodString,Transform:ZodTransform},...e);function json(e){const t=lazy(()=>union([string$1(e),number$1(),boolean$1(),_null(),array(t),record(string$1(),t)]));return t}function preprocess(e,t){return pipe(transform(e),t)}const ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(e){config({customError:e})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;function string(e){return _coercedString(ZodString,e)}function number(e){return _coercedNumber(ZodNumber,e)}function boolean(e){return _coercedBoolean(ZodBoolean,e)}function bigint(e){return _coercedBigint(ZodBigInt,e)}function date(e){return _coercedDate(ZodDate,e)}ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={});var coerce=Object.freeze({__proto__:null,bigint:bigint,boolean:boolean,date:date,number:number,string:string});config(en());var z=Object.freeze({__proto__:null,$brand:$brand,$input:$input,$output:$output,NEVER:NEVER,TimePrecision:TimePrecision,ZodAny:ZodAny,ZodArray:ZodArray,ZodBase64:ZodBase64,ZodBase64URL:ZodBase64URL,ZodBigInt:ZodBigInt,ZodBigIntFormat:ZodBigIntFormat,ZodBoolean:ZodBoolean,ZodCIDRv4:ZodCIDRv4,ZodCIDRv6:ZodCIDRv6,ZodCUID:ZodCUID,ZodCUID2:ZodCUID2,ZodCatch:ZodCatch,ZodCustom:ZodCustom,ZodCustomStringFormat:ZodCustomStringFormat,ZodDate:ZodDate,ZodDefault:ZodDefault,ZodDiscriminatedUnion:ZodDiscriminatedUnion,ZodE164:ZodE164,ZodEmail:ZodEmail,ZodEmoji:ZodEmoji,ZodEnum:ZodEnum,ZodError:ZodError,ZodFile:ZodFile,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind},ZodGUID:ZodGUID,ZodIPv4:ZodIPv4,ZodIPv6:ZodIPv6,ZodISODate:ZodISODate,ZodISODateTime:ZodISODateTime,ZodISODuration:ZodISODuration,ZodISOTime:ZodISOTime,ZodIntersection:ZodIntersection,ZodIssueCode:ZodIssueCode,ZodJWT:ZodJWT,ZodKSUID:ZodKSUID,ZodLazy:ZodLazy,ZodLiteral:ZodLiteral,ZodMap:ZodMap,ZodNaN:ZodNaN,ZodNanoID:ZodNanoID,ZodNever:ZodNever,ZodNonOptional:ZodNonOptional,ZodNull:ZodNull,ZodNullable:ZodNullable,ZodNumber:ZodNumber,ZodNumberFormat:ZodNumberFormat,ZodObject:ZodObject,ZodOptional:ZodOptional,ZodPipe:ZodPipe,ZodPrefault:ZodPrefault,ZodPromise:ZodPromise,ZodReadonly:ZodReadonly,ZodRealError:ZodRealError,ZodRecord:ZodRecord,ZodSet:ZodSet,ZodString:ZodString,ZodStringFormat:ZodStringFormat,ZodSuccess:ZodSuccess,ZodSymbol:ZodSymbol,ZodTemplateLiteral:ZodTemplateLiteral,ZodTransform:ZodTransform,ZodTuple:ZodTuple,ZodType:ZodType,ZodULID:ZodULID,ZodURL:ZodURL,ZodUUID:ZodUUID,ZodUndefined:ZodUndefined,ZodUnion:ZodUnion,ZodUnknown:ZodUnknown,ZodVoid:ZodVoid,ZodXID:ZodXID,_ZodString:_ZodString,_default:_default,any:any,array:array,base64:base64,base64url:base64url,bigint:bigint$1,boolean:boolean$1,catch:_catch,check:check,cidrv4:cidrv4,cidrv6:cidrv6,clone:clone,coerce:coerce,config:config,core:index,cuid:cuid,cuid2:cuid2,custom:custom,date:date$1,discriminatedUnion:discriminatedUnion,e164:e164,email:email,emoji:emoji,endsWith:_endsWith,enum:_enum,file:file,flattenError:flattenError,float32:float32,float64:float64,formatError:formatError,function:_function,getErrorMap:getErrorMap,globalRegistry:globalRegistry,gt:_gt,gte:_gte,guid:guid,hostname:hostname,includes:_includes,instanceof:_instanceof,int:int,int32:int32,int64:int64,intersection:intersection,ipv4:ipv4,ipv6:ipv6,iso:iso,json:json,jwt:jwt,keyof:keyof,ksuid:ksuid,lazy:lazy,length:_length,literal:literal,locales:index$1,looseObject:looseObject,lowercase:_lowercase,lt:_lt,lte:_lte,map:map,maxLength:_maxLength,maxSize:_maxSize,mime:_mime,minLength:_minLength,minSize:_minSize,multipleOf:_multipleOf,nan:nan,nanoid:nanoid$1,nativeEnum:nativeEnum,negative:_negative,never:never,nonnegative:_nonnegative,nonoptional:nonoptional,nonpositive:_nonpositive,normalize:_normalize,null:_null,nullable:nullable,nullish:nullish,number:number$1,object:object,optional:optional,overwrite:_overwrite,parse:parse,parseAsync:parseAsync,partialRecord:partialRecord,pipe:pipe,positive:_positive,prefault:prefault,preprocess:preprocess,prettifyError:prettifyError,promise:promise,property:_property,readonly:readonly,record:record,refine:refine,regex:_regex,regexes:regexes,registry:registry,safeParse:safeParse,safeParseAsync:safeParseAsync,set:set,setErrorMap:setErrorMap,size:_size,startsWith:_startsWith,strictObject:strictObject,string:string$1,stringFormat:stringFormat,stringbool:stringbool,success:success,superRefine:superRefine,symbol:symbol,templateLiteral:templateLiteral,toJSONSchema:toJSONSchema,toLowerCase:_toLowerCase,toUpperCase:_toUpperCase,transform:transform,treeifyError:treeifyError,trim:_trim,tuple:tuple,uint32:uint32,uint64:uint64,ulid:ulid,undefined:_undefined,union:union,unknown:unknown,uppercase:_uppercase,url:url,uuid:uuid,uuidv4:uuidv4,uuidv6:uuidv6,uuidv7:uuidv7,void:_void,xid:xid}),clientCapabilities=[{capability:"ADMIN_API_V2_APP_ADD",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_APP_ADD_OR_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_APP_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_ADD",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_ADD_OR_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_UPDATE",introducedInVersion:"1.5.0"},{capability:"METRICS_ENDPOINTS_DB_CONNECTIVITY",introducedInVersion:"1.7.0"},{capability:"API_V2_SERVER_INFO_ENHANCED",introducedInVersion:"2.0.0"},{capability:"HTTP_TEST",introducedInVersion:"2.0.0"}],clientCapabilitiesByName=new Map;for(const e of clientCapabilities)clientCapabilitiesByName.set(e.capability,e);var BaseAPI=class{constructor(e){this.options=e,this.setOptions(e)}_responseSuccessCallback;_responseErrorCallback;_errorsInterceptorsId;_headersInterceptorId;_serverInfoWrapper={initialized:!1};axiosInstance;setOptions(e){if(!e.auth)throw new Error("please provide auth info");this.options=e,this._errorsInterceptorsId&&this.axiosInstance?.interceptors?.response?.eject(this._errorsInterceptorsId),this._headersInterceptorId&&this.axiosInstance?.interceptors?.request?.eject(this._headersInterceptorId);const t=this.getBaseHeaders(e);this.axiosInstance=axios.create({transformResponse:e.transformResponse,baseURL:e.baseUrl,headers:t,timeout:this.options.requestTimeout,withCredentials:e?.auth?.includeCredentials,validateStatus:this.defaultIsStatusCodeValid,maxContentLength:1/0,maxBodyLength:1/0}),this._errorsInterceptorsId=this.axiosInstance?.interceptors?.response?.use(e=>{try{this._responseSuccessCallback?.(e)}catch{}return e},e=>{try{this._responseErrorCallback?.(e)}catch{}return Promise.reject(e)}),this._headersInterceptorId=this.axiosInstance?.interceptors?.request?.use(async e=>{const t=this.getBaseHeaders(this.options);for(const[r,n]of Object.entries(t))e.headers.set(r,n);if(this.options.getHeaders){const t=await this.options.getHeaders({...e,method:e.method,url:e.url,body:e.data})??{};for(const[r,n]of Object.entries(t))e.headers.set(r,n)}return e},e=>Promise.reject(e))}async whoAmI(){return(await this.axiosInstance.get("/whoami")).data}onResponseSuccessCallback(e){this._responseSuccessCallback=e}onResponseErrorCallback(e){this._responseErrorCallback=e}async initialize(){try{const e=await this.axiosInstance.get("/v2/server/info");this.initializeServerInfo(e.data)}catch(e){if(404===(e?.response?.status??e?.status))return console.warn('Warning: The "GET /v2/server/info" endpoint returned a status code of 404. This means that the io.Manager server is version is < 1.5.0. Proceeding with an empty set of capabilities.'),void this.initializeServerInfo({version:"< 1.5.0",capabilities:[],licenseInfo:{licenseSupported:!1},base:void 0,machine:void 0,start:void 0});throw e}}get serverInfo(){return this._serverInfoWrapper.initialized||this.throwNotInitialized(),this._serverInfoWrapper}hasCapability(e){return this._serverInfoWrapper.initialized||this.throwNotInitialized(),this._serverInfoWrapper.capabilitiesByName.has(e)}async unloadClient(e,t){if(!e||!t)return;const r=new Headers({...this.getBaseHeaders(this.options),...await(this.options.getHeaders?.({method:"POST",url:`${this.options.baseUrl}/user/goodbye`}))}),n=new Request(`${this.options.baseUrl}/user/goodbye`,{method:"POST",headers:r,mode:"cors",cache:"default",keepalive:!0,body:JSON.stringify({session:e})});window.fetch(n)}getHeaders(e){return this.getBaseHeaders(e)}getBaseHeaders(e){const t={};if(e.auth?.username&&(t.user=e.auth.username),(e.auth?.basic?.username||e.auth?.basic?.password)&&(t.Authorization=`Basic ${this.toBase64(`${e.auth.basic.username}:${e.auth.basic.password}`)}`),e.auth?.token?.bearer&&(t.Authorization=`Bearer ${e.auth.token.bearer}`),e.headers)for(const r of Object.keys(e.headers))t[r]=e.headers[r];return t}initializeServerInfo(e){const t=new Map;for(const r of e.capabilities)t.set(r.capability,r);if("2.0.0"===e.version){const e={capability:"HTTP_TEST",introducedInVersion:"2.0.0"};t.set(e.capability,e)}Object.assign(this._serverInfoWrapper,{initialized:!0,capabilitiesByName:t,...e})}ensureCapability(e){if(this.options.disableCapabilityCheck)return;this._serverInfoWrapper.initialized||this.throwNotInitialized();if(!this._serverInfoWrapper.capabilitiesByName.get(e)){const t=clientCapabilitiesByName.get(e);if(!t)throw new Error(`Client capability "${e}" not found.`);throw new Error(`io.Manager server version "${this.serverInfo.version}" doesn't support capability "${e}" which was introduced in version "${t.introducedInVersion}".`)}}throwNotInitialized(){throw new Error("You need to call initialize() first, before calling this API.")}toBase64(e){return"undefined"!=typeof window?window.btoa(e):Buffer.from(e,"utf-8").toString("base64")}defaultIsStatusCodeValid(e){return e<400}};function customEncodeURIComponent(e){return decodeURIComponent(e)!==e?e:encodeURIComponent(e)}var PromiseWrapper=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve=()=>{};reject=()=>{};promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};function debugSanitizeValue(e){switch(typeof e){case"number":case"bigint":case"boolean":return e;case"string":return`Sanitized(type=string, length=${e.length})`;case"function":return`Sanitized(type=function, name=${e.name||"anonymous"})`;case"object":return null===e?"Sanitized(type=object, value=null)":e instanceof Date||e instanceof RegExp?e:`Sanitized(type=object, propertyCount=${Object.keys(e).length})`;default:return`Sanitized(type=${typeof e})`}}var RequestLogger=class{constructor(e,t,r,n){this.logger=e,this.logLevel=t,this.disableLogSanitization=r,this.logHTTPHeaders=n}shouldLogRequest(){return this.logger.isLevelEnabled(this.logLevel)}logRequest(e){if(!this.shouldLogRequest())return;const t=e();let r=`Calling endpoint "${t.endpointName}" (${t.operationName})`,n=!1;if(t.pathParameters&&Object.keys(t.pathParameters).length>0){const e=structuredClone(t.pathParameters);n&&(r+=" and"),r+=` with path parameters: ${JSON.stringify(e)}`,n=!0}if(t.queryParameters&&Object.keys(t.queryParameters).length>0){const e=structuredClone(t.queryParameters);n&&(r+=" and"),r+=` with query parameters: ${JSON.stringify(e)}`,n=!0}if(t.requestBody){const e=structuredClone(t.requestBody);if(!this.disableLogSanitization)for(const r of t.sanitizeRequestBodyProperties??[]){const t=e[r];t&&(e[r]=debugSanitizeValue(t))}n&&(r+=" and"),r+=` with request body: ${JSON.stringify(e)}`,n=!0}this.logger.log(this.logLevel,r)}logResponse(e){if(!this.shouldLogRequest())return;const t=e();let r=`Endpoint "${t.endpointName}" (${t.operationName}) returned status code of ${t.response.statusCode} and response body`;if("string"==typeof t.response.body)r+=" (string): ",r+=t.response.body;else if("boolean"==typeof t.response.body)r+=" (boolean): ",r+=t.response.body.toString();else if("number"==typeof t.response.body)r+=" (number): ",r+=t.response.body.toString();else if(void 0===t.response.body)r+=" is undefined";else if(null===t.response.body)r+=" is null";else if("object"==typeof t.response.body){const e=structuredClone(t.response.body);if(!this.disableLogSanitization)for(const r of t.sanitizeResponseBodyProperties??[]){const t=e[r];t&&(e[r]=debugSanitizeValue(t))}r+=" (object): ",r+=JSON.stringify(e)}else r+=" is something strange";this.logger.log(this.logLevel,r)}logRequestHeaders(e){if(!this.shouldLogRequest())return;if(!this.logHTTPHeaders)return;if(!this.disableLogSanitization)return;const t=e();this.logger.log(this.logLevel,`Using request headers: ${JSON.stringify(t)}`)}logResponseHeaders(e){if(!this.shouldLogRequest())return;if(!this.logHTTPHeaders)return;if(!this.disableLogSanitization)return;const t=e();this.logger.log(this.logLevel,`Received response headers: ${JSON.stringify(t)}`)}};function extendedOptional(e){return z.union([e,z.null(),z.undefined()]).optional()}function anyIsoDate(){return z.union([z.iso.datetime({offset:!0,local:!0}),z.iso.date()])}var zodHelpers={extendedOptional:extendedOptional,anyIsoDate:anyIsoDate};z.looseObject({name:z.string(),base:z.string(),version:z.string(),start:zodHelpers.anyIsoDate(),status:z.string()}),z.looseObject({id:z.string(),email:zodHelpers.extendedOptional(z.string()),groups:z.array(z.string()),apps:z.array(z.string())});var App2=z.looseObject({definition:z.looseObject({}),name:z.string(),disabled:z.boolean(),public:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),createdBy:z.string(),createdOn:zodHelpers.anyIsoDate(),lastModifiedBy:zodHelpers.extendedOptional(z.string()),lastModifiedOn:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())});z.looseObject({items:z.array(App2),total:z.number()}),z.looseObject({items:z.array(App2),total:z.number()});var AddOrUpdateAppRequest2=z.looseObject({definition:z.looseObject({}),name:z.string(),disabled:z.boolean(),public:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string()))});z.looseObject({apps:z.array(AddOrUpdateAppRequest2)}),z.looseObject({application:App2}),z.looseObject({definition:z.looseObject({}),name:z.string(),disabled:z.boolean(),public:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string()))}),z.looseObject({definition:z.looseObject({}),name:z.string(),disabled:z.boolean(),public:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string()))});var Layout2=z.looseObject({definition:z.string(),id:z.string(),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),public:z.boolean(),disabled:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),createdBy:z.string(),createdOn:zodHelpers.anyIsoDate(),lastModifiedBy:zodHelpers.extendedOptional(z.string()),lastModifiedOn:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),default:zodHelpers.extendedOptional(z.boolean())});z.looseObject({items:z.array(Layout2),total:z.number()}),z.looseObject({definition:z.string(),id:zodHelpers.extendedOptional(z.string()),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),public:z.boolean(),disabled:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),default:zodHelpers.extendedOptional(z.boolean())}),z.looseObject({layout:Layout2}),z.looseObject({definition:z.string(),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),public:z.boolean(),disabled:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),default:zodHelpers.extendedOptional(z.boolean())}),z.looseObject({definition:z.string(),id:zodHelpers.extendedOptional(z.string()),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),public:z.boolean(),disabled:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),default:zodHelpers.extendedOptional(z.boolean())});var Group=z.looseObject({name:z.string()});z.looseObject({items:z.array(Group),total:z.number()}),z.looseObject({canGetUserGroups:z.boolean(),canGetAllGroups:z.boolean(),canAddGroup:z.boolean(),canRemoveGroup:z.boolean(),canAddUserToGroup:z.boolean(),canRemoveUserFromGroup:z.boolean()}),z.looseObject({name:z.string()});var RefreshRequestLastDataInfoOthers=z.looseObject({groups:zodHelpers.extendedOptional(z.array(z.string()))}),RefreshRequestLastDataInfo=z.looseObject({checksum:zodHelpers.extendedOptional(z.string()),last:z.number(),other:zodHelpers.extendedOptional(RefreshRequestLastDataInfoOthers)}),RefreshRequestCategory=z.looseObject({include:z.boolean(),latestDataInfo:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),RefreshDataRequest=z.looseObject({applications:zodHelpers.extendedOptional(RefreshRequestCategory),layouts:zodHelpers.extendedOptional(RefreshRequestCategory),commands:zodHelpers.extendedOptional(RefreshRequestCategory),configs:zodHelpers.extendedOptional(RefreshRequestCategory)}),ApplicationRefreshResponseData=z.looseObject({data:zodHelpers.extendedOptional(z.array(z.looseObject({}))),hasChanges:z.boolean(),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),UserLayoutDefinition=z.looseObject({definition:z.string(),id:z.string(),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),default:zodHelpers.extendedOptional(z.boolean())}),LayoutRefreshResponseData=z.looseObject({hasChanges:z.boolean(),data:zodHelpers.extendedOptional(z.array(UserLayoutDefinition)),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),CommandStatus2=z.string().min(1),ResultType2=z.string().min(1),Command2=z.looseObject({status:CommandStatus2,resultType:zodHelpers.extendedOptional(ResultType2),traceContext:zodHelpers.extendedOptional(z.looseObject({})),id:z.string(),user:z.string(),session:z.string(),machine:z.string(),createdBy:z.string(),createdAt:z.number(),command:z.string(),commandParams:zodHelpers.extendedOptional(z.string()),resultData:zodHelpers.extendedOptional(z.looseObject({})),resultAt:zodHelpers.extendedOptional(z.number())}),CommandRefreshResponseData=z.looseObject({hasChanges:z.boolean(),data:zodHelpers.extendedOptional(z.array(Command2)),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),ConfigRefreshResponseData=z.looseObject({hasChanges:z.boolean(),data:zodHelpers.extendedOptional(z.array(z.looseObject({}))),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),RefreshDataResponse=z.looseObject({applications:zodHelpers.extendedOptional(ApplicationRefreshResponseData),layouts:zodHelpers.extendedOptional(LayoutRefreshResponseData),commands:zodHelpers.extendedOptional(CommandRefreshResponseData),config:zodHelpers.extendedOptional(ConfigRefreshResponseData)});z.looseObject({session:z.string(),user:z.string(),email:zodHelpers.extendedOptional(z.string()),exp:z.number(),iat:z.number()}),z.looseObject({version:z.string()});var ConnectBrowserPlatformInfo=z.looseObject({version:z.string()});z.looseObject({platform:ConnectBrowserPlatformInfo});var ConnectBrowserInfo=z.looseObject({platform:ConnectBrowserPlatformInfo}),ConnectInfo=z.looseObject({version:z.string(),core:zodHelpers.extendedOptional(ConnectBrowserInfo),build:z.string(),region:z.string(),env:z.string()}),OSInfo=z.looseObject({name:zodHelpers.extendedOptional(z.string()),version:zodHelpers.extendedOptional(z.string()),arch:zodHelpers.extendedOptional(z.string())}),Bounds=z.looseObject({x:zodHelpers.extendedOptional(z.number()),y:zodHelpers.extendedOptional(z.number()),width:zodHelpers.extendedOptional(z.number()),height:zodHelpers.extendedOptional(z.number())}),Display=z.looseObject({bounds:zodHelpers.extendedOptional(Bounds),workingArea:zodHelpers.extendedOptional(Bounds),dpi:zodHelpers.extendedOptional(z.number()),isPrimary:zodHelpers.extendedOptional(z.boolean()),aspectRatio:zodHelpers.extendedOptional(z.string()),scaleFactor:zodHelpers.extendedOptional(z.number())}),MachineInfo=z.looseObject({user:z.string(),name:zodHelpers.extendedOptional(z.string()),os:zodHelpers.extendedOptional(OSInfo),displays:zodHelpers.extendedOptional(z.array(Display))}),HelloRequest=z.looseObject({glue:ConnectInfo,machine:zodHelpers.extendedOptional(MachineInfo),initialDataRequest:zodHelpers.extendedOptional(RefreshDataRequest),includeServerInfo:zodHelpers.extendedOptional(z.boolean())}),ServerCapability2=z.string().min(1),ServerCapabilityWithMetadata2=z.looseObject({capability:ServerCapability2,introducedInVersion:z.string()}),LicenseType2=z.string().min(1),LicenseOrganization=z.looseObject({displayName:z.string(),identifier:z.string()}),LicensePayload=z.looseObject({type:LicenseType2,licensee:z.string(),expiration:z.number(),organization:LicenseOrganization,email:z.string(),issuedBy:z.string()}),LicenseInfo2=z.looseObject({licensePayload:LicensePayload,isExpired:z.boolean(),licenseSupported:z.boolean()}),ServerInfoResponse2=z.looseObject({capabilities:z.array(ServerCapabilityWithMetadata2),version:z.string(),licenseInfo:zodHelpers.extendedOptional(LicenseInfo2),base:zodHelpers.extendedOptional(z.string()),start:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),machine:zodHelpers.extendedOptional(z.string())}),HelloResponse=z.looseObject({token:z.string(),data:RefreshDataResponse,serverInfo:zodHelpers.extendedOptional(ServerInfoResponse2),sessionNotPersisted:zodHelpers.extendedOptional(z.boolean())}),GoodbyeRequest=z.looseObject({session:z.string()}),RefreshTokenRequest=z.looseObject({token:z.string()}),RefreshTokenResponse=z.looseObject({token:z.string()}),SaveUserLayoutRequest=z.looseObject({definition:z.string(),id:zodHelpers.extendedOptional(z.string()),type:z.string(),name:z.string(),default:zodHelpers.extendedOptional(z.boolean())}),RenameLayoutRequest=z.looseObject({newName:z.string()}),SetDefaultLayoutRequest=z.looseObject({id:zodHelpers.extendedOptional(z.string())}),AddCommandResultRequest=z.looseObject({result:z.looseObject({})}),AddCommandFileResultRequest=z.looseObject({fileName:z.string(),contents:z.string()});z.looseObject({result:zodHelpers.extendedOptional(z.looseObject({}))});var AppPreferences=z.looseObject({data:z.looseObject({}),id:z.string(),app:z.string(),user:z.string(),lastUpdate:zodHelpers.anyIsoDate()}),AddOrUpdatePrefsRequest=z.looseObject({data:z.looseObject({}),merge:z.boolean(),id:zodHelpers.extendedOptional(z.string()),app:zodHelpers.extendedOptional(z.string()),user:zodHelpers.extendedOptional(z.string())});z.looseObject({attachment:z.string(),description:z.string()});var Feedback=z.looseObject({id:z.string(),date:zodHelpers.anyIsoDate(),user:z.string(),session:z.string(),description:z.string(),attachment:z.string(),reviewed:z.boolean(),comment:zodHelpers.extendedOptional(z.string())}),HttpTestRequest=z.looseObject({}),HttpTestResponse=z.looseObject({requestBody:z.looseObject({}),statusCode:z.number(),customHeader:zodHelpers.extendedOptional(z.string())}),LayoutIdentifier=z.looseObject({id:zodHelpers.extendedOptional(z.string()),name:zodHelpers.extendedOptional(z.string()),type:zodHelpers.extendedOptional(z.string())}),User2=z.looseObject({layouts:zodHelpers.extendedOptional(z.array(LayoutIdentifier)),id:z.string(),email:zodHelpers.extendedOptional(z.string()),password:zodHelpers.extendedOptional(z.string()),apps:z.array(z.string()),groups:z.array(z.string()),lastUpdated:zodHelpers.extendedOptional(z.number()),firstName:zodHelpers.extendedOptional(z.string()),lastName:zodHelpers.extendedOptional(z.string())});z.looseObject({items:z.array(User2),total:z.number()}),z.looseObject({items:z.array(User2),total:z.number()});var AddUserRequest=z.looseObject({layouts:zodHelpers.extendedOptional(z.array(LayoutIdentifier)),id:z.string(),email:zodHelpers.extendedOptional(z.string()),password:zodHelpers.extendedOptional(z.string()),apps:z.array(z.string()),groups:z.array(z.string()),lastUpdated:zodHelpers.extendedOptional(z.number()),firstName:zodHelpers.extendedOptional(z.string()),lastName:zodHelpers.extendedOptional(z.string())});z.looseObject({users:z.array(AddUserRequest)}),z.looseObject({user:User2}),z.looseObject({layouts:zodHelpers.extendedOptional(z.array(LayoutIdentifier)),apps:zodHelpers.extendedOptional(z.array(z.string()))});var UserAppStatusExplain2=z.string().min(1),UserAppStatus=z.looseObject({explain:UserAppStatusExplain2,app:App2,available:z.boolean(),explainMore:zodHelpers.extendedOptional(z.string())});z.looseObject({apps:z.array(UserAppStatus)}),z.looseObject({app:z.string()}),z.looseObject({layouts:z.array(Layout2)}),z.looseObject({id:LayoutIdentifier}),z.looseObject({user:z.string(),groups:z.array(z.string())}),z.looseObject({groups:z.array(z.string())});var Machine=z.looseObject({id:z.string(),user:z.string(),name:zodHelpers.extendedOptional(z.string()),os:zodHelpers.extendedOptional(OSInfo),displays:zodHelpers.extendedOptional(z.array(Display))});z.looseObject({items:z.array(Command2),total:z.number()}),z.looseObject({command:Command2}),z.looseObject({resultType:zodHelpers.extendedOptional(ResultType2),traceContext:zodHelpers.extendedOptional(z.looseObject({})),session:z.string(),command:z.string(),commandParams:zodHelpers.extendedOptional(z.string())}),z.looseObject({id:z.string()});var CommandType2=z.string().min(1);z.looseObject({type:CommandType2,paramsExample:zodHelpers.extendedOptional(z.string()),description:z.string()}),z.looseObject({version:z.string(),core:zodHelpers.extendedOptional(ConnectBrowserInfo),build:z.string(),region:z.string(),env:z.string()});var UserSession2=z.looseObject({id:z.string(),user:z.string(),start:zodHelpers.anyIsoDate(),end:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),glue:ConnectInfo,machine:z.string(),lastDataFetch:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),closed:zodHelpers.extendedOptional(z.boolean()),closeReason:zodHelpers.extendedOptional(z.string())});z.looseObject({items:z.array(UserSession2),total:z.number()});var CleanSessionsAction2=z.string().min(1);z.looseObject({action:CleanSessionsAction2,all:zodHelpers.extendedOptional(z.boolean()),lastFetchThresholdInMinutes:zodHelpers.extendedOptional(z.number()),createdBefore:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())}),z.looseObject({itemsCount:z.number()}),z.looseObject({items:z.array(Machine),total:z.number()});var ClientCrashInfo=z.looseObject({_companyName:z.string(),_productName:z.string(),_version:z.string(),build:z.string(),env:z.string(),guid:z.string(),machine:z.string(),osArch:z.string(),osPlatform:z.string(),osUser:z.string(),osVersion:z.string(),osarch:z.string(),pid:z.string(),plat:z.string(),platform:z.string(),process_type:z.string(),prod:z.string(),ptype:z.string(),region:z.string(),session:z.string(),user:z.string(),ver:z.string(),version:z.string(),filename:z.string(),isStoredCompressed:z.boolean()}),ClientCrash=z.looseObject({id:z.string(),date:zodHelpers.anyIsoDate(),user:zodHelpers.extendedOptional(z.string()),info:ClientCrashInfo,reviewed:z.boolean(),comment:zodHelpers.extendedOptional(z.string())});z.looseObject({items:z.array(ClientCrash),total:z.number()}),z.looseObject({upload_file_minidump:z.string(),_companyName:z.string(),_productName:z.string(),_version:z.string(),build:z.string(),env:z.string(),guid:z.string(),machine:z.string(),osArch:z.string(),osPlatform:z.string(),osUser:z.string(),osVersion:z.string(),osarch:z.string(),pid:z.string(),plat:z.string(),platform:z.string(),process_type:z.string(),prod:z.string(),ptype:z.string(),region:z.string(),session:z.string(),user:z.string(),ver:z.string(),version:z.string(),filename:z.string()}),z.looseObject({comment:zodHelpers.extendedOptional(z.string()),reviewed:z.boolean()}),z.looseObject({version:z.string(),started:z.string(),name:z.string(),machine:z.string()});var AppsDataSummary=z.looseObject({total:z.number()}),LayoutsDataSummary=z.looseObject({total:z.number(),common:z.number(),private:z.number()}),CrashesDataSummary=z.looseObject({total:z.number(),notReviewed:z.number()}),FeedbacksDataSummary=z.looseObject({total:z.number(),notReviewed:z.number()}),CommandsDataSummary=z.looseObject({total:z.number()}),UsersDataSummary=z.looseObject({total:z.number()}),SessionsDataSummary=z.looseObject({active:z.number()}),PrefsDataSummary=z.looseObject({total:z.number()});z.looseObject({apps:AppsDataSummary,layouts:LayoutsDataSummary,crashes:CrashesDataSummary,feedbacks:FeedbacksDataSummary,commands:CommandsDataSummary,users:UsersDataSummary,sessions:SessionsDataSummary,prefs:PrefsDataSummary}),z.looseObject({items:z.array(Feedback),total:z.number()}),z.looseObject({comment:zodHelpers.extendedOptional(z.string()),reviewed:z.boolean()}),z.looseObject({items:z.array(AppPreferences),total:z.number()});var AuditLogEntityType2=z.string().min(1),AuditLogOperation2=z.string().min(1),AuditLogRequest=z.looseObject({body:z.looseObject({}),action:z.string(),path:z.string(),params:z.string(),query:z.string()}),AuditLogResponse=z.looseObject({status:z.string(),body:z.looseObject({})}),AuditLog=z.looseObject({entityType:AuditLogEntityType2,operation:AuditLogOperation2,newValue:zodHelpers.extendedOptional(z.looseObject({})),oldValue:zodHelpers.extendedOptional(z.looseObject({})),id:z.string(),user:zodHelpers.extendedOptional(z.string()),parent:zodHelpers.extendedOptional(z.string()),date:zodHelpers.anyIsoDate(),session:zodHelpers.extendedOptional(z.string()),server:z.string(),entityId:zodHelpers.extendedOptional(z.string()),entityDisplayName:zodHelpers.extendedOptional(z.string()),operationComment:zodHelpers.extendedOptional(z.string()),request:zodHelpers.extendedOptional(AuditLogRequest),response:zodHelpers.extendedOptional(AuditLogResponse)});z.looseObject({items:z.array(AuditLog),total:z.number()}),z.looseObject({all:zodHelpers.extendedOptional(z.boolean()),createdBefore:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())}),z.looseObject({version:z.string(),group:z.string(),user:z.string()});var ConfigEntry=z.looseObject({contents:z.looseObject({}),meta:zodHelpers.extendedOptional(z.looseObject({})),merge:zodHelpers.extendedOptional(z.boolean())});z.looseObject({"system.json":zodHelpers.extendedOptional(ConfigEntry),"themes.json":zodHelpers.extendedOptional(ConfigEntry),"stickywindows.json":zodHelpers.extendedOptional(ConfigEntry),"channels.json":zodHelpers.extendedOptional(ConfigEntry),"logger.json":zodHelpers.extendedOptional(ConfigEntry)});var ConnectSystemConfigIdentifier=z.looseObject({version:z.string(),group:z.string(),user:z.string()}),ConnectConfigs=z.looseObject({"system.json":zodHelpers.extendedOptional(ConfigEntry),"themes.json":zodHelpers.extendedOptional(ConfigEntry),"stickywindows.json":zodHelpers.extendedOptional(ConfigEntry),"channels.json":zodHelpers.extendedOptional(ConfigEntry),"logger.json":zodHelpers.extendedOptional(ConfigEntry)}),ConnectSystemConfigEntry=z.looseObject({identifier:ConnectSystemConfigIdentifier,configs:ConnectConfigs,weight:zodHelpers.extendedOptional(z.number())});z.looseObject({items:z.array(ConnectSystemConfigEntry),total:z.number()}),z.looseObject({identifiers:z.array(ConnectSystemConfigIdentifier),configs:ConnectConfigs}),z.looseObject({identifier:ConnectSystemConfigIdentifier,exact:z.boolean()}),z.looseObject({identifier:ConnectSystemConfigIdentifier,configs:ConnectConfigs,weight:zodHelpers.extendedOptional(z.number())});var ConnectConfigKey2=z.string().min(1);z.looseObject({config:ConnectConfigKey2,identifier:ConnectSystemConfigIdentifier}),z.looseObject({type:z.string().min(1),data:z.array(z.looseObject({}))}),z.looseObject({isValid:z.boolean(),errors:z.array(z.looseObject({}))});var TextFilterType2=z.string().min(1),TextFilterCondition=z.looseObject({filterType:z.string().min(1),type:TextFilterType2,filter:z.string(),in:zodHelpers.extendedOptional(z.array(z.string()))}),NumberFilterType2=z.string().min(1),NumberFilterCondition=z.looseObject({filterType:z.string().min(1),type:NumberFilterType2,filter:zodHelpers.extendedOptional(z.number()),filterTo:zodHelpers.extendedOptional(z.number())}),DateFilterType2=z.string().min(1),DateFilterCondition=z.looseObject({filterType:z.string().min(1),type:DateFilterType2,dateFrom:zodHelpers.extendedOptional(z.string()),dateTo:zodHelpers.extendedOptional(z.string())}),BooleanFilterType2=z.string().min(1),BooleanFilterCondition=z.looseObject({filterType:z.string().min(1),type:BooleanFilterType2,filter:z.boolean()}),LogicalConditionOperator2=z.string().min(1);z.looseObject({condition1:zodHelpers.extendedOptional(z.union([TextFilterCondition,NumberFilterCondition,DateFilterCondition,BooleanFilterCondition,z.looseObject({})])),condition2:zodHelpers.extendedOptional(z.union([TextFilterCondition,NumberFilterCondition,DateFilterCondition,BooleanFilterCondition,z.looseObject({})])),operator:zodHelpers.extendedOptional(LogicalConditionOperator2)});var SortOrderEnum2=z.string().min(1),SortOrder=z.looseObject({sort:SortOrderEnum2,colId:z.string()}),DataRequestOffset=z.looseObject({start:z.number(),count:z.number()});z.looseObject({filter:zodHelpers.extendedOptional(z.looseObject({})),ORFilters:zodHelpers.extendedOptional(z.array(z.looseObject({}))),groupKeys:zodHelpers.extendedOptional(z.array(z.string())),rowGroupCols:zodHelpers.extendedOptional(z.array(z.string())),sort:zodHelpers.extendedOptional(z.array(SortOrder)),offset:zodHelpers.extendedOptional(DataRequestOffset),excludeFields:zodHelpers.extendedOptional(z.array(z.string()))});var ZodSchemas={RefreshDataRequest:RefreshDataRequest,UserLayoutDefinition:UserLayoutDefinition,Command:Command2,RefreshDataResponse:RefreshDataResponse,HelloRequest:HelloRequest,HelloResponse:HelloResponse,GoodbyeRequest:GoodbyeRequest,RefreshTokenRequest:RefreshTokenRequest,RefreshTokenResponse:RefreshTokenResponse,SaveUserLayoutRequest:SaveUserLayoutRequest,RenameLayoutRequest:RenameLayoutRequest,SetDefaultLayoutRequest:SetDefaultLayoutRequest,AddCommandResultRequest:AddCommandResultRequest,AddCommandFileResultRequest:AddCommandFileResultRequest,AppPreferences:AppPreferences,AddOrUpdatePrefsRequest:AddOrUpdatePrefsRequest,Feedback:Feedback,HttpTestRequest:HttpTestRequest,HttpTestResponse:HttpTestResponse},RequestValidator=class{constructor(e){this.options=e}async validateRequestBody(e){if(this.options.disableRequestBodyValidation)return;const{requestBody:t,schema:r,operationName:n,endpointName:i}=e(),o=await r.safeParseAsync(t,{reportInput:!0});if(!o.success)throw new IOManagerRequestValidationError(`Request body schema validation failed for endpoint "${i}" (${n})`,{cause:o.error,schema:r})}async validateResponseBody(e){if(this.options.disableResponseBodyValidation)return;const{responseBody:t,schema:r,operationName:n,endpointName:i}=e(),o=await r.safeParseAsync(t,{reportInput:!0});if(!o.success)throw new IOManagerRequestValidationError(`Response body schema validation failed for endpoint "${i}" (${n})`,{cause:o.error,schema:r})}},IOManagerRequestValidationError=class extends Error{#c;constructor(e,t){super(e,t),this.name="IOManagerRequestValidationError",this.#c=t}getZodError(){return this.#c.cause}getSchema(){return this.#c.schema}},ClientAPI=class extends BaseAPI{sessionTokenString;sessionToken;requestLogger;requestValidator;constructor(e){super(e),this.setOptions(e)}setOptions(e){super.setOptions(e),this.sessionTokenString&&this.updateToken(this.sessionTokenString),e.logger&&(this.requestLogger=new RequestLogger(e.logger,e.requestLoggerLevel??"trace",e.disableLogSanitization??!1,e.logHTTPHeaders??!1)),this.requestValidator=new RequestValidator({disableLogSanitization:e.disableLogSanitization??!1,disableRequestBodyValidation:e.disableRequestBodyValidation??!1,disableResponseBodyValidation:e.disableResponseBodyValidation??!1})}unload(){this.sessionToken&&this.sessionTokenString&&this.unloadClient(this.sessionToken.session,this.sessionTokenString)}async refreshData(e,t){const r="POST",n="/user",i=`${r} ${n}`,o="refreshData";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.RefreshDataRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixRefreshDataResponse(s?.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.RefreshDataResponse,operationName:o,endpointName:i})),s.body}async getApps(e){const t="/user/apps",r=`GET ${t}`,n="getApps";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:z.array(z.looseObject({})),operationName:n,endpointName:r})),i.body}async getLayouts(e){const t="/user/layouts",r=`GET ${t}`,n="getLayouts";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),this.fixLayouts(i.body),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:z.array(ZodSchemas.UserLayoutDefinition),operationName:n,endpointName:r})),i.body}async saveLayout(e,t){const r="POST",n="/user/layouts",i=`${r} ${n}`,o="saveLayout";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.SaveUserLayoutRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixLayout(s.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.UserLayoutDefinition,operationName:o,endpointName:i})),s.body}async deleteUserLayout(e,t){const r="DELETE",n=`${r} /user/layouts/:id`,i="deleteUserLayout";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{id:e}}));const o=await this.sendRequest({method:r,url:`/user/layouts/${customEncodeURIComponent(e)}`,...t});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async deleteAllUserLayouts(e){const t="DELETE",r="/user/layouts/",n=`${t} ${r}`,i="deleteAllUserLayouts";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i}));const o=await this.sendRequest({method:t,url:r,...e});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o})),this.fixLayouts(o.body),await this.requestValidator.validateResponseBody(()=>({responseBody:o.body,schema:z.array(ZodSchemas.UserLayoutDefinition),operationName:i,endpointName:n})),o.body}async renameLayout(e,t,r){const n="POST",i=`${n} /user/layouts/:id/rename`,o="renameLayout",s={newName:t};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,pathParameters:{id:e},requestBody:s})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.RenameLayoutRequest,operationName:o,endpointName:i}));const a=await this.sendRequest({method:n,url:`/user/layouts/${customEncodeURIComponent(e)}/rename`,body:s,...r});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:a})),this.fixLayout(a.body),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:ZodSchemas.UserLayoutDefinition,operationName:o,endpointName:i})),a.body}async getDefaultLayout(e){const t="/user/layouts/default",r=`GET ${t}`,n="getDefaultLayout";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});if(this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),204!==i.statusCode)return await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:ZodSchemas.UserLayoutDefinition,operationName:n,endpointName:r})),this.fixLayout(i.body),i.body}async setDefaultLayout(e,t){const r="POST",n="/user/layouts/default",i=`${r} ${n}`,o="setDefaultLayout",s={id:e};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:s})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.SetDefaultLayoutRequest,operationName:o,endpointName:i}));const a=await this.sendRequest({method:r,url:n,body:s,...t});if(this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:a})),204!==a.statusCode)return this.fixLayout(a.body),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:zodHelpers.extendedOptional(ZodSchemas.UserLayoutDefinition),operationName:o,endpointName:i})),a.body}async openSession(e,t,r,n){const i="POST",o="/user/hello",s=`${i} ${o}`,a="openSession",c={machine:e,glue:t,...r??{}},l={"serverx-token":""};this.requestLogger?.logRequest(()=>({endpointName:s,operationName:a,requestBody:c,headers:l})),await this.requestValidator.validateRequestBody(()=>({requestBody:c,schema:ZodSchemas.HelloRequest,operationName:a,endpointName:s}));const u=await this.sendRequest({method:i,url:o,body:c,headers:l,...n});this.requestLogger?.logResponse(()=>({endpointName:s,operationName:a,response:u,sanitizeResponseBodyProperties:["token"]})),this.fixRefreshDataResponse(u?.body?.data),await this.requestValidator.validateResponseBody(()=>({responseBody:u.body,schema:ZodSchemas.HelloResponse,operationName:a,endpointName:s}));const d=this.updateToken(u.body.token);return u.body.serverInfo&&this.initializeServerInfo(u.body.serverInfo),{...u.body,token:d}}async closeSession(e,t){if(!(e=e??this.sessionToken.session))throw new Error("no active session");const r="POST",n="/user/goodbye",i=`${r} ${n}`,o="closeSession",s={session:e},a={"serverx-token":""};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:s,headers:a})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.GoodbyeRequest,operationName:o,endpointName:i}));const c=await this.sendRequest({method:r,url:n,body:s,headers:a,...t});this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:c}))}async refreshToken(e){const t="POST",r="/user/refresh",n=`${t} ${r}`,i="refreshToken",o={token:this.sessionTokenString};this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,requestBody:o,sanitizeRequestBodyProperties:["token"]})),await this.requestValidator.validateRequestBody(()=>({requestBody:o,schema:ZodSchemas.RefreshTokenRequest,operationName:i,endpointName:n}));const s=await this.sendRequest({method:t,url:r,body:o,...e});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:s,sanitizeResponseBodyProperties:["token"]})),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.RefreshTokenResponse,operationName:i,endpointName:n})),this.updateToken(s.body.token)}async getCommands(e){const t="GET /user/commands/:session",r="getCommands";this.requestLogger?.logRequest(()=>({endpointName:t,operationName:r,pathParameters:{session:this.sessionToken.session}}));const n=await this.sendRequest({method:"GET",url:`/user/commands/${customEncodeURIComponent(this.sessionToken.session)}`,...e});return this.requestLogger?.logResponse(()=>({endpointName:t,operationName:r,response:n})),await this.requestValidator.validateResponseBody(()=>({responseBody:n.body,schema:z.array(ZodSchemas.Command),operationName:r,endpointName:t})),n.body}async setCommandResult(e,t,r){const n="POST",i=`${n} /user/commands/:commandId`,o="setCommandResult";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,pathParameters:{commandId:e},requestBody:t})),await this.requestValidator.validateRequestBody(()=>({requestBody:t,schema:ZodSchemas.AddCommandResultRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:n,url:`/user/commands/${customEncodeURIComponent(e)}`,body:t,...r});this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s}))}async setCommandFileResult(e,t,r,n){const i="POST",o=`${i} /user/commands/:commandId/file`,s="setCommandFileResult",a={fileName:t,contents:r};this.requestLogger?.logRequest(()=>({endpointName:o,operationName:s,pathParameters:{commandId:e},requestBody:a,sanitizeRequestBodyProperties:["contents"]})),await this.requestValidator.validateRequestBody(()=>({requestBody:a,schema:ZodSchemas.AddCommandFileResultRequest,operationName:s,endpointName:o}));const c=await this.sendRequest({method:i,url:`/user/commands/${customEncodeURIComponent(e)}/file`,body:a,...n});this.requestLogger?.logResponse(()=>({endpointName:o,operationName:s,response:c}))}async getPrefs(e,t,r){const n="GET /user/prefs/:app",i="getPrefs";let o=`/user/prefs/${customEncodeURIComponent(e)}`;const s=new URLSearchParams;t&&s.set("last",t.getTime().toString()),o+=`?${s.toString()}`,this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{app:e},queryParameters:Object.fromEntries(s.entries())}));const a=await this.sendRequest({method:"GET",url:o,validateStatusCode:e=>e<400||404===e,...r});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:a})),404===a.statusCode&&(a.body=void 0),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:zodHelpers.extendedOptional(ZodSchemas.AppPreferences),operationName:i,endpointName:n})),a.body}async getAllPrefs(e){const t="/user/prefs/",r=`GET ${t}`,n="getAllPrefs";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:ZodSchemas.AppPreferences.array(),operationName:n,endpointName:r})),i.body}async setPrefs(e,t){const r="POST",n="/user/prefs/",i=`${r} ${n}`,o="setPrefs";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.AddOrUpdatePrefsRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixSetPrefsResponse(s?.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.AppPreferences,operationName:o,endpointName:i})),s.body}async deletePrefs(e,t){const r="DELETE",n=`${r} /user/prefs/:app`,i="deletePrefs";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{app:e}}));const o=await this.sendRequest({method:r,url:`/user/prefs/${customEncodeURIComponent(e)}`,...t});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async deleteAllPrefs(e){const t="DELETE",r="/user/prefs/",n=`${t} ${r}`,i="deleteAllPrefs";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i}));const o=await this.sendRequest({method:t,url:r,...e});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async addFeedback(e,t,r){const n="POST",i="/user/feedbacks",o=`${n} ${i}`,s="addFeedback",a=new FormData$1;a.append("description",e),a.append("attachment",t),this.requestLogger?.logRequest(()=>({endpointName:o,operationName:s}));const c=await this.sendRequest({method:n,url:i,body:a,json:!1,...r});return this.requestLogger?.logResponse(()=>({endpointName:o,operationName:s,response:c})),await this.requestValidator.validateResponseBody(()=>({responseBody:c.body,schema:ZodSchemas.Feedback,operationName:s,endpointName:o})),c.body}async httpTest(e,t,r,n){this.ensureCapability("HTTP_TEST");const i="POST",o="/user/http-test",s=`${i} ${o}`,a="httpTest",c=new URLSearchParams;c.append("statusCode",e?.toString());const l=`${o}?${c.toString()}`,u={};r&&(u["X-Custom-IOManager-Header"]=r),this.requestLogger?.logRequest(()=>({endpointName:s,operationName:a,requestBody:t,queryParams:Object.fromEntries(c.entries()),headers:u})),await this.requestValidator.validateRequestBody(()=>({requestBody:t,schema:zodHelpers.extendedOptional(ZodSchemas.HttpTestRequest),operationName:a,endpointName:s}));const d=await this.sendRequest({method:i,url:l,body:t,headers:u,validateStatusCode:()=>!0,...n});return this.requestLogger?.logResponse(()=>({endpointName:s,operationName:a,response:d})),await this.requestValidator.validateResponseBody(()=>({responseBody:d.body,schema:ZodSchemas.HttpTestResponse,operationName:a,endpointName:s})),d}fixRefreshDataResponse(e){"string"==typeof e?.config?.info?.last&&(e.config.info.last=Number(e.config.info.last)),"string"==typeof e?.commands?.info?.last&&(e.commands.info.last=Number(e.commands.info.last)),"string"==typeof e?.applications?.info?.last&&(e.applications.info.last=Number(e.applications.info.last)),"string"==typeof e?.layouts?.info?.last&&(e.layouts.info.last=Number(e.layouts.info.last)),this.fixLayouts(e?.layouts?.data)}fixSetPrefsResponse(e){"string"==typeof e?.data&&(e.data=JSON.parse(e.data))}fixLayouts(e){if(Array.isArray(e))for(const t of e)this.fixLayout(t)}fixLayout(e){if(!e)return;let t;function r(){if(!t)try{t=JSON.parse(e.definition)}catch{}}"string"!=typeof e.name&&(r(),e.name="string"==typeof t?.name?t.name:""),"string"!=typeof e.type&&(r(),e.type="string"==typeof t?.type?t.type:"")}updateToken(e){return this.sessionToken=jwtDecode(e),this.sessionTokenString=e,this.options.headers=this.options.headers??{},this.options.headers["serverx-token"]=e,this.sessionToken}async sendRequest(e){return this.options.req?this.callCustomRequestImplementation(e):this.callAxiosRequestImplementation(e)}async callAxiosRequestImplementation(e){const t=await this.axiosInstance.request({method:e.method,url:e.url,headers:e.headers,timeout:e.timeout,data:e.body,validateStatus:e.validateStatusCode??this.defaultIsStatusCodeValid});return{body:t.data,statusCode:t.status,headers:t.headers}}async callCustomRequestImplementation(e){if(!this.options.req)throw new Error("this.options.req is falsy.");const t={...e,method:e.method?.toLowerCase(),baseUrl:e.baseUrl??this.options.baseUrl,url:this.resolveFullUrl(e.url,e.baseUrl??this.options.baseUrl),json:e.json??!0,timeout:e.timeout??this.options.requestTimeout},r={...this.getBaseHeaders(this.options)??{},...await(this.options.getHeaders?.(t)),...e.headers??{}};t.headers=r,this.interceptCustomRequest?.(t),this.requestLogger?.logRequestHeaders(()=>t.headers);const n=new PromiseWrapper;return this.options.req(t,(r,i)=>{if(r)if(this.interceptCustomResponseError){const e=this.interceptCustomResponseError?.(t,r,void 0);n.reject(e)}else n.reject(r);else{if(i?.body){const e=this.options?.transformResponse;i.body=e?.(i.body,i.headers)??i.body}this.requestLogger?.logResponseHeaders(()=>i?.headers);const r=e.validateStatusCode??this.defaultIsStatusCodeValid;if(i?.statusCode&&!r(i.statusCode)){const e=new CustomRequestError(`Request failed with status code ${i.statusCode}`),r=Math.floor(i.statusCode/100);if(4===r?e.code="ERR_BAD_REQUEST":5===r&&(e.code="ERR_BAD_RESPONSE"),this.interceptCustomResponseError){const r=this.interceptCustomResponseError?.(t,e,i);n.reject(r)}else n.reject(e)}else this.interceptCustomResponse?.(t,i),n.resolve(i)}}),n.promise}resolveFullUrl(e,t){let r=e;r.startsWith("/")&&(r=r.substring(1));let n=t;return n.endsWith("/")||(n+="/"),new URL(r,n).href}interceptCustomRequest;interceptCustomResponse;interceptCustomResponseError},CustomRequestError=class extends Error{code;status},SanitizedIOManagerApiError=class e extends Error{code;status;isSessionExpired;isCustomTimeoutError;validationErrors;request;responseBodyError;static fromAxiosError(t){const r=Number(t?.response?.status),n=t?.response?.data;let i;if(t?.message)i=t?.message;else if("errors"in t&&t?.errors&&Array.isArray(t?.errors)){const e=t?.errors?.map(e=>e?.message).filter(e=>e);e.length&&(i=e.join(", "))}const o=new e(i);if(o.name="SanitizedIOManagerApiError",o.stack=t?.stack,t instanceof IOManagerRequestValidationError){const e=t;o.validationErrors=e.getZodError().issues}Number.isFinite(r)&&(o.status=r),t?.code&&(o.code=t?.code),o.request={baseUrl:t?.config?.baseURL,url:t?.config?.url,method:t?.config?.method};const s=400===r&&"invalid-glue42-server-token"===n?.error?.message;return s&&(o.isSessionExpired=s),o.responseBodyError=n?.error,o}static fromCustomRequestError(t,r,n){const i=Number(r?.statusCode),o=r?.body,s=new e(n?.message);if(s.name="SanitizedIOManagerApiError",s.stack=n?.stack,n instanceof IOManagerRequestValidationError){const e=n;s.validationErrors=e.getZodError().issues}let a;Number.isFinite(i)&&(s.status=i),n?.code?s.code=n?.code:n?.message?.includes("net::ERR_CONNECTION_REFUSED")&&(s.code="ECONNREFUSED"),t.baseUrl&&t.url.startsWith(t.baseUrl)?(a=t.url.slice(t.baseUrl.length),a.startsWith("/")||(a=`/${a}`)):a=t.url,s.request={baseUrl:t.baseUrl,url:a,method:t.method};const c=400===i&&"invalid-glue42-server-token"===o?.error?.message;return c&&(s.isSessionExpired=c),s.responseBodyError=o?.error,n.isCustomTimeoutError&&(s.isCustomTimeoutError=n.isCustomTimeoutError),s}},CachedClientAPI=class extends ClientAPI{get connectionState(){return{isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching,disconnectionError:this._disconnectionError}}get token(){return this.sessionToken?this.sessionToken:this.options.enableCaching?this._cachedToken:void 0}_callbacks=CallbackRegistryFactory$2();_isConnected=!1;_refreshTokenIntervalId;_refreshDataIntervalId;_slowestRequests=[];_statParams;_lastApplicationsInfo;_lastLayoutsInfo;_lastCommandsInfo;_lastConfigsInfo;_lastApplicationsData;_lastLayoutsData;_lastConfigsData;_cachedToken;_disconnectionError;_sessionNotPersisted;_cachedClientRequestInterceptor;_cachedClientResponseInterceptor;get logger(){return this.options.logger}get cache(){if(!this.options.enableCaching)throw new Error("Accessing the cache is not allowed when caching is disabled.");return this.options.managerCache}constructor(e){super(e),this.setOptions(e)}setOptions(e){e.refresh??={},e.refresh.applications??=!0,e.refresh.layouts??=!0,e.refresh.commands??=!0,e.refresh.configs??=!1,super.setOptions(e);const t=e=>{const t={startTime:this.getNowMs(),startTimeDate:new Date,operation:`${e.method} ${e.url}`};e.__perf=t},r=e=>{const t=e.__perf;t.endTime=this.getNowMs(),t.duration=t.endTime-t.startTime,this._slowestRequests.push(t),this._slowestRequests.sort((e,t)=>t.duration-e.duration),this._slowestRequests.length>5&&this._slowestRequests.pop()};this._cachedClientRequestInterceptor&&this.axiosInstance.interceptors?.request?.eject(this._cachedClientRequestInterceptor),this._cachedClientRequestInterceptor=this.axiosInstance.interceptors.request.use(e=>(t(e),e),e=>e?.config?.method?Promise.reject(SanitizedIOManagerApiError.fromAxiosError(e)):Promise.reject(e)),this.interceptCustomRequest=e=>{t(e)},this._cachedClientResponseInterceptor&&this.axiosInstance.interceptors?.response?.eject(this._cachedClientResponseInterceptor),this._cachedClientResponseInterceptor=this.axiosInstance.interceptors.response.use(e=>(r(e.config),e),e=>(r(e.config),e?.config?.method?Promise.reject(SanitizedIOManagerApiError.fromAxiosError(e)):Promise.reject(e))),this.interceptCustomResponse=e=>{r(e)},this.interceptCustomResponseError=(e,t,n)=>(r(e),SanitizedIOManagerApiError.fromCustomRequestError(e,n,t))}async start(...e){this._statParams=e;const t=this._statParams[2]??={};let r;t.initialDataRequest??=this.createRefreshDataRequest(!0),t.includeServerInfo=!0,this.logger.info(`Initiating connection to ${this.options.baseUrl}`);let n=!1;try{let e;if(this.logger.info("Opening a session..."),this.options.enableCaching){const i=await this.cache.get("session");if(i&&(this._cachedToken=i.value),r=await this.readDataCache(t.initialDataRequest),n=Boolean(i&&r),n){const t=[...this._statParams];t[3]??={},t[3].timeout=this.options.openSessionRequestTimeout,e=await super.openSession(...t)}else e=await this.retryStart(...this._statParams)}else e=await this.retryStart(...this._statParams);return this.logger.info(`Session opened. Initial data received: ${this.getSnapshotSummary(e.data).join(", ")}`),this._sessionNotPersisted=e.sessionNotPersisted,e.sessionNotPersisted&&this.logger.warn("Session was opened in read-only mode and was not persisted on the server."),this.writeToFields(e.data),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",e.token),await this.cache.set("sessionNotPersisted",e.sessionNotPersisted),await this.writeDataCache(e.data)),this.notifyConnected(),this.startTokenTimer(),this.startDataTimer(),e}catch(e){if(this.notifyDisconnected(e),!this.options.enableCaching)throw this.logger.error("Failed to open a session.",e),e;if(!n)throw this.logger.error("Failed to open a session. Cache miss.",e),e;this.logger.warn("Failed to open a session. Proceeding from cache.",e);const t=await this.cache.get("sessionNotPersisted");return t?.value&&this.logger.warn("Cached session was opened in read-only mode and was not persisted on the server."),this.writeToFields(r),this.startTokenTimer(),this.startDataTimer(),{token:this._cachedToken,data:r}}}async stop(){this.stopTokenTimer(),this.stopDataTimer(),this.logger.info("Slowest requests:");for(const e of this._slowestRequests)this.logger.info(`${e.startTimeDate.toISOString()} - operation: ${e.operation}, duration (ms): ${e.duration}`);this.logger.info("Closing session."),await super.closeSession(void 0,{timeout:this.options.closeSessionRequestTimeout})}onConnectedStateChanged(e){return this._callbacks.add("onConnectedStateChanged",e)}async onAppsChanged(e){const t=this._callbacks.add("onAppsChanged",e);try{this._lastApplicationsData&&(this.logger.debug("Calling onAppsChanged",this._lastApplicationsData),this._callbacks.execute("onAppsChanged",this._lastApplicationsData))}catch(e){throw t(),e}return t}async onLayoutsChanged(e){const t=this._callbacks.add("onLayoutsChanged",e);try{this._lastLayoutsData&&(this.logger.debug("Calling onLayoutsChanged",this._lastLayoutsData),this._callbacks.execute("onLayoutsChanged",this._lastLayoutsData))}catch(e){throw t(),e}return t}async onCommandsReceived(e){return this._callbacks.add("onCommandsReceived",e)}async onConfigsChanged(e){const t=this._callbacks.add("onConfigsChanged",e);try{this._lastConfigsData&&(this.logger.debug("Calling onConfigsChanged",this._lastConfigsData),this._callbacks.execute("onConfigsChanged",this._lastConfigsData))}catch(e){throw t(),e}return t}openSession(...e){throw new Error("Calling `openSession` directly is not supported. Call `start` instead.")}closeSession(...e){throw new Error("Calling `closeSession` directly is not supported. Call `stop` instead.")}async refreshData(...e){this.logger.isTraceEnabled()?this.logger.trace(`Requesting data changes: ${JSON.stringify(e[0])}`):this.logger.info(`Requesting data changes: ${JSON.stringify(this.sanitizeGroups(e[0]))}`);let t=!1;try{const r=await this.handleAuth(async r=>(t=Boolean(r),r?r.data:await super.refreshData(...e)));if(this.notifyConnected(),r&&!t){const e=this.getSnapshotSummary(r);e.length?this.logger.info(`Data received: ${e.join(", ")}`):this.logger.info("No new data was received."),this.writeToFields(r),this.options.enableCaching&&await this.writeDataCache(r)}return r}catch(t){if(this.notifyDisconnected(t),!this.options.enableCaching)throw this.logger.debug("Refresh data request failed.",t),t;const r=await this.readDataCache(e[0]);if(!r)throw this.logger.debug("Refresh data request failed. Cache miss.",t),t;return this.logger.warn("Refresh data request failed. Returning data from cache.",t),r}}async refreshToken(...e){this.logger.info("Refreshing session token.");try{const t=await this.handleAuth(()=>super.refreshToken(...e));return this.notifyConnected(),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",t)),t}catch(e){throw this.notifyDisconnected(e),this.logger.debug("Refresh token request failed.",e),e}}async getPrefs(...e){const t=e[0];try{const r=await this.handleAuth(()=>super.getPrefs(...e));return this.notifyConnected(),this.options.enableCaching&&await this.updateAllPreferencesCache(t,r),r}catch(e){if(this.notifyDisconnected(e),!this.options.enableCaching)throw this.logger.debug("getPrefs request failed.",e),e;const r=await this.cache.get("prefs_data");if(!r)throw this.logger.debug("getPrefs request failed. Cache miss.",e),e;this.logger.debug("getPrefs request failed. Returning data from cache.",e);const n=r.value.find(e=>e.app===t);return n&&"string"==typeof n?.data&&(n.data=JSON.parse(n.data)),n}}getAllPrefs(...e){return this.handleRead("getAllPrefs","prefs_data",()=>super.getAllPrefs(...e))}getDefaultLayout(...e){return this.handleRead("getDefaultLayout","read_getDefaultLayout",()=>super.getDefaultLayout(...e))}whoAmI(...e){return this.handleRead("whoAmI","read_whoAmI",()=>super.whoAmI(...e))}async getLayouts(...e){const t=await this.handleRead("getLayouts","layouts_data",()=>super.getLayouts(...e));return this._lastLayoutsData=t,this._callbacks.execute("onLayoutsChanged",t),t}getLastLayouts(){return this._lastLayoutsData}getLastApps(){return this._lastApplicationsData}async getApps(...e){const t=await this.handleRead("getApps","applications_data",()=>super.getApps(...e));return this._lastApplicationsData=t,this._callbacks.execute("onAppsChanged",t),t}async getCommands(...e){const t=await this.handleAuth(()=>super.getCommands(...e));return this._callbacks.execute("onCommandsReceived",t),t}setPrefs(...e){return this.handleWrite("setPrefs","write_setPrefs",()=>super.setPrefs(...e))}setCommandResult(...e){return this.handleWrite("setCommandResult","write_setCommandResult",()=>super.setCommandResult(...e))}addFeedback(...e){return this.handleWrite("addFeedback","write_addFeedback",()=>super.addFeedback(...e))}setDefaultLayout(...e){return this.handleWrite("setDefaultLayout","write_setDefaultLayout",()=>super.setDefaultLayout(...e))}deleteAllPrefs(...e){return this.handleWrite("deleteAllPrefs","write_deleteAllPrefs",()=>super.deleteAllPrefs(...e))}deleteAllUserLayouts(...e){return this.handleWrite("deleteAllUserLayouts","write_deleteAllUserLayouts",()=>super.deleteAllUserLayouts(...e))}setCommandFileResult(...e){return this.handleWrite("setCommandFileResult","write_setCommandFileResult",()=>super.setCommandFileResult(...e))}saveLayout(...e){return this.handleWrite("saveLayout","write_saveLayout",()=>super.saveLayout(...e))}renameLayout(...e){return this.handleWrite("renameLayout","write_renameLayout",()=>super.renameLayout(...e))}deletePrefs(...e){return this.handleWrite("deletePrefs","write_deletePrefs",()=>super.deletePrefs(...e))}deleteUserLayout(...e){return this.handleWrite("deleteUserLayout","write_deleteUserLayout",()=>super.deleteUserLayout(...e))}notifyDisconnected(e){if(this._isConnected){this._isConnected=!1,this._disconnectionError=e,this.logger.warn("io.Manager connection state changed: disconnected.",e);const t={isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching,disconnectionError:e};this._callbacks.execute("onConnectedStateChanged",t)}}notifyConnected(){if(!this._isConnected){this._isConnected=!0,this._disconnectionError=void 0,this.logger.info("io.Manager connection state changed: connected.");const e={isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching};this._callbacks.execute("onConnectedStateChanged",e)}}async refreshTokenTimeout(){try{this.options.asyncSequelizer?await this.options.asyncSequelizer.enqueue(async()=>{await this.refreshToken()}):await this.refreshToken()}catch(e){this.logger.warn("Refresh token request failed.",e)}finally{this.startTokenTimer()}}async refreshDataTimeout(){const e=this.createRefreshDataRequest();try{this.options.asyncSequelizer?await this.options.asyncSequelizer.enqueue(async()=>{await this.refreshData(e)}):await this.refreshData(e)}catch(e){this.logger.warn("Refresh data request failed.",e)}finally{this.startDataTimer()}}createRefreshDataRequest(e){return{applications:{include:Boolean(this.options.refresh?.applications),latestDataInfo:e?void 0:this._lastApplicationsInfo},layouts:{include:Boolean(this.options.refresh?.layouts),latestDataInfo:e?void 0:this._lastLayoutsInfo},commands:{include:Boolean(this.options.refresh?.commands),latestDataInfo:e?void 0:this._lastCommandsInfo},configs:{include:Boolean(this.options.refresh?.configs),latestDataInfo:e?void 0:this._lastConfigsInfo}}}startTokenTimer(){this.logger.info(`Starting the session token refresh timer for ${this.options.tokenRefreshInterval}s`),this._refreshTokenIntervalId=setTimeout(this.refreshTokenTimeout.bind(this),1e3*this.options.tokenRefreshInterval)}startDataTimer(){this.logger.info(`Starting data refresh timer for ${this.options.fetchInterval}s`),this._refreshDataIntervalId=setTimeout(this.refreshDataTimeout.bind(this),1e3*this.options.fetchInterval)}async recreateSession(e){if(this.logger.debug("Opening a session..."),e&&!this._sessionNotPersisted)try{this.logger.debug("Closing old session."),await super.closeSession(e,{timeout:this.options.closeSessionRequestTimeout}),this.logger.debug("Old session closed.")}catch(e){this.logger.debug("Failed to close old session.",e)}const t=await super.openSession(...this._statParams);return this.logger.info(`Session opened. Initial data received: ${this.getSnapshotSummary(t.data).join(", ")}`),this._sessionNotPersisted=t.sessionNotPersisted,t.sessionNotPersisted&&this.logger.warn("Session was opened in read-only mode and was not persisted on the server."),this.writeToFields(t.data),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",t.token),await this.cache.set("sessionNotPersisted",t.sessionNotPersisted),await this.writeDataCache(t.data)),t}stopTokenTimer(){this.logger.info("Stopping the session token refresh timer."),this._refreshTokenIntervalId&&clearTimeout(this._refreshTokenIntervalId)}stopDataTimer(){this.logger.info("Stopping the data refresh timer."),this._refreshDataIntervalId&&clearTimeout(this._refreshDataIntervalId)}writeToFields(e){e.applications?.hasChanges&&(this._lastApplicationsData=e.applications.data,this._lastApplicationsInfo=e.applications.info,this._callbacks.execute("onAppsChanged",e.applications.data)),e.layouts?.hasChanges&&(this._lastLayoutsData=e.layouts.data,this._lastLayoutsInfo=e.layouts.info,this._callbacks.execute("onLayoutsChanged",e.layouts.data)),e.config?.hasChanges&&(this._lastConfigsData=e.config.data,this._lastConfigsInfo=e.config.info,this._callbacks.execute("onConfigsChanged",e.config.data)),e.commands?.hasChanges&&(this._lastCommandsInfo=e.commands.info,this._callbacks.execute("onCommandsReceived",e.commands.data))}async writeDataCache(e){e.applications?.hasChanges&&(await this.cache.set("applications_data",e.applications.data),await this.cache.set("applications_info",e.applications.info)),e.layouts?.hasChanges&&(await this.cache.set("layouts_data",e.layouts.data),await this.cache.set("layouts_info",e.layouts.info)),e.config?.hasChanges&&(await this.cache.set("config_data",e.config.data),await this.cache.set("config_info",e.config.info)),e.commands?.hasChanges&&await this.cache.set("commands_info",e.commands.info)}async readDataCache(e){const t={};if(!0===e.applications?.include){const r=await this.cache.get("applications_info");if(!r)return void this.logger.debug('readDataCache: Could not find "applications_info" in cache.');if(this.lastDataInfoEquals(e.applications?.latestDataInfo,r.value))t.applications={hasChanges:!1};else{const e=await this.cache.get("applications_data");t.applications={hasChanges:!0,data:e?.value,info:r.value}}}if(!0===e.layouts?.include){const r=await this.cache.get("layouts_info");if(!r)return void this.logger.debug('readDataCache: Could not find "layouts_info" in cache.');if(this.lastDataInfoEquals(e.layouts?.latestDataInfo,r.value))t.layouts={hasChanges:!1};else{const e=await this.cache.get("layouts_data");t.layouts={hasChanges:!0,data:e?.value,info:r.value}}}if(!0===e.configs?.include){const r=await this.cache.get("config_info");if(!r)return void this.logger.debug('readDataCache: Could not find "config_info" in cache.');if(this.lastDataInfoEquals(e.configs?.latestDataInfo,r.value))t.config={hasChanges:!1};else{const e=await this.cache.get("config_data");t.config={hasChanges:!0,data:e?.value,info:r.value}}}return t}async updateAllPreferencesCache(e,t){const r=await this.cache.get("prefs_data");let n=r?.value||[];if(t){const r=n.findIndex(t=>t.app===e);-1!==r?n[r]=t:n.push(t)}else n=n.filter(t=>t.app!==e);await this.cache.set("prefs_data",n)}lastDataInfoEquals(e,t){return!(!e||!t)&&(e.checksum===t.checksum||Number(e.last)===Number(t.last))}async handleRead(e,t,r){this.logger.debug(`calling handleRead operationName=${e} cacheKey=${t}`);try{const e=await this.handleAuth(r);return this.notifyConnected(),this.options.enableCaching&&await this.cache.set(t,e),e}catch(r){if(this.notifyDisconnected(r),!this.options.enableCaching)throw this.logger.debug(`${e} request failed.`,r),r;const n=await this.cache.get(t);if(!n)throw this.logger.debug(`${e} request failed. Cache miss.`,r),r;if(this.logger.debug(`${e} request failed. Returning data from cache.`,r),"prefs_data"===t){const e=n.value;if(e)for(const t of e)"string"==typeof t.data&&(t.data=JSON.parse(t.data))}return n.value}}async handleWrite(e,t,r){this.logger.debug(`calling handleWrite operationName=${e} cacheKey=${t}`);try{const e=await this.handleAuth(r);return this.notifyConnected(),e}catch(t){const r=t;throw this.logger.debug(`${e} request failed.`,t),"ReadOnlyRequestViolationError"!==r.responseBodyError?.type&&this.notifyDisconnected(t),t}}async retryStart(...e){let t=0;for(;;)try{return t>0&&this.logger.info(`Opening a session [retry ${t} of ${this.options.startRetries}]`),await super.openSession(...e)}catch(e){if(t>=this.options.startRetries)throw e;this.logger.warn(`Failed to open a session. Retrying after ${this.options.startRetryInterval}s.`,e),t+=1,await new Promise(e=>setTimeout(e,1e3*this.options.startRetryInterval))}}getSnapshotSummary(e){const t=[];return e.applications?.hasChanges&&t.push(`applications (${e.applications.data?.length})`),e.layouts?.hasChanges&&t.push(`layouts (${e.layouts.data?.length})`),e.commands?.hasChanges&&t.push(`commands (${e.commands.data?.length})`),e.config?.hasChanges&&t.push(`remote configs (${e.config.data?.length})`),t}async handleAuth(e){let t;if(!this.sessionToken||!this.sessionTokenString||this._sessionNotPersisted){let e;if(this.sessionToken||this.logger.info("Session is not open (started from cache). Opening a session..."),this._sessionNotPersisted&&this.logger.info("Session is not persisted on the server (server was in read-only mode when it created it). Opening a new session..."),this.options.enableCaching){const t=await this.cache.get("session");e=t?.value?.session}try{t=await this.recreateSession(e)}catch(e){throw this.logger.warn("Failed to open a session.",e),e}}try{return await e(t)}catch(r){if(r?.isSessionExpired){try{this.logger.warn("Session expired. Opening a new session...",r),t=await this.recreateSession(this.sessionToken?.session)}catch(e){throw this.logger.warn("Failed to re-open the session.",e),r}return await e(t)}throw r}}getNowMs(){return this.options.getNowMs?this.options.getNowMs():Number(new Date)}sanitizeGroups(e){if(null==e)return e;if("object"!=typeof e)return e;const t=structuredClone(e);function r(e){return e?Array.isArray(e)?`__REMOVED(length=${e.length})`:"__REMOVED(NON_ARRAY_TRUTHY_VALUE)":"__REMOVED(falsy)"}return function e(t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))for(const r of t)e(r);else for(const n in t)t.hasOwnProperty(n)&&("groups"===n?t[n]=r(t[n]):e(t[n]))}(t),t}};const managerOperationDecoder=oneOf$1(constant$2("operationCheck")),DEFAULT_RESPONSE_TIMEOUT_MS=1e4,PREFS_CACHE_KEY="prefs_data",LAYOUTS_CACHE_KEY="layouts_data",DEFAULT_LAYOUT_CACHE_KEY="read_getDefaultLayout",PREFS_CHANGED_EVENT_KEY="onPrefsChanged",APPS_ADDED_EVENT_KEY="onAppsAdded",APPS_DELETED_EVENT_KEY="onAppsDeleted",APPS_CHANGED_EVENT_KEY="onAppsChanged",LAYOUTS_CHANGED_EVENT_KEY="onLayoutsChanged",LAYOUTS_ADDED_EVENT_KEY="onLayoutsAdded",LAYOUTS_REMOVED_EVENT_KEY="onLayoutsRemoved",LAYOUTS_RENAMED_EVENT_KEY="onLayoutsRenamed",CONNECTED_STATE_CHANGED_EVENT_KEY="onConnectedStateChanged",defaultDataRefreshIntervalMS=6e4,defaultTokenRefreshIntervalMS=36e5;class ManagerController{identity;sequelizer;buildClient;buildCache;started=!1;name="io.Manager Client";globalConfig;config;unloadCallback;callbacks=CallbackRegistryFactory$2();lastApps=[];lastLayouts=[];lastLayoutIdsByKey=new Map;client;managerCache;get managerConnectionState(){const e={serverEnabled:!1,isConnected:!1};return this.config?this.client.connectionState:e}operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n){this.identity=e,this.sequelizer=t,this.buildClient=r,this.buildCache=n,this.unloadCallback=this.handleUnload.bind(this),window.addEventListener("pagehide",this.unloadCallback)}get logger(){return logger.get("manager.controller")}get isStarted(){return this.started}get isCritical(){return this.config?.critical??!0}ready(){return Promise.resolve()}handlePlatformShutdown(){this.started=!1,window.removeEventListener("pagehide",this.unloadCallback),this.handleUnload(),this.managerCache?.dispose()}async configurePostStart(){if(!this.config)return;const e=this.globalConfig?.user?.id||"__no_user__";this.managerCache=this.buildCache(this.config,e),await this.managerCache.initialize();const t={baseUrl:this.config.url,auth:this.config.auth,headers:this.config.headers,getHeaders:this.config.getHeaders,fetchInterval:(this.config.fetchIntervalMS||defaultDataRefreshIntervalMS)/1e3,tokenRefreshInterval:(this.config.tokenRefreshIntervalMS||defaultTokenRefreshIntervalMS)/1e3,startRetries:0,startRetryInterval:1e4,refresh:{applications:Boolean(this.config.features?.applicationsStore??!0),layouts:Boolean(this.config.features?.layoutsStore??!0),commands:!1,configs:!1},requestTimeout:this.config.requests?.timeout??this.config.responseTimeoutMS??DEFAULT_RESPONSE_TIMEOUT_MS,openSessionRequestTimeout:this.config.requests?.openSessionTimeout??DEFAULT_RESPONSE_TIMEOUT_MS,closeSessionRequestTimeout:this.config.requests?.closeSessionTimeout??DEFAULT_RESPONSE_TIMEOUT_MS,enableCaching:!0,managerCache:this.managerCache,asyncSequelizer:this.sequelizer,logger:this.createManagerLogger()};this.client=this.buildClient(t),this.logger?.trace("The client API is ready.");const r=await this.identity.getMachineInfo(e),n=this.identity.getGlueInfo();this.logger?.trace(`Opening a session for machine: ${JSON.stringify(r)} and glue: ${JSON.stringify(n)}`),this.client.onConnectedStateChanged(this.handleOnConnectedStateChanged.bind(this)),await this.client.onAppsChanged(this.handleOnAppsChanged.bind(this)),await this.client.onLayoutsChanged(this.handleOnLayoutsChanged.bind(this)),await this.client.start(r,n),this.config.features?.preferencesStore&&await this.client.getAllPrefs(),this.started=!0,this.logger?.info(`Module ${this.name} started`)}async start(e){e.manager&&(this.globalConfig=e,this.config=e.manager,this.logger?.info("Starting the Manager controller."))}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this manager control message, because the controller has not been started");const t=e.data,r=e.commandId,n=managerOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This manager request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Manager request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Manager request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}onConnectedStateChanged(e){return this.callbacks.add(CONNECTED_STATE_CHANGED_EVENT_KEY,e)}async saveLayouts(e,t,r){return this.sequelizer.enqueue(async()=>{let n;if(r&&this.logger?.trace(`[${r}] handling "saveLayouts" request | mode=${t}`),n="replace"===t?await this.client.deleteAllUserLayouts():await this.getAllCachedLayouts(),e.length){const t=new Map;for(const e of n)t.set(this.getLayoutKey(e),e);for(const r of e){const e={type:r.type,name:r.name,definition:JSON.stringify(r)},n=await this.client.saveLayout(e);t.set(this.getLayoutKey(r),n)}n=Array.from(t.values()),await this.managerCache.set(LAYOUTS_CACHE_KEY,n)}this.handleOnLayoutsChanged(n),r&&this.logger?.trace(`[${r}] request completed, layouts saved`)})}async renameLayout(e,t,r,n){return this.sequelizer.enqueue(async()=>{n&&this.logger?.trace(`[${n}] handling "renameLayout" request | oldName=${e}, newName=${t}, type=${r}`);const i=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:r}));if(!i)throw new Error(`Layout with name="${e}" and type="${r}" not found.`);const o=await this.client.renameLayout(i,t),s={id:o.id,name:o.name,type:o.type,definition:o.definition};let a=await this.getAllCachedLayouts();a=a.filter(e=>e.id!==i),a.push(s),await this.managerCache.set(LAYOUTS_CACHE_KEY,a),this.setLastLayouts(a,this.parseLayouts(a));const c=this.parseLayouts([s]).map(t=>({...t,prevName:e}));this.callbacks.execute(LAYOUTS_RENAMED_EVENT_KEY,c),n&&this.logger?.trace(`[${n}] request completed, layout renamed`)})}async deleteLayout(e,t,r){return this.sequelizer.enqueue(async()=>{r&&this.logger?.trace(`[${r}] handling "deleteLayout" request | layoutName=${e}, type=${t}`);const n=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:t}));if(!n)throw new Error(`Layout with name="${e}" and type="${t}" not found.`);await this.client.deleteUserLayout(n);let i=await this.getAllCachedLayouts();i=i.filter(e=>e.id!==n),await this.managerCache.set(LAYOUTS_CACHE_KEY,i),this.handleOnLayoutsChanged(i),r&&this.logger?.trace(`[${r}] request completed, layout deleted`)})}async getAllLayouts(e,t){t&&this.logger?.trace(`[${t}] handling "getAllLayouts" request | type=${e}`);const r=this.lastLayouts.filter(t=>t.type===e);return t&&this.logger?.trace(`[${t}] request completed, layouts retrieved`),r}async getLayout(e,t,r){r&&this.logger?.trace(`[${r}] handling "getLayout" request | layoutName=${e}, type=${t}`);const n=this.lastLayouts.find(r=>r.name===e&&r.type===t);return r&&this.logger?.trace(`[${r}] request completed, layout retrieved`),n}onLayoutsChanged(e){return this.callbacks.add(LAYOUTS_CHANGED_EVENT_KEY,e)}onLayoutsAdded(e){return this.callbacks.add(LAYOUTS_ADDED_EVENT_KEY,e)}onLayoutsRemoved(e){return this.callbacks.add(LAYOUTS_REMOVED_EVENT_KEY,e)}onLayoutsRenamed(e){return this.callbacks.add(LAYOUTS_RENAMED_EVENT_KEY,e)}async clearDefaultLayout(e){return this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "clearDefaultLayout" request`);const t=await this.client.setDefaultLayout();await this.managerCache.set(DEFAULT_LAYOUT_CACHE_KEY,t),e&&this.logger?.trace(`[${e}] request completed, default layout cleared`)})}async getDefaultLayout(e){return this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "getDefaultLayout" request`);const t=await this.client.getDefaultLayout();if(!t)return;const r="string"==typeof t.definition?JSON.parse(t.definition):t.definition,n=glueLayoutDecoder.run(r);if(!n.ok)throw n.error;return e&&this.logger?.trace(`[${e}] request completed, default layout retrieved`),r})}async setDefaultLayout(e,t){return this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "setDefaultLayout" request`);const r=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:"Global"}));if(!r)throw new Error(`Layout with name="${e}" and type="Global" not found.`);const n=await this.client.setDefaultLayout(r);await this.managerCache.set(DEFAULT_LAYOUT_CACHE_KEY,n),t&&this.logger?.trace(`[${t}] request completed, default layout set`)})}getAllApps(){return this.lastApps}onAppsAdded(e){return this.callbacks.add(APPS_ADDED_EVENT_KEY,e)}onAppsDeleted(e){return this.callbacks.add(APPS_DELETED_EVENT_KEY,e)}onAppsChanged(e){return this.callbacks.add(APPS_CHANGED_EVENT_KEY,e)}async getPrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "getPrefs" request for app=${e}`);const r=await this.getAllCachedPrefs();let n;try{n=await this.client.getPrefs(e)}catch(e){if(!(e instanceof SanitizedIOManagerApiError&&404===e.status))throw e;n=void 0}if(n){const e=r.find(e=>e.app===n?.app);if(e&&!objEqualFast(e.data,n.data)){const e={app:n.app,prefs:this.transformPrefs(n)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,e)}}const i=n?this.transformPrefs(n):void 0;return t&&this.logger?.trace(`[${t}] request completed, prefs retrieved`),i}):ioError.raiseError("Cannot get preferences, because the feature is not enabled")}async getAllPrefs(e){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "getAllPrefs" request`);const t=await this.getAllCachedPrefs(),r=await this.client.getAllPrefs();this.notifyPrefs(t,r);const n=r.map(this.transformPrefs);return e&&this.logger?.trace(`[${e}] request completed, all prefs retrieved`),n}):ioError.raiseError("Cannot get all preferences, because the feature is not enabled")}async savePrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "savePrefs" request`);const r=await this.client.setPrefs({app:e.app,data:e.data,merge:!e.overwrite});await this.mergeInPreferenceCache([r]);const n={app:r.app,prefs:this.transformPrefs(r)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,n),t&&this.logger?.trace(`[${t}] request completed, preferences saved`)}):ioError.raiseError("Cannot save preferences, because the feature is not enabled")}async clearPrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "clearPrefs" request`);const r=await Promise.all(e.map(e=>this.client.setPrefs({app:e,data:{},merge:!1})));await this.mergeInPreferenceCache(r);for(const e of r){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}t&&this.logger?.trace(`[${t}] request completed, preferences cleared`)}):ioError.raiseError("Cannot clear preferences, because the feature is not enabled")}async clearAllPrefs(e){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "clearAllPrefs" request`);let t=await this.client.getAllPrefs();t=await Promise.all(t.map(e=>this.client.setPrefs({app:e.app,data:{},merge:!1}))),await this.managerCache.set(PREFS_CACHE_KEY,t);for(const e of t){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}e&&this.logger?.trace(`[${e}] request completed, all preferences cleared`)}):ioError.raiseError("Cannot clear all preferences, because the feature is not enabled")}clearCache(){return this.managerCache?.clear()}onPrefsChanged(e){return this.config?.features?.preferencesStore?this.callbacks.add(PREFS_CHANGED_EVENT_KEY,e):ioError.raiseError("Cannot subscribe to prefs changes, because the feature is not enabled")}handleOnLayoutsChanged(e){const t=this.parseLayouts(e);this.notifyLayouts(this.lastLayouts,t),this.setLastLayouts(e,t)}setLastLayouts(e,t){this.lastLayouts=t,this.lastLayoutIdsByKey.clear();for(const t of e)this.lastLayoutIdsByKey.set(this.getLayoutKey(t),t.id)}getLayoutKey(e){return e.name+" | "+e.type}notifyLayouts(e,t){const r=[],n=[],i=[],o=new Set(t.map(e=>e.name)),s=new Map;for(const t of e)o.has(t.name)||n.push(t),s.set(this.getLayoutKey(t),t);for(const e of t){const t=s.get(this.getLayoutKey(e));t?objEqualFast(e,t)||i.push(e):r.push(e)}r.length&&this.callbacks.execute(LAYOUTS_ADDED_EVENT_KEY,r),n.length&&this.callbacks.execute(LAYOUTS_REMOVED_EVENT_KEY,n),i.length&&this.callbacks.execute(LAYOUTS_CHANGED_EVENT_KEY,i)}parseLayouts(e){const t=e.map(e=>"string"==typeof e.definition?JSON.parse(e.definition):e.definition);return this.sanitizeLayouts(t).valid}sanitizeLayouts(e){return e.reduce((e,t)=>{const r=glueLayoutDecoder.run(t);return r.ok?e.valid.push(t):this.logger?.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]})}sanitizeApps(e){return e.reduce((e,t)=>{const r=allApplicationDefinitionsDecoder.run(t);return r.ok?e.valid.push(t):this.logger?.warn(`An app with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]})}notifyPrefs(e,t){const r=[],n=new Map;for(const t of e)n.set(t.app,t);for(const e of t){const t=n.get(e.app);t&&!objEqualFast(e.data,t.data)&&r.push(e)}for(const e of r){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}}async mergeInPreferenceCache(e){const t=await this.getAllCachedPrefs();for(const r of e){const e=t.findIndex(e=>e.app===r.app);-1!==e?t[e]=r:t.push(r)}await this.managerCache.set(PREFS_CACHE_KEY,t)}async getAllCachedPrefs(){const e=(await this.managerCache.get(PREFS_CACHE_KEY))?.value??[];for(const t of e)"string"==typeof t?.data&&(t.data=JSON.parse(t.data));return e}async getAllCachedLayouts(){return(await this.managerCache.get(LAYOUTS_CACHE_KEY))?.value??[]}handleOnConnectedStateChanged(e){const t=e=>e?{message:e.message,name:e.name,code:e.code,status:e.status,request:e.request,isSessionExpired:e.isSessionExpired}:e;this.callbacks.execute(CONNECTED_STATE_CHANGED_EVENT_KEY,(e=>{const{disconnectionError:r,...n}=e;return{...n,disconnectionError:t(r)}})(e))}handleOnAppsChanged(e){let t=e;t=this.sanitizeApps(t)?.valid,this.notifyApps(this.lastApps,t),this.lastApps=t}notifyApps(e,t){const r=[],n=[],i=[],o=new Set(t.map(e=>e.name)),s=new Map;for(const t of e)o.has(t.name)||n.push(t),s.set(t.name,t);for(const e of t){const t=s.get(e.name);t?objEqualFast(e,t)||i.push(e):r.push(e)}r.length&&this.callbacks.execute(APPS_ADDED_EVENT_KEY,r),n.length&&this.callbacks.execute(APPS_DELETED_EVENT_KEY,n),i.length&&this.callbacks.execute(APPS_CHANGED_EVENT_KEY,i)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}handleUnload(){this.client&&this.client.unload()}transformPrefs({app:e,data:t,lastUpdate:r}){return{app:e,data:t,lastUpdate:r}}createManagerLogger(){const e=logger.get("io-manager-connection"),t=e=>{if(e instanceof SanitizedIOManagerApiError)return JSON.stringify(e,null,2);if(e instanceof IOManagerRequestValidationError)return`${e.toString()} ${e.getZodError().toString()}`;if(e instanceof Error)return extractErrorMsg$1(e);try{return JSON.stringify(e)}catch{return"[Unable to serialize]"}},r=(e,r)=>r.length?`${e} ${r.map(t).join(" ").trim()}`:e;return{trace(t,...n){e?.canPublish("trace")&&e?.trace(r(t,n))},debug(t,...n){e?.canPublish("debug")&&e?.debug(r(t,n))},info(t,...n){e?.canPublish("info")&&e?.info(r(t,n))},warn(t,...n){e?.canPublish("warn")&&e?.warn(r(t,n))},error(t,...n){e?.canPublish("error")&&e?.error(r(t,n))},isTraceEnabled:()=>Boolean(e?.canPublish("trace")),isDebugEnabled:()=>Boolean(e?.canPublish("debug")),isInfoEnabled:()=>Boolean(e?.canPublish("info")),isWarnEnabled:()=>Boolean(e?.canPublish("warn")),isErrorEnabled:()=>Boolean(e?.canPublish("error")),isLevelEnabled:t=>Boolean(e?.canPublish(t)),log:(t,n,...i)=>{e?.canPublish(t)&&e?.log(r(n,i),t)}}}}class Identity{uaParser;glueController;pluginsController;workspacesFrameUrl;constructor(e,t,r,n){this.uaParser=e,this.glueController=t,this.pluginsController=r,this.workspacesFrameUrl=n}get logger(){return logger.get("manager.identity")}async getMachineInfo(e){const t=this.uaParser.getResult();return{user:e,name:"",os:{name:t.os.name||"",version:t.os.version||"",arch:t.cpu.architecture||""},browser:{name:t.browser.name,version:t.browser.version,engine:t.engine.name},mobileDevice:"mobile"===t.device?.type?{vendor:t.device.vendor,model:t.device.model}:void 0,displays:await this.getDisplays()}}getGlueInfo(){return{version:"",build:"",region:"",env:"",core:{web:{version:this.glueController.clientGlue.version},platform:{version:this.glueController.platformVersion,plugins:this.pluginsController.registeredPlugins},plus:{version:version$1}},workspaces:this.glueController.isWorkspacesEnabled?{version:this.glueController.clientGlue.workspaces?.version,frameUrl:this.workspacesFrameUrl}:void 0}}async getDisplays(){try{const{state:e}=await getWindowManagementPermissionStatus(this.logger);if("granted"!==e)return[]}catch(e){return this.logger?.warn(extractErrorMsg$1(e)),[]}return(await window.getScreenDetails()).screens.map(e=>({bounds:{x:e.left,y:e.top,width:e.width,height:e.height},workingArea:{x:e.availLeft,y:e.availTop,width:e.availWidth,height:e.availHeight},dpi:e.devicePixelRatio,isPrimary:e.isPrimary}))}}const prefsOperationTypesDecoder=oneOf$1(constant$2("operationCheck"),constant$2("clear"),constant$2("clearAll"),constant$2("get"),constant$2("getAll"),constant$2("set"),constant$2("update"),constant$2("prefsHello"),constant$2("registerSubscriber")),appPreferencesDecoder=object$3({app:nonEmptyStringDecoder$2,data:object$3(),lastUpdate:optional$3(nonEmptyStringDecoder$2)}),basePrefsConfigDecoder=object$3({app:nonEmptyStringDecoder$2}),subscriberRegisterConfigDecoder=object$3({interopId:nonEmptyStringDecoder$2,appName:optional$3(nonEmptyStringDecoder$2)}),getPrefsResultDecoder=object$3({prefs:appPreferencesDecoder}),getAllPrefsResultDecoder=object$3({all:array$3(appPreferencesDecoder)}),changePrefsDataDecoder=object$3({app:nonEmptyStringDecoder$2,data:object$3()}),prefsHelloSuccessDecoder=object$3({platform:object$3({app:nonEmptyStringDecoder$2}),validNonExistentApps:optional$3(array$3(nonEmptyStringDecoder$2))});class PrefsController{glueController;localStore;managerStore;restStore;operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},clear:{name:"clear",execute:this.clear.bind(this),dataDecoder:basePrefsConfigDecoder},clearAll:{name:"clearAll",execute:this.clearAll.bind(this)},get:{name:"get",execute:this.get.bind(this),dataDecoder:basePrefsConfigDecoder,resultDecoder:getPrefsResultDecoder},getAll:{name:"getAll",execute:this.getAll.bind(this),resultDecoder:getAllPrefsResultDecoder},set:{name:"set",execute:this.set.bind(this),dataDecoder:changePrefsDataDecoder},update:{name:"update",execute:this.update.bind(this),dataDecoder:changePrefsDataDecoder},prefsHello:{name:"prefsHello",execute:this.prefsHello.bind(this),resultDecoder:prefsHelloSuccessDecoder},registerSubscriber:{name:"registerSubscriber",dataDecoder:subscriberRegisterConfigDecoder,execute:this.registerSubscriber.bind(this)}};started=!1;unsubFuncs=[];_platformAppName=`Platform-${window.location.origin}`;config;store;constructor(e,t,r,n){this.glueController=e,this.localStore=t,this.managerStore=r,this.restStore=n}get logger(){return logger.get("prefs.controller")}get systemValidNonExistentApps(){return[systemPrefsAppName]}get validNonExistentApps(){return this.systemValidNonExistentApps.concat(this.config?.validNonExistentApps??[])}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.store.stop()}get platformAppName(){return this._platformAppName}get storeType(){return this.store.type}async start(e){this.logger?.trace("initializing prefs"),this.started=!0,this.config=e.applicationPreferences,this.store=this.getStore(e),this.setupStoreListeners(),await this.store.start(e),this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this prefs control message, because the controller has not been started");const t=e.data,r=e.commandId,n=prefsOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This prefs request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Prefs request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Prefs request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async registerSubscriber({interopId:e,appName:t},r){this.trace(`[${r}] handling registerSubscriber command with interopId: ${e}`,r);const n=t?this.glueController.clientGlue.appManager.applications().find(e=>e.name===t):void 0;if(t&&!n)return ioError.raiseError(`Cannot register subscriber with appName "${t}", because the application is not valid.`);this.store.processNewSubscriber(t),this.trace(`[${r}] registerSubscriber command was executed successfully`,r)}async get({app:e},t){this.trace(`[${t}] handling get command with app: ${e}`,t);const r={app:e,data:{}};return{prefs:await this.store.getPrefs(e,t)||r}}async update({app:e,data:t},r){this.trace(`[${r}] handling update command with app: ${e} and data: ${JSON.stringify(t)}`,r);const n=this.validateApp(e);await this.store.savePrefs({app:n,data:t,overwrite:!1},r),this.trace(`[${r}] update command was executed successfully`,r)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async clear({app:e},t){this.trace(`[${t}] handling clear command with app: ${e}`,t);const r=this.validateApp(e);await this.store.clearPrefs([r],t),this.trace(`[${t}] clear command was executed successfully`,t)}async clearAll(e,t){this.trace(`[${t}] handling clearAll command`,t),await this.store.clearAllPrefs(t),this.trace(`[${t}] clearAll command was executed successfully`,t)}async getAll(e,t){this.trace(`[${t}] handling getAll command`,t);const r=await this.store.getAllPrefs(t);return this.trace(`[${t}] getAll command was executed successfully`,t),{all:r}}async set({app:e,data:t},r){this.trace(`[${r}] handling set command with app: ${e} and data: ${JSON.stringify(t)}`,r);const n=this.validateApp(e);await this.store.savePrefs({app:n,data:t,overwrite:!0},r),this.trace(`[${r}] set command was executed successfully`,r)}async prefsHello(){return{platform:{app:this._platformAppName},validNonExistentApps:this.validNonExistentApps}}validateApp(e){const t=this.glueController.getAllApplicationNames();return e===this._platformAppName||t.includes(e)||this.validNonExistentApps.includes(e)?e:ioError.raiseError(`The provided app name "${e}" is not valid.`)}trace(e,t){t&&this.logger?.trace(e)}setupStoreListeners(){const e=this.store.onPrefsChanged(e=>{this.emitStreamData("prefsChanged",{prefs:e.prefs})});this.unsubFuncs.push(e)}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("prefs",e,t)}getStore(e){const t=e.applicationPreferences?.store?.type,r=!(!e?.manager?.url||!e?.manager?.features?.preferencesStore),n=!!e?.applicationPreferences?.store?.rest?.url;return!t&&r?this.managerStore:t||r?"local"===t?this.localStore:"rest"===t&&n?this.restStore:"rest"!==t||n?"manager"===t&&r?this.managerStore:"manager"!==t||r?ioError.raiseError("Cannot set prefs store."):ioError.raiseError("The prefs store is configured to be managed, but the manager is not configured."):ioError.raiseError("The prefs store is configured to be rest, but the rest url is not configured."):this.localStore}}class IdbBasedIOManagerCache{kvStoreName="data";dbVersion=1;dbNamePrefix="IOManagerCache";logger=logger.get("io-manager-cache");config;dbName;database;data={};constructor(e,t){if(!("indexedDB"in window))throw new Error("Cannot initialize the local storage, because IndexedDB is not supported");this.config=e,this.dbName=`${this.dbNamePrefix}-${t}-${e.url}`}async get(e){const t=this.data[e];return t?(this.logger?.trace(`Read cache data for key: ${e}`),t):void this.logger?.trace(`Read cache data for key: ${e} - key not found.`)}async set(e,t){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Write cache data for key: ${e}`);const r=this.data[e];r?r.value=t:this.data[e]={value:t},await this.database.put(this.kvStoreName,{value:t,key:e})}async remove(e){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Remove cache data for key: ${e}`),delete this.data[e],await this.database.delete(this.kvStoreName,e)}async initialize(){if(this.database=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)}),this.config.cache?.clearOld)if("databases"in indexedDB){const e=(await indexedDB.databases()).filter(e=>e.name?.startsWith(this.dbNamePrefix)&&e.name!==this.dbName);for(const t of e)if(t.name)try{this.logger?.info(`Deleting cache db "${t.name}"`),await deleteDB(t.name)}catch(e){this.logger?.warn(`Failed to delete db "${t.name}". Error: ${extractErrorMsg$1(e)}`)}}else this.logger?.warn("Could not delete extraneous cache databases. This engine does not support indexedDB.databases.");await this.readFromDB()}async dispose(){this.logger?.trace(`Closing idb connection: "${this.dbName}"`),this.database?.close(),delete this.database}async clear(){await this.dispose(),this.logger?.trace(`Deleting idb database: "${this.dbName}"`),await deleteDB(this.dbName),await this.initialize()}setUpDB(e){e.objectStoreNames.contains(this.kvStoreName)||e.createObjectStore(this.kvStoreName,{keyPath:"key"})}async readFromDB(){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Reading from db: "${this.dbName}"`);const e=await this.database.getAll(this.kvStoreName),t={};for(const r of e)t[r.key]=r;this.data=t}}class SessionStorageBasedIOManagerCache{storageKeyPrefix="IOManagerCache";storageKey;logger=logger.get("io-manager-cache");config;data={};constructor(e,t){if(!("sessionStorage"in window))throw new Error("Cannot initialize the local storage, because sessionStorage is not supported");this.config=e,this.storageKey=`${this.storageKeyPrefix}-${t}-${e.url}`}async get(e){const t=this.data[e];return t?(this.logger?.trace(`Read cache data for key: ${e}`),t):void this.logger?.trace(`Read cache data for key: ${e} - key not found.`)}async set(e,t){this.logger?.trace(`Write cache data for key: ${e}`);const r=this.data[e];r?r.value=t:this.data[e]={value:t},this.writeToSessionStorage()}async remove(e){this.logger?.trace(`Remove cache data for key: ${e}`),delete this.data[e],this.writeToSessionStorage()}async initialize(){if(this.config.cache?.clearOld){const e=Object.keys(sessionStorage).filter(e=>e.startsWith(this.storageKeyPrefix)&&e!==this.storageKey);for(const t of e)try{this.logger?.info(`Deleting cache item "${t}"`),sessionStorage.removeItem(t)}catch(e){this.logger?.warn(`Failed to delete cache with key "${t}". Error: ${extractErrorMsg$1(e)}`)}}await this.readFromSessionStorage()}async dispose(){}async clear(){this.logger?.trace(`Deleting sessionStorage item with key "${this.storageKey}"`),sessionStorage.removeItem(this.storageKey),await this.initialize(),this.writeToSessionStorage()}async readFromSessionStorage(){let e;this.logger?.trace(`Reading sessionStorage item with key "${this.storageKey}"`);try{e=sessionStorage.getItem(this.storageKey)}catch(e){return this.logger?.warn(`Failed to read sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`),void(this.data={})}if(!e)return this.logger?.warn(`sessionStorage item with key "${this.storageKey}" does not exist.`),void(this.data={});try{this.data=JSON.parse(e)}catch(e){this.logger?.warn(`Failed to parse json from sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`),this.data={}}}writeToSessionStorage(){let e;this.logger?.trace(`Writing cache to sessionStorage item with key "${this.storageKey}"`);try{e=JSON.stringify(this.data)}catch(e){return void this.logger?.warn(`Failed to serialize io-manager cache. ${extractErrorMsg$1(e)}`)}try{sessionStorage.setItem(this.storageKey,e)}catch(e){this.logger?.warn(`Failed to write to sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`)}}}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let nanoid=(e=21)=>{let t="",r=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=urlAlphabet[63&r[e]];return t};const otelOperationTypesDecoder=oneOf$1(constant$2("operationCheck"));class OtelController{telemetry;getNewMetricsDependencyBuilder;glueController;getPlatformController;systemController;applicationsController;layoutsController;workspacesController;serviceId=nanoid();serviceName="io.Connect Browser";config;platformController;started=!1;operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i,o,s,a){this.telemetry=e,this.getNewMetricsDependencyBuilder=t,this.glueController=r,this.getPlatformController=n,this.systemController=i,this.applicationsController=o,this.layoutsController=s,this.workspacesController=a}get logger(){return logger.get("otel.controller")}get glue(){return this.glueController.clientGlue}get metricsDependencyContainer(){const e=this.getNewMetricsDependencyBuilder();e.withInstanceStartedHandler(this.instanceStartedHandler.bind(this)).withInstanceStoppedHandler(this.instanceStoppedHandler.bind(this)).withInstanceReadyHandler(this.instanceReadyHandler.bind(this)).withInstanceFocusedHandler(this.instanceFocusedHandler.bind(this)).withInstanceErrorHandler(this.instanceErrorHandler.bind(this)).withLayoutRestoredHandler(this.layoutRestoredHandler.bind(this)).withWorkspaceRestoredHandler(this.workspaceRestoredHandler.bind(this)).withWorkspaceStoppedHandler(this.workspaceStoppedHandler.bind(this)).withPlatformStartedHandler(this.platformStartedHandler.bind(this)).withPlatformErrorHandler(this.platformErrorHandler.bind(this));return e.build()}get metricsSettings(){if(!this.config.otel?.metrics)return{enabled:!1};const{additionalResourceAttributes:e,getAdditionalAttributes:t,headers:r,metrics:n,publishInterval:i=3e4,url:o}=this.config.otel.metrics,s=t?.();this.warnIfPlatformVersionAttributeIsProvided(s),this.warnIfPlatformVersionAttributeIsProvided(e);const a=n?.map(e=>({...e,enabled:e.enabled??!0,name:e.name??e.type,description:e.description??"no description"}));return{additionalResourceAttributes:e,additionalAttributes:s,enabled:!0,headers:r,metrics:a,platformMetricsEnabled:!0,publishInterval:i,url:o}}get settings(){const e=this.config.otel?.getAdditionalAttributes?.(),t=this.config.otel?.additionalResourceAttributes;return this.warnIfPlatformVersionAttributeIsProvided(e),this.warnIfPlatformVersionAttributeIsProvided(t),{additionalAttributes:e,additionalResourceAttributes:t,enabled:!!this.config.otel?.metrics,headers:this.config.otel?.headers,metrics:this.metricsSettings,platformVersion:this.glueController.platformVersion,serviceId:this.serviceId,serviceName:this.serviceName,serviceVersion:this.glueController.platformVersion,userId:this.config.user?.id}}warnIfPlatformVersionAttributeIsProvided(e){e&&"platformVersion"in e&&this.logger?.warn("The provided additional attributes override the default platform version settings.")}async start(e){this.config=e,this.shouldStartController()&&(this.platformController=this.getPlatformController(),this.logger?.trace("Starting the Otel controller."))}async configurePostStart(){if(this.shouldStartController())try{await this.telemetry.start(this.settings,this.metricsDependencyContainer),this.started=!0}catch(e){const t=extractErrorMsg$1(e);this.logger?.error(`Failed to start Otel Controller. Reason: ${t}`)}}ready(){return Promise.resolve()}async handlePlatformShutdown(){if(this.started)try{await this.telemetry.stop(),this.started=!1,this.resetMetricHandlerSubscriptionCounters()}catch(e){const t=extractErrorMsg$1(e);this.logger?.error(`Failed to stop Otel Controller. Reason: ${t}`)}}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this otel control message, because the controller has not been started");const t=e.data,r=e.commandId,n=otelOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This otel request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Otel request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Otel request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}shouldStartController(){return!!this.config.otel?.metrics?.url}incrementMetricHandlerSubscriptionCounter(e){window.testingOtel&&++window.testingOtel.metricHandlers[e].numberOfSubscriptions}resetMetricHandlerSubscriptionCounters(){window.testingOtel&&Object.values(window.testingOtel.metricHandlers).forEach(e=>{e.numberOfSubscriptions=0})}instanceStartedHandler(e){this.incrementMetricHandlerSubscriptionCounter("instanceStarted");const t=t=>{const r={application:t.application.name};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceStarted.callback(r);e(r)},r=this.glue.appManager.onInstanceStarted(t);return this.glue.appManager.instances().forEach(t),r}instanceStoppedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceStopped"),this.glue.appManager.onInstanceStopped(t=>{const r={application:t.application.name};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceStopped.callback(r);e(r)})}instanceReadyHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceReady"),this.applicationsController.onInstanceStarted(({api:t="unknown",applicationName:r,startup:n})=>{const i={api:t,application:r,startTime:n.start,endTime:n.end};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceReady.callback(i);e(i)})}instanceFocusedHandler(e){this.incrementMetricHandlerSubscriptionCounter("instanceFocused");const t=this.glue.windows.onWindowGotFocus(t=>{const r=this.glue.appManager.instances().find(e=>e.id===t.id),n={application:r?.application?.name??t.name,focused:!0};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceFocused.callback(n);e(n)}),r=this.glue.windows.onWindowLostFocus(t=>{const r=this.glue.appManager.instances().find(e=>e.id===t.id),n={application:r?.application?.name??t.name,focused:!1};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceFocused.callback(n);e(n)});return()=>{t(),r()}}instanceErrorHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceError"),this.systemController.onClientError(({callerId:t})=>{const r={application:this.glueController.getAppNameByInstanceId(t??"")??"unknown"};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceError.callback(r);e(r)})}layoutRestoredHandler(e){return this.incrementMetricHandlerSubscriptionCounter("layoutRestored"),this.layoutsController.onLayoutRestored(({layoutName:t,startTime:r,endTime:n})=>{const i={layout:t,startTime:r,endTime:n};if(window.testingOtel)return window.testingOtel.metricHandlers.layoutRestored.callback(i);e(i)})}workspaceRestoredHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceRestored"),this.workspacesController.onWorkspaceRestored(({layoutName:t,startTime:r,endTime:n})=>{const i={layout:t,startTime:r,endTime:n};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceRestored.callback(i);e(i)})}workspaceStoppedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceStopped"),this.workspacesController.onWorkspaceClosed(({layoutName:t})=>{const r={layout:t};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceStopped.callback(r);e(r)})}platformStartedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("platformStarted"),this.platformController.onPlatformStarted(({platformVersion:t,startup:r})=>{const n={startTime:r.start,endTime:r.end,api:t};if(window.testingOtel)return window.testingOtel.metricHandlers.platformStarted.callback(n);e(n)})}platformErrorHandler(e){return this.incrementMetricHandlerSubscriptionCounter("platformError"),this.systemController.onPlatformError(()=>{const t={};if(window.testingOtel)return window.testingOtel.metricHandlers.platformError.callback(t);e(t)})}}class Telemetry{getNewContainerBuilder;buildLogger;container=null;constructor(e,t){this.getNewContainerBuilder=e,this.buildLogger=t}get logger(){return logger.get("otel.telemetry")}async start(e,t){if(this.container)return ioError.raiseError("An Otel container has already been started");this.logger?.trace(`Starting an Otel container with settings: ${JSON.stringify(e)}`);const r=this.buildContainer(e,t);await r.start(),this.container=r,this.logger?.trace("The Otel container has been started successfully")}async stop(){this.container&&(await this.container.stop(),this.container=null,this.logger?.trace("The Otel container has been stopped successfully"))}buildContainer(e,t){const r=this.getNewContainerBuilder();if(this.logger&&r.withLogger(this.buildLogger(this.logger)),r.withSettings(e),e.metrics?.enabled){r.withMetrics().withDependencyContainer(t)}return r.build()}}class LoggerAdapter{logger;logLevelMap={error:30,warn:50,info:60,debug:70,trace:80};constructor(e){this.logger=e}get level(){const e=this.logger.consoleLevel();return this.logLevelMap[e]??60}error(e,...t){const r=this.tryStringify(e,t);this.logger.error(r)}warn(e,...t){const r=this.tryStringify(e,t);this.logger.warn(r)}info(e,...t){const r=this.tryStringify(e,t);this.logger.info(r)}debug(e,...t){const r=this.tryStringify(e,t);this.logger.debug(r)}verbose(e,...t){const r=this.tryStringify(e,t);this.logger.trace(r)}tryStringify(e,t){try{return JSON.stringify(t.length?{message:e,args:t}:{message:e})}catch(t){return e}}}const defaultWidgetConfig={channels:{selector:{enable:!0,type:"default"},displayMode:"all"},position:"bottom-center",displayInWorkspace:!1,restoreLastKnownPosition:!0};class UIController{sessionStorage;glueController;started=!1;config;operations={getResources:{name:"getResources",dataDecoder:getResourcesDataDecoder,resultDecoder:getResourcesResultDecoder,execute:this.handleGetResources.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},requestAlert:{name:"requestAlert",dataDecoder:uiAlertRequestMessageDecoder,execute:this.handleAlertRequest.bind(this)},requestDialog:{name:"requestDialog",dataDecoder:uiDialogRequestMessageDecoder,resultDecoder:uiDialogClientResponseDecoder,execute:this.handleDialogRequest.bind(this)},alertInteropAction:{name:"alertInteropAction",dataDecoder:alertInteropActionDataDecoder,execute:this.handleAlertInteropAction.bind(this)},getModalsStatus:{name:"getModalsStatus",resultDecoder:modalsStatusResponseDecoder,execute:this.handleGetModalsStatus.bind(this)}};clientOperations={showAlert:{name:"showAlert",execute:noop$1},showDialog:{name:"showDialog",execute:noop$1},operationCheck:{name:"operationCheck",execute:noop$1},showResolver:{name:"showResolver",execute:noop$1}};constructor(e,t){this.sessionStorage=e,this.glueController=t}async start(e){this.started=!0,this.config=e}ready(){return Promise.resolve()}async openResolver({config:e,initialCaller:t,methodResponseTimeoutMs:r,commandId:n}){this.logger?.trace(`[${n}] Handling open resolver request with config: ${JSON.stringify(e)}`);const i=this.getIntentResolverTargetInstance(t.instanceId,n);return(await this.glueController.callInstance("ui",this.clientOperations.showResolver,{config:e},{instance:i},{methodResponseTimeoutMs:r})).result}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this UI control message, because the controller has not been started");const t=e.data,r=e.commandId,n=uiOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This UI request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`UI request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`UI request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}get logger(){return logger.get("ui.controller")}async handleGetResources({origin:e}){return{resources:{widget:this.getWidgetResources(e),modals:this.getModalsResources(e),intentResolver:this.getIntentResolverResources(e)}}}async handleGetModalsStatus(e,t){this.logger?.trace(`[${t}] Handling get status request`);const r={status:{platformConfigured:!!this.config.modals}};return this.logger?.trace(`[${t}] Get status request was handled successfully with response: ${JSON.stringify(r)}`),r}async handleAlertRequest(e,t){if(this.logger?.trace(`[${t}] Handling alert request with config: ${JSON.stringify(e)}`),!this.config.modals)return ioError.raiseError(`[${t}] Cannot handle alert request, because modals are not configured in the platform`);const r=this.getModalsTargetInstance(e.target.instance,t,e.target.container);this.logger?.trace(`[${t}] Target instance for the alert request is: ${r}`);const{isSupported:n}=await this.glueController.checkClientOperationSupport("ui",this.clientOperations.showAlert,{instance:r});if(!n)return ioError.raiseError(`[${t}] Cannot handle alert request, because the target instance does not support the operation`);this.logger?.trace(`[${t}] Calling the showAlert operation with the provided config`),await this.glueController.callInstance("ui",this.clientOperations.showAlert,e,{instance:r}),this.logger?.trace(`[${t}] Alert request was handled successfully`)}async handleDialogRequest(e,t){if(this.logger?.trace(`[${t}] Handling dialog request with config: ${JSON.stringify(e)}`),!this.config.modals)return ioError.raiseError(`[${t}] Cannot handle dialog request, because modals are not configured in the platform`);const r=this.getModalsTargetInstance(e.target.instance,t,e.target.container);this.logger?.trace(`[${t}] Target instance for the dialog request is: ${r}`);const{isSupported:n}=await this.glueController.checkClientOperationSupport("ui",this.clientOperations.showDialog,{instance:r});if(!n)return ioError.raiseError(`[${t}] Cannot handle dialog request, because the target instance does not support the operation`);this.logger?.trace(`[${t}] Calling the showDialog operation with the provided config`);const{timer:i}=e.config,o={methodResponseTimeoutMs:i?.duration?getSafeTimeoutDelay(i.duration+DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1):MAX_SET_TIMEOUT_DELAY},s=await this.glueController.callInstance("ui",this.clientOperations.showDialog,e,{instance:r},o);return this.logger?.trace(`[${t}] Dialog request was handled successfully.`),s}getWidgetResources(e){if(!this.config?.widget)return;return checkIsOriginBlocked(e,this.config.widget.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,config:this.config?.widget?.defaultConfig||defaultWidgetConfig,sources:this.config.widget.sources}}getModalsResources(e){if(!this.config?.modals)return;return checkIsOriginBlocked(e,this.config.modals.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,sources:this.config.modals.sources}}getIntentResolverResources(e){if(!this.config?.intentResolver)return;return checkIsOriginBlocked(e,this.config.intentResolver.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,sources:this.config.intentResolver.sources}}getModalsTargetInstance(e,t,r){const n=r?this.retrieveWindowContainerInstanceId(e,r):e;return this.glueController.getLocalServers().some(e=>e.instance===n)?n:ioError.raiseError(`[${t}] Cannot handle modals request, because the target instance does not exist - ${n}`)}retrieveWindowContainerInstanceId(e,t){if("Global"===t)return ioError.raiseError(`Cannot retrieve the instance id for the client with id: ${e}, because the container type - "Global" is not supported`);const r=this.sessionStorage.getWorkspaceClientById(e);return r?r.frameId:e}async handleAlertInteropAction(e,t){this.logger?.trace(`[${t}] Handling alert interop action with config: ${JSON.stringify(e)}`);const{method:r,arguments:n,target:i}=e.interopAction.settings,o=i?this.getInteropInstanceTarget(i,t):void 0;this.logger?.trace(`[${t}] Instance target for the alert interop action is: ${JSON.stringify(o)}`),await this.glueController.invokeMethod(r,n,o)}getInteropInstanceTarget(e,t){if("best"===e||"all"===e)return e;const r=this.glueController.getLocalServers().find(t=>t.instance===e);return r||ioError.raiseError(`[${t}] No interop instance was found for the provided target ${e}.`)}getIntentResolverTargetInstance(e,t){const r=this.sessionStorage.getWorkspaceClientById(e);this.logger?.trace(`[${t}] Initial caller id '${e}' ${r?"is":"isn't"} a workspace client.`);const n=r?r.frameId:e;return this.logger?.trace(`[${t}] Target instance id for the intent resolver is: ${n}`),n}}class LocalPrefsStore{idbController;registry=CallbackRegistryFactory$2();type="local";constructor(e){this.idbController=e}async start(){}stop(){}async getPrefs(e){return await this.idbController.getPrefs(e)}async savePrefs(e){const t=e.overwrite?"setPrefs":"updatePrefs",r=await this.idbController[t]({app:e.app,data:e.data,lastUpdate:getLastUpdateTimestamp()});this.registry.execute("prefsChanged",{app:e.app,prefs:r})}async clearPrefs(e){await Promise.all(e.map(async e=>{const t=await this.idbController.setPrefs({app:e,data:{},lastUpdate:getLastUpdateTimestamp()});this.registry.execute("prefsChanged",{app:e,prefs:t})}))}async clearAllPrefs(){(await this.idbController.clearAllPrefs(getLastUpdateTimestamp())).forEach(e=>{this.registry.execute("prefsChanged",{app:e.app,prefs:e})})}async getAllPrefs(){return await this.idbController.getAllPrefs()}onPrefsChanged(e){return this.registry.add("prefsChanged",e)}processNewSubscriber(){}}class ManagerPrefsStore{managerController;type="manager";constructor(e){this.managerController=e}async start(){}stop(){}async getPrefs(e,t){return await this.managerController.getPrefs(e,t)}async savePrefs(e,t){await this.managerController.savePrefs(e,t)}async clearPrefs(e,t){await this.managerController.clearPrefs(e,t)}async clearAllPrefs(e){await this.managerController.clearAllPrefs(e)}async getAllPrefs(e){return await this.managerController.getAllPrefs(e)}onPrefsChanged(e){return this.managerController.onPrefsChanged(e)}processNewSubscriber(){}}const defaultRestHeaders={"Content-Type":"application/json",Accept:"application/json"},defaultRestRequestTimeoutMS=3e4;class RestPrefsStore{sequelizer;scheduler;cache;sessionController;type="rest";registry=CallbackRegistryFactory$2();cacheConfig;url;requestTimeout;pollingInterval;userCustomHeaders={};getUserRequestInit=()=>({});fetched={};get logger(){return logger.get("applications.prefs.rest.store")}constructor(e,t,r,n){this.sequelizer=e,this.scheduler=t,this.cache=r,this.sessionController=n}async start(e){const t=e.applicationPreferences?.store?.rest;if(!t)return ioError.raiseError("Cannot setup prefs rest store, because of missing config");if(!t.pollingInterval&&t.cache?.enabled)return ioError.raiseError("Cannot setup prefs rest store, because polling interval is not set while cache is enabled");if(t.pollingInterval&&t.pollingInterval<5e3)return ioError.raiseError("Cannot setup prefs rest store, because polling interval is set to less than 5000ms");this.url=this.getBaseUrl(t.url),this.requestTimeout=t.requestTimeout??defaultRestRequestTimeoutMS,this.userCustomHeaders=t.customHeaders??{},this.getUserRequestInit=t.getRequestInit??(()=>({})),this.pollingInterval=t.pollingInterval??0,this.cacheConfig=t.cache??{},await this.cache.start(t);const r=this.sessionController.getAllPrefsRestSchedulerCache().map(e=>e.app);this.sessionController.clearAllPrefsRestSchedulerCache(),r.forEach(e=>this.addSchedulerEntry(e))}stop(){this.cache.stop()}async getPrefs(e,t){return this.sequelizer.enqueue(async()=>{const r=this.cacheConfig.enabled,n=r&&this.fetched[e]?await this.cache.getPrefs(e):void 0;let i;try{i=n??await this.getPrefsFromServer(e,t)}catch(t){const n=r&&await this.cache.getPrefs(e);return n?(this.logger?.warn(`Failed to fetch prefs for app ${e} from server, using cached prefs: ${t}`),n):ioError.raiseError(`Failed to fetch prefs for app ${e} from server and no cached prefs available: ${t}`)}return await this.comparePrefs(i),this.addSchedulerEntry(e),await this.cache.setPrefs(i),i})}async savePrefs(e,t){return this.sequelizer.enqueue(async()=>{const r=await this.getPrefsFromServer(e.app),n=e.overwrite?{}:r.data,i=e.overwrite?{app:e.app,data:e.data}:{app:e.app,data:{...n,...e.data}},o=this.getRequest("/","POST",i),s=await fetchTimeout(o,this.requestTimeout);if(!s.ok)return ioError.raiseError(`[${t}] The POST rest for prefs for app ${e.app} returned invalid status: ${s.status}`);const a=await this.getPrefsFromServer(e.app);await this.comparePrefs(a,r),this.addSchedulerEntry(e.app),await this.cache.setPrefs(a)})}async clearPrefs(e,t){return this.sequelizer.enqueue(async()=>{await Promise.all(e.map(async e=>{await this.clearPrefsFromServer(e,t),await this.comparePrefs({app:e,data:{}}),await this.cache.clearPrefs(e)}))})}async clearAllPrefs(e){return this.sequelizer.enqueue(async()=>{const t=(await this.getAllPrefsFromServer(e)).filter(e=>Object.keys(e.data).length);for(const r of t)try{await this.clearPrefsFromServer(r.app,e),await this.comparePrefs({app:r.app,data:{}})}catch(e){this.logger?.warn(`Failed to clear prefs for app ${r.app}: ${e}`)}await this.cache.clearAllPrefs()})}async getAllPrefs(e){return this.sequelizer.enqueue(async()=>{const t=await this.getAllPrefsFromServer(e),r=await this.cache.getAllPrefs();for(const e of r){const r=t.find(t=>t.app===e.app);r&&(await this.comparePrefs(r,e),await this.cache.setPrefs(r))}return t})}onPrefsChanged(e){return this.registry.add("prefsChanged",e)}processNewSubscriber(e){e?(this.logger?.info(`Processing new subscriber for appName: ${e}`),this.addSchedulerEntry(e)):this.logger?.trace("No appName provided, skipping new subscriber processing.")}async getAllPrefsFromServer(e){const t=this.getRequest("/all","GET"),r=await fetchTimeout(t,this.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The GET all rest for all prefs returned invalid status: ${r.status}`);const n=await r.json(),i=array$3(appPreferencesDecoder).run(n);return i.ok?i.result:ioError.raiseError(`[${e}] The GET all rest for all prefs returned invalid data: ${i.error}`)}async getPrefsFromServer(e,t){const r=new URLSearchParams({app:e}).toString(),n=this.getRequest(`/?${r}`,"GET"),i=await fetchTimeout(n,this.requestTimeout);if(!i.ok)return ioError.raiseError(`[${t}] The GET rest for prefs for app ${e} returned invalid status: ${i.status}`);const o=await i.json(),s=appPreferencesDecoder.run(o);return s.ok?(this.fetched[o.app]=!0,s.result):ioError.raiseError(`[${t}] The GET rest for prefs for app ${e} returned invalid data: ${s.error}`)}async clearPrefsFromServer(e,t){const r={app:e,data:{}},n=this.getRequest("/","POST",r),i=await fetchTimeout(n,this.requestTimeout);if(!i.ok)return ioError.raiseError(`[${t}] The POST rest for prefs for app ${e} returned invalid status: ${i.status}`)}async comparePrefs(e,t){const r=t??await this.cache.getPrefs(e.app);r&&JSON.stringify(r.data)===JSON.stringify(e.data)||this.registry.execute("prefsChanged",{app:e.app,prefs:e})}getRequest(e,t,r){const n=new Headers;for(const e in defaultRestHeaders)n.append(e,defaultRestHeaders[e]);for(const e in this.userCustomHeaders)n.append(e,this.userCustomHeaders[e]);const i={method:t,headers:n,mode:"cors",cache:"default",body:r?JSON.stringify(r):void 0},o=`${this.url}${e}`,s=this.getUserRequestInit({url:o,requestInit:i});return new Request(o,{...i,...s})}getBaseUrl(e){return e.endsWith("/")?e.slice(0,-1):e}addSchedulerEntry(e){if(!this.pollingInterval)return void this.logger?.info(`Polling interval is not set, skipping scheduler entry addition for app: ${e}`);const t=new URLSearchParams({app:e}).toString(),r=`prefs:get:${e}`,n={key:r,getRequest:()=>this.getRequest(`/?${t}`,"GET"),timeout:this.requestTimeout,refreshIntervalMS:this.pollingInterval,onData:this.processSchedulerGetPrefsUpdate.bind(this),onError:t=>this.logger?.error(`Error during get prefs for ${e} request:`,t)};this.scheduler.checkEntryExists(r)||(this.sessionController.savePrefsRestSchedulerCache({app:e}),this.scheduler.register(n))}processSchedulerGetPrefsUpdate(e){return this.sequelizer.enqueue(async()=>{this.fetched[e.app]=!0;const t=appPreferencesDecoder.run(e);if(!t.ok)return this.logger?.warn(`The GET rest for prefs as part of polling for app ${e.app} returned invalid data: ${t.error}`);await this.comparePrefs(t.result),await this.cache.setPrefs(t.result)})}}class LocalLayoutsStore{idbController;sessionStore;localStore;registry=CallbackRegistryFactory$2();mode="idb";get logger(){return logger.get("layouts.local.store")}constructor(e,t,r){this.idbController=e,this.sessionStore=t,this.localStore=r}async start(e){if(this.mode=e.layouts.mode,!e.layouts.local.length)return;const t=e.layouts.local.filter(e=>"Global"===e.type),r=e.layouts.local.filter(e=>"Workspace"===e.type);await Promise.all([this.localMergeImport(t,"Global"),this.localMergeImport(r,"Workspace")])}stop(){"idb"===this.mode&&(this.idbController.clearLayouts("Global").catch(e=>this.logger?.warn(extractErrorMsg$1(e))),this.idbController.clearLayouts("Workspace").catch(e=>this.logger?.warn(extractErrorMsg$1(e))))}async saveLayouts(e,t,r,n){const i="merge"===r?this.localMergeImport.bind(this):this.localReplaceImport.bind(this);this.logger?.trace(`[${n}] importing the layouts in local ${r} mode`),await Promise.all([i(t,"Global"),i(e,"Workspace")]),this.logger?.trace(`[${n}] mass import completed, responding to caller`)}async deleteLayout(e,t){await this.localDelete(e.name,e.type),this.registry.execute("layouts-removed",[e]),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed`)}async renameLayout(e,t,r){let n;try{n=await this.localRename(e,t)}catch(t){const n=extractErrorMsg$1(t);return this.logger?.trace(`[${r}] Layout named ${e.name} has not been renamed. Reason: ${n}.`),{status:n}}return this.registry.execute("layouts-renamed",[{...n,prevName:e.name}]),this.logger?.trace(`[${r}] Layout named ${e.name} has been renamed to ${t}.`),{status:"Success"}}async getDefaultLayout(e){const t=this.localStore.getDefaultGlobalLayoutName(),r=await this.getAll("Global");return this.logger?.trace(this.createGetDefaultGlobalLogMessage(e,t)),r.find(e=>e.name===t)}async setDefaultLayout(e,t){this.localStore.saveDefaultGlobalLayout(e),this.logger?.trace(`[${t}] request completed for global layout with name ${e}, responding to the caller`)}async clearDefaultLayout(e){this.localStore.clearDefaultGlobalLayout(),this.logger?.trace(`[${e}] request completed, responding to the caller`)}async getAllLayouts(e){return"idb"===this.mode?await this.idbController.getAllLayouts(e):this.sessionStore.getLayoutSnapshot(e).layouts}onLayoutsAdded(e){return this.registry.add("layouts-added",e)}onLayoutsChanged(e){return this.registry.add("layouts-changed",e)}onLayoutsRemoved(e){return this.registry.add("layouts-removed",e)}onLayoutsRenamed(e){return this.registry.add("layouts-renamed",e)}async localMergeImport(e,t){const r=await this.getAll(t),n=[],i=[];for(const t of e){const e=r.findIndex(e=>e.name===t.name);e>-1&&!objEqual(t,r[e])?(this.logger?.trace(`change detected at layout ${t.name}`),i.push(t),r[e]=t):e<0&&(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),n.push(t),r.push(t))}await this.localCleanSave(r,t),await this.announceEvents({added:n,changed:i})}async localReplaceImport(e,t){const r=await this.getAll(t),n=[],i=[],o=[];for(const t of e){const e=r.findIndex(e=>e.name===t.name);e<0?(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),n.push(t)):(objEqual(t,r[e])||(this.logger?.trace(`change detected at layout ${t.name}`),i.push(t)),r.splice(e,1))}r.forEach(e=>{this.logger?.trace(`layout ${e.name} missing, removing and announcing`),o.push(e)}),await this.localCleanSave(e,t),await this.announceEvents({added:n,changed:i,removed:o})}async localCleanSave(e,t){if("session"!==this.mode){await this.idbController.clearLayouts(t);for(const t of e)await this.idbController.storeLayout(t)}else this.sessionStore.saveLayoutSnapshot({layouts:e},t)}async localDelete(e,t){if("idb"===this.mode)return void await this.idbController.deleteLayout(e,t);const r=this.sessionStore.getLayoutSnapshot(t).layouts,n=r.findIndex(t=>t.name===e);n>-1&&r.splice(n,1),this.sessionStore.saveLayoutSnapshot({layouts:r},t)}async localRename(e,t){const r={...e,name:t};if("idb"===this.mode)return this.idbController.renameLayout(r,e.name);const n=this.sessionStore.getLayoutSnapshot(e.type).layouts,i=n.findIndex(({name:t})=>t===e.name),o=-1===i?n.length:i;return n.splice(o,1,r),this.sessionStore.saveLayoutSnapshot({layouts:n},e.type),r}async getAll(e){const t="Workspace"===e?"Workspace":"Global";return"idb"===this.mode?await this.idbController.getAllLayouts(t):this.sessionStore.getLayoutSnapshot(t).layouts}async announceEvents(e){const t=[];e.added?.length&&t.push(this.throttleEvents(e.added,"layouts-added")),e.changed?.length&&t.push(this.throttleEvents(e.changed,"layouts-changed")),e.removed?.length&&t.push(this.throttleEvents(e.removed,"layouts-removed")),e.renamed?.length&&t.push(this.throttleEvents(e.renamed,"layouts-renamed")),await Promise.all(t),await this.waitEventFlush()}async throttleEvents(e,t){let r=0;for(const n of e)++r,r%10==0&&await this.waitEventFlush(),this.registry.execute(t,[n])}createGetDefaultGlobalLogMessage(e,t){return t?`[${e}] request completed, responding to the caller with layout with name ${t}`:`[${e}] request completed, no default global layout found, responding to the caller`}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}class ManagerLayoutsStore{manager;get logger(){return logger.get("layouts.manager.store")}constructor(e){this.manager=e}async start(){}stop(){}async saveLayouts(e,t,r,n){this.logger?.trace(`[${n}] importing the layouts to manager`),await this.manager.saveLayouts([...e,...t],r,n),this.logger?.trace(`[${n}] mass import to manager completed, responding to caller`)}async deleteLayout(e,t){await this.manager.deleteLayout(e.name,e.type,t),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed from manager`)}async renameLayout(e,t,r){return await this.manager.renameLayout(e.name,t,e.type,r),this.logger?.trace(`[${r}] Layout named ${e.name} has been renamed to ${t} in manager.`),{status:"Success"}}async getDefaultLayout(e){this.logger?.trace(`[${e}] getting default global layout from manager`);const t=await this.manager.getDefaultLayout(e);return this.logger?.trace(this.createGetDefaultGlobalLogMessage(e,t?.name)),t}async setDefaultLayout(e,t){this.logger?.trace(`[${t}] setting default global layout in manager`),await this.manager.setDefaultLayout(e,t),this.logger?.trace(`[${t}] request completed for global layout with name ${e}, responding to the caller`)}async clearDefaultLayout(e){this.logger?.trace(`[${e}] clearing default global layout in manager`),await this.manager.clearDefaultLayout(e),this.logger?.trace(`[${e}] request completed, responding to the caller`)}async getAllLayouts(e,t){return await this.manager.getAllLayouts(e,t)}onLayoutsAdded(e){return this.manager.onLayoutsAdded(e)}onLayoutsChanged(e){return this.manager.onLayoutsChanged(e)}onLayoutsRemoved(e){return this.manager.onLayoutsRemoved(e)}onLayoutsRenamed(e){return this.manager.onLayoutsRenamed(e)}createGetDefaultGlobalLogMessage(e,t){return t?`[${e}] request completed, responding to the caller with layout with name ${t}`:`[${e}] request completed, no default global layout found, responding to the caller`}}class RestLayoutsStore{sequelizer;scheduler;cache;registry=CallbackRegistryFactory$2();cacheConfig;config;get logger(){return logger.get("layouts.rest.store")}constructor(e,t,r){this.sequelizer=e,this.scheduler=t,this.cache=r}async start(e){const t=e.layouts?.rest;if(!t)return ioError.raiseError("Cannot setup layouts rest store, because of missing config");this.config=this.prepareConfig(t),this.logger?.info(`Starting layouts rest store with config: ${JSON.stringify({...this.config,customHeaders:"omitted"})}`),this.cacheConfig=t.cache??{},await this.cache.start(t),this.logger?.trace("Finished starting layouts rest store"),await this.dataWarmUp(),this.logger?.trace("Finished data warm up"),this.configureScheduler(),this.logger?.info("Layouts rest store started")}stop(){this.cache.stop()}async getAllLayouts(e,t){return this.sequelizer.enqueue(()=>this.getAllLayoutsNoSeq(e,t))}async saveLayouts(e,t,r,n){return this.sequelizer.enqueue(async()=>{const i=[...e,...t];"replace"===r&&await this.deleteAllLayoutsFromServer(n);const o=1===i.length;for(const e of i)try{await this.saveLayoutToServer(e,n)}catch(t){if(!o){this.logger?.warn(`Failed to save layout ${e.name} type:${e.type} with error: ${t}, continuing with the rest`);continue}return ioError.raiseError(`Failed to save layout ${e.name} type:${e.type} with error: ${t}`)}const s=await this.getAllLayoutsFromServer(n);await this.processNewLayoutsSnapshot(s)})}async deleteLayout(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] Deleting layout ${e.name} type:${e.type}`);const r=this.getRequest("/layouts","DELETE",{name:e.name,type:e.type}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`Failed to remove layout ${e.name} and type: ${e.type}: ${n.statusText}`);this.logger?.trace(`[${t}] Removed layout ${e.name} type:${e.type}`),await this.cache.deleteLayout(e),await this.announceEvents({removed:[e]})})}async renameLayout(e,t,r){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${r}] Renaming layout ${e.name} type:${e.type} to ${t}`);const n=this.getRequest("/layouts","PUT",{layout:e,newName:t}),i=await fetchTimeout(n,this.config.requestTimeout);return i.ok?(await this.cache.updateLayout({...e,name:t}),this.registry.execute("layouts-renamed",[{...e,name:t,prevName:e.name}]),{status:"Success"}):{status:`Failed to rename layout ${e.name} type:${e.type}: ${i.statusText}`}})}async getDefaultLayout(e){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${e}] Getting default layout`);const t=this.getRequest("/layouts/default","GET"),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for get default layout returned invalid status: ${r.status}`);let n;try{n=await r.json()}catch(t){return void this.logger?.trace(`[${e}] No default layout found`)}if(!n?.name)return void this.logger?.trace(`[${e}] No default layout found`);const i=n.name;return(await this.getAllLayoutsNoSeq("Global",e)).find(e=>e.name===i)})}async setDefaultLayout(e,t){this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] Setting default layout to ${e}`);const r=this.getRequest("/layouts/default","POST",{name:e}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`[${t}] The rest for set default layout returned invalid status: ${n.status}`);this.logger?.trace(`[${t}] Set default layout to ${e}`)})}async clearDefaultLayout(e){this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${e}] Clearing default layout`);const t=this.getRequest("/layouts/default","POST",{}),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for clear default layout returned invalid status: ${r.status}`);this.logger?.trace(`[${e}] Default layout cleared`)})}onLayoutsAdded(e){return this.registry.add("layouts-added",e)}onLayoutsChanged(e){return this.registry.add("layouts-changed",e)}onLayoutsRemoved(e){return this.registry.add("layouts-removed",e)}onLayoutsRenamed(e){return this.registry.add("layouts-renamed",e)}async getAllLayoutsNoSeq(e,t){const r=this.cacheConfig.enabled?await this.cache.getAllLayouts("all"):void 0;if(r?.length)return r.filter(t=>t.type===e);const n=await this.getAllLayoutsFromServer(t);return(await this.processNewLayoutsSnapshot(n)).filter(t=>t.type===e)}async getAllLayoutsFromServer(e){this.logger?.trace(`[${e}] Fetching all layouts from server`);const t=this.getRequest("/layouts","GET"),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for get all layouts returned invalid status: ${r.status}`);const n=await r.json();if(!n?.layouts)return ioError.raiseError(`[${e}] The rest for get all layouts returned invalid response`);return this.sanitizeLayouts(n.layouts)}async deleteAllLayoutsFromServer(e){const t=(await this.getAllLayoutsFromServer(e)).map(e=>this.getLayoutId(e.name,e.type)),r=this.getRequest("/layouts","DELETE",{ids:t}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`[${e}] Failed to remove all layouts: ${n.statusText}`);this.logger?.trace(`[${e}] Removed all layouts`)}async saveLayoutToServer(e,t){const r=this.getRequest("/layouts","POST",{layout:e}),n=await fetchTimeout(r,this.config.requestTimeout),i=`[${t}] Failed to save layout ${e.name} type:${e.type}: ${n.statusText}`;if(!n.ok)throw new Error(i);this.logger?.trace(`[${t}] Saved layout ${e.name} type:${e.type}`)}getBaseUrl(e){return e.endsWith("/")?e.slice(0,-1):e}getRequest(e,t,r){const n=new Headers;for(const e in defaultRestHeaders$1)n.append(e,defaultRestHeaders$1[e]);for(const e in this.config.customHeaders)n.append(e,this.config.customHeaders[e]);const i={method:t,headers:n,mode:"cors",cache:"default",body:r?JSON.stringify(r):void 0},o=`${this.config.url}${e}`,s=this.config.getRequestInit?.({url:o,requestInit:i});return new Request(o,{...i,...s})}getLayoutId(e,t){return`${e.toLowerCase()} (${t})`}sanitizeLayouts(e){return e.reduce((e,t)=>{const r=glueLayoutDecoder.run(t);return r.ok&&e.push(t),r.ok||this.logger?.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},[])}async executeLayoutsChangeDetection(e,t){if(!e.length)return;const r=[],n=[],i=[],o=await this.cache.getAllLayouts(t);for(const t of e){const e=o.findIndex(e=>e.name===t.name);e<0?(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),r.push(t)):(objEqual(t,o[e])||(this.logger?.trace(`change detected at layout ${t.name}`),n.push(t)),o.splice(e,1))}o.forEach(e=>{this.logger?.trace(`layout ${e.name} missing, removing and announcing`),i.push(e)}),await this.announceEvents({added:r,changed:n,removed:i})}async announceEvents(e){const t=[];e.added?.length&&t.push(this.throttleEvents(e.added,"layouts-added")),e.changed?.length&&t.push(this.throttleEvents(e.changed,"layouts-changed")),e.removed?.length&&t.push(this.throttleEvents(e.removed,"layouts-removed")),e.renamed?.length&&t.push(this.throttleEvents(e.renamed,"layouts-renamed")),await Promise.all(t),await this.waitEventFlush()}async throttleEvents(e,t){let r=0;for(const n of e)++r,r%10==0&&await this.waitEventFlush(),this.registry.execute(t,[n])}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}processSchedulerGetAllLayoutsUpdate(e){return this.sequelizer.enqueue(async()=>{this.logger?.trace("Processing scheduler get all layouts update"),await this.processNewLayoutsSnapshot(e.layouts),this.logger?.trace("Finished processing scheduler get all layouts update")})}async processNewLayoutsSnapshot(e){const t=this.sanitizeLayouts(e),r=t.filter(e=>"Workspace"===e.type),n=t.filter(e=>"Global"===e.type);return await this.executeLayoutsChangeDetection(r,"Workspace"),await this.executeLayoutsChangeDetection(n,"Global"),await this.cache.saveLayouts(t,"replace"),t}configureScheduler(){if(!this.config.pollingInterval)return void this.logger?.info("Polling interval is not set, skipping scheduler setup");const e="layouts:get:all";if(this.scheduler.checkEntryExists(e))return;const t={key:e,getRequest:()=>this.getRequest("/layouts","GET"),timeout:this.config.requestTimeout,refreshIntervalMS:this.config.pollingInterval,onData:this.processSchedulerGetAllLayoutsUpdate.bind(this),onError:e=>this.logger?.error("Error during get all layouts from scheduler",e)};this.scheduler.register(t)}async dataWarmUp(){const e=this.getAllLayoutsFromServer("start-up");if(this.config.waitInitialResponse)try{const t=await e;await this.cache.saveLayouts(t,"replace")}catch(e){return this.handleDataWarmUpFail(e)}else e.then(e=>this.cache.saveLayouts(e,"replace")).catch(e=>{const t=extractErrorMsg$1(e);this.logger?.warn(`Layouts store initial data warm up failed: ${t}`)})}prepareConfig(e){const t={...e,url:this.getBaseUrl(e.url),requestTimeout:e.requestTimeout??defaultRestRequestTimeoutMS$1,customHeaders:e.customHeaders??{},getRequestInit:e.getRequestInit??(()=>({})),waitInitialResponse:e.waitInitialResponse??!0};return t.pollingInterval&&t.pollingInterval<5e3?ioError.raiseError("Polling interval must be at least 5000ms"):t.cache?.enabled&&!t.pollingInterval?ioError.raiseError("Polling interval is required when cache is enabled"):t}async handleDataWarmUpFail(e){const t=await this.cache.getAllLayouts("all"),r=extractErrorMsg$1(e);if(!this.cacheConfig.enabled||!t.length)return ioError.raiseError(`Layouts store initial data warm up failed: ${r}`);this.logger?.warn(`Layouts store initial data warm up failed, but cache is not empty, continuing with cached data. Response error: ${r}`)}}class RestScheduler{localStorageController;entries=new Map;currentAbortControllers=new Map;_handleConnectionChange;isAppOnline=navigator.onLine;isActive=!1;schedulerLockName;constructor(e){this.localStorageController=e}start(e){if(this.isActive)return;this.entries.size?(this.schedulerLockName=`io-connect-rest-scheduler-lock-${e?.id||"public"}`,this.isActive=!0,this.setupOnlineTracker(),this.tick()):this.logger?.info("No entries registered in the RestScheduler, skipping start.")}stop(){this.isActive=!1,this.currentAbortControllers.forEach(e=>e.abort()),this.currentAbortControllers.clear(),this.entries.clear(),this.localStorageController.clearRestSchedulerEntries(),window.removeEventListener("offline",this._handleConnectionChange),window.removeEventListener("online",this._handleConnectionChange)}checkEntryExists(e){return this.entries.has(e)}register(e){if(this.checkEntryExists(e.key))return ioError.raiseError(`Request with key "${e.key}" is already registered.`);this.entries.set(e.key,e);this.localStorageController.getRestSchedulerEntry(e.key)||this.setInitialLocalStorageEntry(e)}async tick(){if(this.isActive){if(await this.waitInterval(),!this.isAppOnline)return this.isActive=!1,void this.logger?.warn("App is offline, ticking stopped.");await navigator.locks.request(this.schedulerLockName,{ifAvailable:!0},async e=>{if(e)try{await this.executeTick()}catch(e){this.logger?.error("Error during rest scheduler tick:",e)}else this.logger?.trace("The scheduler lock is already held by another process, skipping this tick.")}),this.tick()}}async executeTick(){const e=Date.now(),t=this.localStorageController.getAllRestSchedulerEntries(),r=Array.from(this.entries).reduce((r,[n,i])=>{const o=t[n];return o||(this.setInitialLocalStorageEntry(i),r.push(n)),o&&e>=o.nextRefreshAt&&r.push(n),r},[]);if(!r.length)return;const n=this.splitKeysBasedOnConcurrency(r);for(const e of n)try{const t=Promise.all(e.map(async e=>{await this.refreshKey(e)}));await t}catch(e){const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(t)}}async refreshKey(e){const t=this.entries.get(e);if(!t)return ioError.raiseError(`No request registered with key "${e}".`);if(t.continuationCheck&&!t.continuationCheck())return this.logger?.trace(`Cancelling request for key "${e}" as continuation check failed.`),this.entries.delete(e),void this.localStorageController.deleteRestSchedulerEntry(e);const r=t.getRequest(),n=new AbortController;let i,o;this.currentAbortControllers.set(e,n);try{i=await fetchTimeout(r,t.timeout,n),o=Date.now()}catch(t){return this.setEntryFailure(e,Date.now())}if(!i.ok)return this.setEntryFailure(e,o,i.status);let s=null;try{s=await i.json()}catch(e){}finally{this.setEntrySuccess(e,s,o)}}setupOnlineTracker(){this._handleConnectionChange=this.handleConnectionChange.bind(this),window.addEventListener("offline",this._handleConnectionChange),window.addEventListener("online",this._handleConnectionChange)}setEntryFailure(e,t,r){this.currentAbortControllers.delete(e);const n=this.localStorageController.getRestSchedulerEntry(e),i=this.entries.get(e);if(!i)return ioError.raiseError(`No entry found for key "${e}" in local storage.`);const o=Math.ceil(250*Math.random())+t+Math.min(i.refreshIntervalMS*Math.pow(2,n?.errorCount??0),36e5),s=n?{...n,nextRefreshAt:o,errorCount:n.errorCount+1}:{key:i.key,nextRefreshAt:o,lastRefreshedAt:0,errorCount:1};this.localStorageController.saveRestSchedulerEntry(s);const a=`Request failed with status ${r||"timeout"} for key "${e}" and url "${i.getRequest().url}".`;return i.onError?.(a),ioError.raiseError(a)}setEntrySuccess(e,t,r){this.currentAbortControllers.delete(e);const n=this.localStorageController.getRestSchedulerEntry(e),i=this.entries.get(e);if(!i)return ioError.raiseError(`No entry found for key "${e}" in local storage.`);const o=r+i.refreshIntervalMS+Math.ceil(250*Math.random()),s=n?{...n,errorCount:0,lastRefreshedAt:r,nextRefreshAt:o}:{key:i.key,nextRefreshAt:o,lastRefreshedAt:r,errorCount:0};this.localStorageController.saveRestSchedulerEntry(s);try{i.onData(t)}catch(e){this.logger?.warn(`[${i.key}] Error occurred while processing data: ${e}`)}}setInitialLocalStorageEntry(e){const t={key:e.key,nextRefreshAt:Date.now()+e.refreshIntervalMS+Math.ceil(250*Math.random()),lastRefreshedAt:0,errorCount:0};this.localStorageController.saveRestSchedulerEntry(t)}splitKeysBasedOnConcurrency(e){const t=[],r=e.length;for(let n=0;nsetTimeout(t,e??globalTickIntervalMSForScheduler))}get logger(){return logger.get("system.rest.scheduler")}}class PrefsRestCache{idbCacheController;allKnownPrefs=[];cacheConfig={};constructor(e){this.idbCacheController=e}async start(e){this.allKnownPrefs=[],this.cacheConfig=e.cache??{}}async stop(){this.allKnownPrefs=[]}async getPrefs(e){return this.cacheConfig.enabled?(await this.idbCacheController.getPrefs(e))?.prefs:this.allKnownPrefs.find(t=>t.app===e)}async getAllPrefs(){if(!this.cacheConfig.enabled)return this.allKnownPrefs;return(await this.idbCacheController.getAllPrefs()).map(e=>e.prefs)}async setPrefs(e){this.allKnownPrefs=this.allKnownPrefs.filter(t=>t.app!==e.app),this.allKnownPrefs.push(e),this.cacheConfig.enabled&&await this.idbCacheController.setPrefs(e,Date.now())}async clearPrefs(e){this.allKnownPrefs=this.allKnownPrefs.filter(t=>t.app!==e),this.cacheConfig.enabled&&await this.idbCacheController.deleteManyPrefs([e])}async clearAllPrefs(){this.allKnownPrefs=[],this.cacheConfig.enabled&&await this.idbCacheController.clearPrefs()}}class IdbCacheController{_database;dbName;dbVersion=1;globalLayoutsObjectStoreName="globalLayouts";prefsObjectStoreName="prefs";workspaceLayoutsObjectStoreName="workspaceLayouts";appsDefObjectStoreName="applicationDefinitions";constructor(){this.dbName=defaultCacheDBName,"indexedDB"in window||ioError.raiseError("Cannot initialize the local storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open database")}async start(e){this.dbName=`${defaultCacheDBName}-${e?.id??"public"}`;const t=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=t}stop(){this._database&&(this.database.close(),delete this._database,this.dbName=defaultCacheDBName)}async clear(){this._database&&(await this.database.clear(this.globalLayoutsObjectStoreName),await this.database.clear(this.workspaceLayoutsObjectStoreName),await this.database.clear(this.prefsObjectStoreName),await this.database.clear(this.appsDefObjectStoreName))}async deleteOtherDBs(){const e=(await indexedDB.databases()).filter(e=>e.name&&e.name!==this.dbName&&e.name.startsWith(defaultCacheDBName)).map(e=>new Promise((t,r)=>{if(!e.name)return t();const n=indexedDB.deleteDatabase(e.name);n.onerror=t=>{console.error("Error deleting database:",t),r(new Error(`Error deleting database: ${e.name}`))},n.onsuccess=()=>{t()}}));await Promise.all(e)}async getAllLayouts(e){if("all"===e){return[...(await this.database.getAll(this.globalLayoutsObjectStoreName)).map(e=>e.layout),...(await this.database.getAll(this.workspaceLayoutsObjectStoreName)).map(e=>e.layout)]}return(await this.database.getAll(this.getLayoutsObjectStoreName(e))).map(e=>e.layout)}deleteLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.delete(r,e)}storeLayout(e,t){const r=this.getLayoutsObjectStoreName(e.type);return this.database.put(r,{layout:e,lastUpdated:t},e.name)}clearLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.clear(t)}async getPrefs(e){return this.database.get(this.prefsObjectStoreName,e)}getAllPrefs(){return this.database.getAll(this.prefsObjectStoreName)}async setPrefs(e,t){await this.database.put(this.prefsObjectStoreName,{prefs:e,lastUpdated:t},e.app)}async deleteManyPrefs(e){for(const t of e)await this.database.delete(this.prefsObjectStoreName,t)}async clearPrefs(){await this.database.clear(this.prefsObjectStoreName)}async getAllApps(){return(await this.database.getAll(this.appsDefObjectStoreName)).map(e=>e.definition)}async setApps(e,t){const r=this.database.transaction(this.appsDefObjectStoreName,"readwrite");await Promise.all([r.store.clear(),...e.map(e=>r.store.put({definition:e,lastUpdated:t},e.name)),r.done])}setUpDB(e){e.objectStoreNames.contains(this.workspaceLayoutsObjectStoreName)||e.createObjectStore(this.workspaceLayoutsObjectStoreName),e.objectStoreNames.contains(this.globalLayoutsObjectStoreName)||e.createObjectStore(this.globalLayoutsObjectStoreName),e.objectStoreNames.contains(this.prefsObjectStoreName)||e.createObjectStore(this.prefsObjectStoreName),e.objectStoreNames.contains(this.appsDefObjectStoreName)||e.createObjectStore(this.appsDefObjectStoreName)}getLayoutsObjectStoreName(e){return"Global"!==e&&"Workspace"!==e?ioError.raiseError(`Invalid layout type: ${e}`):"Global"===e?this.globalLayoutsObjectStoreName:this.workspaceLayoutsObjectStoreName}}class LayoutsRestCache{idbCacheController;allKnownLayouts=[];cacheConfig={};constructor(e){this.idbCacheController=e}async start(e){this.allKnownLayouts=[],this.cacheConfig=e.cache??{}}async stop(){this.allKnownLayouts=[]}async getAllLayouts(e){return this.cacheConfig.enabled?await this.idbCacheController.getAllLayouts(e):this.allKnownLayouts.filter(t=>"all"===e||t.type===e)}saveLayouts(e,t){return"replace"===t?this.replaceLayouts(e):this.mergeLayouts(e)}async deleteLayout(e){this.allKnownLayouts=this.allKnownLayouts.filter(t=>t.name!==e.name&&t.type!==e.type),this.cacheConfig.enabled&&await this.idbCacheController.deleteLayout(e.name,e.type)}async updateLayout(e){this.allKnownLayouts=this.allKnownLayouts.filter(t=>t.name!==e.name&&t.type!==e.type),this.allKnownLayouts.push(e),this.cacheConfig.enabled&&await this.idbCacheController.storeLayout(e,Date.now())}async replaceLayouts(e){if(this.allKnownLayouts=e,this.cacheConfig.enabled){await this.idbCacheController.clearLayouts("Global"),await this.idbCacheController.clearLayouts("Workspace");for(const t of e)await this.idbCacheController.storeLayout(t,Date.now())}}async mergeLayouts(e){for(const t of e)await this.updateLayout(t)}}class AppsRestCache{idbCacheController;sessionController;cacheConfig={};constructor(e,t){this.idbCacheController=e,this.sessionController=t}async start(e){this.cacheConfig=e?.cache??{}}async getAllRemoteApps(){return this.cacheConfig.enabled?this.idbCacheController.getAllApps():this.sessionController.getAllApps("remote")}async getAllMemoryApps(){return this.sessionController.getAllApps("inmemory")}async saveMemoryApps(e){this.sessionController.overwriteApps(e,"inmemory")}async saveRemoteApps(e){return this.cacheConfig.enabled?this.idbCacheController.setApps(e,Date.now()):this.sessionController.overwriteApps(e,"remote")}async removeMemoryApp(e){return this.sessionController.removeApp(e,"inmemory")}}class IoC{config;_gatewayInstance;_platformInstance;_mainController;_glueController;_portsBridge;_windowsController;_applicationsController;_appDirectory;_remoteWatcher;_layoutsController;_workspacesController;_hibernationWatcher;_intentsController;_legacyResolverController;_channelsController;_notificationsController;_extensionController;_sessionController;_localStorageController;_stateChecker;_framesController;_systemController;_idbController;_serviceWorkerController;_preferredConnectionController;_transactionsController;_interceptionController;_pluginsController;_domainsController;_licenseController;_layoutsBuilder;_layoutsRestorer;_layoutsValidator;_layoutsResetter;_searchController;_appsSearchRepo;_layoutsSearchRepo;_workspacesSearchRepo;_themesController;_managerController;_managerIdentity;_prefsController;_otelController;_otelTelemetry;_uiController;_localPrefsStore;_managerPrefsStore;_restPrefsStore;_localLayoutsStore;_managerLayoutsStore;_restLayoutsStore;_restScheduler;_prefsRestCache;_layoutsRestCache;_appsRestCache;_idbCacheController;constructor(e){this.config=e}get gateway(){return this._gatewayInstance||(this._gatewayInstance=new Gateway),this._gatewayInstance}get platform(){return this._platformInstance||(this._platformInstance=new Platform(this.controller,this.sessionController,this.localStorageController,this.config)),this._platformInstance}get domainsController(){return this._domainsController||(this._domainsController=new DomainsController(this.systemController,this.windowsController,this.applicationsController,this.layoutsController,this.workspacesController,this.intentsController,this.channelsController,this.notificationsController,this.extensionController,this.searchController,this.themesController,this.managerController,this.prefsController,this.otelController,this.uiController)),this._domainsController}get controller(){return this._mainController||(this._mainController=new PlatformController(this.domainsController,this.glueController,this.portsBridge,this.stateController,this.serviceWorkerController,this.preferredConnectionController,this.interceptionController,this.pluginsController,this.sessionController,this.licenseController,this.localStorageController,this.idbController,this.idbCacheController,this.restScheduler)),this._mainController}get glueController(){return this._glueController||(this._glueController=new GlueController(this.portsBridge,this.sessionController)),this._glueController}get restScheduler(){return this._restScheduler||(this._restScheduler=new RestScheduler(this.localStorageController)),this._restScheduler}get idbCacheController(){return this._idbCacheController||(this._idbCacheController=new IdbCacheController),this._idbCacheController}get prefsRestCache(){return this._prefsRestCache||(this._prefsRestCache=new PrefsRestCache(this.idbCacheController)),this._prefsRestCache}get layoutsRestCache(){return this._layoutsRestCache||(this._layoutsRestCache=new LayoutsRestCache(this.idbCacheController)),this._layoutsRestCache}get appsRestCache(){return this._appsRestCache||(this._appsRestCache=new AppsRestCache(this.idbCacheController,this.sessionController)),this._appsRestCache}get systemController(){return this._systemController||(this._systemController=new SystemController(this.sessionController,this.workspacesController,this.glueController,this.pluginsController)),this._systemController}get searchController(){return this._searchController||(this._searchController=new SearchController(this.glueController,this.appsSearchRepo,this.layoutsSearchRepo,this.workspacesSearchRepo)),this._searchController}get uiController(){return this._uiController||(this._uiController=new UIController(this.sessionController,this.glueController)),this._uiController}get themesController(){return this._themesController||(this._themesController=new ThemesController(this.glueController,this.localStorageController)),this._themesController}get sessionController(){return this._sessionController||(this._sessionController=new SessionStorageController),this._sessionController}get localStorageController(){return this._localStorageController||(this._localStorageController=new LocalStoreController),this._localStorageController}get stateController(){return this._stateChecker||(this._stateChecker=new WindowsStateController(this.sessionController)),this._stateChecker}get windowsController(){return this._windowsController||(this._windowsController=new WindowsController(this.glueController,this.sessionController,this.stateController,this)),this._windowsController}get applicationsController(){return this._applicationsController||(this._applicationsController=new ApplicationsController(this.glueController,this.sessionController,this.stateController,this.appDirectory,this.managerController,this)),this._applicationsController}get appDirectory(){return this._appDirectory||(this._appDirectory=new AppDirectory(this.remoteWatcher,this.managerController,this.appsRestCache)),this._appDirectory}get remoteWatcher(){return this._remoteWatcher||(this._remoteWatcher=new RemoteWatcher(this.restScheduler)),this._remoteWatcher}get licenseController(){return this._licenseController||(this._licenseController=new LicenseController),this._licenseController}get localLayoutsStore(){return this._localLayoutsStore||(this._localLayoutsStore=new LocalLayoutsStore(this.idbController,this.sessionController,this.localStorageController)),this._localLayoutsStore}get managerLayoutsStore(){return this._managerLayoutsStore||(this._managerLayoutsStore=new ManagerLayoutsStore(this.managerController)),this._managerLayoutsStore}get restLayoutsStore(){return this._restLayoutsStore||(this._restLayoutsStore=new RestLayoutsStore(this.createSequelizer(),this.restScheduler,this.layoutsRestCache)),this._restLayoutsStore}get layoutsController(){return this._layoutsController||(this._layoutsController=new LayoutsController(this.glueController,this.layoutsBuilder,this.layoutsRestorer,this.localLayoutsStore,this.managerLayoutsStore,this.restLayoutsStore,this.sessionController)),this._layoutsController}get workspacesController(){return this._workspacesController||(this._workspacesController=new WorkspacesController(this.framesController,this.glueController,this.stateController,this.hibernationWatcher,this.createSequelizer(),this.sessionController,this)),this._workspacesController}get hibernationWatcher(){return this._hibernationWatcher||(this._hibernationWatcher=new WorkspaceHibernationWatcher(this.sessionController,this.createSequelizer())),this._hibernationWatcher}get intentsController(){return this._intentsController||(this._intentsController=new IntentsController(this.glueController,this.legacyResolverController,this.appDirectory,this.windowsController,this.prefsController,this.uiController)),this._intentsController}get legacyResolverController(){return this._legacyResolverController||(this._legacyResolverController=new LegacyResolverController(this.glueController,this.workspacesController,this.windowsController,this.prefsController)),this._legacyResolverController}get channelsController(){return this._channelsController||(this._channelsController=new ChannelsController(this.glueController,this.sessionController,this.workspacesController)),this._channelsController}get extensionController(){return this._extensionController||(this._extensionController=new ExtensionController(this.sessionController)),this._extensionController}get layoutsBuilder(){return this._layoutsBuilder||(this._layoutsBuilder=new Builder(this.glueController,this.sessionController,this.windowsController,this.workspacesController)),this._layoutsBuilder}get layoutsRestorer(){return this._layoutsRestorer||(this._layoutsRestorer=new Restorer(this.glueController,this.layoutsValidator,this.layoutsResetter,this.workspacesController,this.sessionController)),this._layoutsRestorer}get layoutsValidator(){return this._layoutsValidator||(this._layoutsValidator=new LayoutValidator(this.glueController,this.workspacesController)),this._layoutsValidator}get layoutsResetter(){return this._layoutsResetter||(this._layoutsResetter=new Resetter(this.glueController,this.workspacesController)),this._layoutsResetter}get notificationsController(){return this._notificationsController||(this._notificationsController=new NotificationsController(this.glueController,this.serviceWorkerController,this.sessionController,this.localStorageController,this.prefsController)),this._notificationsController}get framesController(){return this._framesController||(this._framesController=new FramesController(this.sessionController,this.glueController,this)),this._framesController}get idbController(){return this._idbController||(this._idbController=new IDBController),this._idbController}get portsBridge(){return this._portsBridge||(this._portsBridge=new PortsBridge(this.gateway,this.sessionController,this.stateController,this)),this._portsBridge}get serviceWorkerController(){return this._serviceWorkerController||(this._serviceWorkerController=new ServiceWorkerController(this.idbController)),this._serviceWorkerController}get transactionsController(){return this._transactionsController||(this._transactionsController=new TransactionsController),this._transactionsController}get interceptionController(){return this._interceptionController||(this._interceptionController=new InterceptionController),this._interceptionController}get pluginsController(){return this._pluginsController||(this._pluginsController=new PluginsController(this.interceptionController,this.glueController)),this._pluginsController}get appsSearchRepo(){return this._appsSearchRepo||(this._appsSearchRepo=new ApplicationsRepository(this.glueController)),this._appsSearchRepo}get managerController(){return this._managerController||(this._managerController=new ManagerController(this.managerIdentity,this.createSequelizer(),this.buildClient.bind(this),this.buildCache.bind(this))),this._managerController}get managerIdentity(){return this._managerIdentity||(this._managerIdentity=new Identity(new uaParserExports.UAParser,this.glueController,this.pluginsController,this.config?.workspaces?.src)),this._managerIdentity}get layoutsSearchRepo(){return this._layoutsSearchRepo||(this._layoutsSearchRepo=new LayoutsRepository(this.glueController)),this._layoutsSearchRepo}get workspacesSearchRepo(){return this._workspacesSearchRepo||(this._workspacesSearchRepo=new WorkspacesRepository(this.glueController)),this._workspacesSearchRepo}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new PreferredConnectionController(this.glueController,this.portsBridge,this.createSequelizer())),this._preferredConnectionController}get localPrefsStore(){return this._localPrefsStore||(this._localPrefsStore=new LocalPrefsStore(this.idbController)),this._localPrefsStore}get managerPrefsStore(){return this._managerPrefsStore||(this._managerPrefsStore=new ManagerPrefsStore(this.managerController)),this._managerPrefsStore}get restPrefsStore(){return this._restPrefsStore||(this._restPrefsStore=new RestPrefsStore(this.createSequelizer(),this.restScheduler,this.prefsRestCache,this.sessionController)),this._restPrefsStore}get prefsController(){return this._prefsController||(this._prefsController=new PrefsController(this.glueController,this.localPrefsStore,this.managerPrefsStore,this.restPrefsStore)),this._prefsController}get otelController(){return this._otelController||(this._otelController=new OtelController(this.otelTelemetry,this.getNewMetricsDependencyBuilder.bind(this),this.glueController,this.getPlatformController.bind(this),this.systemController,this.applicationsController,this.layoutsController,this.workspacesController)),this._otelController}createMessageChannel(){return new MessageChannel}createSequelizer(e){return new AsyncSequelizer(e)}buildClient(e){return new CachedClientAPI(e)}buildCache(e,t){return e.cache?.enabled??1?new IdbBasedIOManagerCache(e,t):new SessionStorageBasedIOManagerCache(e,t)}getPlatformController(){return this.controller}getNewMetricsDependencyBuilder(){return new dist.MetricsDependencyBuilder}getNewOtelContainerBuilder(){return new dist.Builder}buildOtelLogger(e){return new LoggerAdapter(e)}get otelTelemetry(){return this._otelTelemetry||(this._otelTelemetry=new Telemetry(this.getNewOtelContainerBuilder.bind(this),this.buildOtelLogger.bind(this))),this._otelTelemetry}}let platformCache;const checkSingleton=()=>{const e=window.glue42core||window.iobrowser;if(e?.platformStarted)throw new Error("The Glue42 Core Platform has already been started for this application.")},initPlatformAPi=async e=>{const t=new IoC(e);await t.platform.ready();return{io:t.platform.getClientGlue(),platform:t?.platform.getPlatformApi()}},ioConnectBrowserPlatformFactory=async e=>{if(window.glue42gd||window.iodesktop)return fallbackToEnterprise(e);const t=!e?.connection?.alwaysPlatform&&await checkIsOpenerIOConnect(e?.connection),r=checkIfPlacedInWorkspace();if(e?.clientOnly||t||r){return{io:e?.browserFactory?await(e?.browserFactory(e?.browser)):await iOConnectBrowserFactory(e?.browser)}}try{checkSingleton()}catch(e){return void 0===platformCache?Promise.reject(new Error(e)):platformCache}const n=initPlatformAPi(e);return e?.browser?.memoizeAPI&&(platformCache=n),n};"undefined"!=typeof window&&(window.IOBrowserPlatform=ioConnectBrowserPlatformFactory);const legacyGlobal=window.glue42gd||window.glue42core,ioGlobal=window.iodesktop||window.iobrowser;return legacyGlobal||ioGlobal||(window.iobrowser={webStarted:!1}),ioConnectBrowserPlatformFactory}); -//# sourceMappingURL=browser.platform.umd.js.map diff --git a/javascript/solution/clients/lib/workspaces.umd.js b/javascript/solution/clients/lib/workspaces.umd.js deleted file mode 100644 index 8d833a0..0000000 --- a/javascript/solution/clients/lib/workspaces.umd.js +++ /dev/null @@ -1,5618 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.workspaces = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder.oneOf; - /** See `Decoder.union` */ - Decoder.union; - /** See `Decoder.intersection` */ - var intersection = Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - Decoder.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder.lazy; - - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number"); - const positiveNumberDecoder = number().where((num) => num > 0, "Expected a positive number"); - const windowDragModeDecoder = oneOf(constant("keepInside"), constant("autoEject")); - const isWindowInSwimlaneResultDecoder = object({ - inWorkspace: boolean() - }); - const frameVisibilityResultDecoder = object({ - isVisible: boolean() - }); - const iconDecoder = object({ - base64Image: nonEmptyStringDecoder - }); - const setIconArgumentsDecoder = object({ - icon: iconDecoder, - frameId: nonEmptyStringDecoder - }); - const allParentDecoder = oneOf(constant("workspace"), constant("row"), constant("column"), constant("group")); - const subParentDecoder = oneOf(constant("row"), constant("column"), constant("group")); - const frameStateDecoder = oneOf(constant("maximized"), constant("minimized"), constant("normal")); - const loadingAnimationTypeDecoder = oneOf(constant("workspace")); - const checkThrowCallback = (callback, allowUndefined) => { - const argumentType = typeof callback; - if (allowUndefined && argumentType !== "function" && argumentType !== "undefined") { - throw new Error(`Provided argument must be either undefined or of type function, provided: ${argumentType}`); - } - if (!allowUndefined && argumentType !== "function") { - throw new Error(`Provided argument must be of type function, provided: ${argumentType}`); - } - }; - const workspaceBuilderCreateConfigDecoder = optional(object({ - saveLayout: optional(boolean()) - })); - const deleteLayoutConfigDecoder = object({ - name: nonEmptyStringDecoder - }); - const windowDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const groupDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropHeader: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()) - }); - const rowDefinitionConfigDecoder = object({ - minHeight: optional(number()), - maxHeight: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const columnDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const swimlaneWindowDefinitionDecoder = object({ - type: optional(constant("window")), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const strictSwimlaneWindowDefinitionDecoder = object({ - type: constant("window"), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const parentDefinitionDecoder = optional(object({ - type: optional(subParentDecoder), - children: optional(lazy(() => array(oneOf(swimlaneWindowDefinitionDecoder, parentDefinitionDecoder)))), - config: optional(anyJson()) - })); - const strictColumnDefinitionDecoder = object({ - type: constant("column"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(columnDefinitionConfigDecoder) - }); - const strictRowDefinitionDecoder = object({ - type: constant("row"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(rowDefinitionConfigDecoder) - }); - const strictGroupDefinitionDecoder = object({ - type: constant("group"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(groupDefinitionConfigDecoder) - }); - const strictParentDefinitionDecoder = oneOf(strictGroupDefinitionDecoder, strictColumnDefinitionDecoder, strictRowDefinitionDecoder); - oneOf(string().where((s) => s.toLowerCase() === "maximized", "Expected a case insensitive variation of 'maximized'"), string().where((s) => s.toLowerCase() === "normal", "Expected a case insensitive variation of 'normal'")); - const newFrameConfigDecoder = object({ - bounds: optional(object({ - left: optional(number()), - top: optional(number()), - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - })), - isVisible: optional(boolean()), - frameId: optional(nonEmptyStringDecoder) - }); - const loadingStrategyDecoder = oneOf(constant("direct"), constant("delayed"), constant("lazy")); - const restoreWorkspaceConfigDecoder = optional(object({ - app: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - loadingStrategy: optional(loadingStrategyDecoder), - title: optional(nonEmptyStringDecoder), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - frameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - lockdown: optional(boolean()), - activateFrame: optional(boolean()), - newFrame: optional(oneOf(newFrameConfigDecoder, boolean())), - noTabHeader: optional(boolean()), - inMemoryLayout: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - allowSystemHibernation: optional(boolean()) - })); - const openWorkspaceConfigDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const workspaceDefinitionDecoder = object({ - children: optional(array(oneOf(swimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder))), - context: optional(anyJson()), - config: optional(object({ - title: optional(nonEmptyStringDecoder), - position: optional(nonNegativeNumberDecoder), - isFocused: optional(boolean()), - noTabHeader: optional(boolean()), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - loadingStrategy: optional(loadingStrategyDecoder), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showCloseButton: optional(boolean()), - allowSplitters: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - windowDragMode: optional(windowDragModeDecoder) - })), - frame: optional(object({ - activate: optional(boolean()), - reuseFrameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - newFrame: optional(oneOf(boolean(), newFrameConfigDecoder)) - })) - }); - const workspaceSelectorDecoder = object({ - workspaceId: nonEmptyStringDecoder - }); - const restoreWorkspaceDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const emptyFrameDefinitionDecoder = optional(object({ - applicationName: optional(string()), - frameConfig: optional(newFrameConfigDecoder), - context: optional(object()), - layoutComponentId: optional(nonEmptyStringDecoder) - })); - const frameInitConfigDecoder = object({ - workspaces: array(oneOf(optional(workspaceDefinitionDecoder), optional(restoreWorkspaceDefinitionDecoder))) - }); - const frameInitProtocolConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaces: array(oneOf(workspaceDefinitionDecoder, restoreWorkspaceDefinitionDecoder)) - }); - const builderConfigDecoder = object({ - type: allParentDecoder, - definition: optional(oneOf(workspaceDefinitionDecoder, parentDefinitionDecoder)) - }); - const workspaceCreateConfigDecoder = intersection(workspaceDefinitionDecoder, object({ - saveConfig: optional(object({ - saveLayout: optional(boolean()) - })) - })); - const getFrameSummaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const frameInitializationContextDecoder = object({ - context: optional(object()) - }); - const frameSummaryDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - object({ - type: subParentDecoder, - id: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number() - }); - const eventTypeDecoder = oneOf(constant("frame"), constant("workspace"), constant("container"), constant("window")); - const streamRequestArgumentsDecoder = object({ - type: eventTypeDecoder, - branch: nonEmptyStringDecoder - }); - const workspaceEventActionDecoder = oneOf(constant("opened"), constant("closing"), constant("closed"), constant("focus"), constant("added"), constant("loaded"), constant("removed"), constant("childrenUpdate"), constant("containerChange"), constant("maximized"), constant("restored"), constant("minimized"), constant("normal"), constant("selected"), constant("lock-configuration-changed"), constant("hibernated"), constant("resumed")); - const workspaceConfigResultDecoder = object({ - frameId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder, - positionIndex: nonNegativeNumberDecoder, - name: nonEmptyStringDecoder, - layoutName: optional(nonEmptyStringDecoder), - isHibernated: optional(boolean()), - isSelected: optional(boolean()), - allowDrop: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - widthInPx: optional(number()), - heightInPx: optional(number()), - isPinned: optional(boolean()), - windowDragMode: optional(windowDragModeDecoder), - loadingStrategy: optional(loadingStrategyDecoder) - }); - const baseChildSnapshotConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number(), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()) - }); - const parentSnapshotConfigDecoder = anyJson(); - const swimlaneWindowSnapshotConfigDecoder = intersection(baseChildSnapshotConfigDecoder, object({ - windowId: optional(nonEmptyStringDecoder), - isMaximized: optional(boolean()), - isFocused: boolean(), - isSelected: optional(boolean()), - title: optional(string()), - appName: optional(nonEmptyStringDecoder), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - widthInPx: optional(number()), - heightInPx: optional(number()), - context: optional(anyJson()) - })); - const customWorkspaceSubParentSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: parentSnapshotConfigDecoder, - children: optional(lazy(() => array(customWorkspaceChildSnapshotDecoder))), - type: oneOf(constant("row"), constant("column"), constant("group")) - }); - const customWorkspaceWindowSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: swimlaneWindowSnapshotConfigDecoder, - type: constant("window") - }); - const customWorkspaceChildSnapshotDecoder = oneOf(customWorkspaceWindowSnapshotDecoder, customWorkspaceSubParentSnapshotDecoder); - const childSnapshotResultDecoder = customWorkspaceChildSnapshotDecoder; - const workspaceSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder, - children: array(childSnapshotResultDecoder), - frameSummary: frameSummaryDecoder, - context: optional(anyJson()) - }); - const windowLayoutItemDecoder = object({ - type: constant("window"), - config: object({ - appName: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - url: optional(nonEmptyStringDecoder), - title: optional(string()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - isMaximized: optional(boolean()) - }) - }); - const groupLayoutItemDecoder = object({ - type: constant("group"), - config: anyJson(), - children: array(oneOf(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object({ - type: constant("column"), - config: anyJson(), - children: array(oneOf(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object({ - type: constant("row"), - config: anyJson(), - children: array(oneOf(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutDecoder = object({ - name: nonEmptyStringDecoder, - type: constant("Workspace"), - metadata: optional(anyJson()), - components: array(object({ - type: constant("Workspace"), - application: optional(string()), - state: object({ - config: anyJson(), - context: anyJson(), - children: array(oneOf(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }) - })) - }); - const workspacesImportLayoutDecoder = object({ - layout: workspaceLayoutDecoder, - mode: oneOf(constant("replace"), constant("merge")) - }); - const workspacesImportLayoutsDecoder = object({ - layouts: array(workspaceLayoutDecoder), - mode: oneOf(constant("replace"), constant("merge")) - }); - const exportedLayoutsResultDecoder = object({ - layouts: array(workspaceLayoutDecoder) - }); - const frameSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - const frameSummariesResultDecoder = object({ - summaries: array(frameSummaryResultDecoder) - }); - const workspaceSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder - }); - const workspaceSummariesResultDecoder = object({ - summaries: array(workspaceSummaryResultDecoder) - }); - const frameSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: anyJson(), - workspaces: array(workspaceSnapshotResultDecoder) - }); - const layoutSummaryDecoder = object({ - name: nonEmptyStringDecoder, - applicationName: optional(string()) - }); - const layoutSummariesDecoder = object({ - summaries: array(layoutSummaryDecoder) - }); - const simpleWindowOperationSuccessResultDecoder = object({ - windowId: nonEmptyStringDecoder - }); - const voidResultDecoder = anyJson(); - const frameStateResultDecoder = object({ - state: frameStateDecoder - }); - const frameBoundsDecoder = object({ - top: number(), - left: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const frameBoundsResultDecoder = object({ - bounds: frameBoundsDecoder - }); - const getWorkspaceIconResultDecoder = object({ - icon: optional(nonEmptyStringDecoder) - }); - const getPlatformFrameIdResultDecoder = object({ - id: optional(nonEmptyStringDecoder) - }); - const operationCheckResultDecoder = object({ - isSupported: boolean() - }); - const resizeConfigDecoder = object({ - width: optional(positiveNumberDecoder), - height: optional(positiveNumberDecoder), - relative: optional(boolean()) - }); - const moveConfigDecoder = object({ - top: optional(number()), - left: optional(number()), - relative: optional(boolean()) - }); - const simpleItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const closeOptionsDecoder = object({ - allowPrevent: optional(boolean()), - showDialog: optional(boolean()), - }); - const closeItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - closeOptions: optional(closeOptionsDecoder) - }); - const frameSnapshotConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - excludeIds: optional(boolean()) - }); - const frameStateConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - requestedState: frameStateDecoder - }); - const setItemTitleConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder - }); - const moveWindowConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - containerId: nonEmptyStringDecoder - }); - const resizeItemConfigDecoder = intersection(simpleItemConfigDecoder, resizeConfigDecoder); - const setMaximizationBoundaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - enabled: boolean() - }); - const moveFrameConfigDecoder = intersection(simpleItemConfigDecoder, moveConfigDecoder); - object({ - id: nonEmptyStringDecoder, - type: subParentDecoder - }); - const addWindowConfigDecoder = object({ - definition: swimlaneWindowDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addContainerConfigDecoder = object({ - definition: strictParentDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addItemResultDecoder = object({ - itemId: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder) - }); - const pingResultDecoder = object({ - live: boolean() - }); - const bundleWorkspaceConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - workspaceId: nonEmptyStringDecoder - }); - const bundleItemConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - itemId: nonEmptyStringDecoder - }); - const containerSummaryResultDecoder = object({ - itemId: nonEmptyStringDecoder, - config: parentSnapshotConfigDecoder - }); - const frameStreamDataDecoder = object({ - frameSummary: frameSummaryDecoder, - frameBounds: optional(frameBoundsDecoder) - }); - const workspaceStreamDataDecoder = object({ - workspaceSummary: workspaceSummaryResultDecoder, - frameSummary: frameSummaryDecoder, - workspaceSnapshot: optional(workspaceSnapshotResultDecoder), - frameBounds: optional(frameBoundsDecoder) - }); - const containerStreamDataDecoder = object({ - containerSummary: containerSummaryResultDecoder - }); - const windowStreamDataDecoder = object({ - windowSummary: object({ - itemId: nonEmptyStringDecoder, - parentId: nonEmptyStringDecoder, - config: swimlaneWindowSnapshotConfigDecoder - }) - }); - const workspaceLayoutSaveConfigDecoder = object({ - name: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - saveContext: optional(boolean()), - allowMultiple: optional(boolean()), - metadata: optional(object()) - }); - const workspaceLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - }); - const lockWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - config: optional(workspaceLockConfigDecoder) - }); - const windowLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const elementResizeConfigDecoder = object({ - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - }); - const lockWindowDecoder = object({ - windowPlacementId: nonEmptyStringDecoder, - config: optional(windowLockConfigDecoder) - }); - const rowLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const columnLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const groupLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - allowDropHeader: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()), - }); - const lockRowDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("row"), - config: optional(rowLockConfigDecoder) - }); - const lockColumnDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("column"), - config: optional(columnLockConfigDecoder) - }); - const lockGroupDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("group"), - config: optional(groupLockConfigDecoder) - }); - const lockContainerDecoder = oneOf(lockRowDecoder, lockColumnDecoder, lockGroupDecoder); - const pinWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const setWorkspaceIconDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const workspacePinOptionsDecoder = optional(object({ - icon: optional(nonEmptyStringDecoder) - })); - const frameShowConfigDecoder = optional(object({ - activate: optional(boolean()) - })); - const shortcutConfigDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const shortcutClickedDataDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const frameClosingDataDecoder = object({ - frameId: nonEmptyStringDecoder, - }); - const setMaximizationBoundaryAPIConfigDecoder = object({ - enabled: boolean() - }); - const loadingAnimationConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - type: loadingAnimationTypeDecoder - }); - const operationCheckConfigDecoder = object({ - operation: nonEmptyStringDecoder - }); - const setWindowDragModeDecoder = object({ - itemId: nonEmptyStringDecoder, - dragMode: windowDragModeDecoder - }); - const setLoadingStrategyDecoder = object({ - itemId: nonEmptyStringDecoder, - strategy: loadingStrategyDecoder - }); - const frameClosingResultDecoder = object({ - prevent: boolean() - }); - const sizeDecoder = object({ - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const boundsDecoder = object({ - left: number(), - top: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const popupTargetLocationDecoder = oneOf(constant("none"), constant("left"), constant("right"), constant("top"), constant("bottom")); - const popupConfigDecoder = object({ - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const ShowPopupConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const changeFrameVisibilityConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - activate: optional(boolean()), - isVisible: boolean() - }); - const frameDialogOptionsDecoder = object({ - mode: optional(oneOf(constant("Global"), constant("WindowContainer"))), - type: string(), - size: optional(sizeDecoder), - message: nonEmptyStringDecoder, - messageTitle: optional(nonEmptyStringDecoder), - movable: optional(boolean()), - transparent: optional(boolean()), - title: nonEmptyStringDecoder, - context: optional(anyJson()), - affirmativeButtonName: optional(nonEmptyStringDecoder), - showAffirmativeButton: optional(boolean()), - cancelButtonName: optional(nonEmptyStringDecoder), - showCancelButton: optional(boolean()), - negativeButtonName: optional(nonEmptyStringDecoder), - showNegativeButton: optional(boolean()), - defaultAction: optional(oneOf(constant("affirmative"), constant("negative"), constant("cancel"))), - timerDuration: optional(positiveNumberDecoder), - showTimer: optional(boolean()), - inputMaxLength: optional(positiveNumberDecoder), - inputPattern: optional(nonEmptyStringDecoder), - inputPatternErrorMessage: optional(nonEmptyStringDecoder), - inputPlaceholder: optional(string()), - blur: optional(boolean()) - }); - const showFrameDialogConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - options: frameDialogOptionsDecoder - }); - - const webPlatformMethodName = "T42.Web.Platform.Control"; - const webPlatformWspStreamName = "T42.Web.Platform.WSP.Stream"; - const OUTGOING_METHODS = { - control: { name: "T42.Workspaces.Control", isStream: false }, - frameStream: { name: "T42.Workspaces.Stream.Frame", isStream: true }, - workspaceStream: { name: "T42.Workspaces.Stream.Workspace", isStream: true }, - containerStream: { name: "T42.Workspaces.Stream.Container", isStream: true }, - windowStream: { name: "T42.Workspaces.Stream.Window", isStream: true } - }; - const INCOMING_METHODS = { - control: { name: "T42.Workspaces.Client.Control", isStream: false }, - }; - const STREAMS = { - frame: { name: "T42.Workspaces.Stream.Frame", payloadDecoder: frameStreamDataDecoder }, - workspace: { name: "T42.Workspaces.Stream.Workspace", payloadDecoder: workspaceStreamDataDecoder }, - container: { name: "T42.Workspaces.Stream.Container", payloadDecoder: containerStreamDataDecoder }, - window: { name: "T42.Workspaces.Stream.Window", payloadDecoder: windowStreamDataDecoder } - }; - const CLIENT_OPERATIONS = { - shortcutClicked: { name: "shortcutClicked", argsDecoder: shortcutClickedDataDecoder, resultDecoder: voidResultDecoder }, - frameClosing: { name: "frameClosing", argsDecoder: frameClosingDataDecoder, resultDecoder: frameClosingResultDecoder }, - }; - const OPERATIONS = { - ping: { name: "ping", resultDecoder: pingResultDecoder }, - isWindowInWorkspace: { name: "isWindowInWorkspace", argsDecoder: simpleItemConfigDecoder, resultDecoder: isWindowInSwimlaneResultDecoder }, - createWorkspace: { name: "createWorkspace", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: workspaceCreateConfigDecoder }, - createFrame: { name: "createFrame", resultDecoder: frameSummaryResultDecoder, argsDecoder: emptyFrameDefinitionDecoder }, - initFrame: { name: "initFrame", resultDecoder: voidResultDecoder, argsDecoder: frameInitProtocolConfigDecoder }, - getAllFramesSummaries: { name: "getAllFramesSummaries", resultDecoder: frameSummariesResultDecoder }, - getFrameSummary: { name: "getFrameSummary", resultDecoder: frameSummaryDecoder, argsDecoder: getFrameSummaryConfigDecoder }, - getAllWorkspacesSummaries: { name: "getAllWorkspacesSummaries", resultDecoder: workspaceSummariesResultDecoder }, - getWorkspaceSnapshot: { name: "getWorkspaceSnapshot", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: simpleItemConfigDecoder }, - getAllLayoutsSummaries: { name: "getAllLayoutsSummaries", resultDecoder: layoutSummariesDecoder }, - openWorkspace: { name: "openWorkspace", argsDecoder: openWorkspaceConfigDecoder, resultDecoder: workspaceSnapshotResultDecoder }, - deleteLayout: { name: "deleteLayout", resultDecoder: voidResultDecoder, argsDecoder: deleteLayoutConfigDecoder }, - saveLayout: { name: "saveLayout", resultDecoder: workspaceLayoutDecoder, argsDecoder: workspaceLayoutSaveConfigDecoder }, - importLayout: { name: "importLayout", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutDecoder }, - importLayouts: { name: "importLayouts", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutsDecoder }, - exportAllLayouts: { name: "exportAllLayouts", resultDecoder: exportedLayoutsResultDecoder }, - restoreItem: { name: "restoreItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - maximizeItem: { name: "maximizeItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - focusItem: { name: "focusItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeItem: { name: "closeItem", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeWorkspace: { name: "closeWorkspace", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - resizeItem: { name: "resizeItem", argsDecoder: resizeItemConfigDecoder, resultDecoder: voidResultDecoder }, - setMaximizationBoundary: { name: "setMaximizationBoundary", argsDecoder: setMaximizationBoundaryConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameState: { name: "changeFrameState", argsDecoder: frameStateConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameState: { name: "getFrameState", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameStateResultDecoder }, - getFrameBounds: { name: "getFrameBounds", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameBoundsResultDecoder }, - moveFrame: { name: "moveFrame", argsDecoder: moveFrameConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameSnapshot: { name: "getFrameSnapshot", argsDecoder: frameSnapshotConfigDecoder, resultDecoder: frameSnapshotResultDecoder }, - forceLoadWindow: { name: "forceLoadWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - ejectWindow: { name: "ejectWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - setItemTitle: { name: "setItemTitle", argsDecoder: setItemTitleConfigDecoder, resultDecoder: voidResultDecoder }, - moveWindowTo: { name: "moveWindowTo", argsDecoder: moveWindowConfigDecoder, resultDecoder: voidResultDecoder }, - addWindow: { name: "addWindow", argsDecoder: addWindowConfigDecoder, resultDecoder: addItemResultDecoder }, - addContainer: { name: "addContainer", argsDecoder: addContainerConfigDecoder, resultDecoder: addItemResultDecoder }, - bundleWorkspace: { name: "bundleWorkspace", argsDecoder: bundleWorkspaceConfigDecoder, resultDecoder: voidResultDecoder }, - bundleItem: { name: "bundleItem", argsDecoder: bundleItemConfigDecoder, resultDecoder: voidResultDecoder }, - hibernateWorkspace: { name: "hibernateWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - resumeWorkspace: { name: "resumeWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - lockWorkspace: { name: "lockWorkspace", argsDecoder: lockWorkspaceDecoder, resultDecoder: voidResultDecoder }, - lockWindow: { name: "lockWindow", argsDecoder: lockWindowDecoder, resultDecoder: voidResultDecoder }, - lockContainer: { name: "lockContainer", argsDecoder: lockContainerDecoder, resultDecoder: voidResultDecoder }, - pinWorkspace: { name: "pinWorkspace", argsDecoder: pinWorkspaceDecoder, resultDecoder: voidResultDecoder }, - unpinWorkspace: { name: "unpinWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - getWorkspaceIcon: { name: "getWorkspaceIcon", argsDecoder: workspaceSelectorDecoder, resultDecoder: getWorkspaceIconResultDecoder }, - setWorkspaceIcon: { name: "setWorkspaceIcon", argsDecoder: setWorkspaceIconDecoder, resultDecoder: voidResultDecoder }, - registerShortcut: { name: "registerShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - unregisterShortcut: { name: "unregisterShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - showLoadingAnimation: { name: "showLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - hideLoadingAnimation: { name: "hideLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - getPlatformFrameId: { name: "getPlatformFrameId", resultDecoder: getPlatformFrameIdResultDecoder }, - operationCheck: { name: "operationCheck", argsDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - setWindowDragMode: { name: "setWindowDragMode", argsDecoder: setWindowDragModeDecoder, resultDecoder: voidResultDecoder }, - setLoadingStrategy: { name: "setLoadingStrategy", argsDecoder: setLoadingStrategyDecoder, resultDecoder: voidResultDecoder }, - getTaskbarIcon: { name: "getTaskbarIcon", resultDecoder: iconDecoder }, - setTaskbarIcon: { name: "setTaskbarIcon", argsDecoder: setIconArgumentsDecoder, resultDecoder: voidResultDecoder }, - subscribeToFrameClosing: { name: "subscribeToFrameClosing", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - showPopup: { name: "showPopup", argsDecoder: ShowPopupConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameVisibility: { name: "changeFrameVisibility", argsDecoder: changeFrameVisibilityConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameVisibility: { name: "getFrameVisibility", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameVisibilityResultDecoder }, - showFrameDialog: { name: "showFrameDialog", argsDecoder: showFrameDialogConfigDecoder, resultDecoder: anyJson() } - }; - - class PromiseWrapper { - resolve; - reject; - promise; - constructor() { - this.promise = new Promise((res, rej) => { - this.resolve = res; - this.reject = rej; - }); - } - } - - class Bridge { - transport; - registry; - activeSubscriptions = []; - pendingSubScriptions = []; - constructor(transport, registry) { - this.transport = transport; - this.registry = registry; - } - async createCoreEventSubscription() { - await this.transport.coreSubscriptionReady(this.handleCoreEvent.bind(this)); - } - handleCoreSubscription(config) { - const registryKey = `${config.eventType}-${config.action}`; - const scope = config.scope; - const scopeId = config.scopeId; - return this.registry.add(registryKey, (args) => { - const scopeConfig = { - type: scope, - id: scopeId - }; - const receivedIds = { - frame: args.frameSummary?.id || args.windowSummary?.config.frameId, - workspace: args.workspaceSummary?.id || args.windowSummary?.config.workspaceId, - container: args.containerSummary?.itemId, - window: args.windowSummary?.itemId - }; - const shouldInvokeCallback = this.checkScopeMatch(scopeConfig, receivedIds); - if (!shouldInvokeCallback) { - return; - } - config.callback(args); - }); - } - async send(operationName, operationArgs, invocationOptions) { - const operationDefinition = Object.values(OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - try { - const operationResult = await this.transport.transmitControl(operationDefinition.name, operationArgs, invocationOptions); - operationDefinition.resultDecoder.runWithException(operationResult); - return operationResult; - } - catch (error) { - if (error.kind) { - throw new Error(`Unexpected internal incoming validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - throw new Error(error.message); - } - } - async subscribe(config) { - const pendingSub = this.getPendingSubscription(config); - if (pendingSub) { - await pendingSub.promise; - } - let activeSub = this.getActiveSubscription(config); - const registryKey = this.getRegistryKey(config); - if (!activeSub) { - const pendingPromise = new PromiseWrapper(); - const pendingSubscription = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - promise: pendingPromise.promise - }; - this.pendingSubScriptions.push(pendingSubscription); - try { - const stream = STREAMS[config.eventType]; - const gdSub = await this.transport.subscribe(stream.name, this.getBranchKey(config), config.eventType); - gdSub.onData((streamData) => { - const data = streamData.data; - const requestedArgumentsResult = streamRequestArgumentsDecoder.run(streamData.requestArguments); - const actionResult = workspaceEventActionDecoder.run(data.action); - if (!requestedArgumentsResult.ok || !actionResult.ok) { - return; - } - const streamType = requestedArgumentsResult.result.type; - const branch = requestedArgumentsResult.result.branch; - const keyToExecute = `${streamType}-${branch}-${actionResult.result}`; - const validatedPayload = STREAMS[streamType].payloadDecoder.run(data.payload); - if (!validatedPayload.ok) { - return; - } - this.registry.execute(keyToExecute, validatedPayload.result); - }); - activeSub = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - callbacksCount: 0, - gdSub - }; - this.activeSubscriptions.push(activeSub); - pendingPromise.resolve(); - } - catch (error) { - pendingPromise.reject(error); - throw error; - } - finally { - this.removePendingSubscription(pendingSubscription); - } - } - const unsubscribe = this.registry.add(registryKey, config.callback); - ++activeSub.callbacksCount; - return () => { - unsubscribe(); - --activeSub.callbacksCount; - if (activeSub.callbacksCount === 0) { - activeSub.gdSub.close(); - this.activeSubscriptions.splice(this.activeSubscriptions.indexOf(activeSub), 1); - } - }; - } - onOperation(callback) { - const wrappedCallback = (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - callback(payload, caller); - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - onOperationWithResponse(callback) { - const wrappedCallback = async (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - const result = await callback(payload, caller); - if (operationDefinition.resultDecoder) { - try { - operationDefinition.resultDecoder.runWithException(result); - } - catch (error) { - throw new Error(`Unexpected internal outgoing result validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - return result; - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - checkScopeMatch(scope, receivedIds) { - if (scope.type === "global") { - return true; - } - if (scope.type === "frame" && scope.id === receivedIds.frame) { - return true; - } - if (scope.type === "workspace" && scope.id === receivedIds.workspace) { - return true; - } - if (scope.type === "container" && scope.id === receivedIds.container) { - return true; - } - if (scope.type === "window" && scope.id === receivedIds.window) { - return true; - } - return false; - } - handleCoreEvent(args) { - const data = args.data; - try { - const verifiedAction = workspaceEventActionDecoder.runWithException(data.action); - const verifiedType = eventTypeDecoder.runWithException(data.type); - const verifiedPayload = STREAMS[verifiedType].payloadDecoder.runWithException(data.payload); - const registryKey = `${verifiedType}-${verifiedAction}`; - this.registry.execute(registryKey, verifiedPayload); - } - catch (error) { - console.warn(`Cannot handle event with data ${JSON.stringify(data)}, because of validation error: ${error.message}`); - } - } - getBranchKey(config) { - return config.scope === "global" ? config.scope : `${config.scope}_${config.scopeId}`; - } - getRegistryKey(config) { - return `${config.eventType}-${this.getBranchKey(config)}-${config.action}`; - } - getActiveSubscription(config) { - return this.activeSubscriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - getPendingSubscription(config) { - return this.pendingSubScriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - removePendingSubscription(pendingSubscription) { - const index = this.pendingSubScriptions.indexOf(pendingSubscription); - if (index >= 0) { - this.pendingSubScriptions.splice(index, 1); - } - } - } - - const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage; - reject(message); - }, timeoutMilliseconds); - promise() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - - const isDesktop = () => { - return typeof window === "undefined" ? - true : - window.glue42gd || window.iodesktop; - }; - const browserGlobal = () => { - return typeof window === "undefined" ? null : - window.glue42core || window.iobrowser; - }; - - class InteropTransport { - agm; - registry; - defaultTransportTimeout = 120000; - coreEventMethodInitiated = false; - corePlatformSubPromise; - constructor(agm, registry) { - this.agm = agm; - this.registry = registry; - } - async initiate(actualWindowId) { - if (isDesktop()) { - await Promise.all(Object.values(OUTGOING_METHODS).map((method) => { - return this.verifyMethodLive(method.name); - })); - await Promise.all(Object.keys(INCOMING_METHODS).map((method) => { - return this.registerMethod(method); - })); - return; - } - const systemId = browserGlobal().communicationId; - await Promise.all([ - this.verifyMethodLive(webPlatformMethodName, systemId), - this.verifyMethodLive(webPlatformWspStreamName, systemId) - ]); - await this.transmitControl("frameHello", { windowId: actualWindowId }); - } - coreSubscriptionReady(eventCallback) { - if (!this.coreEventMethodInitiated) { - this.subscribePlatform(eventCallback); - } - return this.corePlatformSubPromise; - } - subscribePlatform(eventCallback) { - this.coreEventMethodInitiated = true; - const systemId = browserGlobal().communicationId; - this.corePlatformSubPromise = this.agm.subscribe(webPlatformWspStreamName, systemId ? { target: { instance: systemId } } : undefined); - this.corePlatformSubPromise - .then((sub) => { - sub.onData((data) => eventCallback(data.data)); - }); - } - async subscribe(streamName, streamBranch, streamType) { - const subscriptionArgs = { - branch: streamBranch, - type: streamType - }; - let subscription; - try { - subscription = await this.agm.subscribe(streamName, { arguments: subscriptionArgs }); - } - catch (error) { - const message = `Internal subscription error! Error details: stream - ${streamName}, branch: ${streamBranch}. Internal message: ${error.message}`; - throw new Error(message); - } - return subscription; - } - async transmitControl(operation, operationArguments, invocationOptions) { - const invocationArguments = isDesktop() ? { operation, operationArguments } : { operation, domain: "workspaces", data: operationArguments }; - const methodName = isDesktop() ? OUTGOING_METHODS.control.name : webPlatformMethodName; - const platformTarget = isDesktop() ? undefined : browserGlobal().communicationId; - let invocationResult; - const baseErrorMessage = `Internal Workspaces Communication Error. Attempted operation: ${JSON.stringify(invocationArguments)}. `; - try { - invocationResult = await this.agm.invoke(methodName, invocationArguments, platformTarget ? { instance: platformTarget } : "best", { methodResponseTimeoutMs: invocationOptions?.timeout ?? this.defaultTransportTimeout }); - if (!invocationResult) { - throw new Error("Received unsupported result from GD - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from GD - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - onInternalMethodInvoked(key, callback) { - return this.registry.add(key, callback); - } - verifyMethodLive(name, systemId) { - return promisePlus(() => { - return new Promise((resolve) => { - const hasMethod = this.agm.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = systemId ? - method.getServers().some((server) => server.instance === systemId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - resolve(); - return; - } - const unSub = this.agm.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = systemId ? - server.instance === systemId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }); - }, 15000, "Timeout waiting for the Workspaces communication channels"); - } - registerMethod(key) { - const method = INCOMING_METHODS[key]; - return this.agm.register(method.name, (args, caller) => { - return Promise.all(this.registry.execute(key, args, caller)); - }); - } - } - - const privateData$4 = new WeakMap(); - class ParentBuilder { - constructor(definition, base) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$4.set(this, { base, children, definition }); - } - get type() { - return privateData$4.get(this).definition.type; - } - addColumn(definition) { - const base = privateData$4.get(this).base; - return base.add("column", privateData$4.get(this).children, definition); - } - addRow(definition) { - const base = privateData$4.get(this).base; - return base.add("row", privateData$4.get(this).children, definition); - } - addGroup(definition) { - const base = privateData$4.get(this).base; - return base.add("group", privateData$4.get(this).children, definition); - } - addWindow(definition) { - const base = privateData$4.get(this).base; - base.addWindow(privateData$4.get(this).children, definition); - return this; - } - serialize() { - const definition = privateData$4.get(this).definition; - definition.children = privateData$4.get(this).base.serializeChildren(privateData$4.get(this).children); - return definition; - } - } - - class BaseBuilder { - getBuilder; - constructor(getBuilder) { - this.getBuilder = getBuilder; - } - wrapChildren(children) { - return children.map((child) => { - if (child.type === "window") { - return child; - } - return this.getBuilder({ type: child.type, definition: child }); - }); - } - add(type, children, definition) { - const validatedDefinition = parentDefinitionDecoder.runWithException(definition); - const childBuilder = this.getBuilder({ type, definition: validatedDefinition }); - children.push(childBuilder); - return childBuilder; - } - addWindow(children, definition) { - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - validatedDefinition.type = "window"; - children.push(validatedDefinition); - } - serializeChildren(children) { - return children.map((child) => { - if (child instanceof ParentBuilder) { - return child.serialize(); - } - else { - return child; - } - }); - } - } - - const privateData$3 = new WeakMap(); - class WorkspaceBuilder { - constructor(definition, base, controller) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$3.set(this, { base, children, definition, controller }); - } - addColumn(definition) { - const children = privateData$3.get(this).children; - const areAllColumns = children.every((child) => child instanceof ParentBuilder && child.type === "column"); - if (!areAllColumns) { - throw new Error("Cannot add a column to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("column", children, definition); - } - addRow(definition) { - const children = privateData$3.get(this).children; - const areAllRows = children.every((child) => child instanceof ParentBuilder && child.type === "row"); - if (!areAllRows) { - throw new Error("Cannot add a row to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("row", children, definition); - } - addGroup(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a group to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - return base.add("group", children, definition); - } - addWindow(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a window to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - base.addWindow(children, definition); - return this; - } - getChildAt(index) { - nonNegativeNumberDecoder.runWithException(index); - const data = privateData$3.get(this).children; - return data[index]; - } - async create(config) { - const saveConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - const definition = privateData$3.get(this).definition; - definition.children = privateData$3.get(this).base.serializeChildren(privateData$3.get(this).children); - const controller = privateData$3.get(this).controller; - return controller.createWorkspace(definition, saveConfig); - } - } - - const privateData$2 = new WeakMap(); - const getBase$2 = (model) => { - return privateData$2.get(model).base; - }; - class Row { - constructor(base) { - privateData$2.set(this, { base }); - } - get type() { - return "row"; - } - get id() { - return getBase$2(this).getId(this); - } - get frameId() { - return getBase$2(this).getFrameId(this); - } - get workspaceId() { - return getBase$2(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$2(this).getPositionIndex(this); - } - get children() { - return getBase$2(this).getAllChildren(this); - } - get parent() { - return getBase$2(this).getMyParent(this); - } - get frame() { - return getBase$2(this).getMyFrame(this); - } - get workspace() { - return getBase$2(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$2(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$2(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$2(this).getMinWidth(this); - } - get minHeight() { - return getBase$2(this).getMinHeight(this); - } - get maxWidth() { - return getBase$2(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$2(this).getMaxHeight(this); - } - get width() { - return getBase$2(this).getWidthInPx(this); - } - get height() { - return getBase$2(this).getHeightInPx(this); - } - get isPinned() { - return getBase$2(this).getIsPinned(this); - } - get isMaximized() { - return getBase$2(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$2(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$2(this).addWindow(this, definition, "row"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "group", "row", definition); - } - async addColumn(definition) { - if (definition?.type && definition.type !== "column") { - throw new Error(`Expected a column definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "column", "row", definition); - } - async addRow() { - throw new Error("Adding rows as row children is not supported"); - } - removeChild(predicate) { - return getBase$2(this).removeChild(this, predicate); - } - maximize() { - return getBase$2(this).maximize(this); - } - restore() { - return getBase$2(this).restore(this); - } - close() { - return getBase$2(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : rowLockConfigDecoder.runWithException(lockConfigResult); - return getBase$2(this).lockContainer(this, verifiedConfig); - } - async setHeight(height) { - nonNegativeNumberDecoder.runWithException(height); - return getBase$2(this).setHeight(this, height); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$2(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$2(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData$1 = new WeakMap(); - const getBase$1 = (model) => { - return privateData$1.get(model).base; - }; - class Column { - constructor(base) { - privateData$1.set(this, { base }); - } - get type() { - return "column"; - } - get id() { - return getBase$1(this).getId(this); - } - get frameId() { - return getBase$1(this).getFrameId(this); - } - get workspaceId() { - return getBase$1(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$1(this).getPositionIndex(this); - } - get children() { - return getBase$1(this).getAllChildren(this); - } - get parent() { - return getBase$1(this).getMyParent(this); - } - get frame() { - return getBase$1(this).getMyFrame(this); - } - get workspace() { - return getBase$1(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$1(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$1(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$1(this).getMinWidth(this); - } - get minHeight() { - return getBase$1(this).getMinHeight(this); - } - get maxWidth() { - return getBase$1(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$1(this).getMaxHeight(this); - } - get width() { - return getBase$1(this).getWidthInPx(this); - } - get height() { - return getBase$1(this).getHeightInPx(this); - } - get isPinned() { - return getBase$1(this).getIsPinned(this); - } - get isMaximized() { - return getBase$1(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$1(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$1(this).addWindow(this, definition, "column"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "group", "column", definition); - } - async addColumn() { - throw new Error("Adding columns as column children is not supported"); - } - async addRow(definition) { - if (definition?.type && definition.type !== "row") { - throw new Error(`Expected a row definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "row", "column", definition); - } - removeChild(predicate) { - return getBase$1(this).removeChild(this, predicate); - } - maximize() { - return getBase$1(this).maximize(this); - } - restore() { - return getBase$1(this).restore(this); - } - close() { - return getBase$1(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : columnLockConfigDecoder.runWithException(lockConfigResult); - return getBase$1(this).lockContainer(this, verifiedConfig); - } - async setWidth(width) { - nonNegativeNumberDecoder.runWithException(width); - return getBase$1(this).setWidth(this, width); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$1(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$1(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData = new WeakMap(); - const getBase = (model) => { - return privateData.get(model).base; - }; - class Group { - constructor(base) { - privateData.set(this, { base }); - } - get type() { - return "group"; - } - get id() { - return getBase(this).getId(this); - } - get frameId() { - return getBase(this).getFrameId(this); - } - get workspaceId() { - return getBase(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase(this).getPositionIndex(this); - } - get children() { - return getBase(this).getAllChildren(this); - } - get parent() { - return getBase(this).getMyParent(this); - } - get frame() { - return getBase(this).getMyFrame(this); - } - get workspace() { - return getBase(this).getMyWorkspace(this); - } - get allowExtract() { - return getBase(this).getAllowExtract(this); - } - get allowReorder() { - return getBase(this).getAllowReorder(this); - } - get allowDropLeft() { - return getBase(this).getAllowDropLeft(this); - } - get allowDropRight() { - return getBase(this).getAllowDropRight(this); - } - get allowDropTop() { - return getBase(this).getAllowDropTop(this); - } - get allowDropBottom() { - return getBase(this).getAllowDropBottom(this); - } - get allowDropHeader() { - return getBase(this).getAllowDropHeader(this); - } - get allowDrop() { - return getBase(this).getAllowDrop(this); - } - get showMaximizeButton() { - return getBase(this).getShowMaximizeButton(this); - } - get showEjectButton() { - return getBase(this).getShowEjectButton(this); - } - get showAddWindowButton() { - return getBase(this).getShowAddWindowButton(this); - } - get minWidth() { - return getBase(this).getMinWidth(this); - } - get minHeight() { - return getBase(this).getMinHeight(this); - } - get maxWidth() { - return getBase(this).getMaxWidth(this); - } - get maxHeight() { - return getBase(this).getMaxHeight(this); - } - get width() { - return getBase(this).getWidthInPx(this); - } - get height() { - return getBase(this).getHeightInPx(this); - } - get isMaximized() { - return getBase(this).getIsMaximized(this); - } - addWindow(definition) { - return getBase(this).addWindow(this, definition, "group"); - } - async addGroup() { - throw new Error("Adding groups as group child is not supported"); - } - async addColumn() { - throw new Error("Adding columns as group child is not supported"); - } - async addRow() { - throw new Error("Adding rows as group child is not supported"); - } - removeChild(predicate) { - return getBase(this).removeChild(this, predicate); - } - maximize() { - return getBase(this).maximize(this); - } - restore() { - return getBase(this).restore(this); - } - close() { - return getBase(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropRight: this.allowDropRight, - allowDropTop: this.allowDropTop, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : groupLockConfigDecoder.runWithException(lockConfigResult); - return getBase(this).lockContainer(this, verifiedConfig); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - return getBase(this).setSize(this, config.width, config.height); - } - async bundleToRow() { - await getBase(this).bundleTo(this, "row"); - await this.workspace.refreshReference(); - } - async bundleToColumn() { - await getBase(this).bundleTo(this, "column"); - await this.workspace.refreshReference(); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase(this).processLocalSubscription(this, config); - return unsubscribe; - } - } - - const DEFAULT_WINDOW_DRAG_MODE = "keepInside"; - const ONE_DAY_MS = 86_400_000; - - const data$3 = new WeakMap(); - const getData$3 = (model) => { - return data$3.get(model).manager.getWorkspaceData(model); - }; - const getDataManager = (model) => { - return data$3.get(model).manager; - }; - class Workspace { - constructor(dataManager) { - data$3.set(this, { manager: dataManager }); - } - get id() { - return getData$3(this).id; - } - get frameId() { - return getData$3(this).config.frameId; - } - get positionIndex() { - return getData$3(this).config.positionIndex; - } - get title() { - return getData$3(this).config.title; - } - get layoutName() { - return getData$3(this).config.layoutName; - } - get isHibernated() { - return getData$3(this).config.isHibernated; - } - get isSelected() { - return getData$3(this).config.isSelected; - } - get children() { - return getData$3(this).children; - } - get frame() { - return getData$3(this).frame; - } - get allowSplitters() { - return getData$3(this).config.allowSplitters; - } - get allowSystemHibernation() { - return getData$3(this).config.allowSystemHibernation; - } - get allowDrop() { - return getData$3(this).config.allowDrop; - } - get allowDropLeft() { - return getData$3(this).config.allowDropLeft; - } - get allowDropTop() { - return getData$3(this).config.allowDropTop; - } - get allowDropRight() { - return getData$3(this).config.allowDropRight; - } - get allowDropBottom() { - return getData$3(this).config.allowDropBottom; - } - get allowExtract() { - return getData$3(this).config.allowExtract; - } - get allowWindowReorder() { - return getData$3(this).config.allowWindowReorder; - } - get showCloseButton() { - return getData$3(this).config.showCloseButton; - } - get showSaveButton() { - return getData$3(this).config.showSaveButton; - } - get allowWorkspaceTabReorder() { - return getData$3(this).config.allowWorkspaceTabReorder; - } - get allowWorkspaceTabExtract() { - return getData$3(this).config.allowWorkspaceTabExtract; - } - get minWidth() { - return getData$3(this).config.minWidth; - } - get minHeight() { - return getData$3(this).config.minHeight; - } - get maxWidth() { - return getData$3(this).config.maxWidth; - } - get maxHeight() { - return getData$3(this).config.maxHeight; - } - get width() { - return getData$3(this).config.widthInPx; - } - get height() { - return getData$3(this).config.heightInPx; - } - get showWindowCloseButtons() { - return getData$3(this).config.showWindowCloseButtons; - } - get showEjectButtons() { - return getData$3(this).config.showEjectButtons; - } - get showAddWindowButtons() { - return getData$3(this).config.showAddWindowButtons; - } - get isPinned() { - return getData$3(this).config.isPinned; - } - get windowDragMode() { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - return DEFAULT_WINDOW_DRAG_MODE; - } - return getData$3(this).config.windowDragMode; - } - get loadingStrategy() { - if (!isDesktop()) { - console.warn("The workspace.loadingStrategy property is not supported in IO Connect Browser"); - } - return getData$3(this).config.loadingStrategy; - } - async setLoadingStrategy(strategy) { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - const controller = getData$3(this).controller; - await controller.setLoadingStrategy(this.id, strategy); - await this.refreshReference(); - } - async removeChild(predicate) { - checkThrowCallback(predicate); - const child = this.children.find(predicate); - if (!child) { - return; - } - await child.close(); - await this.refreshReference(); - } - async remove(predicate) { - checkThrowCallback(predicate); - const controller = getData$3(this).controller; - const child = controller.iterateFindChild(this.children, predicate); - await child.close(); - await this.refreshReference(); - } - async focus() { - await getData$3(this).controller.focusItem(this.id); - await this.refreshReference(); - } - async close() { - const controller = getData$3(this).controller; - await controller.closeWorkspace(this.id, this.frameId); - } - snapshot() { - return getData$3(this).controller.getSnapshot(this.id, "workspace"); - } - async saveLayout(name, config) { - nonEmptyStringDecoder.runWithException(name); - await getData$3(this).controller.saveLayout({ name, workspaceId: this.id, saveContext: config?.saveContext, metadata: config?.metadata, allowMultiple: config?.allowMultiple }); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const controller = getData$3(this).controller; - await controller.setItemTitle(this.id, title); - await this.refreshReference(); - } - getContext() { - const controller = getData$3(this).controller; - return controller.getWorkspaceContext(this.id); - } - setContext(data) { - const controller = getData$3(this).controller; - return controller.setWorkspaceContext(this.id, data); - } - updateContext(data) { - const controller = getData$3(this).controller; - return controller.updateWorkspaceContext(this.id, data); - } - onContextUpdated(callback) { - const controller = getData$3(this).controller; - return controller.subscribeWorkspaceContextUpdated(this.id, callback); - } - async refreshReference() { - const newSnapshot = (await getData$3(this).controller.getSnapshot(this.id, "workspace")); - const currentChildrenFlat = getData$3(this).controller.flatChildren(getData$3(this).children); - const newChildren = getData$3(this).controller.refreshChildren({ - existingChildren: currentChildrenFlat, - workspace: this, - parent: this, - children: newSnapshot.children - }); - const currentFrame = this.frame; - let actualFrame; - if (currentFrame.id === newSnapshot.config.frameId) { - getDataManager(this).remapFrame(currentFrame, newSnapshot.frameSummary); - actualFrame = currentFrame; - } - else { - const frameCreateConfig = { - summary: newSnapshot.frameSummary - }; - const newFrame = getData$3(this).ioc.getModel("frame", frameCreateConfig); - actualFrame = newFrame; - } - getDataManager(this).remapWorkspace(this, { - config: newSnapshot.config, - children: newChildren, - frame: actualFrame - }); - } - async getIcon() { - const controller = getData$3(this).controller; - return controller.getWorkspaceIcon(this.id); - } - async setIcon(icon) { - const controller = getData$3(this).controller; - return controller.setWorkspaceIcon(this.id, icon); - } - getBox(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type !== "window" && predicate(child)); - } - getAllBoxes(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allParents = controller.iterateFilterChildren(children, (child) => child.type !== "window"); - if (!predicate) { - return allParents; - } - return allParents.filter(predicate); - } - getRow(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "row" && predicate(parent)); - } - getAllRows(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "row" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "row"); - } - getColumn(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "column" && predicate(parent)); - } - getAllColumns(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "column" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "column"); - } - getGroup(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "group" && predicate(parent)); - } - getAllGroups(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "group" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "group"); - } - getWindow(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type === "window" && predicate(child)); - } - getAllWindows(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allWindows = controller.iterateFilterChildren(children, (child) => child.type === "window"); - if (!predicate) { - return allWindows; - } - return allWindows.filter(predicate); - } - addRow(definition) { - return getData$3(this).base.addParent(this, "row", "workspace", definition); - } - addColumn(definition) { - return getData$3(this).base.addParent(this, "column", "workspace", definition); - } - addGroup(definition) { - return getData$3(this).base.addParent(this, "group", "workspace", definition); - } - addWindow(definition) { - return getData$3(this).base.addWindow(this, definition, "workspace"); - } - async bundleToRow() { - await getData$3(this).controller.bundleWorkspaceTo("row", this.id); - await this.refreshReference(); - } - async bundleToColumn() { - await getData$3(this).controller.bundleWorkspaceTo("column", this.id); - await this.refreshReference(); - } - async hibernate() { - await getData$3(this).controller.hibernateWorkspace(this.id); - await this.refreshReference(); - } - async resume() { - await getData$3(this).controller.resumeWorkspace(this.id); - await this.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowWindowReorder: this.allowWindowReorder, - allowSplitters: this.allowSplitters, - showCloseButton: this.showCloseButton, - showSaveButton: this.showSaveButton, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - showAddWindowButtons: this.showAddWindowButtons, - showEjectButtons: this.showEjectButtons, - showWindowCloseButtons: this.showWindowCloseButtons - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : workspaceLockConfigDecoder.runWithException(lockConfigResult); - await getData$3(this).controller.lockWorkspace(this.id, verifiedConfig); - await this.refreshReference(); - } - async pin(options) { - workspacePinOptionsDecoder.runWithException(options); - await getData$3(this).controller.pinWorkspace(this.id, options?.icon); - await this.refreshReference(); - } - async unpin() { - await getData$3(this).controller.unpinWorkspace(this.id); - await this.refreshReference(); - } - async showLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.showWorkspaceLoadingAnimation(this.id); - } - async hideLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.hideWorkspaceLoadingAnimation(this.id); - } - async setWindowDragMode(mode) { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - throw new Error("Not supported in IO Connect Browser"); - } - windowDragModeDecoder.runWithException(mode); - await getData$3(this).controller.setWindowDragMode(this.id, mode); - await this.refreshReference(); - } - async onClosed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - action: "closed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onHibernated(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "hibernated", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onResumed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "resumed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "added", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - action: "removed", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const foundWindow = this.getWindow((win) => { - return win.id && win.id === payload.windowSummary.config.windowId; - }); - callback(foundWindow); - }; - const config = { - action: "loaded", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowMaximized(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "maximized", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRestored(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "restored", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowSelected(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "selected", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowSplitters: this.allowSplitters, - allowWindowReorder: this.allowWindowReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - showAddWindowButtons: this.showAddWindowButtons, - showCloseButton: this.showCloseButton, - showEjectButtons: this.showEjectButtons, - showSaveButton: this.showSaveButton, - showWindowCloseButtons: this.showWindowCloseButtons - }); - }; - const config = { - action: "lock-configuration-changed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$2 = new WeakMap(); - const getData$2 = (model) => { - return data$2.get(model).manager.getWindowData(model); - }; - class Window { - constructor(dataManager) { - data$2.set(this, { manager: dataManager }); - } - get id() { - return getData$2(this).config.windowId; - } - get elementId() { - return getData$2(this).id; - } - get type() { - return "window"; - } - get frameId() { - return getData$2(this).frame.id; - } - get workspaceId() { - return getData$2(this).workspace.id; - } - get positionIndex() { - return getData$2(this).config.positionIndex; - } - get isMaximized() { - return getData$2(this).config.isMaximized; - } - get isLoaded() { - return getData$2(this).controller.checkIsWindowLoaded(this.id); - } - get isSelected() { - return getData$2(this).config.isSelected; - } - get focused() { - return this.getGdWindow().isFocused; - } - get title() { - return getData$2(this).config.title; - } - get allowExtract() { - return getData$2(this).config.allowExtract; - } - get allowReorder() { - return getData$2(this).config.allowReorder; - } - get showCloseButton() { - return getData$2(this).config.showCloseButton; - } - get width() { - return getData$2(this).config.widthInPx; - } - get height() { - return getData$2(this).config.heightInPx; - } - get minWidth() { - return getData$2(this).config.minWidth; - } - get minHeight() { - return getData$2(this).config.minHeight; - } - get maxWidth() { - return getData$2(this).config.maxWidth; - } - get maxHeight() { - return getData$2(this).config.maxHeight; - } - get workspace() { - return getData$2(this).workspace; - } - get frame() { - return getData$2(this).frame; - } - get parent() { - return getData$2(this).parent; - } - get appName() { - return getData$2(this).config.appName; - } - async forceLoad() { - if (this.isLoaded) { - return; - } - const controller = getData$2(this).controller; - const itemId = getData$2(this).id; - const windowId = await controller.forceLoadWindow(itemId); - getData$2(this).config.windowId = windowId; - await this.workspace.refreshReference(); - } - async focus() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.focusItem(id); - await this.workspace.refreshReference(); - } - async close() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.closeItem(id); - await getData$2(this) - .parent - .removeChild((child) => child.id === id); - await this.workspace.refreshReference(); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const itemId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.setItemTitle(itemId, title); - await this.workspace.refreshReference(); - } - async maximize() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.maximizeItem(id); - await this.workspace.refreshReference(); - } - async restore() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.restoreItem(id); - await this.workspace.refreshReference(); - } - async eject() { - if (!this.isLoaded) { - throw new Error("Cannot eject this window, because it is not loaded yet"); - } - const itemId = getData$2(this).id; - const windowId = getData$2(this).config.windowId; - const newWindowId = await getData$2(this).controller.ejectWindow(itemId, windowId); - getData$2(this).config.windowId = newWindowId; - await this.workspace.refreshReference(); - return this.getGdWindow(); - } - getGdWindow() { - if (!this.isLoaded) { - throw new Error("Cannot fetch this GD window, because the window is not yet loaded"); - } - const myId = getData$2(this).config.windowId; - const controller = getData$2(this).controller; - return controller.getGDWindow(myId); - } - async moveTo(parent) { - if (!(parent instanceof Row || parent instanceof Column || parent instanceof Group)) { - throw new Error("Cannot add to the provided parent, because the provided parent is not an instance of Row, Column or Group"); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - const foundParent = await controller.getParent((p) => p.id === parent.id); - if (!foundParent) { - throw new Error("Cannot move the window to the selected parent, because this parent does not exist."); - } - await controller.moveWindowTo(myId, parent.id); - await this.workspace.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : windowLockConfigDecoder.runWithException(lockConfigResult); - const windowPlacementId = getData$2(this).id; - await getData$2(this).controller.lockWindow(windowPlacementId, verifiedConfig); - await this.workspace.refreshReference(); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.resizeItem(myId, { - height: verifiedConfig.height, - width: verifiedConfig.width, - relative: false - }); - await this.workspace.refreshReference(); - } - async onRemoved(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback(); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$1 = new WeakMap(); - const getData$1 = (model) => { - return data$1.get(model).manager.getFrameData(model); - }; - class Frame { - constructor(dataManager) { - data$1.set(this, { manager: dataManager }); - } - async registerShortcut(shortcut, callback) { - nonEmptyStringDecoder.runWithException(shortcut); - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const unsubscribe = await getData$1(this).controller.registerShortcut(shortcut, myId, callback); - return unsubscribe; - } - get id() { - return getData$1(this).summary.id; - } - get isInitialized() { - return getData$1(this).summary.isInitialized; - } - getBounds() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameBounds(myId); - } - async resize(config) { - const validatedConfig = resizeConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.resizeItem(myId, validatedConfig); - } - async move(config) { - const validatedConfig = moveConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.moveFrame(myId, validatedConfig); - } - focus() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.focusItem(myId); - } - async state() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameState(myId); - } - setIcon(icon) { - if (!isDesktop()) { - throw new Error("frame.setIcon() is not supported in IO Connect Browser"); - } - iconDecoder.runWithException(icon); - const frameId = this.id; - return getData$1(this).controller.setTaskbarIcon(icon, frameId); - } - getIcon() { - if (!isDesktop()) { - throw new Error("frame.getIcon() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getTaskbarIcon(frameId); - } - isVisible() { - if (!isDesktop()) { - throw new Error("frame.isVisible() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getFrameVisibility(frameId); - } - async minimize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "minimized"); - } - async maximize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "maximized"); - } - async restore() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "normal"); - } - close(options) { - const validatedOptions = optional(closeOptionsDecoder).runWithException(options); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.closeFrame(myId, validatedOptions); - } - snapshot() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getSnapshot(myId, "frame"); - } - async workspaces() { - const controller = getData$1(this).controller; - return controller.getWorkspacesByFrameId(this.id); - } - async getConstraints() { - const controller = getData$1(this).controller; - const myId = getData$1(this).summary.id; - return controller.getFrameConstraints(myId); - } - async restoreWorkspace(name, options) { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return getData$1(this).controller.restoreWorkspace(name, validatedOptions); - } - createWorkspace(definition, config) { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - return getData$1(this).controller.createWorkspace(validatedDefinition, validatedConfig); - } - async init(config) { - frameInitConfigDecoder.runWithException(config); - if (getData$1(this).summary.isInitialized) { - throw new Error("The frame has already been initialized"); - } - return getData$1(this).controller.initFrame(this.id, config); - } - async showPopup(config) { - if (!isDesktop()) { - throw new Error("Popup operations are not supported in IO Connect Browser"); - } - const validatedConfig = popupConfigDecoder.runWithException(config); - const controller = getData$1(this).controller; - await controller.showPopup(validatedConfig, this.id); - return controller.getGDWindow(validatedConfig.windowId); - } - async show(config) { - if (!isDesktop()) { - throw new Error("The show operation is not supported in IO Connect Browser"); - } - const validatedConfig = frameShowConfigDecoder.runWithException(config); - return getData$1(this).controller.showFrame(this.id, validatedConfig); - } - async hide() { - if (!isDesktop()) { - throw new Error("The hide operation is not supported in IO Connect Browser"); - } - return getData$1(this).controller.hideFrame(this.id); - } - async showDialog(options) { - if (!isDesktop()) { - throw new Error("The showModal operation is not supported in IO Connect Browser"); - } - frameDialogOptionsDecoder.runWithException(options); - return getData$1(this).controller.showFrameDialog(this.id, options); - } - async onClosing(callback) { - if (!isDesktop()) { - throw new Error("Frame closing operations are not supported in io.Connect Browser"); - } - checkThrowCallback(callback); - const wrappedCallback = async () => { - let shouldPrevent = false; - const preventClose = () => shouldPrevent = true; - await callback({ prevent: preventClose }); - return { prevent: shouldPrevent }; - }; - const unsubscribe = await getData$1(this).controller.registerFrameOnClosing(this.id, wrappedCallback); - return unsubscribe; - } - async onClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMaximized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "maximized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMinimized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "minimized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onNormal(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "normal", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceOpened(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "opened", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceSelected(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.getWorkspaceById(payload.workspaceSummary.id); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "selected", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "added", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => { - return parent.id === payload.windowSummary.parentId; - }); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "loaded", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onInitializationRequested(callback) { - checkThrowCallback(callback); - if (!this.isInitialized) { - callback(getData$1(this).summary.initializationContext); - } - return () => { }; - } - async onFocusChanged(callback) { - checkThrowCallback(callback); - const myData = getData$1(this); - const { id } = myData.summary; - const wrappedCallback = (args) => { - callback({ isFocused: args.frameSummary.isFocused }); - }; - const config = { - callback: wrappedCallback, - action: "focus", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await myData.controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - class PrivateDataManager { - parentsData = new WeakMap(); - workspacesData = new WeakMap(); - windowsData = new WeakMap(); - framesData = new WeakMap(); - deleteData(model) { - if (model instanceof Window) { - this.windowsData.delete(model); - } - if (model instanceof Workspace) { - this.workspacesData.delete(model); - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - this.parentsData.delete(model); - } - if (model instanceof Frame) { - this.framesData.delete(model); - } - } - setWindowData(model, data) { - this.windowsData.set(model, data); - } - setWorkspaceData(model, data) { - this.workspacesData.set(model, data); - } - setParentData(model, data) { - this.parentsData.set(model, data); - } - setFrameData(model, data) { - this.framesData.set(model, data); - } - getWindowData(model) { - return this.windowsData.get(model); - } - getWorkspaceData(model) { - return this.workspacesData.get(model); - } - getParentData(model) { - return this.parentsData.get(model); - } - getFrameData(model) { - return this.framesData.get(model); - } - remapChild(model, newData) { - if (model instanceof Window) { - const data = this.windowsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - const data = this.parentsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - remapFrame(model, newData) { - const data = this.framesData.get(model); - data.summary = newData; - } - remapWorkspace(model, newData) { - const data = this.workspacesData.get(model); - data.frame = newData.frame || data.frame; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - - const data = new WeakMap(); - const getData = (base, model) => { - const manager = data.get(base).manager; - if (model instanceof Workspace) { - return manager.getWorkspaceData(model); - } - return data.get(base).manager.getParentData(model); - }; - class Base { - frameId; - workspaceId; - positionIndex; - constructor(dataManager) { - data.set(this, { manager: dataManager }); - } - getId(model) { - return getData(this, model).id; - } - getPositionIndex(model) { - return getData(this, model).config.positionIndex; - } - getWorkspaceId(model) { - const privateData = getData(this, model); - return privateData.config.workspaceId || privateData.workspace.id; - } - getFrameId(model) { - return getData(this, model).frame.id; - } - getAllChildren(model, predicate) { - checkThrowCallback(predicate, true); - const children = getData(this, model).children; - if (typeof predicate === "undefined") { - return children; - } - return children.filter(predicate); - } - getMyParent(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).parent; - } - getMyFrame(model) { - return getData(this, model).frame; - } - getMyWorkspace(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).workspace; - } - async addWindow(model, definition, parentType) { - if (!definition.appName && !definition.windowId) { - throw new Error("The window definition should contain either an appName or a windowId"); - } - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - const controller = getData(this, model).controller; - const operationResult = await controller.add("window", getData(this, model).id, parentType, validatedDefinition); - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getWindow(w => w.elementId === operationResult.itemId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getWindow(w => w.elementId === operationResult.itemId); - } - async addParent(model, typeToAdd, parentType, definition) { - const parentDefinition = this.transformDefinition(typeToAdd, definition); - const controller = getData(this, model).controller; - const newParentId = (await controller.add("container", getData(this, model).id, parentType, parentDefinition)).itemId; - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getBox((parent) => parent.id === newParentId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getBox((parent) => parent.id === newParentId); - } - async removeChild(model, predicate) { - checkThrowCallback(predicate); - const child = this.getAllChildren(model).find(predicate); - if (!child) { - return; - } - await child.close(); - if (model instanceof Workspace) { - await model.refreshReference(); - return; - } - await this.getMyWorkspace(model).refreshReference(); - } - async maximize(model) { - const { controller, id } = getData(this, model); - await controller.maximizeItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async restore(model) { - const { controller, id } = getData(this, model); - await controller.restoreItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async close(model) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.closeItem(modelData.id); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async lockContainer(model, config) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.lockContainer(modelData.id, model.type, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - getAllowDrop(model) { - return getData(this, model).config.allowDrop; - } - getAllowDropLeft(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropLeft is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropLeft; - } - getAllowDropRight(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropRight is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropRight; - } - getAllowDropTop(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropTop is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropTop; - } - getAllowDropBottom(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropBottom is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropBottom; - } - getAllowDropHeader(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropHeader is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropHeader; - } - getAllowSplitters(model) { - const privateData = getData(this, model); - if (privateData.type === "group") { - throw new Error(`Cannot get allow splitters from private data ${privateData.type}`); - } - return privateData.config.allowSplitters; - } - getAllowExtract(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowExtract; - } - getAllowReorder(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowReorder; - } - getShowMaximizeButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show maximize button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showMaximizeButton; - } - getShowEjectButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show eject button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showEjectButton; - } - getShowAddWindowButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get add window button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showAddWindowButton; - } - getMinWidth(model) { - const privateData = getData(this, model); - return privateData.config.minWidth; - } - getMaxWidth(model) { - const privateData = getData(this, model); - return privateData.config.maxWidth; - } - getMinHeight(model) { - const privateData = getData(this, model); - return privateData.config.minHeight; - } - getMaxHeight(model) { - const privateData = getData(this, model); - return privateData.config.maxHeight; - } - getWidthInPx(model) { - const privateData = getData(this, model); - return privateData.config.widthInPx; - } - getHeightInPx(model) { - const privateData = getData(this, model); - return privateData.config.heightInPx; - } - getIsPinned(model) { - const privateData = getData(this, model); - return privateData.config.isPinned; - } - getIsMaximized(model) { - const privateData = getData(this, model); - return privateData.config.isMaximized; - } - getMaximizationBoundary(model) { - const privateData = getData(this, model); - return privateData.config.maximizationBoundary; - } - async setHeight(model, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setWidth(model, width) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setSize(model, width, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width, - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setMaximizationBoundary(model, config) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.setMaximizationBoundary(id, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async bundleTo(model, type) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.bundleItemTo(type, id); - } - async processLocalSubscription(model, subscriptionConfig) { - return getData(this, model).controller.processLocalSubscription(subscriptionConfig, this.getId(model)); - } - transformDefinition(type, definition) { - let parentDefinition; - if (typeof definition === "undefined") { - parentDefinition = { type, children: [] }; - } - else if (definition instanceof ParentBuilder) { - parentDefinition = definition.serialize(); - } - else { - if (typeof definition.type === "undefined") { - definition.type = type; - } - parentDefinition = strictParentDefinitionDecoder.runWithException(definition); - parentDefinition.children = parentDefinition.children || []; - } - return parentDefinition; - } - } - - class BaseController { - ioc; - windows; - contexts; - layouts; - constructor(ioc, windows, contexts, layouts) { - this.ioc = ioc; - this.windows = windows; - this.contexts = contexts; - this.layouts = layouts; - } - get bridge() { - return this.ioc.bridge; - } - get privateDataManager() { - return this.ioc.privateDataManager; - } - checkIsWindowLoaded(windowId) { - return (!!windowId) && this.windows.list().some((win) => win.id === windowId); - } - async createWorkspace(createConfig) { - const snapshot = await this.bridge.send(OPERATIONS.createWorkspace.name, createConfig); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async createEmptyFrame(definition) { - const frameSummary = await this.bridge.send(OPERATIONS.createFrame.name, definition); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - async initFrame(frameId, config) { - await this.bridge.send(OPERATIONS.initFrame.name, { frameId, ...config }); - } - async restoreWorkspace(name, options) { - const snapshot = await this.bridge.send(OPERATIONS.openWorkspace.name, { name, restoreOptions: options }); - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: snapshot.config.frameId }); - const frameConfig = { - summary: frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async add(type, parentId, parentType, definition) { - let operationName; - const operationArgs = { definition, parentId, parentType }; - if (type === "window") { - operationName = OPERATIONS.addWindow.name; - } - else if (type === "container") { - operationName = OPERATIONS.addContainer.name; - } - else { - throw new Error(`Unrecognized add type: ${type}`); - } - return await this.bridge.send(operationName, operationArgs); - } - async getFrame(windowId) { - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: windowId }); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - getFrames(allFrameSummaries, predicate) { - return allFrameSummaries.reduce((frames, frameSummary) => { - const frameConfig = { - summary: frameSummary - }; - const frameToCheck = this.ioc.getModel("frame", frameConfig); - if (!predicate || predicate(frameToCheck)) { - frames.push(frameToCheck); - } - return frames; - }, []); - } - getAllWorkspaceSummaries(...bridgeResults) { - const allSummaries = bridgeResults.reduce((summaries, summaryResult) => { - summaries.push(...summaryResult.summaries); - return summaries; - }, []); - return allSummaries.map((summary) => { - return Object.assign({}, { id: summary.id, width: summary.config.widthInPx, height: summary.config.heightInPx }, summary.config); - }); - } - handleOnSaved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - const addedUnSub = this.layouts.onAdded(wrappedCallback); - const changedUnSub = this.layouts.onChanged(wrappedCallback); - return () => { - addedUnSub(); - changedUnSub(); - }; - } - handleOnRemoved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - return this.layouts.onRemoved(wrappedCallback); - } - async importLayouts(layouts, mode) { - await this.layouts.import(layouts, mode); - } - async transformStreamPayloadToWorkspace(payload) { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const snapshot = payload.workspaceSnapshot || (await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId: payload.workspaceSummary.id })); - const workspaceConfig = { frame, snapshot }; - const workspace = this.ioc.getModel("workspace", workspaceConfig); - return workspace; - } - async fetchWorkspace(itemId) { - const snapshot = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async bundleWorkspaceTo(type, workspaceId) { - await this.bridge.send(OPERATIONS.bundleWorkspace.name, { type, workspaceId }); - } - async bundleItemTo(type, itemId) { - const isSupported = await this.isOperationSupported(OPERATIONS.bundleItem.name); - if (!isSupported) { - throw new Error(`Operation ${OPERATIONS.bundleItem.name} is not supported. Ensure that you are running the latest version of all packages`); - } - await this.bridge.send(OPERATIONS.bundleItem.name, { type, itemId }); - } - async getTaskbarIcon(frameId) { - return await this.bridge.send(OPERATIONS.getTaskbarIcon.name, { frameId }); - } - async setTaskbarIcon(icon, frameId) { - await this.bridge.send(OPERATIONS.setTaskbarIcon.name, { icon, frameId }); - } - getWorkspaceContext(workspaceId) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.get(contextName); - } - setWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.set(contextName, data); - } - updateWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.update(contextName, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.subscribe(contextName, callback); - } - async restoreItem(itemId) { - await this.bridge.send(OPERATIONS.restoreItem.name, { itemId }); - } - async maximizeItem(itemId) { - await this.bridge.send(OPERATIONS.maximizeItem.name, { itemId }); - } - async focusItem(itemId) { - await this.bridge.send(OPERATIONS.focusItem.name, { itemId }); - } - async closeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.closeWorkspace.name, { itemId: workspaceId }); - } - async closeItem(itemId) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId }); - } - async closeFrame(itemId, closeOptions) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId, closeOptions }); - } - async resizeItem(itemId, config) { - await this.bridge.send(OPERATIONS.resizeItem.name, Object.assign({}, { itemId }, config)); - } - async setMaximizationBoundary(itemId, config) { - await this.bridge.send(OPERATIONS.setMaximizationBoundary.name, Object.assign({}, { itemId }, config)); - } - async showWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.showLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.hideLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async setWindowDragMode(workspaceId, dragMode) { - await this.bridge.send(OPERATIONS.setWindowDragMode.name, { itemId: workspaceId, dragMode }); - } - async moveFrame(itemId, config) { - await this.bridge.send(OPERATIONS.moveFrame.name, Object.assign({}, { itemId }, config)); - } - getGDWindow(itemId) { - return this.windows.list().find((gdWindow) => gdWindow.id === itemId); - } - async forceLoadWindow(itemId) { - const controlResult = await this.bridge.send(OPERATIONS.forceLoadWindow.name, { itemId }); - return controlResult.windowId; - } - async ejectWindow(itemId, windowId) { - return await this.bridge.send(OPERATIONS.ejectWindow.name, { itemId, windowId }); - } - async moveWindowTo(itemId, newParentId) { - await this.bridge.send(OPERATIONS.moveWindowTo.name, { itemId, containerId: newParentId }); - } - async getSnapshot(itemId, type) { - let result; - if (type === "workspace") { - result = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - } - else if (type === "frame") { - result = await this.bridge.send(OPERATIONS.getFrameSnapshot.name, { itemId }); - } - return result; - } - async setItemTitle(itemId, title) { - await this.bridge.send(OPERATIONS.setItemTitle.name, { itemId, title }); - } - refreshChildren(config) { - const { parent, children, existingChildren, workspace } = config; - if (parent instanceof Window || parent.type === "window") { - return; - } - const newChildren = children.map((newChildSnapshot) => { - let childToAdd = existingChildren.find((child) => { - return child.type === "window" ? child.elementId === newChildSnapshot.id : child.id === newChildSnapshot.id; - }); - if (childToAdd) { - this.privateDataManager.remapChild(childToAdd, { - parent: parent, - children: [], - config: newChildSnapshot.config - }); - } - else { - let createConfig; - if (newChildSnapshot.type === "window") { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - }; - } - else { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - children: [] - }; - } - childToAdd = this.ioc.getModel(newChildSnapshot.type, createConfig); - } - if (newChildSnapshot.type !== "window") { - this.refreshChildren({ - workspace, existingChildren, - children: newChildSnapshot.children, - parent: childToAdd - }); - } - return childToAdd; - }); - if (parent instanceof Workspace) { - return newChildren; - } - else { - this.privateDataManager.remapChild(parent, { children: newChildren }); - return newChildren; - } - } - iterateFindChild(children, predicate) { - let foundChild = children.find((child) => predicate(child)); - if (foundChild) { - return foundChild; - } - children.some((child) => { - if (child instanceof Window) { - return false; - } - foundChild = this.iterateFindChild(child.children, predicate); - if (foundChild) { - return true; - } - }); - return foundChild; - } - iterateFilterChildren(children, predicate) { - const foundChildren = children.filter((child) => predicate(child)); - const grandChildren = children.reduce((innerFound, child) => { - if (child instanceof Window) { - return innerFound; - } - innerFound.push(...this.iterateFilterChildren(child.children, predicate)); - return innerFound; - }, []); - foundChildren.push(...grandChildren); - return foundChildren; - } - notifyWindowAdded(windowId) { - return new Promise((resolve) => { - const alreadyPresent = this.windows.list().some((win) => win.id === windowId); - if (alreadyPresent) { - return resolve(); - } - const unsubscribe = this.windows.onWindowAdded((win) => { - if (win.id !== windowId) { - return; - } - if (unsubscribe) { - unsubscribe(); - } - resolve(); - }); - }); - } - async hibernateWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.hibernateWorkspace.name, { workspaceId }); - } - async resumeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.resumeWorkspace.name, { workspaceId }); - } - async lockWorkspace(workspaceId, config) { - await this.bridge.send(OPERATIONS.lockWorkspace.name, { workspaceId, config }); - } - async lockWindow(windowPlacementId, config) { - await this.bridge.send(OPERATIONS.lockWindow.name, { windowPlacementId, config }); - } - async lockContainer(itemId, type, config) { - await this.bridge.send(OPERATIONS.lockContainer.name, { itemId, type, config }); - } - async pinWorkspace(workspaceId, icon) { - await this.bridge.send(OPERATIONS.pinWorkspace.name, { workspaceId, icon }); - } - async unpinWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.unpinWorkspace.name, { workspaceId }); - } - async getWorkspaceIcon(workspaceId) { - const result = await this.bridge.send(OPERATIONS.getWorkspaceIcon.name, { workspaceId }); - return result.icon; - } - setWorkspaceIcon(workspaceId, icon) { - return this.bridge.send(OPERATIONS.setWorkspaceIcon.name, { workspaceId, icon }); - } - async getPlatformFrameId() { - try { - const result = await this.bridge.send(OPERATIONS.getPlatformFrameId.name, {}); - return result; - } - catch (error) { - return {}; - } - } - async setLoadingStrategy(workspaceId, strategy) { - await this.isOperationSupported(OPERATIONS.setLoadingStrategy.name); - return this.bridge.send(OPERATIONS.setLoadingStrategy.name, { itemId: workspaceId, strategy }); - } - async showFrame(frameId, config) { - const payload = { frameId, isVisible: true, ...config }; - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, payload); - } - async hideFrame(frameId) { - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, { frameId, isVisible: false }); - } - async getFrameVisibility(frameId) { - const result = await this.bridge.send(OPERATIONS.getFrameVisibility.name, { itemId: frameId }); - return result.isVisible; - } - async showFrameDialog(frameId, options) { - const result = await this.bridge.send(OPERATIONS.showFrameDialog.name, { frameId, options }, { timeout: ONE_DAY_MS }); - return result; - } - async isOperationSupported(operation) { - if (isDesktop()) { - return { isSupported: true }; - } - return await this.bridge.send(OPERATIONS.operationCheck.name, { operation }); - } - async showPopup(config, frameId) { - return this.bridge.send(OPERATIONS.showPopup.name, { ...config, frameId }); - } - } - - class MainController { - bridge; - base; - shortcutsController; - closingController; - constructor(bridge, base, shortcutsController, closingController) { - this.bridge = bridge; - this.base = base; - this.shortcutsController = shortcutsController; - this.closingController = closingController; - } - setTaskbarIcon(icon, frameId) { - return this.base.setTaskbarIcon(icon, frameId); - } - getTaskbarIcon(frameId) { - return this.base.getTaskbarIcon(frameId); - } - checkIsWindowLoaded(windowId) { - return this.base.checkIsWindowLoaded(windowId); - } - async checkIsInSwimlane(windowId) { - const controlResult = await this.bridge.send(OPERATIONS.isWindowInWorkspace.name, { itemId: windowId }); - return controlResult.inWorkspace; - } - async createWorkspace(definition, saveConfig) { - const createConfig = Object.assign({}, definition, { saveConfig }); - return await this.base.createWorkspace(createConfig); - } - async createEmptyFrame(definition) { - return await this.base.createEmptyFrame(definition); - } - async initFrame(frameId, config) { - return this.base.initFrame(frameId, config); - } - async restoreWorkspace(name, options) { - const allLayouts = await this.getLayoutSummaries(); - const layoutExists = allLayouts.some((summary) => summary.name === name); - if (!layoutExists) { - throw new Error(`This layout: ${name} cannot be restored, because it doesn't exist.`); - } - if (options?.frameId) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - const foundMatchingFrame = allFrameSummaries.summaries.some((summary) => summary.id === options.frameId); - if (!foundMatchingFrame) { - throw new Error(`Cannot reuse the frame with id: ${options.frameId}, because there is no frame with that ID found`); - } - } - return await this.base.restoreWorkspace(name, options); - } - async add(type, parentId, parentType, definition) { - return await this.base.add(type, parentId, parentType, definition); - } - processLocalSubscription(config, levelId) { - return isDesktop() ? - this.handleEnterpriseLocalSubscription(config, levelId) : - this.handleCoreLocalSubscription(config, levelId); - } - processGlobalSubscription(callback, eventType, action) { - return isDesktop() ? - this.handleEnterpriseGlobalSubscription(callback, eventType, action) : - this.handleCoreGlobalSubscription(callback, eventType, action); - } - async getFrame(selector) { - if (selector.windowId) { - return await this.base.getFrame(selector.windowId); - } - if (selector.predicate) { - return (await this.getFrames(selector.predicate))[0]; - } - throw new Error(`The provided selector is not valid: ${JSON.stringify(selector)}`); - } - async getFrames(predicate) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - return this.base.getFrames(allFrameSummaries.summaries, predicate); - } - getWorkspaceById(workspaceId) { - return this.base.fetchWorkspace(workspaceId); - } - async getWorkspaceByWindowId(itemId) { - if (!isDesktop()) { - return (await this.getWorkspaces((wsp) => !!wsp.getWindow((w) => w.id === itemId)))[0]; - } - return this.base.fetchWorkspace(itemId); - } - transformStreamPayloadToWorkspace(payload) { - return this.base.transformStreamPayloadToWorkspace(payload); - } - async getWorkspace(predicate) { - let foundWorkspace; - await this.iterateWorkspaces((wsp, end) => { - if (predicate(wsp)) { - foundWorkspace = wsp; - end(); - } - }); - return foundWorkspace; - } - async getWorkspaces(predicate) { - const matchingWorkspaces = []; - await this.iterateWorkspaces((wsp) => { - if (!predicate || predicate(wsp)) { - matchingWorkspaces.push(wsp); - } - }); - return matchingWorkspaces; - } - async getWorkspacesByFrameId(frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - const workspacesForFrame = await Promise.all(summariesForFrame.map((summary) => { - return this.base.fetchWorkspace(summary.id); - })); - return workspacesForFrame; - } - async isLastWorkspaceInFrame(workspaceId, frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - return summariesForFrame.length === 1 && summariesForFrame[0].id === workspaceId; - } - async getAllWorkspaceSummaries() { - const allSummariesResult = await this.bridge.send(OPERATIONS.getAllWorkspacesSummaries.name, {}); - return this.base.getAllWorkspaceSummaries(allSummariesResult); - } - async getWindow(predicate) { - let resultWindow; - await this.iterateWorkspaces((wsp, end) => { - const foundWindow = wsp.getWindow(predicate); - if (foundWindow) { - resultWindow = foundWindow; - end(); - } - }); - return resultWindow; - } - async getParent(predicate) { - let resultParent; - await this.iterateWorkspaces((wsp, end) => { - const foundParent = wsp.getBox(predicate); - if (foundParent) { - resultParent = foundParent; - end(); - } - }); - return resultParent; - } - async getLayoutSummaries() { - const allLayouts = await this.bridge.send(OPERATIONS.getAllLayoutsSummaries.name); - return allLayouts.summaries; - } - async deleteLayout(name) { - await this.bridge.send(OPERATIONS.deleteLayout.name, { name }); - } - async exportLayout(predicate) { - const allLayoutsResult = await this.bridge.send(OPERATIONS.exportAllLayouts.name); - return allLayoutsResult.layouts.reduce((matchingLayouts, layout) => { - if (!predicate || predicate(layout)) { - matchingLayouts.push(layout); - } - return matchingLayouts; - }, []); - } - async saveLayout(config) { - return await this.bridge.send(OPERATIONS.saveLayout.name, config); - } - async importLayouts(layouts, mode) { - if (isDesktop()) { - try { - await this.bridge.send(OPERATIONS.importLayouts.name, { layouts, mode }); - } - catch (error) { - await Promise.all(layouts.map((layout) => this.bridge.send(OPERATIONS.importLayout.name, { layout, mode }))); - } - return; - } - await this.base.importLayouts(layouts, mode); - } - handleOnSaved(callback) { - return this.base.handleOnSaved(callback); - } - handleOnRemoved(callback) { - return this.base.handleOnRemoved(callback); - } - async bundleWorkspaceTo(type, workspaceId) { - return await this.base.bundleWorkspaceTo(type, workspaceId); - } - async bundleItemTo(type, id) { - return await this.base.bundleItemTo(type, id); - } - getWorkspaceContext(workspaceId) { - return this.base.getWorkspaceContext(workspaceId); - } - setWorkspaceContext(workspaceId, data) { - return this.base.setWorkspaceContext(workspaceId, data); - } - updateWorkspaceContext(workspaceId, data) { - return this.base.updateWorkspaceContext(workspaceId, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - return this.base.subscribeWorkspaceContextUpdated(workspaceId, callback); - } - async restoreItem(itemId) { - return await this.base.restoreItem(itemId); - } - async maximizeItem(itemId) { - return await this.base.maximizeItem(itemId); - } - async focusItem(itemId) { - return await this.base.focusItem(itemId); - } - async changeFrameState(frameId, state) { - await this.bridge.send(OPERATIONS.changeFrameState.name, { frameId, requestedState: state }); - } - async getFrameBounds(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameBounds.name, { itemId: frameId }); - return frameResult.bounds; - } - async getFrameState(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameState.name, { itemId: frameId }); - return frameResult.state; - } - async closeWorkspace(workspaceId, frameId) { - if (isDesktop()) { - return await this.closeItem(workspaceId); - } - let closeWorkspaceCommandExists = false; - try { - const { isSupported } = await this.base.isOperationSupported(OPERATIONS.closeWorkspace.name); - closeWorkspaceCommandExists = isSupported; - } - catch (error) { - closeWorkspaceCommandExists = false; - } - if (closeWorkspaceCommandExists) { - return await this.base.closeWorkspace(workspaceId); - } - return await this.legacyCloseWorkspace(workspaceId, frameId); - } - async closeItem(itemId) { - return await this.base.closeItem(itemId); - } - async closeFrame(itemId, closeOptions) { - return await this.base.closeFrame(itemId, closeOptions); - } - async resizeItem(itemId, config) { - return await this.base.resizeItem(itemId, config); - } - async setMaximizationBoundary(itemId, config) { - return await this.base.setMaximizationBoundary(itemId, config); - } - async showWorkspaceLoadingAnimation(workspaceId) { - return await this.base.showWorkspaceLoadingAnimation(workspaceId); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - return await this.base.hideWorkspaceLoadingAnimation(workspaceId); - } - async setWindowDragMode(workspaceId, dragMode) { - return await this.base.setWindowDragMode(workspaceId, dragMode); - } - async moveFrame(itemId, config) { - return await this.base.moveFrame(itemId, config); - } - getGDWindow(itemId) { - return this.base.getGDWindow(itemId); - } - async forceLoadWindow(itemId) { - const windowId = await this.base.forceLoadWindow(itemId); - await this.base.notifyWindowAdded(windowId); - return windowId; - } - async ejectWindow(itemId, windowId) { - const id = (await this.base.ejectWindow(itemId, windowId)).windowId; - await this.base.notifyWindowAdded(id); - return id; - } - async moveWindowTo(itemId, newParentId) { - return await this.base.moveWindowTo(itemId, newParentId); - } - async getSnapshot(itemId, type) { - return await this.base.getSnapshot(itemId, type); - } - async setItemTitle(itemId, title) { - return await this.base.setItemTitle(itemId, title); - } - flatChildren(children) { - return children.reduce((soFar, child) => { - soFar.push(child); - if (child.type !== "window") { - soFar.push(...this.flatChildren(child.children)); - } - return soFar; - }, []); - } - refreshChildren(config) { - return this.base.refreshChildren(config); - } - iterateFindChild(children, predicate) { - return this.base.iterateFindChild(children, predicate); - } - iterateFilterChildren(children, predicate) { - return this.base.iterateFilterChildren(children, predicate); - } - hibernateWorkspace(workspaceId) { - return this.base.hibernateWorkspace(workspaceId); - } - resumeWorkspace(workspaceId) { - return this.base.resumeWorkspace(workspaceId); - } - lockWorkspace(workspaceId, config) { - return this.base.lockWorkspace(workspaceId, config); - } - lockWindow(windowPlacementId, config) { - return this.base.lockWindow(windowPlacementId, config); - } - lockContainer(itemId, type, config) { - return this.base.lockContainer(itemId, type, config); - } - pinWorkspace(workspaceId, icon) { - return this.base.pinWorkspace(workspaceId, icon); - } - unpinWorkspace(workspaceId) { - return this.base.unpinWorkspace(workspaceId); - } - getWorkspaceIcon(workspaceId) { - return this.base.getWorkspaceIcon(workspaceId); - } - setWorkspaceIcon(workspaceId, icon) { - return this.base.setWorkspaceIcon(workspaceId, icon); - } - async getFrameConstraints(frameId) { - const frameSnapshot = await this.getSnapshot(frameId, "frame"); - return { - minWidth: frameSnapshot.config.minWidth, - maxWidth: frameSnapshot.config.maxWidth, - minHeight: frameSnapshot.config.minHeight, - maxHeight: frameSnapshot.config.maxHeight, - }; - } - registerShortcut(shortcut, frameId, callback) { - return this.shortcutsController.registerShortcut(shortcut, frameId, callback); - } - getPlatformFrameId() { - return this.base.getPlatformFrameId(); - } - setLoadingStrategy(workspaceId, strategy) { - return this.base.setLoadingStrategy(workspaceId, strategy); - } - registerFrameOnClosing(frameId, callback) { - return this.closingController.registerFrameOnClosing(frameId, callback); - } - showPopup(config, frameId) { - return this.base.showPopup(config, frameId); - } - async showFrame(frameId, config) { - return this.base.showFrame(frameId, config); - } - async hideFrame(frameId) { - return this.base.hideFrame(frameId); - } - async getFrameVisibility(frameId) { - return this.base.getFrameVisibility(frameId); - } - async showFrameDialog(frameId, options) { - return this.base.showFrameDialog(frameId, options); - } - async handleCoreLocalSubscription(config, levelId) { - await this.bridge.createCoreEventSubscription(); - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseLocalSubscription(config, levelId) { - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async handleCoreGlobalSubscription(callback, eventType, action) { - await this.bridge.createCoreEventSubscription(); - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseGlobalSubscription(callback, eventType, action) { - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async iterateWorkspaces(callback) { - let ended = false; - const end = () => { ended = true; }; - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - for (const summary of workspaceSummaries) { - if (ended) { - return; - } - const wsp = await this.base.fetchWorkspace(summary.id); - callback(wsp, end); - } - } - async legacyCloseWorkspace(workspaceId, frameId) { - const isLastWorkspaceInFrame = await this.isLastWorkspaceInFrame(workspaceId, frameId); - const platformFrameId = (await this.getPlatformFrameId()).id; - const shouldCloseFrame = isLastWorkspaceInFrame && - platformFrameId !== frameId; - if (shouldCloseFrame) { - return await this.closeFrame(frameId, {}); - } - await this.closeItem(workspaceId); - } - } - - class ShortcutsController { - bridge; - _shortcuts = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.bridge.onOperation((payload) => { - if (payload.operation === CLIENT_OPERATIONS.shortcutClicked.name) { - const data = payload.data; - this._shortcuts.execute(`${data.frameId}-${data.shortcut}`); - } - }); - } - async registerShortcut(shortcut, frameId, callback) { - await this.bridge.send(OPERATIONS.registerShortcut.name, { shortcut, frameId }); - const un = this._shortcuts.add(`${frameId}-${shortcut}`, callback); - return () => { - un(); - this.bridge.send(OPERATIONS.unregisterShortcut.name, { shortcut, frameId }); - }; - } - } - - class ClosingController { - bridge; - registry = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.subscribeToFrameClosing(); - } - async registerFrameOnClosing(frameId, callback) { - await this.bridge.send(OPERATIONS.subscribeToFrameClosing.name, { itemId: frameId }); - return this.registry.add(frameId, callback); - } - subscribeToFrameClosing() { - this.bridge.onOperationWithResponse(async (payload) => { - if (payload.operation !== CLIENT_OPERATIONS.frameClosing.name) { - return; - } - const data = payload.data; - const frameClosingResult = await Promise.all(this.registry.execute(data.frameId)); - return this.aggregateFrameClosingResult(frameClosingResult); - }); - } - aggregateFrameClosingResult(results) { - return { - prevent: results.some((result) => result?.prevent) - }; - } - } - - class IoC { - agm; - windows; - layouts; - contexts; - _controllerInstance; - _bridgeInstance; - _transportInstance; - _privateDataManagerInstance; - _parentBaseInstance; - _baseController; - _shortcutsController; - _closingController; - constructor(agm, windows, layouts, contexts) { - this.agm = agm; - this.windows = windows; - this.layouts = layouts; - this.contexts = contexts; - } - get baseController() { - if (!this._baseController) { - this._baseController = new BaseController(this, this.windows, this.contexts, this.layouts); - } - return this._baseController; - } - get controller() { - if (!this._controllerInstance) { - this._controllerInstance = new MainController(this.bridge, this.baseController, this.shortcutsController, this.closingController); - } - return this._controllerInstance; - } - get shortcutsController() { - if (!this._shortcutsController) { - this._shortcutsController = new ShortcutsController(this.bridge); - } - return this._shortcutsController; - } - get closingController() { - if (!this._closingController) { - this._closingController = new ClosingController(this.bridge); - } - return this._closingController; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new Bridge(this.transport, CallbackFactory()); - } - return this._bridgeInstance; - } - get transport() { - if (!this._transportInstance) { - this._transportInstance = new InteropTransport(this.agm, CallbackFactory()); - } - return this._transportInstance; - } - get privateDataManager() { - if (!this._privateDataManagerInstance) { - this._privateDataManagerInstance = new PrivateDataManager(); - } - return this._privateDataManagerInstance; - } - get parentBase() { - if (!this._parentBaseInstance) { - this._parentBaseInstance = new Base(this.privateDataManager); - } - return this._parentBaseInstance; - } - async initiate(actualWindowId) { - await this.transport.initiate(actualWindowId); - } - getModel(type, createConfig) { - switch (type) { - case "frame": { - const newFrame = new Frame(this.privateDataManager); - const { summary } = createConfig; - const frameData = { summary, controller: this.controller }; - this.privateDataManager.setFrameData(newFrame, frameData); - return newFrame; - } - case "window": { - const { id, parent, frame, workspace, config } = createConfig; - const windowPrivateData = { - type: "window", - controller: this.controller, - config, id, parent, frame, workspace - }; - const newWindow = new Window(this.privateDataManager); - this.privateDataManager.setWindowData(newWindow, windowPrivateData); - return newWindow; - } - case "row": - case "column": - case "group": { - const { id, children, parent, frame, workspace, config } = createConfig; - const newParent = type === "column" ? new Column(this.parentBase) : - type === "row" ? new Row(this.parentBase) : new Group(this.parentBase); - const builtChildren = this.buildChildren(children, frame, workspace, newParent); - const parentPrivateData = { - id, parent, frame, workspace, - config, - type, - controller: this.controller, - children: builtChildren, - }; - this.privateDataManager.setParentData(newParent, parentPrivateData); - return newParent; - } - case "workspace": { - const { snapshot, frame } = createConfig; - const newWorkspace = new Workspace(this.privateDataManager); - const children = this.buildChildren(snapshot.children, frame, newWorkspace, newWorkspace); - const workspacePrivateData = { - id: snapshot.id, - type: "workspace", - config: snapshot.config, - base: this.parentBase, - controller: this.controller, - children, frame, ioc: this - }; - this.privateDataManager.setWorkspaceData(newWorkspace, workspacePrivateData); - return newWorkspace; - } - default: throw new Error(`Unrecognized type: ${type}`); - } - } - getBuilder(config) { - config.definition = config.definition || {}; - if (!Array.isArray(config.definition.children)) { - config.definition.children = []; - } - const baseBuilder = new BaseBuilder(this.getBuilder.bind(this)); - switch (config.type) { - case "workspace": { - return new WorkspaceBuilder(config.definition, baseBuilder, this.controller); - } - case "row": - case "column": - case "group": { - config.definition.type = config.type; - return new ParentBuilder(config.definition, baseBuilder); - } - default: throw new Error(`Unexpected Builder creation error, provided config: ${JSON.stringify(config)}`); - } - } - buildChildren(children, frame, workspace, parent) { - return children.map((child) => { - switch (child.type) { - case "window": return this.getModel("window", { - id: child.id, - config: child.config, - frame, workspace, parent - }); - case "column": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "row": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "group": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - default: throw new Error(`Unsupported child type: ${child.type}`); - } - }); - } - } - - var version = "4.2.3"; - - const composeAPI = (glue, ioc) => { - const controller = ioc.controller; - const inWorkspace = () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - return controller.checkIsInSwimlane(myId); - }; - const getBuilder = (config) => { - const validatedConfig = builderConfigDecoder.runWithException(config); - return ioc.getBuilder(validatedConfig); - }; - const getMyFrame = async () => { - const windowId = glue.windows.my().id; - if (!windowId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(windowId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your frame, because this window is not in a workspace"); - } - return controller.getFrame({ windowId }); - }; - const getFrame = async (predicate) => { - checkThrowCallback(predicate); - return controller.getFrame({ predicate }); - }; - const getAllFrames = async (predicate) => { - checkThrowCallback(predicate, true); - return controller.getFrames(predicate); - }; - const getAllWorkspacesSummaries = () => { - return controller.getAllWorkspaceSummaries(); - }; - const getMyWorkspace = async () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my workspace, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(myId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your workspace, because this window is not in a workspace"); - } - return await controller.getWorkspaceByWindowId(myId); - }; - const getWorkspace = async (predicate) => { - checkThrowCallback(predicate); - return (await controller.getWorkspaces(predicate))[0]; - }; - const getWorkspaceById = async (workspaceId) => { - nonEmptyStringDecoder.runWithException(workspaceId); - return controller.getWorkspaceById(workspaceId); - }; - const getAllWorkspaces = (predicate) => { - checkThrowCallback(predicate, true); - return controller.getWorkspaces(predicate); - }; - const getWindow = async (predicate) => { - checkThrowCallback(predicate); - return controller.getWindow(predicate); - }; - const getParent = async (predicate) => { - checkThrowCallback(predicate); - return controller.getParent(predicate); - }; - const restoreWorkspace = async (name, options) => { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return controller.restoreWorkspace(name, validatedOptions); - }; - const createWorkspace = async (definition, saveConfig) => { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(saveConfig); - return controller.createWorkspace(validatedDefinition, validatedConfig); - }; - const createEmptyFrame = async (definition) => { - const validatedDefinition = emptyFrameDefinitionDecoder.runWithException(definition); - return controller.createEmptyFrame(validatedDefinition ?? {}); - }; - const layouts = { - getSummaries: () => { - return controller.getLayoutSummaries(); - }, - delete: async (name) => { - nonEmptyStringDecoder.runWithException(name); - return controller.deleteLayout(name); - }, - export: async (predicate) => { - checkThrowCallback(predicate, true); - return controller.exportLayout(predicate); - }, - import: async (layouts, mode = "replace") => { - if (!Array.isArray(layouts)) { - throw new Error(`The provided layouts argument is not an array: ${JSON.stringify(layouts)}`); - } - layouts.forEach((layout) => workspaceLayoutDecoder.runWithException(layout)); - return controller.importLayouts(layouts, mode); - }, - save: async (config) => { - const verifiedConfig = workspaceLayoutSaveConfigDecoder.runWithException(config); - return controller.saveLayout(verifiedConfig); - }, - onSaved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnSaved(callback); - }, - onRemoved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnRemoved(callback); - } - }; - const onFrameOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - callback(frame); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "opened"); - return unsubscribe; - }; - const onFrameClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "closed"); - return unsubscribe; - }; - const onWorkspaceOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "opened"); - return unsubscribe; - }; - const onWorkspaceClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "closed"); - return unsubscribe; - }; - const onWorkspaceHibernated = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "hibernated"); - return unsubscribe; - }; - const onWorkspaceResumed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "resumed"); - return unsubscribe; - }; - const onWindowAdded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "added"); - return unsubscribe; - }; - const onWindowLoaded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const foundWindow = workspace.getWindow((win) => win.id && win.id === payload.windowSummary.config.windowId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "loaded"); - return unsubscribe; - }; - const onWindowRemoved = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "removed"); - return unsubscribe; - }; - const onWindowMaximized = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "maximized"); - return unsubscribe; - }; - const onWindowRestored = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "restored"); - return unsubscribe; - }; - const onWindowSelected = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "selected"); - return unsubscribe; - }; - const waitForFrame = async (id) => { - nonEmptyStringDecoder.runWithException(id); - return new Promise((res, rej) => { - let unsub = () => { - }; - onFrameOpened((f) => { - if (f.id === id) { - res(f); - unsub(); - } - }).then((u) => { - unsub = u; - return getAllFrames(); - }).then((frames) => { - const myFrame = frames.find((f) => f.id === id); - if (myFrame) { - res(myFrame); - unsub(); - } - }).catch(rej); - }); - }; - return { - inWorkspace, - getBuilder, - getMyFrame, - getFrame, - getAllFrames, - getAllWorkspacesSummaries, - getMyWorkspace, - getWorkspace, - getWorkspaceById, - getAllWorkspaces, - getWindow, - getBox: getParent, - restoreWorkspace, - createWorkspace, - createEmptyFrame, - waitForFrame, - layouts, - onFrameOpened, - onFrameClosed, - onWorkspaceOpened, - onWorkspaceClosed, - onWorkspaceHibernated, - onWorkspaceResumed, - onWindowAdded, - onWindowLoaded, - onWindowRemoved, - onWindowMaximized, - onWindowRestored, - onWindowSelected, - version - }; - }; - - const factoryFunction = async (io) => { - const ioc = new IoC(io.agm, io.windows, io.layouts, io.contexts); - const actualWindowId = io.interop.instance.windowId; - await ioc.initiate(actualWindowId); - io.workspaces = composeAPI(io, ioc); - }; - if (typeof window !== "undefined") { - window.IOWorkspaces = factoryFunction; - } - - return factoryFunction; - -})); -//# sourceMappingURL=workspaces.umd.js.map diff --git a/javascript/solution/clients/package-lock.json b/javascript/solution/clients/package-lock.json new file mode 100644 index 0000000..0fd5599 --- /dev/null +++ b/javascript/solution/clients/package-lock.json @@ -0,0 +1,1291 @@ +{ + "name": "clients", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "clients", + "version": "1.0.0", + "dependencies": { + "@interopio/browser-platform": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@interopio/browser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser/-/browser-4.2.4.tgz", + "integrity": "sha512-BPgkwH6N8HyGf7st99ZJwQ7arijz9j1bGu7pUAXBrtbv6cu4zH5GR7JKPGANZmFl0uefNPQyAQ4hc7C/i1i++A==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0", + "@interopio/search-api": "^3.2.1", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.2" + } + }, + "node_modules/@interopio/browser-platform": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser-platform/-/browser-platform-4.2.4.tgz", + "integrity": "sha512-Xo3zwB2thiPkMTPsfPMHbLtfxvhhip3UX/CHFK2H1ymyF3+PcETn+TZdz1a+awJOICAvDbW6n9EHPCBj/fQVzQ==", + "license": "Commercial", + "dependencies": { + "@interopio/browser": "^4.2.4", + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0" + } + }, + "node_modules/@interopio/core": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@interopio/core/-/core-6.8.1.tgz", + "integrity": "sha512-WFWIV8JilNuAcxXaB+81IjL9j82sU73ABMUUEOWpvWoyqxhPlneOS+rSYViFX5gdk5pLH3fM6T/MmRGn3UFLwQ==", + "license": "MIT", + "dependencies": { + "callback-registry": "^2.7.2", + "ws": "^8.18.0" + } + }, + "node_modules/@interopio/desktop": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/@interopio/desktop/-/desktop-6.18.0.tgz", + "integrity": "sha512-YqRHRiCymbY2fOCT2HHJnLY4780JSRI1fUtaWEoIa5Z3djZk/3xRgVxIjOVw9Y/TAFGCwyIeW142a7HYnSGD5Q==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/schemas": "^10.1.0", + "@interopio/utils": "^1.4.2", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.1" + } + }, + "node_modules/@interopio/schemas": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@interopio/schemas/-/schemas-10.1.0.tgz", + "integrity": "sha512-8uDEoOAZenTr4a3O8vLq6JyS/LutkT/gh9EjuOrS9fOmHEUfJaS2u+qPo5em9/8MtjKgblZEJStSsW1gr34CtQ==", + "license": "ISC", + "dependencies": { + "ajv": "^6.12.6", + "ajv-keywords": "^3.4.1" + }, + "peerDependencies": { + "log4js": "^6.4.2" + }, + "peerDependenciesMeta": { + "log4js": { + "optional": true + } + } + }, + "node_modules/@interopio/search-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@interopio/search-api/-/search-api-3.2.1.tgz", + "integrity": "sha512-raUZzqBQoidm/6Mvgao2wFWlTDu9D4jghiX1dqor1LdsIfUpelJkkuFGeDl0z/3DWneaxDF8Vc/uoBtLz7qJLw==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1" + } + }, + "node_modules/@interopio/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@interopio/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-14Bb2WI9Cwf9zjhTurP4qP9AVY4cxR1AOrwrOtHrTGAeeHp88mALFWfMEv1QnRhlQ06To2vQcRgebNrPlHDZ8Q==", + "license": "ISC", + "dependencies": { + "decoder-validate": "^0.0.2" + } + }, + "node_modules/@interopio/workspaces-api": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@interopio/workspaces-api/-/workspaces-api-4.2.3.tgz", + "integrity": "sha512-5wrR1yhETKuX4txVrmS5q3G+8KI6GW4yOxsrVdf5qErO2HxN938XUdiAHIesarwlQoncrgnVx7uTn6IeOWUoXg==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/callback-registry": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/callback-registry/-/callback-registry-2.7.2.tgz", + "integrity": "sha512-VVrtF21DaH0VHeNMkLDd4VGuxsYM3V3l3lwYneKVMU/6X3TRtcQszUwlAcqj2HrLcbP1NyS12LsanUwCykaz/Q==", + "license": "ISC" + }, + "node_modules/decoder-validate": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/decoder-validate/-/decoder-validate-0.0.2.tgz", + "integrity": "sha512-9BsqAH9Zq6CvlxKHkSrZrH2iYlhuhHcrh6uTnDvcsa9P5YEweEzt1ci+X/9STgSCE7b9BA7/QIiwhfUDDWmjxw==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/javascript/solution/clients/package.json b/javascript/solution/clients/package.json new file mode 100644 index 0000000..693ae4d --- /dev/null +++ b/javascript/solution/clients/package.json @@ -0,0 +1,14 @@ +{ + "name": "clients", + "version": "1.0.0", + "scripts": { + "start": "vite --port 9000" + }, + "dependencies": { + "@interopio/browser-platform": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } +} diff --git a/javascript/solution/clients/plugins/applicationsPlugin.js b/javascript/solution/clients/plugins/applicationsPlugin.js index ef42500..df732cd 100644 --- a/javascript/solution/clients/plugins/applicationsPlugin.js +++ b/javascript/solution/clients/plugins/applicationsPlugin.js @@ -5,7 +5,7 @@ const fetchAppDefinitions = async (url) => { return appDefinitions; }; -const setupApplications = async (io, { url }) => { +export const setupApplications = async (io, { url }) => { try { const appDefinitions = await fetchAppDefinitions(url); diff --git a/javascript/solution/clients/plugins/layoutsPlugin.js b/javascript/solution/clients/plugins/layoutsPlugin.js index 1bec138..a078021 100644 --- a/javascript/solution/clients/plugins/layoutsPlugin.js +++ b/javascript/solution/clients/plugins/layoutsPlugin.js @@ -5,7 +5,7 @@ const fetchWorkspaceLayoutDefinitions = async (url) => { return layoutDefinitions; }; -const setupLayouts = async (io, { url }) => { +export const setupLayouts = async (io, { url }) => { try { const layoutDefinitions = await fetchWorkspaceLayoutDefinitions(url); diff --git a/javascript/solution/package-lock.json b/javascript/solution/package-lock.json index 7dde13d..71541fc 100644 --- a/javascript/solution/package-lock.json +++ b/javascript/solution/package-lock.json @@ -9,8 +9,927 @@ "version": "1.0.0", "license": "ISC", "dependencies": { + "@interopio/browser": "*", + "@interopio/browser-platform": "*", + "@interopio/workspaces-api": "*", "concurrently": "^5.3.0", "http-server": "^0.12.3" + }, + "devDependencies": { + "vite": "^6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@interopio/browser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser/-/browser-4.2.4.tgz", + "integrity": "sha512-BPgkwH6N8HyGf7st99ZJwQ7arijz9j1bGu7pUAXBrtbv6cu4zH5GR7JKPGANZmFl0uefNPQyAQ4hc7C/i1i++A==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0", + "@interopio/search-api": "^3.2.1", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.2" + } + }, + "node_modules/@interopio/browser-platform": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser-platform/-/browser-platform-4.2.4.tgz", + "integrity": "sha512-Xo3zwB2thiPkMTPsfPMHbLtfxvhhip3UX/CHFK2H1ymyF3+PcETn+TZdz1a+awJOICAvDbW6n9EHPCBj/fQVzQ==", + "license": "Commercial", + "dependencies": { + "@interopio/browser": "^4.2.4", + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0" + } + }, + "node_modules/@interopio/core": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@interopio/core/-/core-6.8.1.tgz", + "integrity": "sha512-WFWIV8JilNuAcxXaB+81IjL9j82sU73ABMUUEOWpvWoyqxhPlneOS+rSYViFX5gdk5pLH3fM6T/MmRGn3UFLwQ==", + "license": "MIT", + "dependencies": { + "callback-registry": "^2.7.2", + "ws": "^8.18.0" + } + }, + "node_modules/@interopio/desktop": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/@interopio/desktop/-/desktop-6.18.0.tgz", + "integrity": "sha512-YqRHRiCymbY2fOCT2HHJnLY4780JSRI1fUtaWEoIa5Z3djZk/3xRgVxIjOVw9Y/TAFGCwyIeW142a7HYnSGD5Q==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/schemas": "^10.1.0", + "@interopio/utils": "^1.4.2", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.1" + } + }, + "node_modules/@interopio/schemas": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@interopio/schemas/-/schemas-10.1.0.tgz", + "integrity": "sha512-8uDEoOAZenTr4a3O8vLq6JyS/LutkT/gh9EjuOrS9fOmHEUfJaS2u+qPo5em9/8MtjKgblZEJStSsW1gr34CtQ==", + "license": "ISC", + "dependencies": { + "ajv": "^6.12.6", + "ajv-keywords": "^3.4.1" + }, + "peerDependencies": { + "log4js": "^6.4.2" + }, + "peerDependenciesMeta": { + "log4js": { + "optional": true + } + } + }, + "node_modules/@interopio/search-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@interopio/search-api/-/search-api-3.2.1.tgz", + "integrity": "sha512-raUZzqBQoidm/6Mvgao2wFWlTDu9D4jghiX1dqor1LdsIfUpelJkkuFGeDl0z/3DWneaxDF8Vc/uoBtLz7qJLw==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1" + } + }, + "node_modules/@interopio/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@interopio/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-14Bb2WI9Cwf9zjhTurP4qP9AVY4cxR1AOrwrOtHrTGAeeHp88mALFWfMEv1QnRhlQ06To2vQcRgebNrPlHDZ8Q==", + "license": "ISC", + "dependencies": { + "decoder-validate": "^0.0.2" + } + }, + "node_modules/@interopio/workspaces-api": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@interopio/workspaces-api/-/workspaces-api-4.2.3.tgz", + "integrity": "sha512-5wrR1yhETKuX4txVrmS5q3G+8KI6GW4yOxsrVdf5qErO2HxN938XUdiAHIesarwlQoncrgnVx7uTn6IeOWUoXg==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" } }, "node_modules/ansi-regex": { @@ -60,6 +979,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/callback-registry": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/callback-registry/-/callback-registry-2.7.2.tgz", + "integrity": "sha512-VVrtF21DaH0VHeNMkLDd4VGuxsYM3V3l3lwYneKVMU/6X3TRtcQszUwlAcqj2HrLcbP1NyS12LsanUwCykaz/Q==", + "license": "ISC" + }, "node_modules/camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -181,6 +1106,12 @@ "node": ">=0.10.0" } }, + "node_modules/decoder-validate": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/decoder-validate/-/decoder-validate-0.0.2.tgz", + "integrity": "sha512-9BsqAH9Zq6CvlxKHkSrZrH2iYlhuhHcrh6uTnDvcsa9P5YEweEzt1ci+X/9STgSCE7b9BA7/QIiwhfUDDWmjxw==", + "license": "MIT" + }, "node_modules/ecstatic": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/ecstatic/-/ecstatic-3.3.2.tgz", @@ -209,6 +1140,48 @@ "is-arrayish": "^0.2.1" } }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, "node_modules/escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -222,6 +1195,36 @@ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==" }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, "node_modules/find-up": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", @@ -252,6 +1255,21 @@ } } }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/function-bind": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", @@ -387,6 +1405,12 @@ "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==" }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, "node_modules/locate-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", @@ -439,6 +1463,25 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, "node_modules/normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", @@ -524,6 +1567,26 @@ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/pify": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", @@ -545,6 +1608,44 @@ "node": ">= 0.12.0" } }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/qs": { "version": "6.11.0", "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", @@ -606,6 +1707,51 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, "node_modules/rxjs": { "version": "6.6.7", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", @@ -648,6 +1794,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/spawn-command": { "version": "0.0.2-1", "resolved": "https://registry.npmjs.org/spawn-command/-/spawn-command-0.0.2-1.tgz", @@ -727,6 +1883,23 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, "node_modules/tree-kill": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", @@ -751,6 +1924,15 @@ "node": ">= 0.8.0" } }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, "node_modules/url-join": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/url-join/-/url-join-2.0.5.tgz", @@ -765,6 +1947,81 @@ "spdx-expression-parse": "^3.0.0" } }, + "node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, "node_modules/which-module": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", @@ -783,6 +2040,27 @@ "node": ">=6" } }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/y18n": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", diff --git a/javascript/solution/package.json b/javascript/solution/package.json index a4db5bd..85abbf4 100644 --- a/javascript/solution/package.json +++ b/javascript/solution/package.json @@ -3,18 +3,13 @@ "version": "1.0.0", "description": "io.Connect Browser JavaScript Tutorial", "scripts": { - "start:clients": "http-server ./Clients -p 9000 -c-1", - "start:stocks": "http-server ./Stocks -p 9100 -c-1", - "start:clientDetails": "http-server ./client-details -p 9200 -c-1", - "start:workspace": "http-server ./workspace -p 9300 -c-1", - "start:downloader": "http-server ./portfolio-downloader -p 9400 -c-1", - "start": "concurrently \"npm run start:clients\" \"npm run start:stocks\" \"npm run start:clientDetails\" \"npm run start:workspace\" \"npm run start:downloader\"" + "install:apps": "concurrently \"cd clients && npm install\" \"cd stocks && npm install\" \"cd client-details && npm install\" \"cd workspace && npm install\" \"cd portfolio-downloader && npm install\"", + "start": "concurrently \"cd clients && npm start\" \"cd stocks && npm start\" \"cd client-details && npm start\" \"cd workspace && npm start\" \"cd portfolio-downloader && npm start\"" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { - "concurrently": "^5.3.0", - "http-server": "^0.12.3" + "concurrently": "^5.3.0" } -} \ No newline at end of file +} diff --git a/javascript/solution/portfolio-downloader/index.html b/javascript/solution/portfolio-downloader/index.html index 9805cd9..051192a 100644 --- a/javascript/solution/portfolio-downloader/index.html +++ b/javascript/solution/portfolio-downloader/index.html @@ -8,8 +8,7 @@ Portfolio Downloader - - + diff --git a/javascript/solution/portfolio-downloader/index.js b/javascript/solution/portfolio-downloader/index.js index 16dd5a6..2a26daa 100644 --- a/javascript/solution/portfolio-downloader/index.js +++ b/javascript/solution/portfolio-downloader/index.js @@ -1,3 +1,5 @@ +import IOBrowser from '@interopio/browser'; + const intentHandler = (context) => { if (!context) { return; diff --git a/javascript/solution/portfolio-downloader/lib/browser.umd.js b/javascript/solution/portfolio-downloader/lib/browser.umd.js deleted file mode 100644 index a5e6fcb..0000000 --- a/javascript/solution/portfolio-downloader/lib/browser.umd.js +++ /dev/null @@ -1,17399 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.browser = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs$1 (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) - }; - - function isNonNullObject(value) { - return !!value && typeof value === 'object' - } - - function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); - - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) - } - - // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 - var canUseSymbol = typeof Symbol === 'function' && Symbol.for; - var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; - - function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE - } - - function emptyTarget(val) { - return Array.isArray(val) ? [] : {} - } - - function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value - } - - function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) - } - - function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge - } - - function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return Object.propertyIsEnumerable.call(target, symbol) - }) - : [] - } - - function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) - } - - function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } - } - - // Protects from prototype poisoning and unexpected merging up the prototype chain. - function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. - } - - function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } - - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination - } - - function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; - - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } - } - - deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } - - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) - }; - - var deepmerge_1 = deepmerge; - - var cjs = deepmerge_1; - - var deepmerge$1 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$2 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$2 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$2 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$2 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$2 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$2 = function (f, r) { - return r.ok === true ? ok$2(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$2(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$2 = function (f, r) { - return r.ok === true ? r : err$2(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$2 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$2 = function() { - __assign$2 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - - function __rest$2(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$2(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$2(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$2(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$2 = function (json) { return Array.isArray(json); }; - var isJsonObject$2 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$2(json); - }; - var typeString$2 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$2 = function (expected, got) { - return "expected " + expected + ", got " + typeString$2(got); - }; - var printPath$2 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$2 = function (newAt, _a) { - var at = _a.at, rest = __rest$2(_a, ["at"]); - return (__assign$2({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$2 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$2(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$2(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$2(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$2(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$2(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$2(json) - : err$2({ message: expectedGot$2('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$2(json) - : err$2({ message: expectedGot$2('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$2(json) - : err$2({ message: expectedGot$2('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$2(json, value) - ? ok$2(value) - : err$2({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$2(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$2({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else if (isJsonObject$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$2(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$2(function (err$$1) { return prependAt$2("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$2([])); - } - else if (isJsonArray$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$2(json)) { - if (json.length !== decoders.length) { - return err$2({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$2(prependAt$2("[" + i + "]", nth.error)); - } - } - return ok$2(result); - } - else { - return err$2({ message: expectedGot$2("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$2(Object.assign, acc, decoder.decode(json)); }, ok$2({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$2(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$2(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$2(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$2(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$2({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$2(withDefault$2(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$2(function (error) { - return jsonAtPath === undefined - ? { at: printPath$2(paths), message: 'path does not exist' } - : prependAt$2(printPath$2(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$2(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$2({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$2 = Decoder$2.string; - /** See `Decoder.number` */ - var number$2 = Decoder$2.number; - /** See `Decoder.boolean` */ - var boolean$2 = Decoder$2.boolean; - /** See `Decoder.anyJson` */ - var anyJson$2 = Decoder$2.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$2.unknownJson; - /** See `Decoder.constant` */ - var constant$2 = Decoder$2.constant; - /** See `Decoder.object` */ - var object$2 = Decoder$2.object; - /** See `Decoder.array` */ - var array$2 = Decoder$2.array; - /** See `Decoder.tuple` */ - Decoder$2.tuple; - /** See `Decoder.dict` */ - Decoder$2.dict; - /** See `Decoder.optional` */ - var optional$2 = Decoder$2.optional; - /** See `Decoder.oneOf` */ - var oneOf$1 = Decoder$2.oneOf; - /** See `Decoder.union` */ - var union$1 = Decoder$2.union; - /** See `Decoder.intersection` */ - var intersection = Decoder$2.intersection; - /** See `Decoder.withDefault` */ - Decoder$2.withDefault; - /** See `Decoder.valueAt` */ - Decoder$2.valueAt; - /** See `Decoder.succeed` */ - Decoder$2.succeed; - /** See `Decoder.fail` */ - Decoder$2.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder$2.lazy; - - const defaultConfig = { - gateway: { webPlatform: {} }, - libraries: [], - exposeAPI: true, - }; - const defaultWidgetConfig = { - awaitFactory: true, - enable: false, - timeout: 5 * 1000, - restoreLastKnownPosition: true, - }; - const defaultModalsConfig = { - alerts: { - enabled: false - }, - dialogs: { - enabled: false - }, - awaitFactory: true, - timeout: 5 * 1000, - }; - const defaultIntentResolverConfig = { - enable: false, - timeout: 5 * 1000, - awaitFactory: true, - }; - - const Glue42CoreMessageTypes = { - platformUnload: { name: "platformUnload" }, - transportSwitchRequest: { name: "transportSwitchRequest" }, - transportSwitchResponse: { name: "transportSwitchResponse" }, - getCurrentTransport: { name: "getCurrentTransport" }, - getCurrentTransportResponse: { name: "getCurrentTransportResponse" }, - checkPreferredLogic: { name: "checkPreferredLogic" }, - checkPreferredConnection: { name: "checkPreferredConnection" }, - checkPreferredLogicResponse: { name: "checkPreferredLogicResponse" }, - checkPreferredConnectionResponse: { name: "checkPreferredConnectionResponse" } - }; - const webPlatformTransportName = "web-platform"; - const latestFDC3Type = "latest_fdc3_type"; - const errorChannel = new MessageChannel(); - const REQUEST_WIDGET_READY = "requestWidgetFactoryReady"; - const REQUEST_MODALS_UI_FACTORY_READY = "requestModalsUIFactoryReady"; - const MAX_SET_TIMEOUT_DELAY = 2147483647; - const REQUEST_INTENT_RESOLVER_UI_FACTORY_READY = "requestIntentResolverUIFactoryReady"; - const READONLY_PROPERTY_DESCRIPTOR = { - configurable: false, - enumerable: true, - writable: false, - }; - - const extractErrorMsg = (error) => { - if (typeof error === "string") { - return error; - } - if (error?.message) { - return typeof error.message === "string" ? error.message : JSON.stringify(error.message); - } - return JSON.stringify(error); - }; - const runDecoderWithIOError = (decoder, json) => { - try { - const result = decoder.runWithException(json); - return result; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const getSupportedOperationsNames = (operations) => { - return Object.keys(operations).filter((operation) => (operations)[operation].execute); - }; - const handleOperationCheck = (supportedOperations, operationName) => { - const isSupported = supportedOperations.some((operation) => operation.toLowerCase() === operationName.toLowerCase()); - return { isSupported }; - }; - const getSafeTimeoutDelay = (delay) => { - return Math.min(delay, MAX_SET_TIMEOUT_DELAY); - }; - const wrapPromise = () => { - let wrapperResolve; - let wrapperReject; - const promise = new Promise((resolve, reject) => { - wrapperResolve = resolve; - wrapperReject = reject; - }); - return { promise, resolve: wrapperResolve, reject: wrapperReject }; - }; - - class IOError { - raiseError(error, shouldThrowOriginalError) { - const errorMessage = extractErrorMsg(error); - errorChannel.port1.postMessage(errorMessage); - if (shouldThrowOriginalError) { - throw error; - } - throw new Error(errorMessage); - } - } - const ioError = new IOError(); - - const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"]; - const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"]; - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$1 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$1 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$1 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$1 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$1 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$1 = function (f, r) { - return r.ok === true ? ok$1(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$1 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$1(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$1 = function (f, r) { - return r.ok === true ? r : err$1(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$1 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$1 = function() { - __assign$1 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - - function __rest$1(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$1(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$1(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$1(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$1 = function (json) { return Array.isArray(json); }; - var isJsonObject$1 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$1(json); - }; - var typeString$1 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$1 = function (expected, got) { - return "expected " + expected + ", got " + typeString$1(got); - }; - var printPath$1 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$1 = function (newAt, _a) { - var at = _a.at, rest = __rest$1(_a, ["at"]); - return (__assign$1({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$1 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$1(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$1(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$1(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$1(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$1(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$1(json) - : err$1({ message: expectedGot$1('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$1(json) - : err$1({ message: expectedGot$1('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$1(json) - : err$1({ message: expectedGot$1('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$1(json, value) - ? ok$1(value) - : err$1({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$1(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$1({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else if (isJsonObject$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$1(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$1(function (err$$1) { return prependAt$1("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$1(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$1([])); - } - else if (isJsonArray$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$1(json)) { - if (json.length !== decoders.length) { - return err$1({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$1(prependAt$1("[" + i + "]", nth.error)); - } - } - return ok$1(result); - } - else { - return err$1({ message: expectedGot$1("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$1(Object.assign, acc, decoder.decode(json)); }, ok$1({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$1(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$1(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$1(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$1(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$1({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$1(withDefault$1(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$1(function (error) { - return jsonAtPath === undefined - ? { at: printPath$1(paths), message: 'path does not exist' } - : prependAt$1(printPath$1(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$1(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$1({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$1 = Decoder$1.string; - /** See `Decoder.number` */ - var number$1 = Decoder$1.number; - /** See `Decoder.boolean` */ - var boolean$1 = Decoder$1.boolean; - /** See `Decoder.anyJson` */ - var anyJson$1 = Decoder$1.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$1.unknownJson; - /** See `Decoder.constant` */ - var constant$1 = Decoder$1.constant; - /** See `Decoder.object` */ - var object$1 = Decoder$1.object; - /** See `Decoder.array` */ - var array$1 = Decoder$1.array; - /** See `Decoder.tuple` */ - Decoder$1.tuple; - /** See `Decoder.dict` */ - var dict = Decoder$1.dict; - /** See `Decoder.optional` */ - var optional$1 = Decoder$1.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder$1.oneOf; - /** See `Decoder.union` */ - Decoder$1.union; - /** See `Decoder.intersection` */ - Decoder$1.intersection; - /** See `Decoder.withDefault` */ - Decoder$1.withDefault; - /** See `Decoder.valueAt` */ - Decoder$1.valueAt; - /** See `Decoder.succeed` */ - Decoder$1.succeed; - /** See `Decoder.fail` */ - Decoder$1.fail; - /** See `Decoder.lazy` */ - Decoder$1.lazy; - - const nonEmptyStringDecoder$3 = string$1().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$3 = number$1().where((num) => num >= 0, "Expected a non-negative number"); - const regexDecoder = anyJson$1().andThen((value) => { - return value instanceof RegExp ? anyJson$1() : fail(`expected a regex, got a ${typeof value}`); - }); - - const intentDefinitionDecoder$1 = object$1({ - name: nonEmptyStringDecoder$3, - displayName: optional$1(string$1()), - contexts: optional$1(array$1(string$1())), - customConfig: optional$1(object$1()) - }); - const v2TypeDecoder = oneOf(constant$1("web"), constant$1("native"), constant$1("citrix"), constant$1("onlineNative"), constant$1("other")); - const v2DetailsDecoder = object$1({ - url: nonEmptyStringDecoder$3 - }); - const v2IconDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3) - }); - const v2ScreenshotDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3), - label: optional$1(nonEmptyStringDecoder$3) - }); - const v2ListensForIntentDecoder = object$1({ - contexts: array$1(nonEmptyStringDecoder$3), - displayName: optional$1(nonEmptyStringDecoder$3), - resultType: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(anyJson$1()) - }); - const v2IntentsDecoder = object$1({ - listensFor: optional$1(dict(v2ListensForIntentDecoder)), - raises: optional$1(dict(array$1(nonEmptyStringDecoder$3))) - }); - const v2UserChannelDecoder = object$1({ - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2AppChannelDecoder = object$1({ - name: nonEmptyStringDecoder$3, - description: optional$1(nonEmptyStringDecoder$3), - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2InteropDecoder = object$1({ - intents: optional$1(v2IntentsDecoder), - userChannels: optional$1(v2UserChannelDecoder), - appChannels: optional$1(array$1(v2AppChannelDecoder)) - }); - const glue42ApplicationDetailsDecoder = object$1({ - url: optional$1(nonEmptyStringDecoder$3), - top: optional$1(number$1()), - left: optional$1(number$1()), - width: optional$1(nonNegativeNumberDecoder$3), - height: optional$1(nonNegativeNumberDecoder$3) - }); - const glue42HostManifestsBrowserDecoder = object$1({ - name: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3.where((s) => s === "window", "Expected a value of window")), - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - customProperties: optional$1(anyJson$1()), - icon: optional$1(string$1()), - caption: optional$1(string$1()), - details: optional$1(glue42ApplicationDetailsDecoder), - intents: optional$1(array$1(intentDefinitionDecoder$1)), - hidden: optional$1(boolean$1()) - }); - const v1DefinitionDecoder = object$1({ - name: nonEmptyStringDecoder$3, - appId: nonEmptyStringDecoder$3, - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - manifest: nonEmptyStringDecoder$3, - manifestType: nonEmptyStringDecoder$3, - tooltip: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - images: optional$1(array$1(object$1({ url: optional$1(nonEmptyStringDecoder$3) }))), - icons: optional$1(array$1(object$1({ icon: optional$1(nonEmptyStringDecoder$3) }))), - customConfig: anyJson$1(), - intents: optional$1(array$1(intentDefinitionDecoder$1)) - }); - const v2LocalizedDefinitionDecoder = object$1({ - appId: optional$1(nonEmptyStringDecoder$3), - name: optional$1(nonEmptyStringDecoder$3), - details: optional$1(v2DetailsDecoder), - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder) - }); - const v2DefinitionDecoder = object$1({ - appId: nonEmptyStringDecoder$3, - name: optional$1(nonEmptyStringDecoder$3), - type: v2TypeDecoder, - details: v2DetailsDecoder, - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder), - localizedVersions: optional$1(dict(v2LocalizedDefinitionDecoder)) - }); - const allDefinitionsDecoder = oneOf(v1DefinitionDecoder, v2DefinitionDecoder); - - const parseDecoderErrorToStringMessage = (error) => { - return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`; - }; - - class FDC3Service { - fdc3ToDesktopDefinitionType = { - web: "window", - native: "exe", - citrix: "citrix", - onlineNative: "clickonce", - other: "window" - }; - toApi() { - return { - isFdc3Definition: this.isFdc3Definition.bind(this), - parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this), - parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this) - }; - } - isFdc3Definition(definition) { - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - return { isFdc3: false, reason: parseDecoderErrorToStringMessage(decodeRes.error) }; - } - if (definition.appId && definition.details) { - return { isFdc3: true, version: "2.0" }; - } - if (definition.manifest) { - return { isFdc3: true, version: "1.2" }; - } - return { isFdc3: false, reason: "The passed definition is not FDC3" }; - } - parseToBrowserBaseAppData(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - const userProperties = this.getUserPropertiesFromDefinition(definition, version); - const createOptions = { url: this.getUrl(definition, version) }; - const baseApplicationData = { - name: definition.appId, - type: "window", - createOptions, - userProperties: { - ...userProperties, - intents: version === "1.2" - ? userProperties.intents - : this.getIntentsFromV2AppDefinition(definition), - details: createOptions - }, - title: definition.title, - version: definition.version, - icon: this.getIconFromDefinition(definition, version), - caption: definition.description, - fdc3: version === "2.0" ? { ...definition, definitionVersion: "2.0" } : undefined, - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return baseApplicationData; - } - const ioDefinitionDecodeRes = glue42HostManifestsBrowserDecoder.run(ioConnectDefinition); - if (!ioDefinitionDecodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(ioDefinitionDecodeRes.error)}`); - } - if (!Object.keys(ioDefinitionDecodeRes.result).length) { - return baseApplicationData; - } - return this.mergeBaseAppDataWithGlueManifest(baseApplicationData, ioDefinitionDecodeRes.result); - } - parseToDesktopAppConfig(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - if (version === "1.2") { - const fdc3v1Definition = definition; - return { - name: fdc3v1Definition.appId, - type: "window", - details: { - url: this.getUrl(definition, version) - }, - version: fdc3v1Definition.version, - title: fdc3v1Definition.title, - tooltip: fdc3v1Definition.tooltip, - caption: fdc3v1Definition.description, - icon: fdc3v1Definition.icons?.[0].icon, - intents: fdc3v1Definition.intents, - customProperties: { - manifestType: fdc3v1Definition.manifestType, - images: fdc3v1Definition.images, - contactEmail: fdc3v1Definition.contactEmail, - supportEmail: fdc3v1Definition.supportEmail, - publisher: fdc3v1Definition.publisher, - icons: fdc3v1Definition.icons, - customConfig: fdc3v1Definition.customConfig - } - }; - } - const fdc3v2Definition = definition; - const desktopDefinition = { - name: fdc3v2Definition.appId, - type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type], - details: fdc3v2Definition.details, - version: fdc3v2Definition.version, - title: fdc3v2Definition.title, - tooltip: fdc3v2Definition.tooltip, - caption: fdc3v2Definition.description, - icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"), - intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition), - fdc3: { ...fdc3v2Definition, definitionVersion: "2.0" } - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return desktopDefinition; - } - if (typeof ioConnectDefinition !== "object" || Array.isArray(ioConnectDefinition)) { - throw new Error(`Invalid '${definition.hostManifests.ioConnect ? "hostManifests.ioConnect" : "hostManifests['Glue42']"}' key`); - } - return this.mergeDesktopConfigWithGlueManifest(desktopDefinition, ioConnectDefinition); - } - getUserPropertiesFromDefinition(definition, version) { - if (version === "1.2") { - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key))); - } - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key))); - } - getUrl(definition, version) { - let url; - if (version === "1.2") { - const parsedManifest = JSON.parse(definition.manifest); - url = parsedManifest.details?.url || parsedManifest.url; - } - else { - url = definition.details?.url; - } - if (!url || typeof url !== "string") { - throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`); - } - return url; - } - getIntentsFromV2AppDefinition(definition) { - const fdc3Intents = definition.interop?.intents?.listensFor; - if (!fdc3Intents) { - return; - } - const intents = Object.entries(fdc3Intents).map((fdc3Intent) => { - const [intentName, intentData] = fdc3Intent; - return { - name: intentName, - ...intentData - }; - }); - return intents; - } - getIconFromDefinition(definition, version) { - if (version === "1.2") { - return definition.icons?.find((iconDef) => iconDef.icon)?.icon || undefined; - } - return definition.icons?.find((iconDef) => iconDef.src)?.src || undefined; - } - mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) { - let baseApplicationDefinition = baseAppData; - if (hostManifestDefinition.customProperties) { - baseApplicationDefinition.userProperties = { ...baseAppData.userProperties, ...hostManifestDefinition.customProperties }; - } - if (hostManifestDefinition.details) { - const details = { ...baseAppData.createOptions, ...hostManifestDefinition.details }; - baseApplicationDefinition.createOptions = details; - baseApplicationDefinition.userProperties.details = details; - } - if (Array.isArray(hostManifestDefinition.intents)) { - baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents); - } - baseApplicationDefinition = { ...baseApplicationDefinition, ...hostManifestDefinition }; - delete baseApplicationDefinition.details; - delete baseApplicationDefinition.intents; - return baseApplicationDefinition; - } - mergeDesktopConfigWithGlueManifest(config, desktopDefinition) { - const appConfig = Object.assign({}, config, desktopDefinition, { details: { ...config.details, ...desktopDefinition.details } }); - if (Array.isArray(desktopDefinition.intents)) { - appConfig.intents = (config.intents || []).concat(desktopDefinition.intents); - } - return appConfig; - } - } - - const decoders$1 = { - common: { - nonEmptyStringDecoder: nonEmptyStringDecoder$3, - nonNegativeNumberDecoder: nonNegativeNumberDecoder$3, - regexDecoder - }, - fdc3: { - allDefinitionsDecoder, - v1DefinitionDecoder, - v2DefinitionDecoder - } - }; - - var INTENTS_ERRORS; - (function (INTENTS_ERRORS) { - INTENTS_ERRORS["USER_CANCELLED"] = "User Closed Intents Resolver UI without choosing a handler"; - INTENTS_ERRORS["CALLER_NOT_DEFINED"] = "Caller Id is not defined"; - INTENTS_ERRORS["TIMEOUT_HIT"] = "Timeout hit"; - INTENTS_ERRORS["INTENT_NOT_FOUND"] = "Cannot find Intent"; - INTENTS_ERRORS["HANDLER_NOT_FOUND"] = "Cannot find Intent Handler"; - INTENTS_ERRORS["TARGET_INSTANCE_UNAVAILABLE"] = "Cannot start Target Instance"; - INTENTS_ERRORS["INTENT_DELIVERY_FAILED"] = "Target Instance did not add a listener"; - INTENTS_ERRORS["RESOLVER_UNAVAILABLE"] = "Intents Resolver UI unavailable"; - INTENTS_ERRORS["RESOLVER_TIMEOUT"] = "User did not choose a handler"; - INTENTS_ERRORS["INVALID_RESOLVER_RESPONSE"] = "Intents Resolver UI returned invalid response"; - INTENTS_ERRORS["INTENT_HANDLER_REJECTION"] = "Intent Handler function processing the raised intent threw an error or rejected the promise it returned"; - })(INTENTS_ERRORS || (INTENTS_ERRORS = {})); - - let IoC$1 = class IoC { - _fdc3; - _decoders = decoders$1; - _errors = { - intents: INTENTS_ERRORS - }; - get fdc3() { - if (!this._fdc3) { - this._fdc3 = new FDC3Service().toApi(); - } - return this._fdc3; - } - get decoders() { - return this._decoders; - } - get errors() { - return this._errors; - } - }; - - const ioc = new IoC$1(); - ioc.fdc3; - const decoders = ioc.decoders; - ioc.errors; - - const nonEmptyStringDecoder$2 = string$2().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$2 = number$2().where((num) => num >= 0, "Expected a non-negative number"); - const optionalNonEmptyStringDecoder = optional$2(nonEmptyStringDecoder$2); - const libDomainDecoder = oneOf$1(constant$2("system"), constant$2("windows"), constant$2("appManager"), constant$2("layouts"), constant$2("intents"), constant$2("notifications"), constant$2("channels"), constant$2("extension"), constant$2("themes"), constant$2("prefs"), constant$2("ui")); - const windowOperationTypesDecoder = oneOf$1(constant$2("openWindow"), constant$2("windowHello"), constant$2("windowAdded"), constant$2("windowRemoved"), constant$2("getBounds"), constant$2("getFrameBounds"), constant$2("getUrl"), constant$2("moveResize"), constant$2("focus"), constant$2("close"), constant$2("getTitle"), constant$2("setTitle"), constant$2("focusChange"), constant$2("getChannel"), constant$2("notifyChannelsChanged"), constant$2("setZoomFactor"), constant$2("zoomFactorChange"), constant$2("refresh"), constant$2("operationCheck")); - const appManagerOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("appDirectoryStateChange"), constant$2("instanceStarted"), constant$2("instanceStopped"), constant$2("applicationStart"), constant$2("instanceStop"), constant$2("clear"), constant$2("operationCheck")); - const layoutsOperationTypesDecoder = oneOf$1(constant$2("layoutAdded"), constant$2("layoutChanged"), constant$2("layoutRemoved"), constant$2("layoutRenamed"), constant$2("get"), constant$2("getAll"), constant$2("export"), constant$2("import"), constant$2("remove"), constant$2("rename"), constant$2("clientSaveRequest"), constant$2("getGlobalPermissionState"), constant$2("checkGlobalActivated"), constant$2("requestGlobalPermission"), constant$2("getDefaultGlobal"), constant$2("setDefaultGlobal"), constant$2("clearDefaultGlobal"), constant$2("updateMetadata"), constant$2("operationCheck"), constant$2("getCurrent"), constant$2("defaultLayoutChanged"), constant$2("layoutRestored")); - const notificationsOperationTypesDecoder = oneOf$1(constant$2("raiseNotification"), constant$2("requestPermission"), constant$2("notificationShow"), constant$2("notificationClick"), constant$2("getPermission"), constant$2("list"), constant$2("notificationRaised"), constant$2("notificationClosed"), constant$2("click"), constant$2("clear"), constant$2("clearAll"), constant$2("configure"), constant$2("getConfiguration"), constant$2("configurationChanged"), constant$2("setState"), constant$2("clearOld"), constant$2("activeCountChange"), constant$2("stateChange"), constant$2("operationCheck"), constant$2("getActiveCount")); - const systemOperationTypesDecoder = oneOf$1(constant$2("getEnvironment"), constant$2("getBase"), constant$2("platformShutdown"), constant$2("isFdc3DataWrappingSupported"), constant$2("clientError"), constant$2("systemHello"), constant$2("operationCheck")); - const windowRelativeDirectionDecoder = oneOf$1(constant$2("top"), constant$2("left"), constant$2("right"), constant$2("bottom")); - const windowBoundsDecoder = object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }); - const windowOpenSettingsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - context: optional$2(anyJson$2()), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - windowId: optional$2(nonEmptyStringDecoder$2), - layoutComponentId: optional$2(nonEmptyStringDecoder$2) - })); - const openWindowConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2, - options: windowOpenSettingsDecoder - }); - const windowHelloDecoder = object$2({ - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const coreWindowDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleWindowDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const helloSuccessDecoder = object$2({ - windows: array$2(coreWindowDataDecoder), - isWorkspaceFrame: boolean$2() - }); - const windowTitleConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - title: string$2() - }); - const focusEventDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - hasFocus: boolean$2() - }); - const windowMoveResizeConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relative: optional$2(boolean$2()) - }); - const windowBoundsResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const frameWindowBoundsResultDecoder = object$2({ - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const windowUrlResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2 - }); - const windowZoomFactorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - factorIndex: nonNegativeNumberDecoder$2 - }); - const anyDecoder = anyJson$2(); - const boundsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2) - }); - const instanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - applicationName: nonEmptyStringDecoder$2 - }); - const iframePermissionsPolicyConfigDecoder = object$2({ - flags: string$2() - }); - const workspacesSandboxDecoder = object$2({ - flags: string$2() - }); - const requestChannelSelectorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelsNames: array$2(nonEmptyStringDecoder$2) - }); - const channelSelectorDecoder$1 = object$2({ - enabled: boolean$2(), - }); - const applicationDetailsDecoder = object$2({ - url: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - workspacesSandbox: optional$2(workspacesSandboxDecoder), - channelSelector: optional$2(channelSelectorDecoder$1), - iframePermissionsPolicy: optional$2(iframePermissionsPolicyConfigDecoder) - }); - const intentDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - displayName: optional$2(string$2()), - contexts: optional$2(array$2(string$2())), - customConfig: optional$2(object$2()), - resultType: optional$2(string$2()) - }); - const applicationDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - customProperties: optional$2(anyJson$2()), - icon: optional$2(string$2()), - caption: optional$2(string$2()), - details: applicationDetailsDecoder, - intents: optional$2(array$2(intentDefinitionDecoder)), - hidden: optional$2(boolean$2()), - fdc3: optional$2(decoders.fdc3.v2DefinitionDecoder) - }); - const appRemoveConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const appsExportOperationDecoder = object$2({ - definitions: array$2(applicationDefinitionDecoder) - }); - const applicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - instances: array$2(instanceDataDecoder), - userProperties: optional$2(anyJson$2()), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const baseApplicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - userProperties: anyJson$2(), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const appDirectoryStateChangeDecoder = object$2({ - appsAdded: array$2(baseApplicationDataDecoder), - appsChanged: array$2(baseApplicationDataDecoder), - appsRemoved: array$2(baseApplicationDataDecoder) - }); - const appHelloSuccessDecoder = object$2({ - apps: array$2(applicationDataDecoder), - initialChannelId: optional$2(nonEmptyStringDecoder$2) - }); - const basicInstanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const layoutTypeDecoder = oneOf$1(constant$2("Global"), constant$2("Activity"), constant$2("ApplicationDefault"), constant$2("Swimlane"), constant$2("Workspace")); - const componentTypeDecoder = oneOf$1(constant$2("application"), constant$2("activity")); - const windowComponentStateDecoder = object$2({ - context: optional$2(anyJson$2()), - bounds: windowBoundsDecoder, - createArgs: object$2({ - name: optional$2(nonEmptyStringDecoder$2), - url: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - instanceId: nonEmptyStringDecoder$2, - isCollapsed: optional$2(boolean$2()), - isSticky: optional$2(boolean$2()), - restoreSettings: object$2({ - groupId: optional$2(nonEmptyStringDecoder$2), - groupZOrder: optional$2(number$2()) - }), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const windowLayoutComponentDecoder = object$2({ - type: constant$2("window"), - componentType: optional$2(componentTypeDecoder), - application: nonEmptyStringDecoder$2, - state: windowComponentStateDecoder - }); - const windowLayoutItemDecoder = object$2({ - type: constant$2("window"), - config: object$2({ - appName: nonEmptyStringDecoder$2, - url: optional$2(nonEmptyStringDecoder$2), - title: optional$2(string$2()), - allowExtract: optional$2(boolean$2()), - allowReorder: optional$2(boolean$2()), - showCloseButton: optional$2(boolean$2()), - isMaximized: optional$2(boolean$2()) - }) - }); - const groupLayoutItemDecoder = object$2({ - type: constant$2("group"), - config: anyJson$2(), - children: array$2(oneOf$1(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object$2({ - type: constant$2("column"), - config: anyJson$2(), - children: array$2(oneOf$1(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object$2({ - type: constant$2("row"), - config: anyJson$2(), - children: array$2(oneOf$1(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutComponentStateDecoder = object$2({ - config: anyJson$2(), - context: anyJson$2(), - children: array$2(oneOf$1(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }); - const workspaceLayoutComponentDecoder = object$2({ - type: constant$2("Workspace"), - application: optional$2(nonEmptyStringDecoder$2), - state: workspaceLayoutComponentStateDecoder - }); - const workspaceFrameComponentStateDecoder = object$2({ - bounds: windowBoundsDecoder, - instanceId: nonEmptyStringDecoder$2, - selectedWorkspace: nonNegativeNumberDecoder$2, - workspaces: array$2(workspaceLayoutComponentStateDecoder), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }); - const workspaceFrameComponentDecoder = object$2({ - type: constant$2("workspaceFrame"), - application: nonEmptyStringDecoder$2, - componentType: optional$2(componentTypeDecoder), - state: workspaceFrameComponentStateDecoder - }); - const glueLayoutDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()) - }); - const renamedLayoutNotificationDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()), - prevName: nonEmptyStringDecoder$2 - }); - const newLayoutOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - instances: optional$2(array$2(nonEmptyStringDecoder$2)), - ignoreInstances: optional$2(array$2(nonEmptyStringDecoder$2)), - setAsCurrent: optional$2(boolean$2()), - ignoreContexts: optional$2(boolean$2()) - }); - const restoreOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - closeRunningInstance: optional$2(boolean$2()), - closeMe: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2) - }); - const layoutSummaryDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()) - }); - const simpleLayoutConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder - }); - const saveLayoutConfigDecoder = object$2({ - layout: newLayoutOptionsDecoder - }); - const renameLayoutConfigDecoder = object$2({ - layout: glueLayoutDecoder, - newName: nonEmptyStringDecoder$2 - }); - const layoutResultDecoder = object$2({ - status: nonEmptyStringDecoder$2 - }); - const updateLayoutMetadataConfigDecoder = object$2({ - layout: glueLayoutDecoder, - }); - const restoreLayoutConfigDecoder = object$2({ - layout: restoreOptionsDecoder - }); - const getAllLayoutsConfigDecoder = object$2({ - type: layoutTypeDecoder - }); - const allLayoutsFullConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder) - }); - const defaultGlobalChangedDecoder = optional$2(object$2({ - name: nonEmptyStringDecoder$2 - })); - const importModeDecoder = oneOf$1(constant$2("replace"), constant$2("merge")); - const layoutsImportConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder), - mode: importModeDecoder, - skipManagerRequest: optional$2(boolean$2()) - }); - const allLayoutsSummariesResultDecoder = object$2({ - summaries: array$2(layoutSummaryDecoder) - }); - const simpleLayoutResultDecoder = object$2({ - layout: glueLayoutDecoder - }); - const optionalSimpleLayoutResult = object$2({ - layout: optional$2(glueLayoutDecoder) - }); - const setDefaultGlobalConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const intentsOperationTypesDecoder = oneOf$1(constant$2("findIntent"), constant$2("getIntents"), constant$2("getIntentsByHandler"), constant$2("raise"), constant$2("filterHandlers")); - const intentHandlerDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2, - applicationTitle: optional$2(string$2()), - applicationDescription: optional$2(string$2()), - applicationIcon: optional$2(string$2()), - type: oneOf$1(constant$2("app"), constant$2("instance")), - displayName: optional$2(string$2()), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - instanceId: optional$2(string$2()), - instanceTitle: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - object$2({ - applicationName: string$2(), - applicationIcon: optional$2(string$2()), - instanceId: optional$2(string$2()), - }); - object$2({ - intent: nonEmptyStringDecoder$2, - handler: intentHandlerDecoder - }); - const intentDecoder = object$2({ - name: nonEmptyStringDecoder$2, - handlers: array$2(intentHandlerDecoder) - }); - const intentTargetDecoder = oneOf$1(constant$2("startNew"), constant$2("reuse"), object$2({ - app: optional$2(nonEmptyStringDecoder$2), - instance: optional$2(nonEmptyStringDecoder$2) - })); - const intentContextDecoder = object$2({ - type: optional$2(nonEmptyStringDecoder$2), - data: optional$2(anyJson$2()) - }); - const intentsDecoder = array$2(intentDecoder); - const wrappedIntentsDecoder = object$2({ - intents: intentsDecoder - }); - const intentFilterDecoder = object$2({ - name: optional$2(nonEmptyStringDecoder$2), - contextType: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const findFilterDecoder = oneOf$1(nonEmptyStringDecoder$2, intentFilterDecoder); - const wrappedIntentFilterDecoder = object$2({ - filter: optional$2(intentFilterDecoder) - }); - const applicationStartOptionsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const intentRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - target: optional$2(intentTargetDecoder), - context: optional$2(intentContextDecoder), - options: optional$2(applicationStartOptionsDecoder), - handlers: optional$2(array$2(intentHandlerDecoder)), - timeout: optional$2(nonNegativeNumberDecoder$2), - waitUserResponseIndefinitely: optional$2(boolean$2()), - clearSavedHandler: optional$2(boolean$2()) - }); - const originAppDecoder = object$2({ - interopInstance: nonEmptyStringDecoder$2, - name: optional$2(nonEmptyStringDecoder$2) - }); - const startReasonDecoder = object$2({ - originApp: originAppDecoder, - intentRequest: optional$2(intentRequestDecoder) - }); - const applicationStartConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - waitForAGMReady: boolean$2(), - id: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()), - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - forceChromeTab: optional$2(boolean$2()), - layoutComponentId: optional$2(nonEmptyStringDecoder$2), - channelId: optional$2(nonEmptyStringDecoder$2), - startReason: startReasonDecoder - }); - const raiseRequestDecoder = oneOf$1(nonEmptyStringDecoder$2, intentRequestDecoder); - const resolverConfigDecoder = object$2({ - enabled: boolean$2(), - appName: nonEmptyStringDecoder$2, - waitResponseTimeout: number$2() - }); - const handlerExclusionCriteriaApplicationNameDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaInstanceIdDecoder = object$2({ - instanceId: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaDecoder = oneOf$1(handlerExclusionCriteriaApplicationNameDecoder, handlerExclusionCriteriaInstanceIdDecoder); - const handlerFilterDecoder = object$2({ - title: optional$2(nonEmptyStringDecoder$2), - openResolver: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2), - intent: optional$2(nonEmptyStringDecoder$2), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - resultType: optional$2(nonEmptyStringDecoder$2), - applicationNames: optional$2(array$2(nonEmptyStringDecoder$2)), - excludeList: optional$2(array$2(handlerExclusionCriteriaDecoder)) - }); - const embeddedResolverConfigDecoder = object$2({ - enabled: boolean$2(), - initialCaller: object$2({ instanceId: nonEmptyStringDecoder$2 }), - }); - const raiseIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const intentResultDecoder = object$2({ - request: intentRequestDecoder, - handler: intentHandlerDecoder, - result: anyJson$2() - }); - const filterHandlersResultDecoder = object$2({ - handlers: array$2(intentHandlerDecoder) - }); - const filterHandlersWithResolverConfigDecoder = object$2({ - filterHandlersRequest: handlerFilterDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const AddIntentListenerRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - displayName: optional$2(string$2()), - icon: optional$2(string$2()), - description: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - const AddIntentListenerDecoder = oneOf$1(nonEmptyStringDecoder$2, AddIntentListenerRequestDecoder); - const intentInfoDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - description: optional$2(nonEmptyStringDecoder$2), - displayName: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const getIntentsResultDecoder = object$2({ - intents: array$2(intentInfoDecoder) - }); - const channelNameDecoder = (channelNames) => { - return nonEmptyStringDecoder$2.where(s => channelNames.includes(s), "Expected a valid channel name"); - }; - const fdc3OptionsDecoder = object$2({ - contextType: optional$2(nonEmptyStringDecoder$2) - }); - const publishOptionsDecoder = optional$2(oneOf$1(nonEmptyStringDecoder$2, object$2({ - name: optional$2(nonEmptyStringDecoder$2), - fdc3: optional$2(boolean$2()) - }))); - const leaveChannelsConfig = object$2({ - windowId: optionalNonEmptyStringDecoder, - channel: optionalNonEmptyStringDecoder - }); - const fdc3ContextDecoder = anyJson$2().where((value) => typeof value.type === "string", "Expected a valid FDC3 Context with compulsory 'type' field"); - const interopActionSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$2, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("all"), constant$2("best"))) - }); - const glue42NotificationActionDecoder = object$2({ - action: string$2(), - title: nonEmptyStringDecoder$2, - icon: optional$2(string$2()), - interop: optional$2(interopActionSettingsDecoder) - }); - const notificationStateDecoder = oneOf$1(constant$2("Active"), constant$2("Acknowledged"), constant$2("Seen"), constant$2("Closed"), constant$2("Stale"), constant$2("Snoozed"), constant$2("Processing")); - const activeNotificationsCountChangeDecoder = object$2({ - count: number$2() - }); - const notificationDefinitionDecoder = object$2({ - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())) - }); - const glue42NotificationOptionsDecoder = object$2({ - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const notificationSetStateRequestDecoder = object$2({ - id: nonEmptyStringDecoder$2, - state: notificationStateDecoder - }); - object$2().where((value) => value.fdc3 ? typeof value.fdc3.type === "string" : true, "Expected a valid FDC3 Context with compulsory 'type' field"); - const channelFDC3DisplayMetadataDecoder = object$2({ - color: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - name: optional$2(nonEmptyStringDecoder$2), - glyph: optional$2(nonEmptyStringDecoder$2) - }); - const channelFdc3MetaDecoder = object$2({ - id: nonEmptyStringDecoder$2, - displayMetadata: optional$2(channelFDC3DisplayMetadataDecoder) - }); - const channelMetaDecoder = object$2({ - color: nonEmptyStringDecoder$2, - fdc3: optional$2(channelFdc3MetaDecoder) - }); - const channelDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - meta: channelMetaDecoder, - data: optional$2(object$2()), - }); - const pathValueDecoder = object$2({ - path: nonEmptyStringDecoder$2, - value: anyJson$2() - }); - const pathsValueDecoder = array$2(pathValueDecoder); - const removeChannelDataDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const channelRestrictionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const channelRestrictionConfigWithWindowIdDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: nonEmptyStringDecoder$2 - }); - const restrictionConfigDataDecoder = object$2({ - config: channelRestrictionConfigWithWindowIdDecoder - }); - const restrictionsDecoder = object$2({ - channels: array$2(channelRestrictionsDecoder) - }); - const getRestrictionsDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const restrictionsConfigDecoder = object$2({ - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const restrictAllDataDecoder = object$2({ - restrictions: restrictionsConfigDecoder - }); - const raiseNotificationDecoder = object$2({ - settings: glue42NotificationOptionsDecoder, - id: nonEmptyStringDecoder$2 - }); - const raiseNotificationResultDecoder = object$2({ - settings: glue42NotificationOptionsDecoder - }); - const permissionRequestResultDecoder = object$2({ - permissionGranted: boolean$2() - }); - const permissionQueryResultDecoder = object$2({ - permission: oneOf$1(constant$2("default"), constant$2("granted"), constant$2("denied")) - }); - const notificationEventPayloadDecoder = object$2({ - definition: notificationDefinitionDecoder, - action: optional$2(string$2()), - id: optional$2(nonEmptyStringDecoder$2) - }); - const notificationFilterDecoder = object$2({ - allowed: optional$2(array$2(nonEmptyStringDecoder$2)), - blocked: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const notificationsConfigurationDecoder = object$2({ - enable: optional$2(boolean$2()), - enableToasts: optional$2(boolean$2()), - sourceFilter: optional$2(notificationFilterDecoder), - showNotificationBadge: optional$2(boolean$2()) - }); - const notificationsConfigurationProtocolDecoder = object$2({ - configuration: notificationsConfigurationDecoder - }); - const strictNotificationsConfigurationProtocolDecoder = object$2({ - configuration: object$2({ - enable: boolean$2(), - enableToasts: boolean$2(), - sourceFilter: object$2({ - allowed: array$2(nonEmptyStringDecoder$2), - blocked: array$2(nonEmptyStringDecoder$2) - }) - }) - }); - const platformSaveRequestConfigDecoder = object$2({ - layoutType: oneOf$1(constant$2("Global"), constant$2("Workspace")), - layoutName: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()) - }); - const saveRequestClientResponseDecoder = object$2({ - windowContext: optional$2(anyJson$2()), - }); - const permissionStateResultDecoder = object$2({ - state: oneOf$1(constant$2("prompt"), constant$2("denied"), constant$2("granted")) - }); - const simpleAvailabilityResultDecoder = object$2({ - isAvailable: boolean$2() - }); - const simpleItemIdDecoder = object$2({ - itemId: nonEmptyStringDecoder$2 - }); - const operationCheckResultDecoder = object$2({ - isSupported: boolean$2() - }); - const operationCheckConfigDecoder = object$2({ - operation: nonEmptyStringDecoder$2 - }); - const workspaceFrameBoundsResultDecoder = object$2({ - bounds: windowBoundsDecoder - }); - const themeDecoder = object$2({ - displayName: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleThemeResponseDecoder = object$2({ - theme: themeDecoder - }); - const allThemesResponseDecoder = object$2({ - themes: array$2(themeDecoder) - }); - const selectThemeConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const notificationsDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const simpleNotificationDataDecoder = object$2({ - notification: notificationsDataDecoder - }); - const allNotificationsDataDecoder = object$2({ - notifications: array$2(notificationsDataDecoder) - }); - const simpleNotificationSelectDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelResultDecoder = object$2({ - windowIds: array$2(nonEmptyStringDecoder$2) - }); - const channelsOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("addChannel"), constant$2("getMyChannel"), constant$2("getWindowIdsOnChannel"), constant$2("getWindowIdsWithChannels"), constant$2("joinChannel"), constant$2("restrict"), constant$2("getRestrictions"), constant$2("restrictAll"), constant$2("notifyChannelsChanged"), constant$2("leaveChannel"), constant$2("getMode"), constant$2("operationCheck")); - const modeDecoder = oneOf$1(constant$2("single"), constant$2("multi")); - const getChannelsModeDecoder = object$2({ - mode: modeDecoder - }); - const channelsAppHelloDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const channelsAppHelloSuccessDecoder = object$2({ - mode: modeDecoder, - channels: array$2(nonEmptyStringDecoder$2), - restrictions: array$2(channelRestrictionsDecoder) - }); - const getMyChanelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2) - }); - const windowWithChannelFilterDecoder = object$2({ - application: optional$2(nonEmptyStringDecoder$2), - channels: optional$2(array$2(nonEmptyStringDecoder$2)), - windowIds: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const wrappedWindowWithChannelFilterDecoder = object$2({ - filter: optional$2(windowWithChannelFilterDecoder) - }); - const getWindowIdsWithChannelsResultDecoder = object$2({ - windowIdsWithChannels: array$2(object$2({ - application: nonEmptyStringDecoder$2, - channel: optional$2(nonEmptyStringDecoder$2), - windowId: nonEmptyStringDecoder$2 - })) - }); - const startApplicationContextDecoder = optional$2(anyJson$2()); - const startApplicationOptionsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - reuseId: optional$2(nonEmptyStringDecoder$2), - originIntentRequest: optional$2(intentRequestDecoder) - })); - const joinChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2, - windowId: nonEmptyStringDecoder$2 - }); - const leaveChannelDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelName: optional$2(nonEmptyStringDecoder$2) - }); - const channelsChangedDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelNames: array$2(nonEmptyStringDecoder$2) - }); - const windowChannelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2), - }); - const prefsOperationTypesDecoder = oneOf$1(constant$2("clear"), constant$2("clearAll"), constant$2("get"), constant$2("getAll"), constant$2("set"), constant$2("update"), constant$2("prefsChanged"), constant$2("prefsHello"), constant$2("operationCheck"), constant$2("registerSubscriber")); - const appPreferencesDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - lastUpdate: optional$2(nonEmptyStringDecoder$2), - }); - const basePrefsConfigDecoder = object$2({ - app: nonEmptyStringDecoder$2, - }); - const getPrefsResultDecoder = object$2({ - prefs: appPreferencesDecoder, - }); - const getAllPrefsResultDecoder = object$2({ - all: array$2(appPreferencesDecoder), - }); - const subscriberRegisterConfigDecoder = object$2({ - interopId: nonEmptyStringDecoder$2, - appName: optional$2(nonEmptyStringDecoder$2) - }); - const changePrefsDataDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - }); - const prefsHelloSuccessDecoder = object$2({ - platform: object$2({ - app: nonEmptyStringDecoder$2, - }), - validNonExistentApps: optional$2(array$2(nonEmptyStringDecoder$2)), - }); - const clientErrorDataDecoder = object$2({ - message: nonEmptyStringDecoder$2 - }); - const systemHelloSuccessDecoder = object$2({ - isClientErrorOperationSupported: boolean$2() - }); - - const nonEmptyStringDecoder$1 = decoders.common.nonEmptyStringDecoder; - const nonNegativeNumberDecoder$1 = decoders.common.nonNegativeNumberDecoder; - const widgetSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const modalsSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const intentResolverSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const channelSelectorTypeDecoder = oneOf$1(constant$2("directional"), constant$2("default")); - const channelSelectorDecoder = object$2({ - type: optional$2(channelSelectorTypeDecoder), - enable: optional$2(boolean$2()) - }); - const positionDecoder = oneOf$1(constant$2("top-left"), constant$2("top-center"), constant$2("top-right"), constant$2("center-left"), constant$2("center-right"), constant$2("bottom-left"), constant$2("bottom-center"), constant$2("bottom-right")); - const displayModeDecoder = oneOf$1(constant$2("all"), constant$2("fdc3")); - const widgetChannelsDecoder = object$2({ - selector: optional$2(channelSelectorDecoder), - displayMode: optional$2(displayModeDecoder) - }); - const platformWidgetDefaultConfigDecoder = object$2({ - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const widgetConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const modalsConfigDecoder = object$2({ - alerts: optional$2(object$2({ - enabled: boolean$2() - })), - dialogs: optional$2(object$2({ - enabled: boolean$2() - })), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - }); - const uiOperationTypesDecoder = oneOf$1(constant$2("getResources"), constant$2("operationCheck"), constant$2("showAlert"), constant$2("showDialog"), constant$2("alertInteropAction"), constant$2("showResolver")); - const getResourcesDataDecoder = object$2({ - origin: nonEmptyStringDecoder$1 - }); - const blockedResourcesDecoder = object$2({ - blockedOrigin: constant$2(true) - }); - const availableWidgetResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - config: platformWidgetDefaultConfigDecoder, - sources: widgetSourcesDecoder - }); - const widgetResourcesDecoder = union$1(blockedResourcesDecoder, availableWidgetResourcesDecoder); - const availableModalsResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: modalsSourcesDecoder - }); - const modalsResourcesDecoder = union$1(blockedResourcesDecoder, availableModalsResourcesDecoder); - const availableIntentResolverResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: intentResolverSourcesDecoder - }); - const intentResolverResourcesDecoder = union$1(blockedResourcesDecoder, availableIntentResolverResourcesDecoder); - const resourcesDecoder = object$2({ - widget: optional$2(widgetResourcesDecoder), - modals: optional$2(modalsResourcesDecoder), - intentResolver: optional$2(intentResolverResourcesDecoder) - }); - const getResourcesResultDecoder = object$2({ - resources: resourcesDecoder, - }); - const alertsInteropSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$1, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("best"), constant$2("all"), nonEmptyStringDecoder$1)) - }); - const modalRequestTargetDecoder = oneOf$1(constant$2("Global"), constant$2("WindowContainer"), nonEmptyStringDecoder$1); - const modalRequestMessageTargetDecoder = object$2({ - instance: nonEmptyStringDecoder$1, - container: optional$2(oneOf$1(constant$2("Global"), constant$2("WindowContainer"))) - }); - const alertRequestConfigDecoder = object$2({ - variant: oneOf$1(constant$2("default"), constant$2("success"), constant$2("critical"), constant$2("info"), constant$2("warning")), - text: nonEmptyStringDecoder$1, - showCloseButton: optional$2(boolean$2()), - clickInterop: optional$2(alertsInteropSettingsDecoder), - onCloseInterop: optional$2(alertsInteropSettingsDecoder), - actions: optional$2(array$2(object$2({ - id: nonEmptyStringDecoder$1, - title: nonEmptyStringDecoder$1, - clickInterop: alertsInteropSettingsDecoder - }))), - data: optional$2(anyJson$2()), - ttl: optional$2(nonNegativeNumberDecoder$1), - target: optional$2(modalRequestTargetDecoder) - }); - const uiAlertRequestMessageDecoder = object$2({ - config: alertRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const dialogRequestConfigDecoder = object$2({ - templateName: nonEmptyStringDecoder$1, - variables: anyJson$2(), - target: optional$2(modalRequestTargetDecoder), - timer: optional$2(object$2({ - duration: nonNegativeNumberDecoder$1 - })), - size: optional$2(object$2({ - width: nonNegativeNumberDecoder$1, - height: nonNegativeNumberDecoder$1 - })), - movable: optional$2(boolean$2()), - transparent: optional$2(boolean$2()) - }); - const dialogResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - isEnterPressed: optional$2(boolean$2()), - responseButtonClicked: optional$2(object$2({ - id: nonEmptyStringDecoder$1, - text: nonEmptyStringDecoder$1 - })), - inputs: optional$2(array$2(object$2({ - type: oneOf$1(constant$2("checkbox"), constant$2("email"), constant$2("number"), constant$2("password"), constant$2("text")), - id: nonEmptyStringDecoder$1, - checked: optional$2(boolean$2()), - value: optional$2(string$2()) - }))) - }); - object$2({ - result: dialogResponseDecoder - }); - const uiDialogRequestMessageDecoder = object$2({ - config: dialogRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const openAlertResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const openDialogResultDecoder = object$2({ - id: nonEmptyStringDecoder$1, - responsePromise: anyJson$2() - }); - const dialogOnCompletionConfigDecoder = object$2({ - response: dialogResponseDecoder - }); - const alertInteropActionDecoder = object$2({ - name: nonEmptyStringDecoder$1, - settings: alertsInteropSettingsDecoder - }); - const alertOnClickConfigDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const alertInteropActionDataDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const intentResolverConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1) - }); - const openResolverResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const userSettingsDecoder = object$2({ - preserveChoice: boolean$2() - }); - const userChoiceResponseDecoder = object$2({ - intent: nonEmptyStringDecoder$1, - handler: intentHandlerDecoder, - userSettings: userSettingsDecoder - }); - const intentResolverResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - userChoice: optional$2(userChoiceResponseDecoder) - }); - const onUserResponseResponseDecoder = object$2({ - response: intentResolverResponseDecoder - }); - const openConfigWithIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder - }); - const openConfigWithHandlerFilterDecoder = object$2({ - handlerFilter: handlerFilterDecoder - }); - const intentResolverOpenConfigDecoder = union$1(openConfigWithIntentRequestDecoder, openConfigWithHandlerFilterDecoder); - const uiResolverRequestMessageConfigDecoder = intersection(intentResolverOpenConfigDecoder, object$2({ timeout: nonNegativeNumberDecoder$1 })); - const uiResolverRequestMessageDecoder = object$2({ - config: uiResolverRequestMessageConfigDecoder - }); - const uiResolverResponseMessageDecoder = object$2({ - result: intentResolverResponseDecoder - }); - - const parseConfig = (config = {}) => { - const isPlatformInternal = !!config?.gateway?.webPlatform?.port; - const decodedWidgetConfigResult = optional$2(widgetConfigDecoder).run(config.widget); - if (!decodedWidgetConfigResult.ok) { - throw ioError.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(decodedWidgetConfigResult.error)}`); - } - const decodedModalsConfigResult = optional$2(modalsConfigDecoder).run(config.modals); - if (!decodedModalsConfigResult.ok) { - throw ioError.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(decodedModalsConfigResult.error)}`); - } - const decodedIntentResolverConfigResult = optional$2(intentResolverConfigDecoder).run(config.intentResolver); - if (!decodedIntentResolverConfigResult.ok) { - throw ioError.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(decodedIntentResolverConfigResult.error)}`); - } - const combined = { - ...defaultConfig, - ...config, - isPlatformInternal, - logger: config.systemLogger?.level ?? "info", - customLogger: config.systemLogger?.customLogger, - widget: deepmerge$1(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}), - modals: deepmerge$1(defaultModalsConfig, decodedModalsConfigResult.result ?? {}), - intentResolver: deepmerge$1(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}), - }; - return combined; - }; - - const checkSingleton = () => { - const ioConnectBrowserNamespace = window.glue42core || window.iobrowser; - if (ioConnectBrowserNamespace && ioConnectBrowserNamespace.webStarted) { - return ioError.raiseError("IoConnect Browser has already been started for this application."); - } - if (!ioConnectBrowserNamespace) { - window.iobrowser = { webStarted: true }; - return; - } - ioConnectBrowserNamespace.webStarted = true; - }; - - const enterprise = (config) => { - const enterpriseConfig = { - windows: true, - layouts: "full", - appManager: "full", - channels: true, - libraries: config?.libraries ?? [], - logger: config?.systemLogger?.level ?? "warn" - }; - const injectedFactory = window.IODesktop || window.Glue; - return injectedFactory(enterpriseConfig); - }; - - const operations$a = { - openWindow: { name: "openWindow", dataDecoder: openWindowConfigDecoder, resultDecoder: coreWindowDataDecoder }, - windowHello: { name: "windowHello", dataDecoder: windowHelloDecoder, resultDecoder: helloSuccessDecoder }, - windowAdded: { name: "windowAdded", dataDecoder: coreWindowDataDecoder }, - windowRemoved: { name: "windowRemoved", dataDecoder: simpleWindowDecoder }, - getBounds: { name: "getBounds", dataDecoder: simpleWindowDecoder, resultDecoder: windowBoundsResultDecoder }, - getFrameBounds: { name: "getFrameBounds", dataDecoder: simpleWindowDecoder, resultDecoder: frameWindowBoundsResultDecoder }, - getUrl: { name: "getUrl", dataDecoder: simpleWindowDecoder, resultDecoder: windowUrlResultDecoder }, - moveResize: { name: "moveResize", dataDecoder: windowMoveResizeConfigDecoder }, - focus: { name: "focus", dataDecoder: simpleWindowDecoder }, - close: { name: "close", dataDecoder: simpleWindowDecoder }, - getTitle: { name: "getTitle", dataDecoder: simpleWindowDecoder, resultDecoder: windowTitleConfigDecoder }, - setTitle: { name: "setTitle", dataDecoder: windowTitleConfigDecoder }, - focusChange: { name: "focusChange", dataDecoder: focusEventDataDecoder }, - getChannel: { name: "getChannel", dataDecoder: simpleWindowDecoder, resultDecoder: windowChannelResultDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - setZoomFactor: { name: "setZoomFactor", dataDecoder: windowZoomFactorConfigDecoder }, - zoomFactorChange: { name: "zoomFactorChange", dataDecoder: windowZoomFactorConfigDecoder }, - refresh: { name: "refresh", dataDecoder: simpleWindowDecoder }, - operationCheck: { name: "operationCheck" } - }; - - function createRegistry$1(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry$1.default = createRegistry$1; - var lib$1 = createRegistry$1; - - - var CallbackRegistryFactory$1 = /*@__PURE__*/getDefaultExportFromCjs$1(lib$1); - - const ZOOM_FACTORS = Object.freeze({ - 0: 24, - 1: 33, - 2: 50, - 3: 67, - 4: 75, - 5: 80, - 6: 90, - 7: 100, - 8: 110, - 9: 125, - 10: 150, - 11: 175, - 12: 200, - 13: 250, - 14: 300, - 15: 400, - 16: 500 - }); - - class WebWindowModel { - _id; - _name; - _bridge; - _logger; - registry = CallbackRegistryFactory$1(); - myCtxKey; - ctxUnsubscribe; - zoomFactorIndex = 7; - me; - constructor(_id, _name, _bridge, _logger) { - this._id = _id; - this._name = _name; - this._bridge = _bridge; - this._logger = _logger; - this.myCtxKey = `___window___${this.id}`; - } - get id() { - return this._id.slice(); - } - get name() { - return this._name.slice(); - } - get zoomFactor() { - return ZOOM_FACTORS[this.zoomFactorIndex]; - } - clean() { - if (this.ctxUnsubscribe) { - this.ctxUnsubscribe(); - } - } - processSelfFocusEvent(hasFocus) { - this.me.isFocused = hasFocus; - this.registry.execute("focus-change", this.me); - } - processChannelsChangedEvent(channelNames) { - this.registry.execute("channels-changed", channelNames); - } - processSelfZoomFactorChangedEvent(factorIndex) { - this.zoomFactorIndex = factorIndex; - this.registry.execute("zoom-factor-changed", this.me); - } - async toApi() { - this.ctxUnsubscribe = await this._bridge.contextLib.subscribe(this.myCtxKey, (data) => this.registry.execute("context-updated", data)); - this.me = { - id: this.id, - name: this.name, - isFocused: false, - zoomFactor: this.zoomFactor, - getURL: this.getURL.bind(this), - moveResize: this.moveResize.bind(this), - resizeTo: this.resizeTo.bind(this), - moveTo: this.moveTo.bind(this), - focus: this.focus.bind(this), - close: this.close.bind(this), - getTitle: this.getTitle.bind(this), - setTitle: this.setTitle.bind(this), - getBounds: this.getBounds.bind(this), - getContext: this.getContext.bind(this), - updateContext: this.updateContext.bind(this), - setContext: this.setContext.bind(this), - refresh: this.refresh.bind(this), - onContextUpdated: this.onContextUpdated.bind(this), - onFocusChanged: this.onFocusChanged.bind(this), - getChannel: this.getChannel.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - zoomIn: this.zoomIn.bind(this), - zoomOut: this.zoomOut.bind(this), - setZoomFactor: this.setZoomFactor.bind(this), - onZoomFactorChanged: this.onZoomFactorChanged.bind(this), - }; - Object.defineProperties(this.me, { - id: READONLY_PROPERTY_DESCRIPTOR, - name: READONLY_PROPERTY_DESCRIPTOR, - zoomFactor: { - get: () => { - return this.zoomFactor; - }, - enumerable: true, - }, - }); - return this.me; - } - async getURL() { - const result = await this._bridge.send("windows", operations$a.getUrl, { windowId: this.id }); - return result.url; - } - onFocusChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - return this.registry.add("focus-change", callback); - } - async moveResize(dimension) { - const targetBounds = runDecoderWithIOError(boundsDecoder, dimension); - const commandArgs = Object.assign({}, targetBounds, { windowId: this.id, relative: false }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async resizeTo(width, height) { - if (typeof width === "undefined" && typeof height === "undefined") { - return this.me; - } - if (typeof width !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, width); - } - if (typeof height !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, height); - } - const commandArgs = Object.assign({}, { width, height }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async moveTo(top, left) { - if (typeof top === "undefined" && typeof left === "undefined") { - return this.me; - } - if (typeof top !== "undefined") { - runDecoderWithIOError(number$2(), top); - } - if (typeof left !== "undefined") { - runDecoderWithIOError(number$2(), left); - } - const commandArgs = Object.assign({}, { top, left }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async focus() { - if (this.name === "Platform") { - window.open(undefined, this.id); - } - else { - await this._bridge.send("windows", operations$a.focus, { windowId: this.id }); - } - return this.me; - } - async close() { - await this._bridge.send("windows", operations$a.close, { windowId: this.id }); - return this.me; - } - async getTitle() { - const result = await this._bridge.send("windows", operations$a.getTitle, { windowId: this.id }); - return result.title; - } - async setTitle(title) { - const ttl = runDecoderWithIOError(nonEmptyStringDecoder$2, title); - await this._bridge.send("windows", operations$a.setTitle, { windowId: this.id, title: ttl }); - return this.me; - } - async getBounds() { - const result = await this._bridge.send("windows", operations$a.getBounds, { windowId: this.id }); - return result.bounds; - } - async getContext() { - const ctx = await this._bridge.contextLib.get(this.myCtxKey); - const { ___io___, ...rest } = ctx; - return rest; - } - async updateContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - await this._bridge.contextLib.update(this.myCtxKey, ctx); - return this.me; - } - async setContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - const current = await this._bridge.contextLib.get(this.myCtxKey); - const newCtx = current.___io___ ? { ...ctx, ___io___: current.___io___ } : ctx; - await this._bridge.contextLib.set(this.myCtxKey, newCtx); - return this.me; - } - onContextUpdated(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - const wrappedCallback = (data) => { - const { ___io___, ...rest } = data; - callback(rest, this.me); - }; - return this.registry.add("context-updated", wrappedCallback); - } - async getChannel() { - const result = await this._bridge.send("windows", operations$a.getChannel, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return result.channel; - } - onChannelsChanged(callback) { - return this.registry.add("channels-changed", callback); - } - getClosestZoomFactorIndex(factor) { - const closestIndex = Object.entries(ZOOM_FACTORS).reduce((closestIndex, [currentIndex, currentValue]) => { - return (Math.abs(currentValue - factor) <= Math.abs(ZOOM_FACTORS[closestIndex] - factor) ? parseInt(currentIndex) : closestIndex); - }, 0); - const closestFactor = ZOOM_FACTORS[closestIndex]; - if (closestFactor !== factor) { - this._logger.warn(`Zoom factor ${factor} is not available, using closest value ${closestFactor} instead.`); - } - return closestIndex; - } - async zoom(factorIndex) { - if (factorIndex === this.zoomFactorIndex || !(factorIndex in ZOOM_FACTORS)) { - return; - } - await this._bridge.send("windows", operations$a.setZoomFactor, { windowId: this.id, factorIndex }, undefined, { includeOperationCheck: true }); - this.zoomFactorIndex = factorIndex; - } - async zoomIn() { - await this.zoom(this.zoomFactorIndex + 1); - return this.me; - } - async zoomOut() { - await this.zoom(this.zoomFactorIndex - 1); - return this.me; - } - async setZoomFactor(factor) { - const targetZoomFactor = runDecoderWithIOError(number$2(), factor); - const closestZoomFactorIndex = this.getClosestZoomFactorIndex(targetZoomFactor); - await this.zoom(closestZoomFactorIndex); - return this.me; - } - onZoomFactorChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"); - } - return this.registry.add("zoom-factor-changed", callback); - } - async refresh() { - await this._bridge.send("windows", operations$a.refresh, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return this.me; - } - } - - const commonOperations = { - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - getWorkspaceWindowFrameBounds: { name: "getWorkspaceWindowFrameBounds", resultDecoder: workspaceFrameBoundsResultDecoder, dataDecoder: simpleItemIdDecoder } - }; - - const PromiseWrap = (callback, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - callback() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - const PromisePlus$1 = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WindowsController { - supportedOperationsNames = []; - focusEventHandler; - registry = CallbackRegistryFactory$1(); - platformRegistration; - ioc; - bridge; - publicWindowId; - allWindowProjections = []; - me; - logger; - isWorkspaceFrame; - instanceId; - channelsController; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("windows.controller.web"); - this.logger.trace("starting the web windows controller"); - this.publicWindowId = ioc.publicWindowId; - this.addWindowOperationExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.instanceId = coreGlue.interop.instance.instance; - this.channelsController = ioc.channelsController; - this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`); - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - await this.initializeFocusTracking(); - this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning"); - const api = this.toApi(); - coreGlue.windows = api; - } - handlePlatformShutdown() { - this.registry.clear(); - this.allWindowProjections = []; - if (!this.focusEventHandler) { - return; - } - document.removeEventListener("visibilityChange", this.focusEventHandler); - window.removeEventListener("focus", this.focusEventHandler); - window.removeEventListener("blur", this.focusEventHandler); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(windowOperationTypesDecoder, args.operation); - const operation = operations$a[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async open(name, url, options) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(nonEmptyStringDecoder$2, url); - const settings = runDecoderWithIOError(windowOpenSettingsDecoder, options); - const windowSuccess = await this.bridge.send("windows", operations$a.openWindow, { name, url, options: settings }); - return this.waitForWindowAdded(windowSuccess.windowId); - } - list() { - return this.allWindowProjections.map((projection) => projection.api); - } - findById(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - return this.allWindowProjections.find((projection) => projection.id === id)?.api; - } - toApi() { - return { - open: this.open.bind(this), - my: this.my.bind(this), - list: this.list.bind(this), - findById: this.findById.bind(this), - onWindowAdded: this.onWindowAdded.bind(this), - onWindowRemoved: this.onWindowRemoved.bind(this), - onWindowGotFocus: this.onWindowGotFocus.bind(this), - onWindowLostFocus: this.onWindowLostFocus.bind(this) - }; - } - addWindowOperationExecutors() { - operations$a.focusChange.execute = this.handleFocusChangeEvent.bind(this); - operations$a.windowAdded.execute = this.handleWindowAdded.bind(this); - operations$a.windowRemoved.execute = this.handleWindowRemoved.bind(this); - operations$a.getBounds.execute = this.handleGetBounds.bind(this); - operations$a.getFrameBounds.execute = this.handleGetBounds.bind(this); - operations$a.getTitle.execute = this.handleGetTitle.bind(this); - operations$a.getUrl.execute = this.handleGetUrl.bind(this); - operations$a.moveResize.execute = this.handleMoveResize.bind(this); - operations$a.setTitle.execute = this.handleSetTitle.bind(this); - operations$a.getChannel.execute = this.handleGetChannel.bind(this); - operations$a.notifyChannelsChanged.execute = this.handleChannelsChanged.bind(this); - operations$a.setZoomFactor.execute = this.handleSetZoomFactor.bind(this); - operations$a.zoomFactorChange.execute = this.handleZoomFactorChanged.bind(this); - operations$a.refresh.execute = this.handleRefresh.bind(this); - operations$a.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$a); - } - my() { - return Object.assign({}, this.me); - } - onWindowAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"); - } - return this.registry.add("window-added", callback); - } - onWindowRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"); - } - return this.registry.add("window-removed", callback); - } - onWindowGotFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-got-focus", callback); - } - onWindowLostFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-lost-focus", callback); - } - async sayHello() { - const helloSuccess = await this.bridge.send("windows", operations$a.windowHello, { windowId: this.publicWindowId }); - return helloSuccess; - } - async registerWithPlatform() { - const { windows, isWorkspaceFrame } = await this.sayHello(); - this.isWorkspaceFrame = isWorkspaceFrame; - this.logger.trace("the platform responded to the hello message"); - if (!this.isWorkspaceFrame && this.publicWindowId) { - this.logger.trace("i am not treated as a workspace frame, setting my window"); - const myWindow = windows.find((w) => w.windowId === this.publicWindowId); - if (!myWindow) { - const windowsInfo = windows.map(w => `${w.windowId}:${w.name}`).join(", "); - return ioError.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${windowsInfo}`); - } - const myProjection = await this.ioc.buildWebWindow(this.publicWindowId, myWindow.name, this.logger); - this.me = myProjection.api; - this.allWindowProjections.push(myProjection); - } - const currentWindows = await Promise.all(windows - .filter((w) => w.windowId !== this.publicWindowId) - .map((w) => this.ioc.buildWebWindow(w.windowId, w.name, this.logger))); - this.logger.trace("all windows projections are completed, building the list collection"); - this.allWindowProjections.push(...currentWindows); - } - async handleFocusChangeEvent(focusData) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === focusData.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfFocusEvent(focusData.hasFocus); - const keyToExecute = focusData.hasFocus ? "window-got-focus" : "window-lost-focus"; - this.registry.execute(keyToExecute, foundProjection.api); - } - async handleWindowAdded(data) { - if (this.allWindowProjections.some((projection) => projection.id === data.windowId)) { - return; - } - const webWindowProjection = await this.ioc.buildWebWindow(data.windowId, data.name, this.logger); - this.allWindowProjections.push(webWindowProjection); - this.registry.execute("window-added", webWindowProjection.api); - } - async handleWindowRemoved(data) { - const removed = this.allWindowProjections.find((w) => w.id === data.windowId); - if (!removed) { - return; - } - this.allWindowProjections = this.allWindowProjections.filter((w) => w.id !== data.windowId); - removed.model.clean(); - this.registry.execute("window-removed", removed.api); - } - async handleGetBounds() { - if (!this.me && !this.isWorkspaceFrame) { - return ioError.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.isWorkspaceFrame ? "noop" : this.me.id, - bounds: { - top: window.screenTop, - left: window.screenLeft, - width: window.innerWidth, - height: window.innerHeight - } - }; - } - async handleGetTitle() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - title: document.title - }; - } - async handleGetUrl() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - url: window.location.href - }; - } - async handleMoveResize(config) { - const targetTop = typeof config.top === "number" ? config.top : - config.relative ? 0 : window.screenTop; - const targetLeft = typeof config.left === "number" ? config.left : - config.relative ? 0 : window.screenLeft; - const targetHeight = typeof config.height === "number" ? config.height : - config.relative ? 0 : window.innerHeight; - const targetWidth = typeof config.width === "number" ? config.width : - config.relative ? 0 : window.innerWidth; - const moveMethod = config.relative ? window.moveBy : window.moveTo; - const resizeMethod = config.relative ? window.resizeBy : window.resizeTo; - moveMethod(targetLeft, targetTop); - resizeMethod(targetWidth, targetHeight); - } - async handleSetTitle(config) { - document.title = config.title; - } - async initializeFocusTracking() { - if (this.isWorkspaceFrame) { - this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame"); - return; - } - try { - await this.bridge.send("windows", commonOperations.operationCheck, { operation: "focusChange" }); - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client."); - return; - } - const hasFocus = document.hasFocus(); - await this.transmitFocusChange(true); - if (!hasFocus) { - await this.transmitFocusChange(false); - } - this.defineEventListeners(); - } - processFocusEvent() { - const hasFocus = document.hasFocus(); - this.transmitFocusChange(hasFocus); - } - waitForWindowAdded(windowId) { - const foundWindow = this.allWindowProjections.find((projection) => projection.id === windowId); - if (foundWindow) { - return Promise.resolve(foundWindow.api); - } - return PromisePlus$1((resolve) => { - const unsubscribe = this.onWindowAdded((addedWindow) => { - if (addedWindow.id === windowId) { - unsubscribe(); - resolve(addedWindow); - } - }); - }, 30000, `Timed out waiting for ${windowId} to be announced`); - } - async transmitFocusChange(hasFocus) { - const eventData = { - windowId: this.me?.id || `iframe-${this.instanceId}`, - hasFocus - }; - if (this.me) { - this.me.isFocused = hasFocus; - } - await this.bridge.send("windows", operations$a.focusChange, eventData); - } - defineEventListeners() { - this.focusEventHandler = this.processFocusEvent.bind(this); - document.addEventListener("visibilityChange", this.focusEventHandler); - window.addEventListener("focus", this.focusEventHandler); - window.addEventListener("blur", this.focusEventHandler); - } - async handleGetChannel() { - if (!this.me) { - return ioError.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe"); - } - const channel = this.channelsController.my(); - return { - ...(channel ? { channel } : {}), - }; - } - async handleRefresh() { - if (!this.me) { - return ioError.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe"); - } - setTimeout(() => { - window.location.reload(); - }, 0); - } - async handleChannelsChanged(data) { - const windowProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - windowProjection?.model.processChannelsChangedEvent(data.channelNames); - } - async handleSetZoomFactor(config) { - if (!this.me) { - return ioError.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe"); - } - document.body.style.zoom = `${ZOOM_FACTORS[config.factorIndex]}%`; - } - async handleZoomFactorChanged(data) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfZoomFactorChangedEvent(data.factorIndex); - } - } - - const GlueWebPlatformControlName = "T42.Web.Platform.Control"; - const GlueWebPlatformStreamName = "T42.Web.Platform.Stream"; - const GlueClientControlName = "T42.Web.Client.Control"; - const GlueCorePlusThemesStream = "T42.Core.Plus.Themes.Stream"; - - class GlueBridge { - coreGlue; - communicationId; - platformMethodTimeoutMs = 10000; - controllers; - sub; - running; - constructor(coreGlue, communicationId) { - this.coreGlue = coreGlue; - this.communicationId = communicationId; - } - get contextLib() { - return this.coreGlue.contexts; - } - get interopInstance() { - return this.coreGlue.interop.instance.instance; - } - async stop() { - this.running = false; - this.sub.close(); - await this.coreGlue.interop.unregister(GlueClientControlName); - } - async start(controllers) { - this.running = true; - this.controllers = controllers; - await Promise.all([ - this.checkWaitMethod(GlueWebPlatformControlName), - this.checkWaitMethod(GlueWebPlatformStreamName) - ]); - const systemId = this.communicationId; - const [sub] = await Promise.all([ - this.coreGlue.interop.subscribe(GlueWebPlatformStreamName, systemId ? { target: { instance: this.communicationId } } : undefined), - this.coreGlue.interop.registerAsync(GlueClientControlName, (args, _, success, error) => this.passMessageController(args, success, error)) - ]); - this.sub = sub; - this.sub.onData((pkg) => this.passMessageController(pkg.data)); - } - getInteropInstance(windowId) { - const result = this.coreGlue.interop.servers().find((s) => s.windowId && s.windowId === windowId); - return { - application: result?.application, - applicationName: result?.applicationName, - peerId: result?.peerId, - instance: result?.instance, - windowId: result?.windowId - }; - } - async send(domain, operation, operationData, options, webOptions) { - if (operation.dataDecoder) { - try { - operation.dataDecoder.runWithException(operationData); - } - catch (error) { - return ioError.raiseError(`Unexpected Web->Platform outgoing validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - } - const operationSupported = webOptions?.includeOperationCheck ? - (await this.checkOperationSupported(domain, operation)).isSupported : - true; - if (!operationSupported) { - return ioError.raiseError(`Cannot complete operation: ${operation.name} for domain: ${domain} because this client is connected to a platform which does not support it`); - } - try { - const operationResult = await this.transmitMessage(domain, operation, operationData, options); - if (operation.resultDecoder) { - operation.resultDecoder.runWithException(operationResult); - } - return operationResult; - } - catch (error) { - if (error?.kind) { - return ioError.raiseError(`Unexpected Web<-Platform incoming validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - return ioError.raiseError(error); - } - } - async createNotificationsSteam() { - const streamExists = this.coreGlue.interop.methods().some((method) => method.name === GlueCorePlusThemesStream); - if (!streamExists) { - return ioError.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus."); - } - return this.coreGlue.interop.subscribe(GlueCorePlusThemesStream, this.communicationId ? { target: { instance: this.communicationId } } : undefined); - } - async checkOperationSupported(domain, operation) { - try { - const result = await this.send(domain, commonOperations.operationCheck, { operation: operation.name }); - return result; - } - catch (error) { - return { isSupported: false }; - } - } - checkWaitMethod(name) { - return PromisePlus$1((resolve) => { - const hasMethod = this.coreGlue.interop.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = this.communicationId ? - method.getServers().some((server) => server.instance === this.communicationId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - return resolve(); - } - const unSub = this.coreGlue.interop.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = this.communicationId ? - server.instance === this.communicationId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }, this.platformMethodTimeoutMs, `Cannot initiate Glue Web, because a system method's discovery timed out: ${name}`); - } - passMessageController(args, success, error) { - const decodeResult = libDomainDecoder.run(args.domain); - if (!decodeResult.ok) { - if (error) { - error(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(decodeResult.error)}`); - } - return; - } - const domain = decodeResult.result; - this.controllers[domain] - .handleBridgeMessage(args) - .then((resolutionData) => { - if (success) { - success(resolutionData); - } - }) - .catch((err) => { - if (error) { - error(err); - } - console.warn(err); - }); - } - async transmitMessage(domain, operation, data, options) { - const messageData = { domain, data, operation: operation.name }; - let invocationResult; - const baseErrorMessage = `Internal Platform Communication Error. Attempted operation: ${JSON.stringify(operation.name)} with data: ${JSON.stringify(data)}. `; - const systemId = this.communicationId; - try { - if (!this.running) { - throw new Error("Cannot send a control message, because the platform shut down"); - } - invocationResult = await this.coreGlue.interop.invoke(GlueWebPlatformControlName, messageData, systemId ? { instance: this.communicationId } : undefined, options); - if (!invocationResult) { - throw new Error("Received unsupported result from the platform - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from the platform - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - } - - const operations$9 = { - appHello: { name: "appHello", dataDecoder: windowHelloDecoder, resultDecoder: appHelloSuccessDecoder }, - appDirectoryStateChange: { name: "appDirectoryStateChange", dataDecoder: appDirectoryStateChangeDecoder }, - instanceStarted: { name: "instanceStarted", dataDecoder: instanceDataDecoder }, - instanceStopped: { name: "instanceStopped", dataDecoder: instanceDataDecoder }, - applicationStart: { name: "applicationStart", dataDecoder: applicationStartConfigDecoder, resultDecoder: instanceDataDecoder }, - instanceStop: { name: "instanceStop", dataDecoder: basicInstanceDataDecoder }, - import: { name: "import" }, - remove: { name: "remove", dataDecoder: appRemoveConfigDecoder }, - export: { name: "export", resultDecoder: appsExportOperationDecoder }, - clear: { name: "clear" }, - operationCheck: { name: "operationCheck" } - }; - - class AppManagerController { - me; - supportedOperationsNames = []; - baseApplicationsTimeoutMS = 60000; - appImportTimeoutMS = 20; - registry = CallbackRegistryFactory$1(); - ioc; - bridge; - publicWindowId; - applications = []; - instances = []; - platformRegistration; - logger; - channelsController; - interop; - initialChannelId; - handlePlatformShutdown() { - this.registry.clear(); - this.applications = []; - this.instances = []; - delete this.me; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("appManger.controller.web"); - this.logger.trace("starting the web appManager controller"); - this.publicWindowId = ioc.publicWindowId; - this.addOperationsExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.interop = coreGlue.interop; - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning"); - const api = this.toApi(); - coreGlue.appManager = api; - } - async postStart() { - if (!this.initialChannelId) { - return; - } - await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(appManagerOperationTypesDecoder, args.operation); - const operation = operations$9[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStarted requires a single argument of type function"); - } - return this.registry.add("instance-started", callback, this.instances); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStopped requires a single argument of type function"); - } - return this.registry.add("instance-stopped", callback); - } - async startApplication(appName, context, options) { - const channels = await this.channelsController.all(); - if (options?.channelId && !channels.includes(options.channelId)) { - return ioError.raiseError(`The channel with name "${options.channelId}" doesn't exist!`); - } - const startOptions = { - name: appName, - waitForAGMReady: options?.waitForAGMReady ?? true, - context, - top: options?.top, - left: options?.left, - width: options?.width, - height: options?.height, - relativeTo: options?.relativeTo, - relativeDirection: options?.relativeDirection, - id: options?.reuseId, - forceChromeTab: options?.forceTab, - layoutComponentId: options?.layoutComponentId, - channelId: options?.channelId, - startReason: { - originApp: { - name: this.me?.application.name, - interopInstance: this.interop.instance.instance - } - } - }; - if (options?.originIntentRequest) { - startOptions.startReason.intentRequest = options.originIntentRequest; - } - const openResult = await this.bridge.send("appManager", operations$9.applicationStart, startOptions); - const app = this.applications.find((a) => a.name === openResult.applicationName); - return this.ioc.buildInstance(openResult, app); - } - getApplication(name) { - const verifiedName = runDecoderWithIOError(nonEmptyStringDecoder$2, name); - return this.applications.find((app) => app.name === verifiedName); - } - getInstances() { - return this.instances.slice(); - } - onAppAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppAdded requires a single argument of type function"); - } - return this.registry.add("application-added", callback, this.applications); - } - onAppRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppRemoved requires a single argument of type function"); - } - return this.registry.add("application-removed", callback); - } - toApi() { - const api = { - myInstance: this.me, - inMemory: { - import: this.importApps.bind(this), - remove: this.remove.bind(this), - export: this.exportApps.bind(this), - clear: this.clear.bind(this) - }, - application: this.getApplication.bind(this), - applications: this.getApplications.bind(this), - instances: this.getInstances.bind(this), - onAppAdded: this.onAppAdded.bind(this), - onAppChanged: this.onAppChanged.bind(this), - onAppRemoved: this.onAppRemoved.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - return api; - } - addOperationsExecutors() { - operations$9.appDirectoryStateChange.execute = this.handleAppDirectoryStateChange.bind(this); - operations$9.instanceStarted.execute = this.handleInstanceStartedMessage.bind(this); - operations$9.instanceStopped.execute = this.handleInstanceStoppedMessage.bind(this); - operations$9.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$9); - } - async handleAppDirectoryStateChange(data) { - data.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)); - data.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)); - data.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this)); - } - onAppChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppChanged requires a single argument of type function"); - } - return this.registry.add("application-changed", callback); - } - async handleApplicationAddedMessage(appData) { - if (this.applications.some((app) => app.name === appData.name)) { - return; - } - const app = await this.ioc.buildApplication(appData, []); - const instances = this.instances.filter((instance) => instance.application.name === app.name); - app.instances.push(...instances); - this.applications.push(app); - this.registry.execute("application-added", app); - } - async handleApplicationRemovedMessage(appData) { - const appIndex = this.applications.findIndex((app) => app.name === appData.name); - if (appIndex < 0) { - return; - } - const app = this.applications[appIndex]; - this.applications.splice(appIndex, 1); - this.registry.execute("application-removed", app); - } - async handleApplicationChangedMessage(appData) { - const app = this.applications.find((app) => app.name === appData.name); - if (!app) { - return this.handleApplicationAddedMessage(appData); - } - app.title = appData.title; - app.version = appData.version; - app.icon = appData.icon; - app.caption = appData.caption; - app.userProperties = appData.userProperties; - this.registry.execute("application-changed", app); - } - async handleInstanceStartedMessage(instanceData) { - if (this.instances.some((instance) => instance.id === instanceData.id)) { - return; - } - const application = this.applications.find((app) => app.name === instanceData.applicationName); - if (!application) { - return ioError.raiseError(`Cannot add instance: ${instanceData.id}, because there is no application definition associated with it`); - } - const instance = this.ioc.buildInstance(instanceData, application); - this.instances.push(instance); - application.instances.push(instance); - this.registry.execute("instance-started", instance); - } - async handleInstanceStoppedMessage(instanceData) { - const instance = this.instances.find((i) => i.id === instanceData.id); - if (instance) { - const instIdx = this.instances.findIndex((inst) => inst.id === instanceData.id); - this.instances.splice(instIdx, 1); - } - const application = this.applications.find((app) => app.instances.some((inst) => inst.id === instanceData.id)); - if (application) { - const instIdxApps = application.instances.findIndex((inst) => inst.id === instanceData.id); - application.instances.splice(instIdxApps, 1); - } - if (!instance) { - return; - } - this.registry.execute("instance-stopped", instance); - } - async importApps(definitions, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(definitions)) { - return ioError.raiseError("Import must be called with an array of definitions"); - } - if (definitions.length > 10000) { - return ioError.raiseError("Cannot import more than 10000 app definitions in Glue42 Core."); - } - const parseResult = definitions.reduce((soFar, definition) => { - const { isValid, error } = this.isValidDefinition(definition); - if (!isValid) { - soFar.invalid.push({ app: definition?.name, error: error ?? `Provided definition is invalid ${JSON.stringify(definition)}` }); - } - else { - soFar.valid.push(definition); - } - return soFar; - }, { valid: [], invalid: [] }); - const responseTimeout = this.baseApplicationsTimeoutMS + this.appImportTimeoutMS * parseResult.valid.length; - await this.bridge.send("appManager", operations$9.import, { definitions: parseResult.valid, mode }, { methodResponseTimeoutMs: responseTimeout }); - return { - imported: parseResult.valid.map((valid) => valid.name), - errors: parseResult.invalid - }; - } - isValidDefinition(definition) { - const isFdc3V2Definition = definition?.appId && definition?.details; - if (isFdc3V2Definition) { - const decodeResult = decoders.fdc3.v2DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v2 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const isFdc3V1Definition = definition?.appId && definition?.manifest; - if (isFdc3V1Definition) { - const decodeResult = decoders.fdc3.v1DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v1 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const decodeResult = applicationDefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("appManager", operations$9.remove, { name }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async clear() { - await this.bridge.send("appManager", operations$9.clear, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async exportApps() { - const response = await this.bridge.send("appManager", operations$9.export, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - return response.definitions; - } - getApplications() { - return this.applications.slice(); - } - async registerWithPlatform() { - const result = await this.bridge.send("appManager", operations$9.appHello, { windowId: this.publicWindowId }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - this.logger.trace("the platform responded to the hello message with a full list of apps"); - this.applications = await Promise.all(result.apps.map((app) => this.ioc.buildApplication(app, app.instances))); - this.instances = this.applications.reduce((instancesSoFar, app) => { - instancesSoFar.push(...app.instances); - return instancesSoFar; - }, []); - this.me = this.findMyInstance(); - this.logger.trace(`all applications were parsed and saved. I am ${this.me ? "NOT a" : "a"} valid instance`); - this.initialChannelId = result.initialChannelId; - } - findMyInstance() { - for (const app of this.applications) { - const foundInstance = app.instances.find((instance) => instance.id === this.publicWindowId); - if (foundInstance) { - return foundInstance; - } - } - return undefined; - } - } - - class InstanceModel { - data; - bridge; - application; - me; - myCtxKey; - constructor(data, bridge, application) { - this.data = data; - this.bridge = bridge; - this.application = application; - this.myCtxKey = `___instance___${this.data.id}`; - } - toApi() { - const agm = this.bridge.getInteropInstance(this.data.id); - const api = { - id: this.data.id, - agm, - application: this.application, - stop: this.stop.bind(this), - getContext: this.getContext.bind(this) - }; - this.me = Object.freeze(api); - return this.me; - } - async getContext() { - return this.bridge.contextLib.get(this.myCtxKey); - } - async stop() { - await this.bridge.send("appManager", operations$9.instanceStop, { id: this.data.id }); - } - } - - class ApplicationModel { - data; - instances; - controller; - me; - constructor(data, instances, controller) { - this.data = data; - this.instances = instances; - this.controller = controller; - } - toApi() { - const api = { - name: this.data.name, - title: this.data.title, - version: this.data.version, - icon: this.data.icon, - caption: this.data.caption, - userProperties: this.data.userProperties, - instances: this.instances, - start: this.start.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - this.me = api; - return this.me; - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStarted((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStopped((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - async start(context, options) { - const verifiedContext = runDecoderWithIOError(startApplicationContextDecoder, context); - const verifiedOptions = runDecoderWithIOError(startApplicationOptionsDecoder, options); - return this.controller.startApplication(this.data.name, verifiedContext, verifiedOptions); - } - } - - const operations$8 = { - layoutAdded: { name: "layoutAdded", dataDecoder: glueLayoutDecoder }, - layoutChanged: { name: "layoutChanged", dataDecoder: glueLayoutDecoder }, - layoutRemoved: { name: "layoutRemoved", dataDecoder: glueLayoutDecoder }, - layoutRestored: { name: "layoutRestored", dataDecoder: glueLayoutDecoder }, - defaultLayoutChanged: { name: "defaultLayoutChanged", dataDecoder: defaultGlobalChangedDecoder }, - layoutRenamed: { name: "layoutRenamed", dataDecoder: renamedLayoutNotificationDecoder }, - get: { name: "get", dataDecoder: simpleLayoutConfigDecoder, resultDecoder: optionalSimpleLayoutResult }, - getAll: { name: "getAll", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsSummariesResultDecoder }, - export: { name: "export", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsFullConfigDecoder }, - import: { name: "import", dataDecoder: layoutsImportConfigDecoder }, - remove: { name: "remove", dataDecoder: simpleLayoutConfigDecoder }, - rename: { name: "rename", dataDecoder: renameLayoutConfigDecoder, resultDecoder: layoutResultDecoder }, - save: { name: "save", dataDecoder: saveLayoutConfigDecoder, resultDecoder: simpleLayoutResultDecoder }, - restore: { name: "restore", dataDecoder: restoreLayoutConfigDecoder }, - clientSaveRequest: { name: "clientSaveRequest", dataDecoder: platformSaveRequestConfigDecoder, resultDecoder: saveRequestClientResponseDecoder }, - getGlobalPermissionState: { name: "getGlobalPermissionState", resultDecoder: permissionStateResultDecoder }, - requestGlobalPermission: { name: "requestGlobalPermission", resultDecoder: simpleAvailabilityResultDecoder }, - checkGlobalActivated: { name: "checkGlobalActivated", resultDecoder: simpleAvailabilityResultDecoder }, - getDefaultGlobal: { name: "getDefaultGlobal", resultDecoder: optionalSimpleLayoutResult }, - setDefaultGlobal: { name: "setDefaultGlobal", dataDecoder: setDefaultGlobalConfigDecoder }, - clearDefaultGlobal: { name: "clearDefaultGlobal" }, - getCurrent: { name: "getCurrent", resultDecoder: optionalSimpleLayoutResult }, - updateMetadata: { name: "updateMetadata", dataDecoder: updateLayoutMetadataConfigDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class LayoutsController { - supportedOperationsNames = []; - defaultLayoutRestoreTimeoutMS = 120000; - registry = CallbackRegistryFactory$1(); - bridge; - logger; - windowsController; - saveRequestSubscription; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("layouts.controller.web"); - this.logger.trace("starting the web layouts controller"); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.addOperationsExecutors(); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"); - coreGlue.layouts = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(layoutsOperationTypesDecoder, args.operation); - const operation = operations$8[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - get: this.get.bind(this), - getAll: this.getAll.bind(this), - getCurrentLayout: this.getCurrentLayout.bind(this), - export: this.exportLayouts.bind(this), - import: this.importLayouts.bind(this), - save: this.save.bind(this), - restore: this.restore.bind(this), - remove: this.remove.bind(this), - onAdded: this.onAdded.bind(this), - onChanged: this.onChanged.bind(this), - onRemoved: this.onRemoved.bind(this), - onDefaultGlobalChanged: this.onDefaultGlobalChanged.bind(this), - onSaveRequested: this.subscribeOnSaveRequested.bind(this), - getMultiScreenPermissionState: this.getGlobalPermissionState.bind(this), - requestMultiScreenPermission: this.requestGlobalPermission.bind(this), - getGlobalTypeState: this.checkGlobalActivated.bind(this), - getDefaultGlobal: this.getDefaultGlobal.bind(this), - setDefaultGlobal: this.setDefaultGlobal.bind(this), - clearDefaultGlobal: this.clearDefaultGlobal.bind(this), - rename: this.rename.bind(this), - onRenamed: this.onRenamed.bind(this), - onRestored: this.onRestored.bind(this), - updateMetadata: this.updateMetadata.bind(this) - }; - return Object.freeze(api); - } - addOperationsExecutors() { - operations$8.layoutAdded.execute = this.handleOnAdded.bind(this); - operations$8.layoutChanged.execute = this.handleOnChanged.bind(this); - operations$8.layoutRemoved.execute = this.handleOnRemoved.bind(this); - operations$8.layoutRenamed.execute = this.handleOnRenamed.bind(this); - operations$8.layoutRestored.execute = this.handleOnRestored.bind(this); - operations$8.defaultLayoutChanged.execute = this.handleOnDefaultChanged.bind(this); - operations$8.clientSaveRequest.execute = this.handleSaveRequest.bind(this); - operations$8.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$8); - } - async get(name, type) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.get, { name, type }); - return result.layout; - } - async getCurrentLayout() { - const result = await this.bridge.send("layouts", operations$8.getCurrent, undefined); - return result.layout; - } - async getAll(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.getAll, { type }); - return result.summaries; - } - async exportLayouts(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.export, { type }); - return result.layouts; - } - async importLayouts(layouts, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(layouts)) { - return ioError.raiseError("Import must be called with an array of layouts"); - } - if (layouts.length > 1000) { - return ioError.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core."); - } - const parseResult = layouts.reduce((soFar, layout) => { - const decodeResult = glueLayoutDecoder.run(layout); - if (decodeResult.ok) { - soFar.valid.push(layout); - } - else { - this.logger.warn(`A layout with name: ${layout.name} was not imported, because of error: ${JSON.stringify(decodeResult.error)}`); - } - return soFar; - }, { valid: [] }); - const layoutsToImport = layouts.filter((layout) => parseResult.valid.some((validLayout) => validLayout.name === layout.name)); - await this.bridge.send("layouts", operations$8.import, { layouts: layoutsToImport, mode }); - } - async save(layout) { - runDecoderWithIOError(newLayoutOptionsDecoder, layout); - const saveResult = await this.bridge.send("layouts", operations$8.save, { layout }); - return saveResult.layout; - } - async restore(options) { - runDecoderWithIOError(restoreOptionsDecoder, options); - const invocationTimeout = options.timeout ? options.timeout * 2 : this.defaultLayoutRestoreTimeoutMS; - await this.bridge.send("layouts", operations$8.restore, { layout: options }, { methodResponseTimeoutMs: invocationTimeout }); - } - async remove(type, name) { - runDecoderWithIOError(layoutTypeDecoder, type); - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.remove, { type, name }); - } - async handleSaveRequest(config) { - const response = {}; - if (this.saveRequestSubscription) { - try { - const onSaveRequestResponse = this.saveRequestSubscription(config); - response.windowContext = onSaveRequestResponse?.windowContext; - } - catch (error) { - this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(error)}`); - } - } - return response; - } - async getGlobalPermissionState() { - const requestResult = await this.bridge.send("layouts", operations$8.getGlobalPermissionState, undefined); - return requestResult; - } - async requestGlobalPermission() { - const currentState = (await this.getGlobalPermissionState()).state; - if (currentState === "denied") { - return { permissionGranted: false }; - } - if (currentState === "granted") { - return { permissionGranted: true }; - } - const myWindow = this.windowsController.my(); - const globalNamespace = window.glue42core || window.iobrowser; - const amIWorkspaceFrame = globalNamespace.isPlatformFrame; - if (myWindow.name !== "Platform" && !amIWorkspaceFrame) { - return ioError.raiseError("Cannot request permission for multi-window placement from any app other than the Platform."); - } - const requestResult = await this.bridge.send("layouts", operations$8.requestGlobalPermission, undefined, { methodResponseTimeoutMs: 180000 }); - return { permissionGranted: requestResult.isAvailable }; - } - async checkGlobalActivated() { - const requestResult = await this.bridge.send("layouts", operations$8.checkGlobalActivated, undefined); - return { activated: requestResult.isAvailable }; - } - async getDefaultGlobal() { - const requestResult = await this.bridge.send("layouts", operations$8.getDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - return requestResult.layout; - } - async setDefaultGlobal(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.setDefaultGlobal, { name }, undefined, { includeOperationCheck: true }); - } - async clearDefaultGlobal() { - await this.bridge.send("layouts", operations$8.clearDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - } - async rename(layout, newName) { - runDecoderWithIOError(glueLayoutDecoder, layout); - runDecoderWithIOError(nonEmptyStringDecoder$2, newName); - const result = await this.bridge.send("layouts", operations$8.rename, { layout, newName }, undefined, { includeOperationCheck: true }); - return result; - } - async updateMetadata(layout) { - runDecoderWithIOError(glueLayoutDecoder, layout); - await this.bridge.send("layouts", operations$8.updateMetadata, { layout }, undefined, { includeOperationCheck: true }); - } - onAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"); - } - this.exportLayouts("Global").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - this.exportLayouts("Workspace").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - return this.registry.add(operations$8.layoutAdded.name, callback); - } - onChanged(callback) { - return this.registry.add(operations$8.layoutChanged.name, callback); - } - onDefaultGlobalChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"); - } - this.getDefaultGlobal().then((layout) => callback(layout ? { name: layout.name } : undefined)).catch(() => { }); - return this.registry.add(operations$8.defaultLayoutChanged.name, callback); - } - onRemoved(callback) { - return this.registry.add(operations$8.layoutRemoved.name, callback); - } - onRenamed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRenamed.name, callback); - } - onRestored(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRestored.name, callback); - } - subscribeOnSaveRequested(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."); - } - if (this.saveRequestSubscription) { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."); - } - this.saveRequestSubscription = callback; - return () => { - delete this.saveRequestSubscription; - }; - } - async handleOnAdded(layout) { - this.registry.execute(operations$8.layoutAdded.name, layout); - } - async handleOnChanged(layout) { - this.registry.execute(operations$8.layoutChanged.name, layout); - } - async handleOnDefaultChanged(layout) { - this.registry.execute(operations$8.defaultLayoutChanged.name, layout); - } - async handleOnRemoved(layout) { - this.registry.execute(operations$8.layoutRemoved.name, layout); - } - async handleOnRestored(layout) { - this.registry.execute(operations$8.layoutRestored.name, layout); - } - async handleOnRenamed(renamedData) { - const { prevName, ...layout } = renamedData; - this.registry.execute(operations$8.layoutRenamed.name, layout, { name: prevName }); - } - } - - const operations$7 = { - raiseNotification: { name: "raiseNotification", dataDecoder: raiseNotificationDecoder, resultDecoder: raiseNotificationResultDecoder }, - requestPermission: { name: "requestPermission", resultDecoder: permissionRequestResultDecoder }, - notificationShow: { name: "notificationShow", dataDecoder: notificationEventPayloadDecoder }, - notificationClick: { name: "notificationClick", dataDecoder: notificationEventPayloadDecoder }, - getPermission: { name: "getPermission", resultDecoder: permissionQueryResultDecoder }, - list: { name: "list", resultDecoder: allNotificationsDataDecoder }, - notificationRaised: { name: "notificationRaised", dataDecoder: simpleNotificationDataDecoder }, - notificationClosed: { name: "notificationClosed", dataDecoder: simpleNotificationSelectDecoder }, - click: { name: "click" }, - clear: { name: "clear" }, - clearAll: { name: "clearAll" }, - clearOld: { name: "clearOld" }, - configure: { name: "configure", dataDecoder: notificationsConfigurationProtocolDecoder }, - getConfiguration: { name: "getConfiguration", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - getActiveCount: { name: "getActiveCount", resultDecoder: activeNotificationsCountChangeDecoder }, - configurationChanged: { name: "configurationChanged", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - setState: { name: "setState", dataDecoder: notificationSetStateRequestDecoder }, - activeCountChange: { name: "activeCountChange", resultDecoder: activeNotificationsCountChangeDecoder }, - stateChange: { name: "stateChange", resultDecoder: notificationSetStateRequestDecoder }, - operationCheck: { name: "operationCheck" } - }; - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet$1 = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid$1 = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet$1[(Math.random() * 64) | 0]; - } - return id - }; - - class NotificationsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - bridge; - notificationsSettings; - notifications = {}; - coreGlue; - buildNotificationFunc; - notificationsConfiguration; - notificationsActiveCount = 0; - handlePlatformShutdown() { - this.notifications = {}; - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("notifications.controller.web"); - this.logger.trace("starting the web notifications controller"); - this.bridge = ioc.bridge; - this.coreGlue = coreGlue; - this.notificationsSettings = ioc.config.notifications; - this.buildNotificationFunc = ioc.buildNotification; - this.notificationsConfiguration = await this.getConfiguration(); - this.notificationsActiveCount = await this.getActiveCount(); - const api = this.toApi(); - this.addOperationExecutors(); - coreGlue.notifications = api; - this.logger.trace("notifications are ready"); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(notificationsOperationTypesDecoder, args.operation); - const operation = operations$7[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - requestPermission: this.requestPermission.bind(this), - getPermission: this.getPermission.bind(this), - list: this.list.bind(this), - onRaised: this.onRaised.bind(this), - onClosed: this.onClosed.bind(this), - click: this.click.bind(this), - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearOld: this.clearOld.bind(this), - configure: this.configure.bind(this), - getConfiguration: this.getConfiguration.bind(this), - getFilter: this.getFilter.bind(this), - setFilter: this.setFilter.bind(this), - setState: this.setState.bind(this), - onConfigurationChanged: this.onConfigurationChanged.bind(this), - onActiveCountChanged: this.onActiveCountChanged.bind(this), - onCounterChanged: this.onActiveCountChanged.bind(this), - onStateChanged: this.onStateChanged.bind(this) - }; - return Object.freeze(api); - } - async getPermission() { - const queryResult = await this.bridge.send("notifications", operations$7.getPermission, undefined); - return queryResult.permission; - } - async requestPermission() { - const permissionResult = await this.bridge.send("notifications", operations$7.requestPermission, undefined); - return permissionResult.permissionGranted; - } - async raise(options) { - const settings = runDecoderWithIOError(glue42NotificationOptionsDecoder, options); - settings.showToast = typeof settings.showToast === "boolean" ? settings.showToast : true; - settings.showInPanel = typeof settings.showInPanel === "boolean" ? settings.showInPanel : true; - const permissionGranted = await this.requestPermission(); - if (!permissionGranted) { - return ioError.raiseError("Cannot raise the notification, because the user has declined the permission request"); - } - const id = nanoid$1(10); - const raiseResult = await this.bridge.send("notifications", operations$7.raiseNotification, { settings, id }); - const notification = this.buildNotificationFunc(raiseResult.settings, id); - this.notifications[id] = notification; - return notification; - } - async list() { - const bridgeResponse = await this.bridge.send("notifications", operations$7.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.notifications; - } - onRaised(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onRaised expects a callback of type function"); - } - return this.registry.add("notification-raised", callback); - } - onClosed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onClosed expects a callback of type function"); - } - return this.registry.add("notification-closed", callback); - } - async click(id, action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - if (action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, action); - } - await this.bridge.send("notifications", operations$7.click, { id, action }, undefined, { includeOperationCheck: true }); - } - async clear(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - await this.bridge.send("notifications", operations$7.clear, { id }, undefined, { includeOperationCheck: true }); - } - async clearAll() { - await this.bridge.send("notifications", operations$7.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearOld() { - await this.bridge.send("notifications", operations$7.clearOld, undefined, undefined, { includeOperationCheck: true }); - } - async configure(config) { - const verifiedConfig = runDecoderWithIOError(notificationsConfigurationDecoder, config); - await this.bridge.send("notifications", operations$7.configure, { configuration: verifiedConfig }, undefined, { includeOperationCheck: true }); - } - async getConfiguration() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration; - } - async getActiveCount() { - try { - const response = await this.bridge.send("notifications", operations$7.getActiveCount, undefined, undefined, { includeOperationCheck: true }); - return response.count; - } - catch (error) { - console.warn("Failed to get accurate active notifications count", error); - return 0; - } - } - async getFilter() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration.sourceFilter; - } - async setFilter(filter) { - const verifiedFilter = runDecoderWithIOError(notificationFilterDecoder, filter); - await this.bridge.send("notifications", operations$7.configure, { configuration: { sourceFilter: verifiedFilter } }, undefined, { includeOperationCheck: true }); - return verifiedFilter; - } - async setState(id, state) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - runDecoderWithIOError(notificationStateDecoder, state); - await this.bridge.send("notifications", operations$7.setState, { id, state }, undefined, { includeOperationCheck: true }); - } - onConfigurationChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"); - } - setTimeout(() => callback(this.notificationsConfiguration), 0); - return this.registry.add("notifications-config-changed", callback); - } - onActiveCountChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"); - } - setTimeout(() => callback({ count: this.notificationsActiveCount }), 0); - return this.registry.add("notifications-active-count-changed", callback); - } - onStateChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"); - } - return this.registry.add("notification-state-changed", callback); - } - addOperationExecutors() { - operations$7.notificationShow.execute = this.handleNotificationShow.bind(this); - operations$7.notificationClick.execute = this.handleNotificationClick.bind(this); - operations$7.notificationRaised.execute = this.handleNotificationRaised.bind(this); - operations$7.notificationClosed.execute = this.handleNotificationClosed.bind(this); - operations$7.configurationChanged.execute = this.handleConfigurationChanged.bind(this); - operations$7.activeCountChange.execute = this.handleActiveCountChanged.bind(this); - operations$7.stateChange.execute = this.handleNotificationStateChanged.bind(this); - operations$7.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$7); - } - async handleConfigurationChanged(data) { - this.notificationsConfiguration = data.configuration; - this.registry.execute("notifications-config-changed", data.configuration); - } - async handleActiveCountChanged(data) { - this.notificationsActiveCount = data.count; - this.registry.execute("notifications-active-count-changed", data); - } - async handleNotificationStateChanged(data) { - this.registry.execute("notification-state-changed", { id: data.id }, data.state); - } - async handleNotificationShow(data) { - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onshow) { - notification.onshow(); - } - } - async handleNotificationClick(data) { - if (!data.action && this.notificationsSettings?.defaultClick) { - this.notificationsSettings.defaultClick(this.coreGlue, data.definition); - } - if (data.action && this.notificationsSettings?.actionClicks?.some((actionDef) => actionDef.action === data.action)) { - const foundHandler = this.notificationsSettings?.actionClicks?.find((actionDef) => actionDef.action === data.action); - foundHandler.handler(this.coreGlue, data.definition); - } - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onclick) { - notification.onclick(); - delete this.notifications[data.id]; - } - } - async handleNotificationRaised(data) { - this.registry.execute("notification-raised", data.notification); - } - async handleNotificationClosed(data) { - this.registry.execute("notification-closed", data); - } - } - - const operations$6 = { - getIntents: { name: "getIntents", resultDecoder: wrappedIntentsDecoder }, - findIntent: { name: "findIntent", dataDecoder: wrappedIntentFilterDecoder, resultDecoder: wrappedIntentsDecoder }, - raise: { name: "raise", dataDecoder: raiseIntentRequestDecoder, resultDecoder: intentResultDecoder }, - filterHandlers: { name: "filterHandlers", dataDecoder: filterHandlersWithResolverConfigDecoder, resultDecoder: filterHandlersResultDecoder }, - getIntentsByHandler: { name: "getIntentsByHandler", dataDecoder: intentHandlerDecoder, resultDecoder: getIntentsResultDecoder } - }; - - const GLUE42_FDC3_INTENTS_METHOD_PREFIX = "Tick42.FDC3.Intents."; - const INTENTS_RESOLVER_APP_NAME = "intentsResolver"; - const DEFAULT_RESOLVER_RESPONSE_TIMEOUT = 60 * 1000; - const ADDITIONAL_BRIDGE_OPERATION_TIMEOUT = 30 * 1000; - const DEFAULT_PICK_HANDLER_BY_TIMEOUT = 90 * 1000; - - class IntentsController { - bridge; - logger; - interop; - appManagerController; - windowsController; - myIntents = new Set(); - prefsController; - uiController; - useIntentsResolverUI = true; - intentsResolverAppName; - intentResolverResponseTimeout = DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - unregisterIntentPromises = []; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("intents.controller.web"); - this.logger.trace("starting the web intents controller"); - this.bridge = ioc.bridge; - this.interop = coreGlue.interop; - this.appManagerController = ioc.appManagerController; - this.windowsController = ioc.windowsController; - this.prefsController = ioc.prefsController; - this.uiController = ioc.uiController; - this.checkIfIntentsResolverIsEnabled(ioc.config); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"); - coreGlue.intents = api; - } - handlePlatformShutdown() { - this.myIntents = new Set(); - this.unregisterIntentPromises = []; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(intentsOperationTypesDecoder, args.operation); - const operation = operations$6[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - all: this.all.bind(this), - addIntentListener: this.addIntentListener.bind(this), - register: this.register.bind(this), - find: this.find.bind(this), - filterHandlers: this.filterHandlers.bind(this), - getIntents: this.getIntentsByHandler.bind(this), - clearSavedHandlers: this.clearSavedHandlers.bind(this), - onHandlerAdded: this.onHandlerAdded.bind(this), - onHandlerRemoved: this.onHandlerRemoved.bind(this) - }; - return api; - } - async raise(request) { - const validatedIntentRequest = runDecoderWithIOError(raiseRequestDecoder, request); - const intentRequest = typeof validatedIntentRequest === "string" - ? { intent: validatedIntentRequest } - : validatedIntentRequest; - await Promise.all(this.unregisterIntentPromises); - if (intentRequest.clearSavedHandler) { - this.logger.trace(`User removes saved handler for intent ${intentRequest.intent}`); - await this.removeRememberedHandler(intentRequest.intent); - } - const resultFromRememberedHandler = await this.checkHandleRaiseWithRememberedHandler(intentRequest); - if (resultFromRememberedHandler) { - return resultFromRememberedHandler; - } - const requestWithResolverInfo = { - intentRequest, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - const methodResponseTimeoutMs = intentRequest.waitUserResponseIndefinitely - ? MAX_SET_TIMEOUT_DELAY - : (intentRequest.timeout || this.intentResolverResponseTimeout) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(request)} and method response timeout of ${methodResponseTimeoutMs}ms`); - const response = await this.bridge.send("intents", operations$6.raise, requestWithResolverInfo, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }); - this.logger.trace(`Raise operation completed with response: ${JSON.stringify(response)}`); - return response; - } - getLegacyResolverConfigByRequest(filter) { - if (filter.handlerFilter) { - return { - enabled: typeof filter.handlerFilter?.openResolver === "boolean" ? filter.handlerFilter?.openResolver : this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout: filter.handlerFilter?.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT - }; - } - const waitResponseTimeout = filter.intentRequest?.waitUserResponseIndefinitely ? MAX_SET_TIMEOUT_DELAY : this.intentResolverResponseTimeout; - return { - enabled: this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout - }; - } - getEmbeddedResolverConfig() { - return { - enabled: this.uiController.isIntentResolverEnabled(), - initialCaller: { instanceId: this.interop.instance.instance } - }; - } - async all() { - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.getIntents, undefined); - return result.intents; - } - addIntentListener(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - let registerPromise; - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - const result = { - unsubscribe: () => { - this.myIntents.delete(intentName); - registerPromise - .then(() => this.interop.unregister(methodName)) - .catch((err) => this.logger.trace(`Unregistration of a method with name ${methodName} failed with reason: ${err}`)); - } - }; - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - registerPromise = this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - return handler(rest); - } - }); - registerPromise.catch(err => { - this.myIntents.delete(intentName); - this.logger.warn(`Registration of a method with name ${methodName} failed with reason: ${err}`); - }); - return result; - } - async register(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - await Promise.all(this.unregisterIntentPromises); - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - try { - await this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - const caller = this.interop.servers().find((server) => server.instance === _initialCallerId); - return handler(rest, caller); - } - }); - } - catch (err) { - this.myIntents.delete(intentName); - return ioError.raiseError(`Registration of a method with name ${methodName} failed with reason: ${JSON.stringify(err)}`); - } - return { - unsubscribe: () => this.unsubscribeIntent(intentName) - }; - } - async find(intentFilter) { - let data = undefined; - if (typeof intentFilter !== "undefined") { - const intentFilterObj = runDecoderWithIOError(findFilterDecoder, intentFilter); - if (typeof intentFilterObj === "string") { - data = { - filter: { - name: intentFilterObj - } - }; - } - else if (typeof intentFilterObj === "object") { - data = { - filter: intentFilterObj - }; - } - } - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.findIntent, data); - return result.intents; - } - onHandlerAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!"); - } - const unOnAppAdded = this.subscribeForAppEvent("onAppAdded", callback); - const unOnServerMethodAdded = this.subscribeForServerMethodEvent("serverMethodAdded", callback); - return () => { - unOnAppAdded(); - unOnServerMethodAdded(); - }; - } - onHandlerRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!"); - } - const unOnAppRemoved = this.subscribeForAppEvent("onAppRemoved", callback); - const unOnServerMethodRemoved = this.subscribeForServerMethodEvent("serverMethodRemoved", callback); - return () => { - unOnAppRemoved(); - unOnServerMethodRemoved(); - }; - } - subscribeForAppEvent(method, callback) { - return this.appManagerController[method]((app) => { - const appIntents = app.userProperties.intents; - if (!appIntents?.length) { - return; - } - appIntents.forEach((intent) => { - const handler = this.buildIntentHandlerFromApp(app, intent); - callback(handler, intent.name); - }); - }); - } - subscribeForServerMethodEvent(eventMethod, callback) { - return this.interop[eventMethod](async ({ server, method }) => { - if (!method.name.startsWith(GLUE42_FDC3_INTENTS_METHOD_PREFIX)) { - return; - } - const intentName = method.name.replace(GLUE42_FDC3_INTENTS_METHOD_PREFIX, ""); - const handler = await this.buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName); - callback(handler, intentName); - }); - } - buildIntentHandlerFromApp(app, intent) { - const handler = { - applicationName: app.name, - type: "app", - applicationDescription: app.caption, - applicationIcon: app.icon, - applicationTitle: app.title, - contextTypes: intent.contexts, - displayName: intent.displayName, - resultType: intent.resultType, - customConfig: intent.customConfig - }; - return handler; - } - async buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName) { - const info = method.flags.intent; - const app = this.appManagerController.getApplication(server.application || server.applicationName); - let title; - if (eventMethod === "serverMethodAdded" && server.windowId) { - title = await (this.windowsController.findById(server.windowId))?.getTitle(); - } - const appIntent = app?.userProperties?.intents?.find((intent) => intent.name === intentName); - const handler = { - applicationName: server.application || server.applicationName || "", - instanceId: server.windowId || server.instance, - type: "instance", - applicationIcon: info?.icon || app?.icon, - applicationTitle: app?.title, - applicationDescription: info?.description || app?.caption, - contextTypes: info?.contextTypes || appIntent?.contexts, - instanceTitle: title, - displayName: info?.displayName || appIntent?.displayName, - resultType: info?.resultType || appIntent?.resultType, - customConfig: info?.customConfig - }; - return handler; - } - async clearSavedHandlers() { - this.logger.trace("Removing all saved handlers from prefs storage for current app"); - await this.prefsController.update({ intents: undefined }); - } - checkIfIntentsResolverIsEnabled(options) { - this.useIntentsResolverUI = typeof options.intents?.enableIntentsResolverUI === "boolean" - ? options.intents.enableIntentsResolverUI - : true; - this.intentsResolverAppName = options.intents?.intentsResolverAppName ?? INTENTS_RESOLVER_APP_NAME; - this.intentResolverResponseTimeout = options.intents?.methodResponseTimeoutMs ?? DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - } - clearUnregistrationPromise(promiseToRemove) { - this.unregisterIntentPromises = this.unregisterIntentPromises.filter(promise => promise !== promiseToRemove); - } - buildInteropMethodName(intentName) { - return `${GLUE42_FDC3_INTENTS_METHOD_PREFIX}${intentName}`; - } - unsubscribeIntent(intentName) { - this.myIntents.delete(intentName); - const methodName = this.buildInteropMethodName(intentName); - const unregisterPromise = this.interop.unregister(methodName); - this.unregisterIntentPromises.push(unregisterPromise); - unregisterPromise - .then(() => { - this.clearUnregistrationPromise(unregisterPromise); - }) - .catch((err) => { - this.logger.error(`Unregistration of a method with name ${methodName} failed with reason: ${err}`); - this.clearUnregistrationPromise(unregisterPromise); - }); - } - async filterHandlers(handlerFilter) { - runDecoderWithIOError(handlerFilterDecoder, handlerFilter); - this.checkIfAtLeastOneFilterIsPresent(handlerFilter); - const embeddedResolverConfig = this.getEmbeddedResolverConfig(); - if (handlerFilter.openResolver && !this.useIntentsResolverUI && !embeddedResolverConfig.enabled) { - return ioError.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled"); - } - const methodResponseTimeoutMs = (handlerFilter.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - const filterHandlersRequestWithResolverConfig = { - filterHandlersRequest: handlerFilter, - resolverConfig: this.getLegacyResolverConfigByRequest({ handlerFilter }), - embeddedResolverConfig - }; - const result = await this.bridge.send("intents", operations$6.filterHandlers, filterHandlersRequestWithResolverConfig, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }, { includeOperationCheck: true }); - return result; - } - checkIfAtLeastOneFilterIsPresent(filter) { - const errorMsg = "Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'"; - if (!Object.keys(filter).length) { - return ioError.raiseError(errorMsg); - } - const { intent, resultType, contextTypes, applicationNames } = filter; - const existingValidContextTypes = contextTypes?.length; - const existingValidApplicationNames = applicationNames?.length; - if (!intent && !resultType && !existingValidContextTypes && !existingValidApplicationNames) { - return ioError.raiseError(errorMsg); - } - } - async getIntentsByHandler(handler) { - runDecoderWithIOError(intentHandlerDecoder, handler); - const result = await this.bridge.send("intents", operations$6.getIntentsByHandler, handler, undefined, { includeOperationCheck: true }); - return result; - } - async removeRememberedHandler(intentName) { - this.logger.trace(`Removing saved handler from prefs storage for intent ${intentName}`); - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const intentPrefs = prefs.data?.intents; - if (!intentPrefs) { - this.logger.trace("No app prefs found for current app"); - return; - } - delete intentPrefs[intentName]; - const updatedPrefs = { - ...prefs.data, - intents: intentPrefs - }; - try { - await this.prefsController.update(updatedPrefs); - } - catch (error) { - this.logger.warn(`prefs.update() threw the following error: ${error}`); - return; - } - this.logger.trace(`Handler saved choice for intent ${intentName} removed successfully`); - } - async checkForRememberedHandler(intentRequest) { - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const prefsForIntent = prefs.data?.intents?.[intentRequest.intent]; - return prefsForIntent?.handler; - } - async checkHandleRaiseWithRememberedHandler(intentRequest) { - if (intentRequest.target) { - return; - } - const rememberedHandler = await this.checkForRememberedHandler(intentRequest); - if (!rememberedHandler) { - return; - } - const operationData = { - intentRequest: { - ...intentRequest, - target: { - app: rememberedHandler.applicationName, - instance: rememberedHandler.instanceId - } - }, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - try { - const response = await this.bridge.send("intents", operations$6.raise, operationData); - return response; - } - catch (error) { - this.logger.trace(`Could not raise intent to remembered handler. Reason: ${error}. Removing it from Prefs store`); - await this.removeRememberedHandler(intentRequest.intent); - } - } - } - - const operations$5 = { - appHello: { name: "appHello", dataDecoder: channelsAppHelloDataDecoder, resultDecoder: channelsAppHelloSuccessDecoder }, - addChannel: { name: "addChannel", dataDecoder: channelDefinitionDecoder }, - removeChannel: { name: "removeChannel", dataDecoder: removeChannelDataDecoder }, - getMyChannel: { name: "getMyChannel", resultDecoder: getMyChanelResultDecoder }, - getWindowIdsOnChannel: { name: "getWindowIdsOnChannel", dataDecoder: getWindowIdsOnChannelDataDecoder, resultDecoder: getWindowIdsOnChannelResultDecoder }, - getWindowIdsWithChannels: { name: "getWindowIdsWithChannels", dataDecoder: wrappedWindowWithChannelFilterDecoder, resultDecoder: getWindowIdsWithChannelsResultDecoder }, - joinChannel: { name: "joinChannel", dataDecoder: joinChannelDataDecoder }, - restrict: { name: "restrict", dataDecoder: restrictionConfigDataDecoder }, - getRestrictions: { name: "getRestrictions", dataDecoder: getRestrictionsDataDecoder, resultDecoder: restrictionsDecoder }, - restrictAll: { name: "restrictAll", dataDecoder: restrictAllDataDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - leaveChannel: { name: "leaveChannel", dataDecoder: leaveChannelDataDecoder }, - requestChannelSelector: { name: "requestChannelSelector", dataDecoder: requestChannelSelectorConfigDecoder }, - getMode: { name: "getMode", resultDecoder: getChannelsModeDecoder }, - operationCheck: { name: "operationCheck" }, - }; - - const DEFAULT_MODE = "single"; - const CHANNELS_PREFIX = "___channel___"; - const SUBS_KEY = "subs"; - const CHANGED_KEY = "changed"; - const CHANNELS_CHANGED = "channels_changed"; - const STORAGE_NAMESPACE = "io_connect_channels"; - const DEFAULT_STORAGE_MODE = "inMemory"; - - class ChannelsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - contexts; - interop; - bridge; - windowsController; - _mode; - myWindowId; - storage; - handlePlatformShutdown() { - this.registry.clear(); - this.storage.clear(); - } - addOperationsExecutors() { - operations$5.getMyChannel.execute = this.handleGetMyChannel.bind(this); - operations$5.joinChannel.execute = this.handleJoinChannel.bind(this); - operations$5.leaveChannel.execute = this.handleLeaveChannel.bind(this); - operations$5.restrict.execute = this.handleRestrict.bind(this); - operations$5.getRestrictions.execute = ({ windowId }) => this.getRestrictions(windowId); - operations$5.restrictAll.execute = this.handleRestrictAll.bind(this); - operations$5.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$5); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("channels.controller.web"); - this.logger.trace("starting the web channels controller"); - this.contexts = coreGlue.contexts; - this.interop = coreGlue.interop; - this.addOperationsExecutors(); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.storage = ioc.channelsStorage; - this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"); - this.myWindowId = this.windowsController.my().id ?? this.interop.instance.instance; - await this.initialize(); - const api = this.toApi(); - coreGlue.channels = api; - } - async postStart(io, ioc) { - try { - await this.requestChannelSelector(io.appManager.myInstance); - } - catch (error) { - this.logger.warn(`Failed to display channel selector: ${extractErrorMsg(error)}`); - } - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(channelsOperationTypesDecoder, args.operation); - const operation = operations$5[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async list() { - const channelNames = this.getAllChannelNames(); - const channelContexts = await Promise.all(channelNames.map((channelName) => this.get(channelName))); - return channelContexts; - } - my() { - return this.current(); - } - async handleGetMyChannel() { - const channel = this.my(); - return channel ? { channel } : {}; - } - async join(name, windowId) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const joinData = { channel: name, windowId: windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.joinChannel, joinData, undefined, { includeOperationCheck: true }); - } - handleJoinChannel({ channel }) { - if (this._mode === "single") { - return this.switchToChannel(channel); - } - return this.joinAdditionalChannel(channel); - } - onChanged(callback) { - return this.changed(callback); - } - async leave(config = {}) { - runDecoderWithIOError(leaveChannelsConfig, config); - if (config.channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.channel); - } - const leaveData = { channelName: config.channel, windowId: config.windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.leaveChannel, leaveData, undefined, { includeOperationCheck: true }); - } - async handleAppManagerInitialChannelId(channel) { - if (this.storage.mode === "inMemory") { - return; - } - if (this.storage.getSessionStorageData()) { - return; - } - return this.handleJoinChannel({ channel, windowId: this.myWindowId }); - } - async handleLeaveChannel({ channelName }) { - const channelNamesToLeave = channelName ? [channelName] : this.storage.channels; - channelNamesToLeave.forEach((name) => this.storage.invokeUnsubscribes(name)); - this.storage.channels = this.storage.channels.filter((channelName) => !channelNamesToLeave.includes(channelName)); - this.executeChangedEvents(); - await this.notifyChannelsChanged(); - } - toApi() { - const api = { - mode: this._mode, - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - publish: this.publish.bind(this), - all: this.all.bind(this), - list: this.list.bind(this), - get: this.get.bind(this), - getMyChannels: this.getMyChannels.bind(this), - myChannels: this.myChannels.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - join: this.join.bind(this), - leave: this.leave.bind(this), - current: this.current.bind(this), - my: this.my.bind(this), - changed: this.changed.bind(this), - onChanged: this.onChanged.bind(this), - add: this.add.bind(this), - remove: this.remove.bind(this), - getMy: this.getMy.bind(this), - getWindowsOnChannel: this.getWindowsOnChannel.bind(this), - getWindowsWithChannels: this.getWindowsWithChannels.bind(this), - restrict: this.restrict.bind(this), - getRestrictions: this.getRestrictions.bind(this), - restrictAll: this.restrictAll.bind(this), - clearChannelData: this.clearChannelData.bind(this), - setPath: this.setPath.bind(this), - setPaths: this.setPaths.bind(this) - }; - return Object.freeze(api); - } - createContextName(channelName) { - return `${CHANNELS_PREFIX}${channelName}`; - } - getAllChannelNames() { - const contextNames = this.contexts.all(); - const channelContextNames = contextNames.filter((contextName) => contextName.startsWith(CHANNELS_PREFIX)); - const channelNames = channelContextNames.map((channelContextName) => channelContextName.replace(CHANNELS_PREFIX, "")); - return channelNames; - } - async joinAdditionalChannel(name) { - if (this.storage.channels.includes(name)) { - return; - } - this.storage.channels = [...this.storage.channels, name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - async switchToChannel(name) { - const currentChannel = this.storage.channels[0]; - if (name === currentChannel) { - return; - } - this.storage.invokeUnsubscribes(currentChannel); - this.storage.channels = [name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - executeChangedEvents(name) { - this.registry.execute(CHANGED_KEY, name); - this.registry.execute(CHANNELS_CHANGED, this.storage.channels); - } - async notifyChannelsChanged() { - const windowId = this.windowsController.my().id; - if (!windowId) { - return; - } - try { - await this.bridge.send("channels", operations$5.notifyChannelsChanged, { channelNames: this.storage.channels, windowId }, undefined, { includeOperationCheck: true }); - } - catch (error) { - this.logger.warn(`Failed to notify channel changed: ${extractErrorMsg(error)}`); - } - } - async updateData(name, data) { - const contextName = this.createContextName(name); - const fdc3Type = this.getFDC3Type(data); - if (this.contexts.setPathSupported) { - const pathValues = Object.keys(data).map((key) => { - return { - path: `data.${key}`, - value: data[key] - }; - }); - if (fdc3Type) { - pathValues.push({ path: latestFDC3Type, value: fdc3Type }); - } - await this.contexts.setPaths(contextName, pathValues); - } - else { - if (fdc3Type) { - data[latestFDC3Type] = fdc3Type; - } - await this.contexts.update(contextName, { data }); - } - } - getFDC3Type(data) { - const fdc3PropsArr = Object.keys(data).filter((key) => key.indexOf("fdc3_") === 0); - if (fdc3PropsArr.length === 0) { - return; - } - if (fdc3PropsArr.length > 1) { - return ioError.raiseError("FDC3 does not support updating of multiple context keys"); - } - return fdc3PropsArr[0].split("_").slice(1).join("_"); - } - subscribe(callback, options) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels, because the provided callback is not a function!"); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const currentChannel = this.current(); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - if (currentChannel) { - this.replaySubscribe(wrappedCallback, currentChannel); - } - return this.registry.add(SUBS_KEY, wrappedCallback); - } - async subscribeFor(name, callback, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (typeof callback !== "function") { - return ioError.raiseError(`Cannot subscribe to channel ${name}, because the provided callback is not a function!`); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - wrappedCallback(context.data, context, delta, extraData?.updaterId); - }); - } - async publish(data, options) { - if (typeof data !== "object") { - return ioError.raiseError("Cannot publish to channel, because the provided data is not an object!"); - } - runDecoderWithIOError(publishOptionsDecoder, options); - if (typeof options === "object") { - return this.publishWithOptions(data, options); - } - if (typeof options === "string") { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options); - } - if (!options && this.storage.channels.length > 1) { - return this.publishOnMultipleChannels(data); - } - const channelName = typeof options === "string" ? options : this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - return this.updateData(channelName, data); - } - async all() { - const channelNames = this.getAllChannelNames(); - return channelNames; - } - async get(name, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const channelContext = await this.contexts.get(contextName); - if (options?.contextType) { - return this.getContextForFdc3Type(channelContext, options.contextType); - } - if (channelContext.latest_fdc3_type) { - return this.getContextWithFdc3Data(channelContext); - } - return channelContext; - } - async getMyChannels() { - return Promise.all(this.storage.channels.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.get(contextName); - })); - } - myChannels() { - return this.storage.channels; - } - getContextForFdc3Type(channelContext, searchedType) { - const encodedType = `fdc3_${searchedType.split(".").join("&")}`; - if (!channelContext.data[encodedType]) { - return { - name: channelContext.name, - meta: channelContext.meta, - data: {} - }; - } - const fdc3Context = { type: searchedType, ...channelContext.data[encodedType] }; - return { - name: channelContext.name, - meta: channelContext.meta, - data: { fdc3: fdc3Context } - }; - } - getContextWithFdc3Data(channelContext) { - const { latest_fdc3_type, ...rest } = channelContext; - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Context = { type: parsedType, ...rest.data[`fdc3_${latest_fdc3_type}`] }; - delete rest.data[`fdc3_${latest_fdc3_type}`]; - const context = { - name: channelContext.name, - meta: channelContext.meta, - data: { - ...rest.data, - fdc3: fdc3Context - } - }; - return context; - } - current() { - return this.storage.channels[0]; - } - changed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"); - } - return this.registry.add(CHANGED_KEY, callback); - } - async add(info) { - const channelContext = runDecoderWithIOError(channelDefinitionDecoder, info); - const channelWithSuchNameExists = this.getAllChannelNames().includes(channelContext.name); - if (channelWithSuchNameExists) { - return ioError.raiseError("There's an already existing channel with such name"); - } - await this.bridge.send("channels", operations$5.addChannel, channelContext); - return { - name: channelContext.name, - meta: channelContext.meta, - data: channelContext.data || {} - }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - const channelWithSuchNameExists = this.getAllChannelNames().includes(name); - if (!channelWithSuchNameExists) { - return ioError.raiseError("There's no channel with such name"); - } - await this.bridge.send("channels", operations$5.removeChannel, { name }, undefined, { includeOperationCheck: true }); - } - replaySubscribe = (callback, channelId) => { - this.get(channelId) - .then((channelContext) => { - if (!channelContext) { - return undefined; - } - const contextName = this.createContextName(channelContext.name); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - callback(context.data, context, delta, extraData?.updaterId); - }); - }) - .then((un) => un?.()) - .catch(err => this.logger.trace(err)); - }; - async getMy(options) { - if (!this.storage.channels.length) { - return; - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - return this.get(this.storage.channels[this.storage.channels.length - 1], options); - } - async getWindowsOnChannel(channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), channel); - const { windowIds } = await this.bridge.send("channels", operations$5.getWindowIdsOnChannel, { channel }, undefined, { includeOperationCheck: true }); - const result = windowIds.reduce((windows, windowId) => { - const window = this.windowsController.findById(windowId); - return window ? [...windows, window] : windows; - }, []); - return result; - } - async getWindowsWithChannels(filter) { - const operationData = filter !== undefined - ? { filter: runDecoderWithIOError(windowWithChannelFilterDecoder, filter) } - : {}; - const { windowIdsWithChannels } = await this.bridge.send("channels", operations$5.getWindowIdsWithChannels, operationData, undefined, { includeOperationCheck: true }); - const result = windowIdsWithChannels.reduce((windowsWithChannels, { application, channel, windowId }) => { - const window = this.windowsController.findById(windowId); - return window ? [...windowsWithChannels, { application, channel, window }] : windowsWithChannels; - }, []); - return result; - } - async clearChannelData(name) { - const paths = [ - { path: "data", value: {} }, - { path: "latest_fdc3_type", value: null }, - ]; - await this.handleSetPaths("clearChannelData", paths, name); - } - async restrict(config) { - runDecoderWithIOError(channelRestrictionsDecoder, config); - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.name); - const configData = { - config: { - ...config, - windowId: config.windowId ?? this.myWindowId - } - }; - await this.bridge.send("channels", operations$5.restrict, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrict({ config }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateRestriction(config); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateRestriction(config); - const isForCurrentChannel = config.name === currentChannel.name; - if (!isForCurrentChannel || prevReadAllowed || !config.read) { - return; - } - this.replaySubscribeCallback(config.name); - } - updateRestriction(config) { - const exists = this.storage.restrictions.some((r) => r.name === config.name); - this.storage.restrictions = exists - ? this.storage.restrictions.map((restriction) => restriction.name === config.name ? config : restriction) - : this.storage.restrictions.concat(config); - } - updateAllRestrictions(config) { - const allChannelNames = this.getAllChannelNames(); - this.storage.restrictions = allChannelNames.map((name) => ({ name, ...config })); - } - async getRestrictions(windowId) { - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const forAnotherClient = windowId && windowId !== this.interop.instance.instance; - if (windowId && forAnotherClient) { - return this.bridge.send("channels", operations$5.getRestrictions, { windowId }, undefined, { includeOperationCheck: true }); - } - return { channels: this.storage.restrictions }; - } - async restrictAll(restrictions) { - runDecoderWithIOError(restrictionsConfigDecoder, restrictions); - const configData = { - restrictions: { - ...restrictions, - windowId: restrictions.windowId ?? this.myWindowId - } - }; - return this.bridge.send("channels", operations$5.restrictAll, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrictAll({ restrictions }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateAllRestrictions(restrictions); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateAllRestrictions(restrictions); - if (prevReadAllowed || !restrictions.read) { - return; - } - this.replaySubscribeCallback(currentChannel.name); - } - async setPath(path, name) { - const validatedPath = runDecoderWithIOError(pathValueDecoder, path); - const paths = [{ path: `data.${validatedPath.path}`, value: validatedPath.value }]; - await this.handleSetPaths("setPath", paths, name); - } - async setPaths(paths, name) { - const validatedPaths = runDecoderWithIOError(pathsValueDecoder, paths); - const dataPaths = validatedPaths.map(({ path, value }) => ({ path: `data.${path}`, value })); - await this.handleSetPaths("setPaths", dataPaths, name); - } - async handleSetPaths(operation, paths, name) { - const channelNamesToUpdate = name ? [name] : this.storage.channels; - if (!channelNamesToUpdate.length) { - return ioError.raiseError(`Cannot complete ${operation} operation, because channel is not specified. Either join one or pass a channel name as second argument!`); - } - this.validateChannelNames(channelNamesToUpdate); - const { allowed, forbidden } = this.groupChannelsByPermission("write", channelNamesToUpdate); - if (channelNamesToUpdate.length === forbidden.length) { - return ioError.raiseError(`Cannot complete ${operation} operation due to write restrictions to the following channels: ${channelNamesToUpdate.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Cannot set paths on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} due to write restrictions`); - } - await Promise.all(allowed.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.setPaths(contextName, paths); - })); - } - validateChannelNames(names) { - const allChannelNames = this.getAllChannelNames(); - names.forEach((name) => runDecoderWithIOError(channelNameDecoder(allChannelNames), name)); - } - groupChannelsByPermission(action, channelNames) { - return channelNames.reduce((byFar, channelName) => { - const isAllowed = this.isAllowedByRestrictions(channelName, action); - if (isAllowed) { - byFar.allowed.push(channelName); - } - else { - byFar.forbidden.push(channelName); - } - return byFar; - }, { allowed: [], forbidden: [] }); - } - isAllowedByRestrictions(channelName, action) { - const restriction = this.storage.restrictions.find((restriction) => restriction.name === channelName); - return restriction ? restriction[action] : true; - } - replaySubscribeCallback(channelName) { - const contextName = this.createContextName(channelName); - this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }).then((unsub) => { - if (unsub && typeof unsub === "function") { - unsub(); - } - }).catch(err => this.logger.error(err)); - } - async publishWithOptions(data, options) { - if (options.name) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options.name); - } - const publishOnMultipleChannels = options.name ? false : this.storage.channels.length > 1; - if (publishOnMultipleChannels) { - return this.publishOnMultipleChannels(data, options.fdc3); - } - const channelName = options.name || this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - if (!options.fdc3) { - return this.updateData(channelName, data); - } - return this.publishFdc3Data(channelName, data); - } - async publishOnMultipleChannels(data, isFdc3) { - const { allowed, forbidden } = this.groupChannelsByPermission("write", this.storage.channels); - if (this.storage.channels.length === forbidden.length) { - return ioError.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Data on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} won't be published due to write restrictions`); - } - const publishMethod = isFdc3 ? this.publishFdc3Data.bind(this) : this.updateData.bind(this); - await Promise.all(allowed.map((channelName) => publishMethod(channelName, data))); - } - async publishFdc3Data(channelName, data) { - runDecoderWithIOError(fdc3ContextDecoder, data); - const { type, ...rest } = data; - const parsedType = type.split(".").join("&"); - const fdc3DataToPublish = { [`fdc3_${parsedType}`]: rest }; - return this.updateData(channelName, fdc3DataToPublish); - } - getWrappedSubscribeCallback(callback) { - const wrappedCallback = (channelData, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const latestTypePropName = `fdc3_${latest_fdc3_type}`; - if (!latest_fdc3_type || (delta.data && !delta.data[latestTypePropName])) { - callback(channelData, context, updaterId); - return; - } - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Data = { type: parsedType, ...data[latestTypePropName] }; - const { [latestTypePropName]: latestFDC3Type, ...rest } = channelData; - callback({ ...rest, fdc3: fdc3Data }, context, updaterId); - }; - return wrappedCallback; - } - getWrappedSubscribeCallbackWithFdc3Type(callback, fdc3Type) { - const didReplay = { replayed: false }; - const wrappedCallback = (_, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const searchedType = `fdc3_${fdc3Type.split(".").join("&")}`; - if (!data[searchedType] || (delta.data && !delta.data[searchedType])) { - return; - } - if (didReplay.replayed) { - return this.parseDataAndInvokeSubscribeCallback({ latestFdc3TypeEncoded: latest_fdc3_type, searchedType: fdc3Type, callback, context, updaterId }); - } - const fdc3Data = { type: fdc3Type, ...data[searchedType] }; - callback({ fdc3: fdc3Data }, context, updaterId); - didReplay.replayed = true; - }; - return wrappedCallback; - } - parseDataAndInvokeSubscribeCallback(args) { - const { latestFdc3TypeEncoded, searchedType, callback, context, updaterId } = args; - const latestPublishedType = latestFdc3TypeEncoded.split("&").join("."); - if (latestPublishedType !== searchedType) { - return; - } - const fdc3Data = { type: searchedType, ...context.data[`fdc3_${latestFdc3TypeEncoded}`] }; - callback({ fdc3: fdc3Data }, context, updaterId); - } - async requestChannelSelector(myInstance) { - if (!myInstance) { - return; - } - const myApplicationData = myInstance.application; - const myAppDetails = myApplicationData.userProperties?.details; - if (!myAppDetails) { - return; - } - if (!myAppDetails?.channelSelector?.enabled) { - return; - } - const windowId = myInstance.id; - const requestChannelSelectorConfig = { windowId, channelsNames: this.storage.channels }; - await this.bridge.send("channels", operations$5.requestChannelSelector, requestChannelSelectorConfig, undefined, { includeOperationCheck: true }); - } - async getPlatformChannelsMode() { - try { - const result = await this.bridge.send("channels", operations$5.getMode, {}, undefined, { includeOperationCheck: true }); - return result.mode; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - return DEFAULT_MODE; - } - } - onChannelsChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"); - } - return this.registry.add(CHANNELS_CHANGED, callback); - } - async initialize() { - const isAppHelloSupported = await this.checkIfAppHelloSupported(); - if (!isAppHelloSupported) { - return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions"); - } - const { success, error } = await this.sendAppHello(); - if (error) { - return this.handleAppHelloFailure(error); - } - this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(success)}`); - const { mode, channels, restrictions } = success; - this.storage.mode = "inMemory"; - this._mode = mode; - this.storage.channels = channels; - this.storage.restrictions = restrictions; - } - async handleAppHelloFailure(errorMsg) { - this.logger.trace(errorMsg); - this.storage.mode = "sessionStorage"; - this._mode = await this.getPlatformChannelsMode(); - } - async sendAppHello() { - try { - const result = await this.bridge.send("channels", operations$5.appHello, { windowId: this.myWindowId }, undefined, { includeOperationCheck: true }); - return { success: result, error: undefined }; - } - catch (error) { - return { error: `Failed to get initial state from platform. Error: ${extractErrorMsg(error)}`, success: undefined }; - } - } - async checkIfAppHelloSupported() { - try { - const { isSupported } = await this.bridge.send("channels", operations$5.operationCheck, { operation: operations$5.appHello.name }, undefined, { includeOperationCheck: true }); - return isSupported; - } - catch (error) { - this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${extractErrorMsg(error)}`); - return false; - } - } - } - - const operations$4 = { - getEnvironment: { name: "getEnvironment", resultDecoder: anyDecoder }, - getBase: { name: "getBase", resultDecoder: anyDecoder }, - platformShutdown: { name: "platformShutdown" }, - isFdc3DataWrappingSupported: { name: "isFdc3DataWrappingSupported" }, - clientError: { name: "clientError", dataDecoder: clientErrorDataDecoder }, - systemHello: { name: "systemHello", resultDecoder: systemHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class SystemController { - supportedOperationsNames = []; - bridge; - ioc; - logger; - errorPort = errorChannel.port2; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("system.controller.web"); - this.logger.trace("starting the web system controller"); - this.bridge = ioc.bridge; - this.ioc = ioc; - this.addOperationsExecutors(); - let isClientErrorOperationSupported = false; - try { - const systemHelloSuccess = await this.bridge.send("system", operations$4.systemHello, undefined, undefined, { includeOperationCheck: true }); - isClientErrorOperationSupported = systemHelloSuccess.isClientErrorOperationSupported; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support some system operations."); - } - this.errorPort.onmessage = async (event) => { - if (!isClientErrorOperationSupported) { - return; - } - await this.bridge.send("system", operations$4.clientError, { message: event.data }, undefined, { includeOperationCheck: true }); - }; - await this.setEnvironment(); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(systemOperationTypesDecoder, args.operation); - const operation = operations$4[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async processPlatformShutdown() { - Object.values(this.ioc.controllers).forEach((controller) => controller.handlePlatformShutdown ? controller.handlePlatformShutdown() : null); - this.ioc.preferredConnectionController.stop(); - this.ioc.eventsDispatcher.stop(); - await this.bridge.stop(); - } - async setEnvironment() { - const environment = await this.bridge.send("system", operations$4.getEnvironment, undefined); - const base = await this.bridge.send("system", operations$4.getBase, undefined); - const globalNamespace = window.glue42core || window.iobrowser; - const globalNamespaceName = window.glue42core ? "glue42core" : "iobrowser"; - const globalObj = Object.assign({}, globalNamespace, base, { environment }); - window[globalNamespaceName] = globalObj; - } - addOperationsExecutors() { - operations$4.platformShutdown.execute = this.processPlatformShutdown.bind(this); - operations$4.isFdc3DataWrappingSupported.execute = this.handleIsFdc3DataWrappingSupported.bind(this); - operations$4.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$4); - } - async handleIsFdc3DataWrappingSupported() { - return { isSupported: true }; - } - } - - class Notification { - onclick = () => { }; - onshow = () => { }; - id; - title; - badge; - body; - data; - dir; - icon; - image; - lang; - renotify; - requireInteraction; - silent; - tag; - timestamp; - vibrate; - clickInterop; - actions; - focusPlatformOnDefaultClick; - severity; - showToast; - showInPanel; - state; - constructor(config, id) { - this.id = id; - this.badge = config.badge; - this.body = config.body; - this.data = config.data; - this.dir = config.dir; - this.icon = config.icon; - this.image = config.image; - this.lang = config.lang; - this.renotify = config.renotify; - this.requireInteraction = config.requireInteraction; - this.silent = config.silent; - this.tag = config.tag; - this.timestamp = config.timestamp; - this.vibrate = config.vibrate; - this.title = config.title; - this.clickInterop = config.clickInterop; - this.actions = config.actions; - this.focusPlatformOnDefaultClick = config.focusPlatformOnDefaultClick; - this.severity = config.severity; - this.showToast = config.showToast; - this.showInPanel = config.showInPanel; - this.state = config.state; - } - } - - oneOf$1(constant$2("clientHello")); - const extensionConfigDecoder = object$2({ - widget: object$2({ - inject: boolean$2() - }) - }); - - const operations$3 = { - clientHello: { name: "clientHello", resultDecoder: extensionConfigDecoder } - }; - - class ExtController { - windowId; - logger; - bridge; - eventsDispatcher; - channelsController; - config; - channels = []; - unsubFuncs = []; - contentCommands = { - widgetVisualizationPermission: { name: "widgetVisualizationPermission", handle: this.handleWidgetVisualizationPermission.bind(this) }, - changeChannel: { name: "changeChannel", handle: this.handleChangeChannel.bind(this) } - }; - handlePlatformShutdown() { - this.unsubFuncs.forEach((unsub) => unsub()); - this.channels = []; - this.unsubFuncs = []; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("extension.controller.web"); - this.windowId = ioc.publicWindowId; - this.logger.trace("starting the extension web controller"); - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.eventsDispatcher = ioc.eventsDispatcher; - try { - await this.registerWithPlatform(); - } - catch (error) { - return; - } - this.channels = await this.channelsController.list(); - const unsubDispatcher = this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)); - const unsubChannels = this.channelsController.onChanged((channel) => { - this.eventsDispatcher.sendContentMessage({ command: "channelChange", newChannel: channel }); - }); - this.unsubFuncs.push(unsubDispatcher); - this.unsubFuncs.push(unsubChannels); - } - async handleBridgeMessage(_) { - } - handleContentMessage(message) { - if (!message || typeof message.command !== "string") { - return; - } - const foundHandler = this.contentCommands[message.command]; - if (!foundHandler) { - return; - } - foundHandler.handle(message); - } - async registerWithPlatform() { - this.logger.trace("registering with the platform"); - this.config = await this.bridge.send("extension", operations$3.clientHello, { windowId: this.windowId }); - this.logger.trace("the platform responded to the hello message with a valid extension config"); - } - async handleWidgetVisualizationPermission() { - if (!this.config?.widget.inject) { - return this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: false }); - } - const currentChannel = this.channels.find((channel) => channel.name === this.channelsController.my()); - this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: true, channels: this.channels, currentChannel }); - } - async handleChangeChannel(message) { - if (message.name === "no-channel") { - await this.channelsController.leave(); - return; - } - await this.channelsController.join(message.name); - } - } - - class EventsDispatcher { - config; - glue; - registry = CallbackRegistryFactory$1(); - glue42EventName = "Glue42"; - _handleMessage; - _resolveWidgetReadyPromise; - _resolveModalsUIFactoryReadyPromise; - _resolveIntentResolverUIFactoryReadyPromise; - constructor(config) { - this.config = config; - } - events = { - notifyStarted: { name: "notifyStarted", handle: this.handleNotifyStarted.bind(this) }, - contentInc: { name: "contentInc", handle: this.handleContentInc.bind(this) }, - requestGlue: { name: "requestGlue", handle: this.handleRequestGlue.bind(this) }, - widgetFactoryReady: { name: "widgetFactoryReady", handle: this.handleWidgetReady.bind(this) }, - modalsUIFactoryReady: { name: "modalsUIFactoryReady", handle: this.handleModalsUIFactoryReady.bind(this) }, - intentResolverUIFactoryReady: { name: "intentResolverUIFactoryReady", handle: this.handleIntentResolverUIFactoryReady.bind(this) }, - }; - stop() { - window.removeEventListener(this.glue42EventName, this._handleMessage); - } - start(glue) { - this.glue = glue; - this.wireCustomEventListener(); - this.announceStarted(); - } - sendContentMessage(message) { - this.send("contentOut", "glue42core", message); - } - onContentMessage(callback) { - return this.registry.add("content-inc", callback); - } - async widgetReady() { - const widgetReadyPromise = new Promise((resolve) => { - this._resolveWidgetReadyPromise = resolve; - }); - this.requestWidgetReady(); - return widgetReadyPromise; - } - async modalsUIFactoryReady() { - const modalsUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveModalsUIFactoryReadyPromise = resolve; - }); - this.requestModalsUIFactoryReady(); - return modalsUIFactoryReadyPromise; - } - async intentResolverUIFactoryReady() { - const intentResolverUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveIntentResolverUIFactoryReadyPromise = resolve; - }); - this.requestIntentResolverUIFactoryReady(); - return intentResolverUIFactoryReadyPromise; - } - wireCustomEventListener() { - this._handleMessage = this.handleMessage.bind(this); - window.addEventListener(this.glue42EventName, this._handleMessage); - } - handleMessage(event) { - const data = event.detail; - const namespace = data?.glue42 ?? data?.glue42core; - if (!namespace) { - return; - } - const glue42Event = namespace.event; - const foundHandler = this.events[glue42Event]; - if (!foundHandler) { - return; - } - foundHandler.handle(namespace.message); - } - announceStarted() { - this.send("start", "glue42"); - } - handleRequestGlue() { - if (!this.config.exposeAPI) { - this.send("requestGlueResponse", "glue42", { error: "Will not give access to the underlying Glue API, because it was explicitly denied upon initialization." }); - return; - } - this.send("requestGlueResponse", "glue42", { glue: this.glue }); - } - handleNotifyStarted() { - this.announceStarted(); - } - handleContentInc(message) { - this.registry.execute("content-inc", message); - } - requestWidgetReady() { - this.send(REQUEST_WIDGET_READY, "glue42"); - } - handleWidgetReady() { - this._resolveWidgetReadyPromise?.(); - } - requestModalsUIFactoryReady() { - this.send(REQUEST_MODALS_UI_FACTORY_READY, "glue42"); - } - handleModalsUIFactoryReady() { - this._resolveModalsUIFactoryReadyPromise?.(); - } - requestIntentResolverUIFactoryReady() { - this.send(REQUEST_INTENT_RESOLVER_UI_FACTORY_READY, "glue42"); - } - handleIntentResolverUIFactoryReady() { - this._resolveIntentResolverUIFactoryReadyPromise?.(); - } - send(eventName, namespace, message) { - const payload = {}; - payload[namespace] = { event: eventName, message }; - const event = new CustomEvent(this.glue42EventName, { detail: payload }); - window.dispatchEvent(event); - } - } - - class PreferredConnectionController { - coreGlue; - transactionTimeout = 15000; - transactionLocks = {}; - webPlatformTransport; - webPlatformMessagesUnsubscribe; - reconnectCounter = 0; - logger; - constructor(coreGlue) { - this.coreGlue = coreGlue; - this.logger = this.coreGlue.logger.subLogger("web.preferred.connection.controller"); - } - stop() { - if (!this.webPlatformMessagesUnsubscribe) { - return; - } - this.webPlatformMessagesUnsubscribe(); - } - async start(coreConfig) { - if (coreConfig.isPlatformInternal) { - this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic."); - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - if (!isConnectedToPlatform) { - return ioError.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport."); - } - if (!this.coreGlue.connection.transport.isPreferredActivated) { - this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization."); - return; - } - this.webPlatformTransport = this.coreGlue.connection.transport; - this.webPlatformMessagesUnsubscribe = this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this)); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - handleWebPlatformMessage(msg) { - if (typeof msg === "string") { - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - const type = msg.type; - const args = msg.args; - const transactionId = msg.transactionId; - if (type === Glue42CoreMessageTypes.transportSwitchRequest.name) { - return this.handleTransportSwitchRequest(args, transactionId); - } - if (type === Glue42CoreMessageTypes.platformUnload.name && !isConnectedToPlatform) { - return this.handlePlatformUnload(); - } - if (type === Glue42CoreMessageTypes.getCurrentTransportResponse.name) { - return this.handleGetCurrentTransportResponse(args, transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredLogic.name) { - return this.handleCheckPreferredLogic(transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredConnection.name) { - return this.handleCheckPreferredConnection(args, transactionId); - } - } - async reEstablishPlatformPort() { - try { - await this.webPlatformTransport.connect(); - } - catch (error) { - this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(error)}`); - --this.reconnectCounter; - if (this.reconnectCounter > 0) { - return this.reEstablishPlatformPort(); - } - this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform."); - } - this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."); - this.reconnectCounter = 0; - this.webPlatformTransport.close(); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - async checkSwitchTransport(config) { - const myCurrentTransportName = this.coreGlue.connection.transport.name(); - if (myCurrentTransportName === config.transportName) { - this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary"); - return; - } - this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${myCurrentTransportName}, but it should reconnect to ${JSON.stringify(config)}`); - const result = await this.coreGlue.connection.switchTransport(config); - this.setConnected(); - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - } - async getCurrentPlatformTransportState() { - this.logger.trace("Requesting the current transport state of the platform."); - const transaction = this.setTransaction(Glue42CoreMessageTypes.getCurrentTransport.name); - this.sendPlatformMessage(Glue42CoreMessageTypes.getCurrentTransport.name, transaction.id); - const transportState = await transaction.lock; - this.logger.trace(`The platform responded with transport state: ${JSON.stringify(transportState)}`); - return transportState; - } - setTransaction(operation) { - const transaction = {}; - const transactionId = nanoid$1(10); - const transactionLock = new Promise((resolve, reject) => { - let transactionLive = true; - transaction.lift = (args) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - resolve(args); - }; - transaction.fail = (reason) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - reject(reason); - }; - setTimeout(() => { - if (!transactionLive) { - return; - } - transactionLive = false; - this.logger.warn(`Transaction for operation: ${operation} timed out.`); - delete this.transactionLocks[transactionId]; - reject(`Transaction for operation: ${operation} timed out.`); - }, this.transactionTimeout); - }); - transaction.lock = transactionLock; - transaction.id = transactionId; - this.transactionLocks[transactionId] = transaction; - return transaction; - } - sendPlatformMessage(type, transactionId, args) { - this.logger.trace(`Sending a platform message of type: ${type}, id: ${transactionId} and args: ${JSON.stringify(args)}`); - this.webPlatformTransport.sendObject({ - glue42core: { type, args, transactionId } - }); - } - handleTransportSwitchRequest(args, transactionId) { - this.logger.trace(`Received a transport switch request with id: ${transactionId} and data: ${JSON.stringify(args)}`); - this.coreGlue.connection.switchTransport(args.switchSettings) - .then((result) => { - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - this.setConnected(); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: result.success }); - }) - .catch((error) => { - this.logger.error(error); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: false }); - }); - } - handlePlatformUnload() { - this.reconnectCounter = 5; - this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."); - this.reEstablishPlatformPort(); - } - handleGetCurrentTransportResponse(args, transactionId) { - this.logger.trace(`Got a current transport response from the platform with id: ${transactionId} and data: ${JSON.stringify(args)}`); - const transportState = args.transportState; - const transaction = this.transactionLocks[transactionId]; - transaction?.lift(transportState); - } - handleCheckPreferredLogic(transactionId) { - setTimeout(() => this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredLogicResponse.name, transactionId), 0); - } - handleCheckPreferredConnection(args, transactionId) { - const url = args.url; - this.logger.trace(`Testing the possible connection to: ${url}`); - this.checkPreferredConnection(url) - .then((result) => { - this.logger.trace(`The connection to ${url} is possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, result); - }) - .catch((error) => { - this.logger.trace(`The connection to ${url} is not possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, { error }); - }); - } - checkPreferredConnection(url) { - return new Promise((resolve) => { - const ws = new WebSocket(url); - ws.onerror = () => resolve({ live: false }); - ws.onopen = () => { - ws.close(); - resolve({ live: true }); - }; - }); - } - setConnected() { - this.webPlatformTransport.manualSetReadyState(); - } - } - - const operations$2 = { - getCurrent: { name: "getCurrent", resultDecoder: simpleThemeResponseDecoder }, - list: { name: "list", resultDecoder: allThemesResponseDecoder }, - select: { name: "select", dataDecoder: selectThemeConfigDecoder } - }; - - class ThemesController { - logger; - bridge; - registry = CallbackRegistryFactory$1(); - themesSubscription; - activeThemeSubs = 0; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("themes.controller.web"); - this.logger.trace("starting the web themes controller"); - this.bridge = ioc.bridge; - const api = this.toApi(); - coreGlue.themes = api; - this.logger.trace("themes are ready"); - } - handlePlatformShutdown() { - this.registry.clear(); - this.activeThemeSubs = 0; - this.themesSubscription?.close(); - delete this.themesSubscription; - } - async handleBridgeMessage() { - } - toApi() { - const api = { - getCurrent: this.getCurrent.bind(this), - list: this.list.bind(this), - select: this.select.bind(this), - onChanged: this.onChanged.bind(this) - }; - return Object.freeze(api); - } - async getCurrent() { - const bridgeResponse = await this.bridge.send("themes", operations$2.getCurrent, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.theme; - } - async list() { - const bridgeResponse = await this.bridge.send("themes", operations$2.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.themes; - } - async select(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("themes", operations$2.select, { name }, undefined, { includeOperationCheck: true }); - } - async onChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onChanged requires a callback of type function"); - } - const subReady = this.themesSubscription ? - Promise.resolve() : - this.configureThemeSubscription(); - await subReady; - ++this.activeThemeSubs; - const unsubFunc = this.registry.add("on-theme-change", callback); - return () => this.themeUnsub(unsubFunc); - } - async configureThemeSubscription() { - if (this.themesSubscription) { - return; - } - this.themesSubscription = await this.bridge.createNotificationsSteam(); - this.themesSubscription.onData((data) => { - const eventData = data.data; - const validation = simpleThemeResponseDecoder.run(eventData); - if (!validation.ok) { - this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`); - return; - } - const themeChanged = validation.result; - this.registry.execute("on-theme-change", themeChanged.theme); - }); - this.themesSubscription.onClosed(() => { - this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"); - this.registry.clear(); - this.activeThemeSubs = 0; - delete this.themesSubscription; - }); - } - themeUnsub(registryUnsub) { - registryUnsub(); - --this.activeThemeSubs; - if (this.activeThemeSubs) { - return; - } - this.themesSubscription?.close(); - delete this.themesSubscription; - } - } - - class ChannelsStorage { - sessionStorage = window.sessionStorage; - _mode = DEFAULT_STORAGE_MODE; - inMemoryChannels = []; - inMemoryRestrictions = []; - _unsubscribeDict = {}; - clear() { - this._mode = DEFAULT_STORAGE_MODE; - this.inMemoryChannels = []; - this.inMemoryRestrictions = []; - this._unsubscribeDict = {}; - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify([])); - } - get mode() { - return this._mode; - } - set mode(mode) { - this._mode = mode; - } - get channels() { - if (this.mode === "inMemory") { - return this.inMemoryChannels.slice(); - } - return this.getSessionStorageData()?.channels ?? []; - } - set channels(channels) { - if (this.mode === "inMemory") { - this.inMemoryChannels = channels; - } - this.setSessionStorageChannels(channels); - } - get restrictions() { - if (this.mode === "inMemory") { - return this.inMemoryRestrictions.slice(); - } - return this.getSessionStorageData()?.restrictions ?? []; - } - set restrictions(restrictions) { - if (this.mode === "inMemory") { - this.inMemoryRestrictions = restrictions; - } - this.setSessionStorageRestrictions(restrictions); - } - getSessionStorageData() { - return JSON.parse(this.sessionStorage.getItem(STORAGE_NAMESPACE) || "null"); - } - addUnsubscribe(channel, unsubscribe) { - this._unsubscribeDict[channel] = unsubscribe; - } - invokeUnsubscribes(channel) { - if (channel) { - this._unsubscribeDict[channel]?.(); - delete this._unsubscribeDict[channel]; - return; - } - Object.values(this._unsubscribeDict).forEach((unsub) => unsub()); - this._unsubscribeDict = {}; - } - setSessionStorageChannels(channels) { - const data = this.getSessionStorageData(); - if (data?.channels) { - data.channels = channels; - return this.setSessionStorageData(data); - } - const newData = { channels, restrictions: data?.restrictions ?? [] }; - return this.setSessionStorageData(newData); - } - setSessionStorageRestrictions(restrictions) { - const data = this.getSessionStorageData(); - if (data?.restrictions) { - data.restrictions = restrictions; - return this.setSessionStorageData(data); - } - const newData = { channels: data?.channels ?? [], restrictions }; - return this.setSessionStorageData(newData); - } - setSessionStorageData(data) { - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify(data)); - } - } - - const operations$1 = { - clear: { name: "clear", dataDecoder: basePrefsConfigDecoder }, - clearAll: { name: "clearAll" }, - get: { name: "get", dataDecoder: basePrefsConfigDecoder, resultDecoder: getPrefsResultDecoder }, - getAll: { name: "getAll", resultDecoder: getAllPrefsResultDecoder }, - set: { name: "set", dataDecoder: changePrefsDataDecoder }, - update: { name: "update", dataDecoder: changePrefsDataDecoder }, - prefsChanged: { name: "prefsChanged", dataDecoder: getPrefsResultDecoder }, - prefsHello: { name: "prefsHello", resultDecoder: prefsHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" }, - registerSubscriber: { name: "registerSubscriber", dataDecoder: subscriberRegisterConfigDecoder }, - }; - - class PrefsController { - supportedOperationsNames = []; - bridge; - config; - logger; - appManagerController; - platformAppName; - registry = CallbackRegistryFactory$1(); - validNonExistentApps; - signaledSubscription = false; - interopId; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("prefs.controller.web"); - this.logger.trace("starting the web prefs controller"); - this.addOperationsExecutors(); - this.interopId = coreGlue.interop.instance.instance; - this.bridge = ioc.bridge; - this.config = ioc.config; - this.appManagerController = ioc.appManagerController; - try { - const prefsHelloSuccess = await this.bridge.send("prefs", operations$1.prefsHello, undefined, undefined, { includeOperationCheck: true }); - this.platformAppName = prefsHelloSuccess.platform.app; - this.validNonExistentApps = prefsHelloSuccess.validNonExistentApps ?? []; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support Prefs API."); - return; - } - this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning"); - const api = this.toApi(); - coreGlue.prefs = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(prefsOperationTypesDecoder, args.operation); - const operation = operations$1[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async get(app) { - const verifiedApp = app === undefined || app === null ? this.getMyAppName() : runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const { prefs } = await this.bridge.send("prefs", operations$1.get, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - return prefs; - } - async update(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.updateFor(app, data); - } - addOperationsExecutors() { - operations$1.prefsChanged.execute = this.handleOnChanged.bind(this); - operations$1.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$1); - } - toApi() { - const api = { - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearFor: this.clearFor.bind(this), - get: this.get.bind(this), - getAll: this.getAll.bind(this), - set: this.set.bind(this), - setFor: this.setFor.bind(this), - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - update: this.update.bind(this), - updateFor: this.updateFor.bind(this), - }; - return api; - } - async clear() { - const app = this.getMyAppName(); - await this.clearFor(app); - } - async clearAll() { - await this.bridge.send("prefs", operations$1.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearFor(app) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - await this.bridge.send("prefs", operations$1.clear, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - } - async getAll() { - const result = await this.bridge.send("prefs", operations$1.getAll, undefined, undefined, { includeOperationCheck: true }); - return result; - } - async set(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.setFor(app, data); - } - async setFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.set, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - subscribe(callback) { - const app = this.getMyAppName(); - return this.subscribeFor(app, callback); - } - subscribeFor(app, callback) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const applications = this.appManagerController.getApplications(); - const isValidApp = verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp); - if (!isValidApp) { - return ioError.raiseError(`The provided app name "${app}" is not valid.`); - } - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!"); - } - if (!this.signaledSubscription) { - this.bridge.send("prefs", operations$1.registerSubscriber, { interopId: this.interopId, appName: verifiedApp }, undefined, { includeOperationCheck: true }) - .catch((error) => { - this.logger.warn("Failed to register subscriber for prefs"); - this.logger.error(error); - }); - this.signaledSubscription = true; - } - const subscriptionKey = this.getSubscriptionKey(verifiedApp); - this.get(verifiedApp).then(callback); - return this.registry.add(subscriptionKey, callback); - } - async updateFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.update, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - getMyAppName() { - const myAppName = this.config.isPlatformInternal ? this.platformAppName : this.appManagerController.me?.application.name; - if (!myAppName) { - return ioError.raiseError("App Preferences operations can not be executed for windows that do not have app!"); - } - return myAppName; - } - getSubscriptionKey(app) { - return `prefs-changed-${app}`; - } - async handleOnChanged({ prefs }) { - const subscriptionKey = this.getSubscriptionKey(prefs.app); - this.registry.execute(subscriptionKey, prefs); - } - } - - const operations = { - getResources: { name: "getResources", dataDecoder: getResourcesDataDecoder, resultDecoder: getResourcesResultDecoder }, - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - showAlert: { name: "showAlert", dataDecoder: uiAlertRequestMessageDecoder }, - showDialog: { name: "showDialog", dataDecoder: uiDialogRequestMessageDecoder }, - alertInteropAction: { name: "alertInteropAction", dataDecoder: alertInteropActionDataDecoder }, - showResolver: { name: "showResolver", dataDecoder: uiResolverRequestMessageDecoder, resultDecoder: uiResolverResponseMessageDecoder }, - }; - - const DEFAULT_ALERT_TTL = 5 * 1000; - const MODALS_SHADOW_HOST_ID = "io-modals-shadow-host"; - const MODALS_ROOT_ELEMENT_ID = "io-modals-root"; - const WIDGET_SHADOW_HOST_ID = "io-widget-shadow-host"; - const WIDGET_ROOT_ELEMENT_ID = "io-widget-root"; - const INTENT_RESOLVER_SHADOW_HOST_ID = "io-intent-resolver-shadow-host"; - const INTENT_RESOLVER_ROOT_ELEMENT_ID = "io-intent-resolver-root"; - const SHADOW_ROOT_ELEMENT_CLASSNAME = "io-body io-variables"; - - class UIController { - ioc; - supportedOperationsNames = []; - logger; - bridge; - config; - zIndexDictionary = { - [WIDGET_SHADOW_HOST_ID]: "100", - [MODALS_SHADOW_HOST_ID]: "101", - [INTENT_RESOLVER_SHADOW_HOST_ID]: "100" - }; - widgetResources; - modalsResources; - intentResolverResources; - modalsUiApi; - isDialogOpen = false; - intentResolverUiApi; - isIntentResolverOpen = false; - constructor(ioc) { - this.ioc = ioc; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("ui.controller.web"); - this.logger.trace("starting the ui controller"); - this.bridge = ioc.bridge; - this.config = ioc.config; - this.addOperationsExecutors(); - const resources = await this.getResources(); - if (!resources) { - this.logger.trace("No UI elements to display - platform is not initialized with any UI resources"); - return; - } - this.logger.trace(`Received UI resources from platform: ${JSON.stringify(resources)}`); - this.setResources(resources); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(uiOperationTypesDecoder, args.operation); - const operation = operations[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async showComponents(io) { - const initializeWidgetPromise = this.widgetResources ? this.initializeWidget(io, this.widgetResources) : Promise.resolve(); - const initializeModalsPromise = this.modalsResources ? this.initializeModalsUi(io, this.modalsResources) : Promise.resolve(); - const initializeIntentResolverPromise = this.intentResolverResources ? this.initializeIntentResolverUI(io, this.intentResolverResources) : Promise.resolve(); - await Promise.all([ - this.config.widget.awaitFactory ? initializeWidgetPromise : Promise.resolve(), - this.config.modals.awaitFactory ? initializeModalsPromise : Promise.resolve(), - this.config.intentResolver.awaitFactory ? initializeIntentResolverPromise : Promise.resolve(), - ]); - } - isIntentResolverEnabled() { - return !!this.intentResolverResources && this.config.intentResolver.enable; - } - addOperationsExecutors() { - operations.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - operations.showAlert.execute = this.handleShowAlert.bind(this); - operations.showDialog.execute = this.handleShowDialog.bind(this); - operations.showResolver.execute = this.handleShowResolver.bind(this); - this.supportedOperationsNames = getSupportedOperationsNames(operations); - } - async handleShowAlert({ config }) { - if (!this.config.modals.alerts.enabled) { - return ioError.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showAlert operation because modalsUiApi is missing."); - } - const { promise: closePromise, resolve: resolveClosePromise } = wrapPromise(); - const onClick = (config) => { - const decodedConfig = alertOnClickConfigDecoder.run(config); - if (!decodedConfig.ok) { - this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(decodedConfig.error)}.`); - return; - } - const { interopAction } = decodedConfig.result; - this.bridge.send("ui", operations.alertInteropAction, { interopAction }, undefined, { includeOperationCheck: true }) - .catch((error) => this.logger.warn(extractErrorMsg(error))); - }; - let result; - try { - this.logger.trace(`Open alert with config: ${JSON.stringify(config)}`); - result = modalsUiApi.alerts.open({ ...config, onClick, onClose: resolveClosePromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openAlertResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - const timeoutId = setTimeout(() => { - resolveClosePromise(); - }, getSafeTimeoutDelay(config.ttl ?? DEFAULT_ALERT_TTL)); - closePromise.then(() => { - clearTimeout(timeoutId); - try { - modalsUiApi.alerts.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close alert with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - }); - } - async handleShowDialog({ config }) { - if (!this.config.modals.dialogs.enabled) { - return ioError.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showDialog operation because modalsUiApi is missing."); - } - if (this.isDialogOpen) { - return ioError.raiseError("Cannot open a dialog because another one is already open."); - } - const { promise: completionPromise, resolve: resolveCompletionPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open dialog with config: ${JSON.stringify(config)}`); - result = modalsUiApi.dialogs.open({ ...config, onCompletion: resolveCompletionPromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openDialogResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - this.isDialogOpen = true; - let timeoutId; - if (config.timer) { - timeoutId = setTimeout(() => { - resolveCompletionPromise({ response: { isExpired: true } }); - }, getSafeTimeoutDelay(config.timer.duration)); - } - const response = await completionPromise; - clearTimeout(timeoutId); - this.isDialogOpen = false; - try { - modalsUiApi.dialogs.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close dialog with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodeResponse = dialogOnCompletionConfigDecoder.run(response); - if (!decodeResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodeResponse.error)}.`); - } - return { result: decodeResponse.result.response }; - } - async handleShowResolver({ config }) { - this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(config)}`); - if (!this.config.intentResolver.enable) { - return ioError.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config."); - } - const intentResolverApi = this.intentResolverUiApi; - if (!intentResolverApi) { - return ioError.raiseError("Unable to perform showResolver operation because intentResolverApi is missing."); - } - if (this.isIntentResolverOpen) { - return ioError.raiseError("Cannot open the intent resolver because another one is already open."); - } - const { promise: completionPromise, resolve: resolveIntentResolverPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open intent resolver with config: ${JSON.stringify(config)}`); - result = intentResolverApi.open({ ...config, onUserResponse: resolveIntentResolverPromise }); - } - catch (error) { - return ioError.raiseError(`intentResolverUI.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodedOpenResult = openResolverResultDecoder.run(result); - if (!decodedOpenResult.ok) { - return ioError.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(decodedOpenResult.error)}.`); - } - const timer = setTimeout(() => resolveIntentResolverPromise({ response: { isExpired: true } }), getSafeTimeoutDelay(config.timeout)); - const response = await completionPromise; - clearTimeout(timer); - this.isIntentResolverOpen = false; - try { - intentResolverApi.close({ id: decodedOpenResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close intent resolver with id ${decodedOpenResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodedResponse = onUserResponseResponseDecoder.run(response); - if (!decodedResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodedResponse.error)}.`); - } - return { result: decodedResponse.result.response }; - } - async getResources() { - const data = { - origin: window.origin - }; - try { - const result = await this.bridge.send("ui", operations.getResources, data, undefined, { includeOperationCheck: true }); - return result.resources; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - } - } - appendModalsResources(resources) { - this.logger.trace("Appending modals resources"); - return this.appendResources(MODALS_SHADOW_HOST_ID, MODALS_ROOT_ELEMENT_ID, resources.sources); - } - appendWidgetResources(resources) { - this.logger.trace("Appending widget resources"); - return this.appendResources(WIDGET_SHADOW_HOST_ID, WIDGET_ROOT_ELEMENT_ID, resources.sources); - } - appendIntentResolverResources(resources) { - this.logger.trace("Appending intent resolver resources"); - return this.appendResources(INTENT_RESOLVER_SHADOW_HOST_ID, INTENT_RESOLVER_ROOT_ELEMENT_ID, resources.sources); - } - appendResources(shadowHostId, rootElementId, sources) { - const { bundle, fonts = [], styles } = sources; - const shadowHost = document.createElement("div"); - shadowHost.id = shadowHostId; - shadowHost.style.position = "fixed"; - shadowHost.style.zIndex = this.zIndexDictionary[shadowHostId]; - const shadowRoot = shadowHost.attachShadow({ mode: "open" }); - const script = document.createElement("script"); - script.src = bundle; - script.type = "module"; - shadowRoot.appendChild(script); - const rootElement = document.createElement("div"); - rootElement.id = rootElementId; - rootElement.className = SHADOW_ROOT_ELEMENT_CLASSNAME; - shadowRoot.appendChild(rootElement); - styles.forEach((style) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = style; - shadowRoot.appendChild(link); - }); - fonts.forEach((font) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = font; - document.head.insertBefore(link, document.head.firstChild); - }); - document.body.appendChild(shadowHost); - return { rootElement }; - } - async initializeWidget(io, resources) { - this.logger.trace("Initializing IOBrowserWidget."); - const { rootElement } = this.appendWidgetResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...deepmerge$1(resources.config, this.config.widget), - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.widgetReady(); - this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(config)}`); - await window.IOBrowserWidget(io, config); - this.logger.trace("IOBrowserWidget was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserWidget to initialize.`); - } - async initializeModalsUi(io, resources) { - this.logger.trace("Initializing IOBrowserModalsUI."); - const { rootElement } = this.appendModalsResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.modals, - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.modalsUIFactoryReady(); - this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.modalsUiApi = await window.IOBrowserModalsUI(io, config); - this.logger.trace("IOBrowserModalsUI was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`); - } - async initializeIntentResolverUI(io, resources) { - this.logger.trace("Initializing IOBrowserIntentResolverUI."); - const { rootElement } = this.appendIntentResolverResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.intentResolver, - rootElement - }; - const timeout = config.timeout; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(); - this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.intentResolverUiApi = await window.IOBrowserIntentResolverUI(io, config); - this.logger.trace("IOBrowserIntentResolverUI initialized successfully."); - }, timeout, `Timeout of ${timeout}ms hit waiting for IOBrowserIntentResolverUI to initialize.`); - } - setResources(resources) { - this.setWidgetResources(resources.widget); - this.setModalsUiResources(resources.modals); - this.setIntentResolverResources(resources.intentResolver); - } - setWidgetResources(resources) { - const baseMsg = "Widget won't be displayed. Reason: "; - const decodedConfig = widgetConfigDecoder.run(this.config.widget); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid widget config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.widget.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'widget: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`); - return; - } - this.widgetResources = resources; - } - setModalsUiResources(resources) { - const baseMsg = "Modals won't be displayed. Reason: "; - const decodedConfig = modalsConfigDecoder.run(this.config.modals); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid modals config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.modals.alerts.enabled && !this.config.modals.dialogs.enabled) { - this.logger.trace(`${baseMsg} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`); - return; - } - this.modalsResources = resources; - } - setIntentResolverResources(resources) { - const baseMsg = "Intent Resolver UI won't be displayed. Reason: "; - const decodedConfig = intentResolverConfigDecoder.run(this.config.intentResolver); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid intent resolver config. Error: ${JSON.stringify(decodedConfig.error)}`); - return; - } - if (!this.config.intentResolver.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'intentResolver: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`); - return; - } - this.intentResolverResources = resources; - } - subscribeForThemeChanges(io, element) { - const themesApi = io.themes; - if (!themesApi) { - return; - } - const changeTheme = async (theme) => { - if (element.classList.contains(theme.name)) { - return; - } - const allThemes = await themesApi.list(); - element.classList.remove(...allThemes.map(({ name }) => name)); - element.classList.add(theme.name); - }; - themesApi.onChanged(changeTheme); - themesApi.getCurrent().then(changeTheme); - } - } - - class IoC { - _coreGlue; - _communicationId; - _publicWindowId; - _webConfig; - _windowsControllerInstance; - _appManagerControllerInstance; - _layoutsControllerInstance; - _notificationsControllerInstance; - _intentsControllerInstance; - _channelsControllerInstance; - _themesControllerInstance; - _extensionController; - _systemControllerInstance; - _bridgeInstance; - _eventsDispatcher; - _preferredConnectionController; - _channelsStorage; - _prefsControllerInstance; - _uiController; - controllers = { - windows: this.windowsController, - appManager: this.appManagerController, - layouts: this.layoutsController, - notifications: this.notificationsController, - intents: this.intentsController, - channels: this.channelsController, - system: this.systemController, - extension: this.extensionController, - themes: this.themesController, - prefs: this.prefsController, - ui: this.uiController - }; - get communicationId() { - return this._communicationId; - } - get publicWindowId() { - return this._publicWindowId; - } - get windowsController() { - if (!this._windowsControllerInstance) { - this._windowsControllerInstance = new WindowsController(); - } - return this._windowsControllerInstance; - } - get uiController() { - if (!this._uiController) { - this._uiController = new UIController(this); - } - return this._uiController; - } - get appManagerController() { - if (!this._appManagerControllerInstance) { - this._appManagerControllerInstance = new AppManagerController(); - } - return this._appManagerControllerInstance; - } - get layoutsController() { - if (!this._layoutsControllerInstance) { - this._layoutsControllerInstance = new LayoutsController(); - } - return this._layoutsControllerInstance; - } - get themesController() { - if (!this._themesControllerInstance) { - this._themesControllerInstance = new ThemesController(); - } - return this._themesControllerInstance; - } - get notificationsController() { - if (!this._notificationsControllerInstance) { - this._notificationsControllerInstance = new NotificationsController(); - } - return this._notificationsControllerInstance; - } - get intentsController() { - if (!this._intentsControllerInstance) { - this._intentsControllerInstance = new IntentsController(); - } - return this._intentsControllerInstance; - } - get systemController() { - if (!this._systemControllerInstance) { - this._systemControllerInstance = new SystemController(); - } - return this._systemControllerInstance; - } - get channelsController() { - if (!this._channelsControllerInstance) { - this._channelsControllerInstance = new ChannelsController(); - } - return this._channelsControllerInstance; - } - get prefsController() { - if (!this._prefsControllerInstance) { - this._prefsControllerInstance = new PrefsController(); - } - return this._prefsControllerInstance; - } - get extensionController() { - if (!this._extensionController) { - this._extensionController = new ExtController(); - } - return this._extensionController; - } - get eventsDispatcher() { - if (!this._eventsDispatcher) { - this._eventsDispatcher = new EventsDispatcher(this.config); - } - return this._eventsDispatcher; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new GlueBridge(this._coreGlue, this.communicationId); - } - return this._bridgeInstance; - } - get preferredConnectionController() { - if (!this._preferredConnectionController) { - this._preferredConnectionController = new PreferredConnectionController(this._coreGlue); - } - return this._preferredConnectionController; - } - get channelsStorage() { - if (!this._channelsStorage) { - this._channelsStorage = new ChannelsStorage(); - } - return this._channelsStorage; - } - get config() { - return this._webConfig; - } - defineGlue(coreGlue) { - this._coreGlue = coreGlue; - this._publicWindowId = coreGlue.connection.transport.publicWindowId; - const globalNamespace = window.glue42core || window.iobrowser; - this._communicationId = coreGlue.connection.transport.communicationId || globalNamespace.communicationId; - } - defineConfig(config) { - this._webConfig = config; - } - async buildWebWindow(id, name, logger) { - const model = new WebWindowModel(id, name, this.bridge, logger); - const api = await model.toApi(); - return { id, model, api }; - } - buildNotification(config, id) { - return new Notification(config, id); - } - async buildApplication(app, applicationInstances) { - const application = (new ApplicationModel(app, [], this.appManagerController)).toApi(); - const instances = applicationInstances.map((instanceData) => this.buildInstance(instanceData, application)); - application.instances.push(...instances); - return application; - } - buildInstance(instanceData, app) { - return (new InstanceModel(instanceData, this.bridge, app)).toApi(); - } - } - - var version$1 = "4.2.4"; - - const setupGlobalSystem = (io, bridge) => { - return { - getContainerInfo: async () => { - if (window === window.parent) { - return; - } - if (window.name.includes("#wsp")) { - return { - workspaceFrame: { - id: "N/A" - } - }; - } - return window.parent === window.top ? - { top: {} } : - { parent: {} }; - }, - getProfileData: async () => { - if (!bridge) { - throw new Error("Bridge is not available and cannot fetch the profile data"); - } - const data = await bridge.send("system", { name: "getProfileData" }, undefined); - return data; - } - }; - }; - - const createFactoryFunction = (coreFactoryFunction) => { - let cachedApiPromise; - const initAPI = async (config) => { - const ioc = new IoC(); - const glue = await PromiseWrap(() => coreFactoryFunction(config, { version: version$1 }), 30000, "Glue Web initialization timed out, because core didn't resolve"); - const logger = glue.logger.subLogger("web.main.controller"); - ioc.defineGlue(glue); - await ioc.preferredConnectionController.start(config); - await ioc.bridge.start(ioc.controllers); - ioc.defineConfig(config); - logger.trace("the bridge has been started, initializing all controllers"); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.start(glue, ioc))); - logger.trace("all controllers reported started, starting all additional libraries"); - try { - await Promise.all(config.libraries.map((lib) => lib(glue, config))); - logger.trace("all libraries were started"); - ioc.eventsDispatcher.start(glue); - logger.trace("start event dispatched, glue is ready, returning it"); - await ioc.uiController.showComponents(glue).catch((err) => logger.warn(err?.message ? err.message : JSON.stringify(err))); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.postStart ? controller.postStart(glue, ioc) : Promise.resolve())); - window.iobrowser.system = setupGlobalSystem(glue, ioc.bridge); - window.iobrowser = Object.freeze({ ...window.iobrowser }); - return glue; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const factory = (userConfig) => { - if (window.glue42gd || window.iodesktop) { - return enterprise(userConfig); - } - const config = parseConfig(userConfig); - try { - checkSingleton(); - } - catch (error) { - return typeof cachedApiPromise === "undefined" ? Promise.reject(new Error(error)) : cachedApiPromise; - } - const apiPromise = initAPI(config); - cachedApiPromise = userConfig?.memoizeAPI ? apiPromise : undefined; - return apiPromise; - }; - return factory; - }; - - var MetricTypes = { - STRING: 1, - NUMBER: 2, - TIMESTAMP: 3, - OBJECT: 4 - }; - - function getMetricTypeByValue(metric) { - if (metric.type === MetricTypes.TIMESTAMP) { - return "timestamp"; - } - else if (metric.type === MetricTypes.NUMBER) { - return "number"; - } - else if (metric.type === MetricTypes.STRING) { - return "string"; - } - else if (metric.type === MetricTypes.OBJECT) { - return "object"; - } - return "unknown"; - } - function getTypeByValue(value) { - if (value.constructor === Date) { - return "timestamp"; - } - else if (typeof value === "number") { - return "number"; - } - else if (typeof value === "string") { - return "string"; - } - else if (typeof value === "object") { - return "object"; - } - else { - return "string"; - } - } - function serializeMetric(metric) { - const serializedMetrics = {}; - const type = getMetricTypeByValue(metric); - if (type === "object") { - const values = Object.keys(metric.value).reduce((memo, key) => { - const innerType = getTypeByValue(metric.value[key]); - if (innerType === "object") { - const composite = defineNestedComposite(metric.value[key]); - memo[key] = { - type: "object", - description: "", - context: {}, - composite, - }; - } - else { - memo[key] = { - type: innerType, - description: "", - context: {}, - }; - } - return memo; - }, {}); - serializedMetrics.composite = values; - } - serializedMetrics.name = normalizeMetricName(metric.path.join("/") + "/" + metric.name); - serializedMetrics.type = type; - serializedMetrics.description = metric.description; - serializedMetrics.context = {}; - return serializedMetrics; - } - function defineNestedComposite(values) { - return Object.keys(values).reduce((memo, key) => { - const type = getTypeByValue(values[key]); - if (type === "object") { - memo[key] = { - type: "object", - description: "", - context: {}, - composite: defineNestedComposite(values[key]), - }; - } - else { - memo[key] = { - type, - description: "", - context: {}, - }; - } - return memo; - }, {}); - } - function normalizeMetricName(name) { - if (typeof name !== "undefined" && name.length > 0 && name[0] !== "/") { - return "/" + name; - } - else { - return name; - } - } - function getMetricValueByType(metric) { - const type = getMetricTypeByValue(metric); - if (type === "timestamp") { - return Date.now(); - } - else { - return publishNestedComposite(metric.value); - } - } - function publishNestedComposite(values) { - if (typeof values !== "object") { - return values; - } - return Object.keys(values).reduce((memo, key) => { - const value = values[key]; - if (typeof value === "object" && value.constructor !== Date) { - memo[key] = publishNestedComposite(value); - } - else if (value.constructor === Date) { - memo[key] = new Date(value).getTime(); - } - else if (value.constructor === Boolean) { - memo[key] = value.toString(); - } - else { - memo[key] = value; - } - return memo; - }, {}); - } - function flatten(arr) { - return arr.reduce((flat, toFlatten) => { - return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); - }, []); - } - function getHighestState(arr) { - return arr.sort((a, b) => { - if (!a.state) { - return 1; - } - if (!b.state) { - return -1; - } - return b.state - a.state; - })[0]; - } - function aggregateDescription(arr) { - let msg = ""; - arr.forEach((m, idx, a) => { - const path = m.path.join("."); - if (idx === a.length - 1) { - msg += path + "." + m.name + ": " + m.description; - } - else { - msg += path + "." + m.name + ": " + m.description + ","; - } - }); - if (msg.length > 100) { - return msg.slice(0, 100) + "..."; - } - else { - return msg; - } - } - function composeMsgForRootStateMetric(system) { - const aggregatedState = system.root.getAggregateState(); - const merged = flatten(aggregatedState); - const highestState = getHighestState(merged); - const aggregateDesc = aggregateDescription(merged); - return { - description: aggregateDesc, - value: highestState.state, - }; - } - - function gw3 (connection, config) { - if (!connection || typeof connection !== "object") { - throw new Error("Connection is required parameter"); - } - let joinPromise; - let session; - const init = (repo) => { - let resolveReadyPromise; - joinPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - session = connection.domain("metrics"); - session.onJoined((reconnect) => { - if (!reconnect && resolveReadyPromise) { - resolveReadyPromise(); - resolveReadyPromise = undefined; - } - const rootStateMetric = { - name: "/State", - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const defineRootMetricsMsg = { - type: "define", - metrics: [rootStateMetric], - }; - session.sendFireAndForget(defineRootMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(err)}`); - }); - if (reconnect) { - replayRepo(repo); - } - }); - session.join({ - system: config.system, - service: config.service, - instance: config.instance - }); - }; - const replayRepo = (repo) => { - replaySystem(repo.root); - }; - const replaySystem = (system) => { - createSystem(system); - system.metrics.forEach((m) => { - createMetric(m); - }); - system.subSystems.forEach((ss) => { - replaySystem(ss); - }); - }; - const createSystem = async (system) => { - if (system.parent === undefined) { - return; - } - await joinPromise; - const metric = { - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const createMetricsMsg = { - type: "define", - metrics: [metric], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const updateSystem = async (system, state) => { - await joinPromise; - const shadowedUpdateMetric = { - type: "publish", - values: [{ - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - value: { - Description: state.description, - Value: state.state, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(shadowedUpdateMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - const stateObj = composeMsgForRootStateMetric(system); - const rootMetric = { - type: "publish", - peer_id: connection.peerId, - values: [{ - name: "/State", - value: { - Description: stateObj.description, - Value: stateObj.value, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(rootMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for root state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const createMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - const m = serializeMetric(metricClone); - const createMetricsMsg = { - type: "define", - metrics: [m], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for metric ${metric.name}: ${JSON.stringify(err)}`); - }); - if (typeof metricClone.value !== "undefined") { - updateMetricCore(metricClone); - } - }; - const updateMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - updateMetricCore(metricClone); - }; - const updateMetricCore = (metric) => { - if (canUpdate()) { - const value = getMetricValueByType(metric); - const publishMetricsMsg = { - type: "publish", - values: [{ - name: normalizeMetricName(metric.path.join("/") + "/" + metric.name), - value, - timestamp: Date.now(), - }], - }; - return session.sendFireAndForget(publishMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to publish metric ${metric.name}: ${JSON.stringify(err)}`); - }); - } - return Promise.resolve(); - }; - const cloneMetric = (metric) => { - const metricClone = { ...metric }; - if (typeof metric.value === "object" && metric.value !== null) { - metricClone.value = { ...metric.value }; - } - return metricClone; - }; - const canUpdate = () => { - try { - const func = config.canUpdateMetric ?? (() => true); - return func(); - } - catch { - return true; - } - }; - return { - init, - createSystem, - updateSystem, - createMetric, - updateMetric, - }; - } - - var Helpers = { - validate: (definition, parent, transport) => { - if (definition === null || typeof definition !== "object") { - throw new Error("Missing definition"); - } - if (parent === null || typeof parent !== "object") { - throw new Error("Missing parent"); - } - if (transport === null || typeof transport !== "object") { - throw new Error("Missing transport"); - } - }, - }; - - class BaseMetric { - definition; - system; - transport; - value; - type; - path = []; - name; - description; - get repo() { - return this.system?.repo; - } - get id() { return `${this.system.path}/${name}`; } - constructor(definition, system, transport, value, type) { - this.definition = definition; - this.system = system; - this.transport = transport; - this.value = value; - this.type = type; - Helpers.validate(definition, system, transport); - this.path = system.path.slice(0); - this.path.push(system.name); - this.name = definition.name; - this.description = definition.description; - transport.createMetric(this); - } - update(newValue) { - this.value = newValue; - return this.transport.updateMetric(this); - } - } - - class NumberMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.NUMBER); - } - incrementBy(num) { - this.update(this.value + num); - } - increment() { - this.incrementBy(1); - } - decrement() { - this.incrementBy(-1); - } - decrementBy(num) { - this.incrementBy(num * -1); - } - } - - class ObjectMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.OBJECT); - } - update(newValue) { - this.mergeValues(newValue); - return this.transport.updateMetric(this); - } - mergeValues(values) { - return Object.keys(this.value).forEach((k) => { - if (typeof values[k] !== "undefined") { - this.value[k] = values[k]; - } - }); - } - } - - class StringMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.STRING); - } - } - - class TimestampMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.TIMESTAMP); - } - now() { - this.update(new Date()); - } - } - - function system(name, repo, protocol, parent, description) { - if (!repo) { - throw new Error("Repository is required"); - } - if (!protocol) { - throw new Error("Transport is required"); - } - const _transport = protocol; - const _name = name; - const _description = description || ""; - const _repo = repo; - const _parent = parent; - const _path = _buildPath(parent); - let _state = {}; - const id = _arrayToString(_path, "/") + name; - const root = repo.root; - const _subSystems = []; - const _metrics = []; - function subSystem(nameSystem, descriptionSystem) { - if (!nameSystem || nameSystem.length === 0) { - throw new Error("name is required"); - } - const match = _subSystems.filter((s) => s.name === nameSystem); - if (match.length > 0) { - return match[0]; - } - const _system = system(nameSystem, _repo, _transport, me, descriptionSystem); - _subSystems.push(_system); - return _system; - } - function setState(state, stateDescription) { - _state = { state, description: stateDescription }; - _transport.updateSystem(me, _state); - } - function stringMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.STRING, value, (metricDef) => new StringMetric(metricDef, me, _transport, value)); - } - function numberMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.NUMBER, value, (metricDef) => new NumberMetric(metricDef, me, _transport, value)); - } - function objectMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.OBJECT, value, (metricDef) => new ObjectMetric(metricDef, me, _transport, value)); - } - function timestampMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.TIMESTAMP, value, (metricDef) => new TimestampMetric(metricDef, me, _transport, value)); - } - function _getOrCreateMetric(metricObject, expectedType, value, createMetric) { - let metricDef = { name: "" }; - if (typeof metricObject === "string") { - metricDef = { name: metricObject }; - } - else { - metricDef = metricObject; - } - const matching = _metrics.filter((shadowedMetric) => shadowedMetric.name === metricDef.name); - if (matching.length > 0) { - const existing = matching[0]; - if (existing.type !== expectedType) { - throw new Error(`A metric named ${metricDef.name} is already defined with different type.`); - } - if (typeof value !== "undefined") { - existing - .update(value) - .catch(() => { }); - } - return existing; - } - const metric = createMetric(metricDef); - _metrics.push(metric); - return metric; - } - function _buildPath(shadowedSystem) { - if (!shadowedSystem || !shadowedSystem.parent) { - return []; - } - const path = _buildPath(shadowedSystem.parent); - path.push(shadowedSystem.name); - return path; - } - function _arrayToString(path, separator) { - return ((path && path.length > 0) ? path.join(separator) : ""); - } - function getAggregateState() { - const aggState = []; - if (Object.keys(_state).length > 0) { - aggState.push({ - name: _name, - path: _path, - state: _state.state, - description: _state.description, - }); - } - _subSystems.forEach((shadowedSubSystem) => { - const result = shadowedSubSystem.getAggregateState(); - if (result.length > 0) { - aggState.push(...result); - } - }); - return aggState; - } - const me = { - get name() { - return _name; - }, - get description() { - return _description; - }, - get repo() { - return _repo; - }, - get parent() { - return _parent; - }, - path: _path, - id, - root, - get subSystems() { - return _subSystems; - }, - get metrics() { - return _metrics; - }, - subSystem, - getState: () => { - return _state; - }, - setState, - stringMetric, - timestampMetric, - objectMetric, - numberMetric, - getAggregateState, - }; - _transport.createSystem(me); - return me; - } - - class Repository { - root; - constructor(options, protocol) { - protocol.init(this); - this.root = system("", this, protocol); - this.addSystemMetrics(this.root, options.clickStream || options.clickStream === undefined); - } - addSystemMetrics(rootSystem, useClickStream) { - if (typeof navigator !== "undefined") { - rootSystem.stringMetric("UserAgent", navigator.userAgent); - } - if (useClickStream && typeof document !== "undefined") { - const clickStream = rootSystem.subSystem("ClickStream"); - const documentClickHandler = (e) => { - if (!e.target) { - return; - } - const target = e.target; - const className = target ? target.getAttribute("class") ?? "" : ""; - clickStream.objectMetric("LastBrowserEvent", { - type: "click", - timestamp: new Date(), - target: { - className, - id: target.id, - type: "<" + target.tagName.toLowerCase() + ">", - href: target.href || "", - }, - }); - }; - clickStream.objectMetric("Page", { - title: document.title, - page: window.location.href, - }); - if (document.addEventListener) { - document.addEventListener("click", documentClickHandler); - } - else { - document.attachEvent("onclick", documentClickHandler); - } - } - rootSystem.stringMetric("StartTime", (new Date()).toString()); - const urlMetric = rootSystem.stringMetric("StartURL", ""); - const appNameMetric = rootSystem.stringMetric("AppName", ""); - if (typeof window !== "undefined") { - if (typeof window.location !== "undefined") { - const startUrl = window.location.href; - urlMetric.update(startUrl); - } - if (typeof window.glue42gd !== "undefined") { - appNameMetric.update(window.glue42gd.appName); - } - } - } - } - - class NullProtocol { - init(repo) { - } - createSystem(system) { - return Promise.resolve(); - } - updateSystem(metric, state) { - return Promise.resolve(); - } - createMetric(metric) { - return Promise.resolve(); - } - updateMetric(metric) { - return Promise.resolve(); - } - } - - class PerfTracker { - api; - lastCount = 0; - initialPublishTimeout = 10 * 1000; - publishInterval = 60 * 1000; - system; - constructor(api, initialPublishTimeout, publishInterval) { - this.api = api; - this.initialPublishTimeout = initialPublishTimeout ?? this.initialPublishTimeout; - this.publishInterval = publishInterval ?? this.publishInterval; - this.scheduleCollection(); - this.system = this.api.subSystem("performance", "Performance data published by the web application"); - } - scheduleCollection() { - setTimeout(() => { - this.collect(); - setInterval(() => { - this.collect(); - }, this.publishInterval); - }, this.initialPublishTimeout); - } - collect() { - try { - this.collectMemory(); - this.collectEntries(); - } - catch { - } - } - collectMemory() { - const memory = window.performance.memory; - this.system.stringMetric("memory", JSON.stringify({ - totalJSHeapSize: memory.totalJSHeapSize, - usedJSHeapSize: memory.usedJSHeapSize - })); - } - collectEntries() { - const allEntries = window.performance.getEntries(); - if (allEntries.length <= this.lastCount) { - return; - } - this.lastCount = allEntries.length; - const jsonfiedEntries = allEntries.map((i) => i.toJSON()); - this.system.stringMetric("entries", JSON.stringify(jsonfiedEntries)); - } - } - - var metrics = (options) => { - let protocol; - if (!options.connection || typeof options.connection !== "object") { - protocol = new NullProtocol(); - } - else { - protocol = gw3(options.connection, options); - } - const repo = new Repository(options, protocol); - let rootSystem = repo.root; - if (!options.disableAutoAppSystem) { - rootSystem = rootSystem.subSystem("App"); - } - const api = addFAVSupport(rootSystem); - initPerf(api, options.pagePerformanceMetrics); - return api; - }; - function initPerf(api, config) { - if (typeof window === "undefined") { - return; - } - const perfConfig = window?.glue42gd?.metrics?.pagePerformanceMetrics; - if (perfConfig) { - config = perfConfig; - } - if (config?.enabled) { - new PerfTracker(api, config.initialPublishTimeout, config.publishInterval); - } - } - function addFAVSupport(system) { - const reportingSystem = system.subSystem("reporting"); - const def = { - name: "features" - }; - let featureMetric; - const featureMetricFunc = (name, action, payload) => { - if (typeof name === "undefined" || name === "") { - throw new Error("name is mandatory"); - } - else if (typeof action === "undefined" || action === "") { - throw new Error("action is mandatory"); - } - else if (typeof payload === "undefined" || payload === "") { - throw new Error("payload is mandatory"); - } - if (!featureMetric) { - featureMetric = reportingSystem.objectMetric(def, { name, action, payload }); - } - else { - featureMetric.update({ - name, - action, - payload - }); - } - }; - system.featureMetric = featureMetricFunc; - return system; - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackRegistryFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - class InProcTransport { - gw; - registry = CallbackRegistryFactory(); - client; - constructor(settings, logger) { - this.gw = settings.facade; - this.gw.connect((_client, message) => { - this.messageHandler(message); - }).then((client) => { - this.client = client; - }); - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - if (this.client) { - this.client.send(msg); - return Promise.resolve(undefined); - } - else { - return Promise.reject(`not connected`); - } - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "in-memory"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class SharedWorkerTransport { - logger; - worker; - registry = CallbackRegistryFactory(); - constructor(workerFile, logger) { - this.logger = logger; - this.worker = new SharedWorker(workerFile); - this.worker.port.onmessage = (e) => { - this.messageHandler(e.data); - }; - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - this.worker.port.postMessage(msg); - return Promise.resolve(); - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "shared-worker"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class Utils { - static isNode() { - if (typeof Utils._isNode !== "undefined") { - return Utils._isNode; - } - if (typeof window !== "undefined") { - Utils._isNode = false; - return false; - } - try { - Utils._isNode = Object.prototype.toString.call(global.process) === "[object process]"; - } - catch (e) { - Utils._isNode = false; - } - return Utils._isNode; - } - static _isNode; - } - - class PromiseWrapper { - static delay(time) { - return new Promise((resolve) => setTimeout(resolve, time)); - } - resolve; - reject; - promise; - rejected = false; - resolved = false; - get ended() { - return this.rejected || this.resolved; - } - constructor() { - this.promise = new Promise((resolve, reject) => { - this.resolve = (t) => { - this.resolved = true; - resolve(t); - }; - this.reject = (err) => { - this.rejected = true; - reject(err); - }; - }); - } - } - - const timers = {}; - function getAllTimers() { - return timers; - } - function timer (timerName) { - const existing = timers[timerName]; - if (existing) { - return existing; - } - const marks = []; - function now() { - return new Date().getTime(); - } - const startTime = now(); - mark("start", startTime); - let endTime; - let period; - function stop() { - endTime = now(); - mark("end", endTime); - period = endTime - startTime; - return period; - } - function mark(name, time) { - const currentTime = time ?? now(); - let diff = 0; - if (marks.length > 0) { - diff = currentTime - marks[marks.length - 1].time; - } - marks.push({ name, time: currentTime, diff }); - } - const timerObj = { - get startTime() { - return startTime; - }, - get endTime() { - return endTime; - }, - get period() { - return period; - }, - stop, - mark, - marks - }; - timers[timerName] = timerObj; - return timerObj; - } - - const WebSocketConstructor = Utils.isNode() ? null : window.WebSocket; - class WS { - ws; - logger; - settings; - startupTimer = timer("connection"); - _running = true; - _registry = CallbackRegistryFactory(); - wsRequests = []; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - if (!this.settings.ws) { - throw new Error("ws is missing"); - } - } - onMessage(callback) { - return this._registry.add("onMessage", callback); - } - send(msg, options) { - return new Promise((resolve, reject) => { - this.waitForSocketConnection(() => { - try { - this.ws?.send(msg); - resolve(); - } - catch (e) { - reject(e); - } - }, reject); - }); - } - open() { - this.logger.info("opening ws..."); - this._running = true; - return new Promise((resolve, reject) => { - this.waitForSocketConnection(resolve, reject); - }); - } - close() { - this._running = false; - if (this.ws) { - this.ws.close(); - } - return Promise.resolve(); - } - onConnectedChanged(callback) { - return this._registry.add("onConnectedChanged", callback); - } - name() { - return this.settings.ws; - } - reconnect() { - this.ws?.close(); - const pw = new PromiseWrapper(); - this.waitForSocketConnection(() => { - pw.resolve(); - }); - return pw.promise; - } - waitForSocketConnection(callback, failed) { - failed = failed ?? (() => { }); - if (!this._running) { - failed(`wait for socket on ${this.settings.ws} failed - socket closed by user`); - return; - } - if (this.ws?.readyState === 1) { - callback(); - return; - } - this.wsRequests.push({ callback, failed }); - if (this.wsRequests.length > 1) { - return; - } - this.openSocket(); - } - async openSocket(retryInterval, retriesLeft) { - this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${retryInterval}, retriesLeft: ${retriesLeft}...`); - this.startupTimer.mark("opening-socket"); - if (retryInterval === undefined) { - retryInterval = this.settings.reconnectInterval; - } - if (typeof retriesLeft === "undefined") { - retriesLeft = this.settings.reconnectAttempts; - } - if (retriesLeft !== undefined) { - if (retriesLeft === 0) { - this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`); - return; - } - this.logger.debug(`will retry ${retriesLeft} more times (every ${retryInterval} ms)`); - } - try { - await this.initiateSocket(); - this.startupTimer.mark("socket-initiated"); - this.notifyForSocketState(); - } - catch { - setTimeout(() => { - const retries = retriesLeft === undefined ? undefined : retriesLeft - 1; - this.openSocket(retryInterval, retries); - }, retryInterval); - } - } - initiateSocket() { - const pw = new PromiseWrapper(); - this.logger.debug(`initiating ws to ${this.settings.ws}...`); - this.ws = new WebSocketConstructor(this.settings.ws ?? ""); - let wasOpen = false; - this.ws.onerror = (err) => { - let reason; - try { - reason = JSON.stringify(err); - } - catch (error) { - const seen = new WeakSet(); - const replacer = (key, value) => { - if (typeof value === "object" && value !== null) { - if (seen.has(value)) { - return; - } - seen.add(value); - } - if (value instanceof Error) { - return { - message: value.message, - name: value.name, - stack: value.stack - }; - } - return value; - }; - reason = JSON.stringify(err, replacer); - } - this.logger.info(`ws error - reason: ${reason}`); - pw.reject("error"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("error"); - } - this.notifyStatusChanged(false, reason); - }; - this.ws.onclose = (err) => { - this.logger.info(`ws closed - code: ${err?.code} reason: ${err?.reason}`); - pw.reject("closed"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("closed"); - } - this.notifyStatusChanged(false); - }; - this.ws.onopen = () => { - this.startupTimer.mark("ws-opened"); - this.logger.info(`ws opened ${this.settings.identity?.application}`); - pw.resolve(); - wasOpen = true; - this.notifyStatusChanged(true); - }; - this.ws.onmessage = (message) => { - this._registry.execute("onMessage", message.data); - }; - return pw.promise; - } - notifyForSocketState(error) { - this.wsRequests.forEach((wsRequest) => { - if (error) { - if (wsRequest.failed) { - wsRequest.failed(error); - } - } - else { - wsRequest.callback(); - } - }); - this.wsRequests = []; - } - notifyStatusChanged(status, reason) { - this._registry.execute("onConnectedChanged", status, reason); - } - } - - class MessageReplayerImpl { - specs; - specsNames = []; - messages = {}; - isDone; - subs = {}; - subsRefCount = {}; - connection; - constructor(specs) { - this.specs = {}; - for (const spec of specs) { - this.specs[spec.name] = spec; - this.specsNames.push(spec.name); - } - } - init(connection) { - this.connection = connection; - for (const name of this.specsNames) { - for (const type of this.specs[name].types) { - let refCount = this.subsRefCount[type]; - if (!refCount) { - refCount = 0; - } - refCount += 1; - this.subsRefCount[type] = refCount; - if (refCount > 1) { - continue; - } - const sub = connection.on(type, (msg) => this.processMessage(type, msg)); - this.subs[type] = sub; - } - } - } - processMessage(type, msg) { - if (this.isDone || !msg) { - return; - } - for (const name of this.specsNames) { - if (this.specs[name].types.indexOf(type) !== -1) { - const messages = this.messages[name] || []; - this.messages[name] = messages; - messages.push(msg); - } - } - } - drain(name, callback) { - if (callback) { - (this.messages[name] || []).forEach(callback); - } - delete this.messages[name]; - for (const type of this.specs[name].types) { - this.subsRefCount[type] -= 1; - if (this.subsRefCount[type] <= 0) { - this.connection?.off(this.subs[type]); - delete this.subs[type]; - delete this.subsRefCount[type]; - } - } - delete this.specs[name]; - if (!this.specs.length) { - this.isDone = true; - } - } - } - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet[(Math.random() * 64) | 0]; - } - return id - }; - - const PromisePlus = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WebPlatformTransport { - settings; - logger; - identity; - isPreferredActivated; - _connectionProtocolVersion; - _communicationId; - publicWindowId; - selfAssignedWindowId; - iAmConnected = false; - parentReady = false; - rejected = false; - parentPingResolve; - parentPingInterval; - connectionResolve; - extConnectionResolve; - extConnectionReject; - connectionReject; - port; - myClientId; - extContentAvailable = false; - extContentConnecting = false; - extContentConnected = false; - parentWindowId; - parentInExtMode = false; - webNamespace = "g42_core_web"; - parent; - parentType; - parentPingTimeout = 5000; - connectionRequestTimeout = 7000; - defaultTargetString = "*"; - registry = CallbackRegistryFactory(); - messages = { - connectionAccepted: { name: "connectionAccepted", handle: this.handleConnectionAccepted.bind(this) }, - connectionRejected: { name: "connectionRejected", handle: this.handleConnectionRejected.bind(this) }, - connectionRequest: { name: "connectionRequest", handle: this.handleConnectionRequest.bind(this) }, - parentReady: { - name: "parentReady", handle: () => { - } - }, - parentPing: { name: "parentPing", handle: this.handleParentPing.bind(this) }, - platformPing: { name: "platformPing", handle: this.handlePlatformPing.bind(this) }, - platformReady: { name: "platformReady", handle: this.handlePlatformReady.bind(this) }, - clientUnload: { name: "clientUnload", handle: () => { } }, - manualUnload: { name: "manualUnload", handle: this.handleManualUnload.bind(this) }, - extConnectionResponse: { name: "extConnectionResponse", handle: this.handleExtConnectionResponse.bind(this) }, - extSetupRequest: { name: "extSetupRequest", handle: this.handleExtSetupRequest.bind(this) }, - gatewayDisconnect: { name: "gatewayDisconnect", handle: this.handleGatewayDisconnect.bind(this) }, - gatewayInternalConnect: { name: "gatewayInternalConnect", handle: this.handleGatewayInternalConnect.bind(this) } - }; - constructor(settings, logger, identity) { - this.settings = settings; - this.logger = logger; - this.identity = identity; - this.extContentAvailable = !!window.glue42ext; - this.setUpMessageListener(); - this.setUpUnload(); - this.setupPlatformUnloadListener(); - this.parentType = window.name.includes("#wsp") ? "workspace" : undefined; - } - manualSetReadyState() { - this.iAmConnected = true; - this.parentReady = true; - } - get transportWindowId() { - return this.publicWindowId; - } - get communicationId() { - return this._communicationId; - } - async sendObject(msg) { - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: msg }, window.origin); - } - if (!this.port) { - throw new Error("Cannot send message, because the port was not opened yet"); - } - this.port.postMessage(msg); - } - get isObjectBasedTransport() { - return true; - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - send() { - return Promise.reject("not supported"); - } - onConnectedChanged(callback) { - return this.registry.add("onConnectedChanged", callback); - } - async open() { - this.logger.debug("opening a connection to the web platform gateway."); - await this.connect(); - this.notifyStatusChanged(true); - } - close() { - this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId || "unknown"}, client connected: ${this.iAmConnected}`); - const message = { - glue42core: { - type: this.messages.gatewayDisconnect.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.port?.postMessage(message); - this.parentReady = false; - this.notifyStatusChanged(false, "manual reconnection"); - return Promise.resolve(); - } - name() { - return "web-platform"; - } - async reconnect() { - await this.close(); - return Promise.resolve(); - } - initiateInternalConnection() { - return new Promise((resolve, reject) => { - this.logger.debug("opening an internal web platform connection"); - this.port = this.settings.port; - if (this.iAmConnected) { - this.logger.warn("cannot open a new connection, because this client is currently connected"); - return; - } - this.port.onmessage = (event) => { - if (this.iAmConnected && !event.data?.glue42core) { - this.registry.execute("onMessage", event.data); - return; - } - const data = event.data?.glue42core; - if (!data) { - return; - } - if (data.type === this.messages.gatewayInternalConnect.name && data.success) { - this.publicWindowId = this.settings.windowId; - if (this.identity && this.publicWindowId) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.publicWindowId; - } - resolve(); - } - if (data.type === this.messages.gatewayInternalConnect.name && data.error) { - reject(data.error); - } - }; - this.port.postMessage({ - glue42core: { - type: this.messages.gatewayInternalConnect.name - } - }); - }); - } - initiateRemoteConnection(target) { - return PromisePlus((resolve, reject) => { - this.connectionResolve = resolve; - this.connectionReject = reject; - this.myClientId = this.myClientId ?? nanoid(10); - const bridgeInstanceId = this.getMyWindowId() || nanoid(10); - const request = { - glue42core: { - type: this.messages.connectionRequest.name, - clientId: this.myClientId, - clientType: "child", - bridgeInstanceId, - selfAssignedWindowId: this.selfAssignedWindowId - } - }; - this.logger.debug(`sending connection request - clientId: ${this.myClientId}`); - if (this.extContentConnecting) { - request.glue42core.clientType = "child"; - request.glue42core.bridgeInstanceId = this.myClientId; - request.glue42core.parentWindowId = this.parentWindowId; - return window.postMessage(request, window.origin); - } - if (!target) { - throw new Error("Cannot send a connection request, because no glue target was specified!"); - } - target.postMessage(request, this.defaultTargetString); - }, this.connectionRequestTimeout, "The connection to the target glue window timed out"); - } - async isParentCheckSuccess(parentCheck) { - try { - await parentCheck; - return { success: true }; - } - catch (error) { - return { success: false }; - } - } - setUpMessageListener() { - if (this.settings.port) { - this.logger.debug("skipping generic message listener, because this is an internal client"); - return; - } - this.logger.debug("setting up window message listener"); - window.addEventListener("message", (event) => { - const data = event.data?.glue42core; - if (!data || this.rejected) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - if (!this.checkMessageTypeValid(data.type)) { - this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${data.type}`); - return; - } - const messageType = data.type; - this.logger.debug(`received valid glue42core message of type: ${messageType}`); - this.messages[messageType].handle(event); - }); - } - setUpUnload() { - if (this.settings.port) { - this.logger.debug("skipping unload event listener, because this is an internal client"); - return; - } - this.logger.debug("setting up unload event listeners"); - window.addEventListener("beforeunload", () => { - if (this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - window.addEventListener("pagehide", () => { - if (!this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - } - signalClientDisappearing() { - if (this.extContentConnected) { - return; - } - this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.parent?.postMessage(message, this.defaultTargetString); - this.port?.postMessage(message); - } - handlePlatformReady(event) { - this.logger.debug("the web platform gave the ready signal"); - this.parentReady = true; - if (this.parentPingResolve) { - this.parentPingResolve(); - delete this.parentPingResolve; - } - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - this.parent = event.source; - this.parentType = window.name.includes("#wsp") ? "workspace" : "window"; - } - handleConnectionAccepted(event) { - const data = event.data?.glue42core; - if (this.myClientId !== data.clientId) { - return this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${data.clientId}`); - } - return this.handleAcceptanceOfMyRequest(data); - } - handleAcceptanceOfMyRequest(data) { - this.logger.debug("handling a connection accepted signal targeted at me."); - this.isPreferredActivated = data.isPreferredActivated; - if (this.extContentConnecting) { - return this.processExtContentConnection(data); - } - if (!data.port) { - this.logger.error("cannot set up my connection, because I was not provided with a port"); - return; - } - this._connectionProtocolVersion = data.connectionProtocolVersion; - this.publicWindowId = this.getMyWindowId(); - if (this.identity) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.identity.instance ? this.identity.instance : this.publicWindowId || nanoid(10); - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - this._communicationId = data.communicationId; - this.port = data.port; - this.port.onmessage = (e) => this.registry.execute("onMessage", e.data); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - this.logger.error("unable to call the connection resolve, because no connection promise was found"); - } - processExtContentConnection(data) { - this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."); - this.extContentConnecting = false; - this.extContentConnected = true; - this.publicWindowId = this.parentWindowId || this.myClientId; - if (this.extContentConnecting && this.identity) { - this.identity.windowId = this.publicWindowId; - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - window.addEventListener("message", (event) => { - const extData = event.data?.glue42ExtInc; - if (!extData) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - this.registry.execute("onMessage", extData); - }); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - } - handleConnectionRejected(event) { - this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"); - if (!this.connectionReject) { - return; - } - const errorMsg = typeof event.data.glue42core?.error === "string" - ? `Connection was rejected. ${event.data.glue42core?.error}` - : "The platform connection was rejected. Most likely because this window was not created by a glue API call"; - this.connectionReject(errorMsg); - delete this.connectionReject; - } - handleConnectionRequest() { - if (this.extContentConnecting) { - this.logger.debug("This connection request event is targeted at the extension content"); - return; - } - } - handleParentPing(event) { - if (!this.parentReady) { - this.logger.debug("my parent is not ready, I am ignoring the parent ping"); - return; - } - if (!this.iAmConnected) { - this.logger.debug("i am not fully connected yet, I am ignoring the parent ping"); - return; - } - const message = { - glue42core: { - type: this.messages.parentReady.name - } - }; - if (this.extContentConnected) { - message.glue42core.extMode = { windowId: this.myClientId }; - } - const source = event.source; - this.logger.debug("responding to a parent ping with a ready message"); - source.postMessage(message, event.origin); - } - setupPlatformUnloadListener() { - this.logger.debug("setting up platform unload listener"); - this.onMessage((msg) => { - if (msg.type === "platformUnload") { - this.logger.debug("detected a web platform unload"); - this.parentReady = false; - this.notifyStatusChanged(false, "Gateway unloaded"); - } - }); - } - handleManualUnload() { - this.logger.debug("handling manual unload"); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: message }, window.origin); - } - this.port?.postMessage(message); - } - handlePlatformPing() { - return; - } - notifyStatusChanged(status, reason) { - this.logger.debug(`status changed - connected: ${status}, reason: ${reason || "none"}`); - this.iAmConnected = status; - this.registry.execute("onConnectedChanged", status, reason); - } - checkMessageTypeValid(typeToValidate) { - return typeof typeToValidate === "string" && !!this.messages[typeToValidate]; - } - requestConnectionPermissionFromExt() { - return this.waitForContentScript() - .then(() => PromisePlus((resolve, reject) => { - this.extConnectionResolve = resolve; - this.extConnectionReject = reject; - const message = { - glue42core: { - type: "extSetupRequest" - } - }; - this.logger.debug("permission request to the extension content script was sent"); - window.postMessage(message, window.origin); - }, this.parentPingTimeout, "Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")); - } - handleExtConnectionResponse(event) { - const data = event.data?.glue42core; - if (!data.approved) { - return this.extConnectionReject ? this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected") : undefined; - } - if (this.extConnectionResolve) { - this.extConnectionResolve(); - delete this.extConnectionResolve; - } - this.extContentConnecting = true; - this.parentType = "extension"; - this.logger.debug("The extension connection was approved, proceeding."); - } - handleExtSetupRequest() { - return; - } - handleGatewayDisconnect() { - return; - } - handleGatewayInternalConnect() { - return; - } - waitForContentScript() { - const contentReady = !!window.glue42ext?.content; - if (contentReady) { - return Promise.resolve(); - } - return PromisePlus((resolve) => { - window.addEventListener("Glue42EXTReady", () => { - resolve(); - }); - }, this.connectionRequestTimeout, "The content script was available, but was never heard to be ready"); - } - async connect() { - if (this.settings.port) { - await this.initiateInternalConnection(); - this.logger.debug("internal web platform connection completed"); - return; - } - this.logger.debug("opening a client web platform connection"); - await this.findParent(); - await this.initiateRemoteConnection(this.parent); - this.logger.debug("the client is connected"); - } - async findParent() { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const myInsideParents = this.getPossibleParentsInWindow(window); - const myOutsideParents = this.getPossibleParentsOutsideWindow(window.top?.opener, window.top); - const uniqueParents = new Set([...myInsideParents, ...myOutsideParents]); - if (!uniqueParents.size && !this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - if (!uniqueParents.size && this.extContentAvailable) { - await this.requestConnectionPermissionFromExt(); - return; - } - const defaultParentCheck = await this.isParentCheckSuccess(this.confirmParent(Array.from(uniqueParents))); - if (defaultParentCheck.success) { - this.logger.debug("The default parent was found!"); - return; - } - if (!this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - await this.requestConnectionPermissionFromExt(); - } - getPossibleParentsInWindow(currentWindow) { - return (!currentWindow?.parent || currentWindow === currentWindow.parent) ? [] : [currentWindow.parent, ...this.getPossibleParentsInWindow(currentWindow.parent)]; - } - getPossibleParentsOutsideWindow(opener, current) { - return (!opener || !current || opener === current) ? [] : [opener, ...this.getPossibleParentsInWindow(opener), ...this.getPossibleParentsOutsideWindow(opener.opener, opener)]; - } - confirmParent(targets) { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const parentCheck = PromisePlus((resolve) => { - this.parentPingResolve = resolve; - const message = { - glue42core: { - type: this.messages.platformPing.name - } - }; - this.parentPingInterval = setInterval(() => { - targets.forEach((target) => { - target.postMessage(message, this.defaultTargetString); - }); - }, 1000); - }, this.parentPingTimeout, connectionNotPossibleMsg); - parentCheck.catch(() => { - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - }); - return parentCheck; - } - getMyWindowId() { - if (this.parentType === "workspace") { - return window.name.substring(0, window.name.indexOf("#wsp")); - } - if (window !== window.top) { - return; - } - if (window.name?.includes("g42")) { - return window.name; - } - this.selfAssignedWindowId = this.selfAssignedWindowId || `g42-${nanoid(10)}`; - return this.selfAssignedWindowId; - } - } - - const waitForInvocations = (invocations, callback) => { - let left = invocations; - return () => { - left--; - if (left === 0) { - callback(); - } - }; - }; - - class AsyncSequelizer { - minSequenceInterval; - queue = []; - isExecutingQueue = false; - constructor(minSequenceInterval = 0) { - this.minSequenceInterval = minSequenceInterval; - } - enqueue(action) { - return new Promise((resolve, reject) => { - this.queue.push({ action, resolve, reject }); - this.executeQueue(); - }); - } - async executeQueue() { - if (this.isExecutingQueue) { - return; - } - this.isExecutingQueue = true; - while (this.queue.length) { - const operation = this.queue.shift(); - if (!operation) { - this.isExecutingQueue = false; - return; - } - try { - const actionResult = await operation.action(); - operation.resolve(actionResult); - } - catch (error) { - operation.reject(error); - } - await this.intervalBreak(); - } - this.isExecutingQueue = false; - } - intervalBreak() { - return new Promise((res) => setTimeout(res, this.minSequenceInterval)); - } - } - - function domainSession (domain, connection, logger, successMessages, errorMessages) { - if (domain == null) { - domain = "global"; - } - successMessages = successMessages ?? ["success"]; - errorMessages = errorMessages ?? ["error"]; - let isJoined = domain === "global"; - let tryReconnecting = false; - let _latestOptions; - let _connectionOn = false; - const callbacks = CallbackRegistryFactory(); - connection.disconnected(handleConnectionDisconnected); - connection.loggedIn(handleConnectionLoggedIn); - connection.on("success", (msg) => handleSuccessMessage(msg)); - connection.on("error", (msg) => handleErrorMessage(msg)); - connection.on("result", (msg) => handleSuccessMessage(msg)); - if (successMessages) { - successMessages.forEach((sm) => { - connection.on(sm, (msg) => handleSuccessMessage(msg)); - }); - } - if (errorMessages) { - errorMessages.forEach((sm) => { - connection.on(sm, (msg) => handleErrorMessage(msg)); - }); - } - const requestsMap = {}; - function join(options) { - _latestOptions = options; - return new Promise((resolve, reject) => { - if (isJoined) { - resolve({}); - return; - } - let joinPromise; - if (domain === "global") { - joinPromise = _connectionOn ? Promise.resolve({}) : Promise.reject("not connected to gateway"); - } - else { - logger.debug(`joining domain ${domain}`); - const joinMsg = { - type: "join", - destination: domain, - domain: "global", - options, - }; - joinPromise = send(joinMsg); - } - joinPromise - .then(() => { - handleJoined(); - resolve({}); - }) - .catch((err) => { - logger.debug("error joining " + domain + " domain: " + JSON.stringify(err)); - reject(err); - }); - }); - } - function leave() { - if (domain === "global") { - return Promise.resolve(); - } - logger.debug("stopping session " + domain + "..."); - const leaveMsg = { - type: "leave", - destination: domain, - domain: "global", - }; - tryReconnecting = false; - return send(leaveMsg) - .then(() => { - isJoined = false; - callbacks.execute("onLeft"); - }) - .catch(() => { - isJoined = false; - callbacks.execute("onLeft"); - }); - } - function handleJoined() { - logger.debug("did join " + domain); - isJoined = true; - const wasReconnect = tryReconnecting; - tryReconnecting = false; - callbacks.execute("onJoined", wasReconnect); - } - function handleConnectionDisconnected() { - logger.debug("connection is down"); - _connectionOn = false; - isJoined = false; - tryReconnecting = true; - Object.keys(requestsMap).forEach(requestId => { - const request = requestsMap[requestId]; - if (request) { - logger.trace(`failing pending request ${requestId} due to connection lost`); - request.error({ - err: "Connection lost - gateway connection was disconnected" - }); - } - }); - callbacks.execute("onLeft", { disconnected: true }); - } - async function handleConnectionLoggedIn() { - _connectionOn = true; - if (tryReconnecting) { - logger.debug("connection is now up - trying to reconnect..."); - try { - await join(_latestOptions); - } - catch { - logger.trace(`failed to reconnect`); - } - } - } - function onJoined(callback) { - if (isJoined) { - callback(false); - } - return callbacks.add("onJoined", callback); - } - function onLeft(callback) { - if (!isJoined) { - callback(); - } - return callbacks.add("onLeft", callback); - } - function handleErrorMessage(msg) { - if (domain !== msg.domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.error(msg); - } - function handleSuccessMessage(msg) { - if (msg.domain !== domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.success(msg); - } - function getNextRequestId() { - return nanoid(10); - } - let queuedCalls = []; - function send(msg, tag, options) { - const ignore = ["hello", "join"]; - if (msg.type && ignore.indexOf(msg.type) === -1) { - if (!isJoined) { - console.warn(`trying to send a message (${msg.domain} ${msg.type}) but not connected, will queue`); - const pw = new PromiseWrapper(); - queuedCalls.push({ msg, tag, options, pw }); - if (queuedCalls.length === 1) { - const unsubscribe = onJoined(() => { - logger.info(`joined - will now send queued messages (${queuedCalls.length} -> [${queuedCalls.map((m) => m.msg.type)}])`); - queuedCalls.forEach((qm) => { - send(qm.msg, qm.tag, qm.options) - .then((t) => qm.pw.resolve(t)) - .catch((e) => qm.pw.reject(e)); - }); - queuedCalls = []; - unsubscribe(); - }); - } - return pw.promise; - } - } - options = options ?? {}; - msg.request_id = msg.request_id ?? getNextRequestId(); - msg.domain = msg.domain ?? domain; - if (!options.skipPeerId) { - msg.peer_id = connection.peerId; - } - const requestId = msg.request_id; - return new Promise((resolve, reject) => { - requestsMap[requestId] = { - success: (successMsg) => { - delete requestsMap[requestId]; - successMsg._tag = tag; - resolve(successMsg); - }, - error: (errorMsg) => { - console.warn(`Gateway error - ${JSON.stringify(errorMsg)}`); - delete requestsMap[requestId]; - errorMsg._tag = tag; - reject(errorMsg); - }, - }; - connection - .send(msg, options) - .catch((err) => { - requestsMap[requestId]?.error({ err }); - }); - }); - } - function sendFireAndForget(msg) { - msg.request_id = msg.request_id ? msg.request_id : getNextRequestId(); - msg.domain = msg.domain ?? domain; - msg.peer_id = connection.peerId; - return connection.send(msg); - } - return { - join, - leave, - onJoined, - onLeft, - send, - sendFireAndForget, - on: (type, callback) => { - connection.on(type, (msg) => { - if (msg.domain !== domain) { - return; - } - try { - callback(msg); - } - catch (e) { - logger.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(msg)}`, e); - } - }); - }, - loggedIn: (callback) => connection.loggedIn(callback), - connected: (callback) => connection.connected(callback), - disconnected: (callback) => connection.disconnected(callback), - get peerId() { - return connection.peerId; - }, - get domain() { - return domain; - }, - }; - } - - class Connection { - settings; - logger; - protocolVersion = 3; - peerId; - token; - info; - resolvedIdentity; - availableDomains; - gatewayToken; - replayer; - messageHandlers = {}; - ids = 1; - registry = CallbackRegistryFactory(); - _connected = false; - isTrace = false; - transport; - _defaultTransport; - _defaultAuth; - _targetTransport; - _targetAuth; - _swapTransport = false; - _switchInProgress = false; - _transportSubscriptions = []; - datePrefix = "#T42_DATE#"; - datePrefixLen = this.datePrefix.length; - dateMinLen = this.datePrefixLen + 1; - datePrefixFirstChar = this.datePrefix[0]; - _sequelizer = new AsyncSequelizer(); - _isLoggedIn = false; - shouldTryLogin = true; - pingTimer; - sessions = []; - globalDomain; - initialLogin = true; - initialLoginAttempts = 3; - loginConfig; - loginRetryInProgress = false; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - settings = settings || {}; - settings.reconnectAttempts = settings.reconnectAttempts ?? 10; - settings.reconnectInterval = settings.reconnectInterval ?? 1000; - if (settings.inproc) { - this.transport = new InProcTransport(settings.inproc, logger.subLogger("inMemory")); - } - else if (settings.sharedWorker) { - this.transport = new SharedWorkerTransport(settings.sharedWorker, logger.subLogger("shared-worker")); - } - else if (settings.webPlatform) { - this.transport = new WebPlatformTransport(settings.webPlatform, logger.subLogger("web-platform"), settings.identity); - } - else if (settings.ws !== undefined) { - this.transport = new WS(settings, logger.subLogger("ws")); - } - else { - throw new Error("No connection information specified"); - } - this.isTrace = logger.canPublish("trace"); - logger.debug(`starting with ${this.transport.name()} transport`); - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - this._defaultTransport = this.transport; - this.ping(); - } - async switchTransport(settings) { - return this._sequelizer.enqueue(async () => { - if (!settings || typeof settings !== "object") { - throw new Error("Cannot switch transports, because the settings are missing or invalid."); - } - if (typeof settings.type === "undefined") { - throw new Error("Cannot switch the transport, because the type is not defined"); - } - this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(settings)}`); - const switchTargetTransport = settings.type === "secondary" ? this.getNewSecondaryTransport(settings) : this._defaultTransport; - this._targetTransport = switchTargetTransport; - this._targetAuth = settings.type === "secondary" ? this.getNewSecondaryAuth(settings) : this._defaultAuth; - const verifyPromise = this.verifyConnection(); - this._swapTransport = true; - this._switchInProgress = true; - this.logger.trace("The new transport has been set, closing the current transport"); - await this.transport.close(); - try { - await verifyPromise; - const isSwitchSuccess = this.transport === switchTargetTransport; - this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${isSwitchSuccess}`); - this._switchInProgress = false; - return { success: isSwitchSuccess }; - } - catch (error) { - this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."); - this.switchTransport({ type: "default" }); - this._switchInProgress = false; - return { success: false }; - } - }); - } - onLibReAnnounced(callback) { - return this.registry.add("libReAnnounced", callback); - } - setLibReAnnounced(lib) { - this.registry.execute("libReAnnounced", lib); - } - send(message, options) { - if (this.transport.sendObject && - this.transport.isObjectBasedTransport) { - const msg = this.createObjectMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${JSON.stringify(msg)}`); - } - return this.transport.sendObject(msg, options); - } - else { - const strMessage = this.createStringMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${strMessage}`); - } - return this.transport.send(strMessage, options); - } - } - on(type, messageHandler) { - type = type.toLowerCase(); - if (this.messageHandlers[type] === undefined) { - this.messageHandlers[type] = {}; - } - const id = this.ids++; - this.messageHandlers[type][id] = messageHandler; - return { - type, - id, - }; - } - off(info) { - delete this.messageHandlers[info.type.toLowerCase()][info.id]; - } - get isConnected() { - return this._isLoggedIn; - } - connected(callback) { - return this.loggedIn(() => { - const currentServer = this.transport.name(); - callback(currentServer); - }); - } - disconnected(callback) { - return this.registry.add("disconnected", callback); - } - async login(authRequest, reconnect) { - this.logger.debug(`Login initiated - reconnect: ${reconnect}, transport: ${this.transport.name()}`); - if (!this._defaultAuth) { - this._defaultAuth = authRequest; - } - if (this._swapTransport) { - this.logger.trace("Detected a transport swap, swapping transports"); - const newAuth = this.transportSwap(); - authRequest = newAuth ?? authRequest; - } - try { - await this.transport.open(); - this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`); - timer("connection").mark("transport-opened"); - const identity = await this.loginCore(authRequest, reconnect); - this.logger.debug(`Logged in with identity: ${JSON.stringify(identity)}`); - timer("connection").mark("protocol-logged-in"); - return identity; - } - catch (error) { - if (this._switchInProgress) { - this.logger.debug("An error while logging in after a transport swap, preparing a default swap."); - this.prepareDefaultSwap(); - } - throw new Error(error); - } - } - async logout() { - await this.logoutCore(); - await this.transport.close(); - } - loggedIn(callback) { - if (this._isLoggedIn) { - callback(); - } - return this.registry.add("onLoggedIn", callback); - } - domain(domain, successMessages, errorMessages) { - let session = this.sessions.find((s) => s.domain === domain); - if (!session) { - session = domainSession(domain, this, this.logger.subLogger(`domain=${domain}`), successMessages, errorMessages); - this.sessions.push(session); - } - return session; - } - authToken() { - const createTokenReq = { - domain: "global", - type: "create-token" - }; - if (!this.globalDomain) { - return Promise.reject(new Error("no global domain session")); - } - return this.globalDomain.send(createTokenReq) - .then((res) => { - return res.token; - }); - } - reconnect() { - return this.transport.reconnect(); - } - setLoggedIn(value) { - this._isLoggedIn = value; - if (this._isLoggedIn) { - this.initialLogin = false; - this.registry.execute("onLoggedIn"); - } - } - distributeMessage(message, type) { - const handlers = this.messageHandlers[type.toLowerCase()]; - if (handlers !== undefined) { - Object.keys(handlers).forEach((handlerId) => { - const handler = handlers[handlerId]; - if (handler !== undefined) { - try { - handler(message); - } - catch (error) { - try { - this.logger.error(`Message handler failed with ${error.stack}`, error); - } - catch (loggerError) { - console.log("Message handler failed", error); - } - } - } - }); - } - } - handleConnectionChanged(connected) { - if (this._connected === connected) { - this.logger.trace("connection state unchanged, skipping"); - return; - } - this.logger.info(`connection state changed to ${connected ? "connected" : "disconnected"}`); - this._connected = connected; - if (connected) { - if (this.settings?.replaySpecs?.length) { - this.replayer = new MessageReplayerImpl(this.settings.replaySpecs); - this.replayer.init(this); - } - this.registry.execute("connected"); - } - else { - this.setLoggedIn(false); - if (this.shouldTryLogin) { - this.attemptLoginWithRetry(); - } - this.registry.execute("disconnected"); - } - } - async attemptLoginWithRetry() { - if (!this.loginConfig) { - throw new Error("no login info"); - } - if (this.loginRetryInProgress) { - this.logger.debug("login attempt already in progress, ignoring request..."); - return; - } - if (this._isLoggedIn) { - this.logger.debug("already logged in, ignoring request..."); - return; - } - if (this.initialLogin) { - this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`); - if (this.initialLoginAttempts <= 0) { - this.logger.info("maximum initial login attempts reached, will not try to login again"); - return; - } - this.initialLoginAttempts--; - } - try { - this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`); - this.loginRetryInProgress = true; - await this.login(this.loginConfig, true); - } - catch (e) { - this.logger.error(`error trying to login: ${e?.message}`, e); - setTimeout(this.attemptLoginWithRetry.bind(this), this.settings.reconnectInterval ?? 1000); - } - finally { - this.loginRetryInProgress = false; - } - } - handleTransportMessage(msg) { - let msgObj; - if (typeof msg === "string") { - msgObj = this.processStringMessage(msg); - } - else { - msgObj = this.processObjectMessage(msg); - } - if (this.isTrace) { - this.logger.trace(`<< ${JSON.stringify(msgObj)}`); - } - this.distributeMessage(msgObj.msg, msgObj.msgType); - } - verifyConnection() { - return PromisePlus((resolve) => { - let unsub; - const ready = waitForInvocations(2, () => { - if (unsub) { - unsub(); - } - resolve(); - }); - unsub = this.onLibReAnnounced((lib) => { - if (lib.name === "interop") { - return ready(); - } - if (lib.name === "contexts") { - return ready(); - } - }); - }, 10000, "Transport switch timed out waiting for all libraries to be re-announced"); - } - getNewSecondaryTransport(settings) { - if (!settings.transportConfig?.url) { - throw new Error("Missing secondary transport URL."); - } - return new WS(Object.assign({}, this.settings, { ws: settings.transportConfig.url, reconnectAttempts: 1 }), this.logger.subLogger("ws-secondary")); - } - getNewSecondaryAuth(settings) { - if (!settings.transportConfig?.auth) { - throw new Error("Missing secondary transport auth information."); - } - return settings.transportConfig.auth; - } - transportSwap() { - this._swapTransport = false; - if (!this._targetTransport || !this._targetAuth) { - this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`); - return; - } - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport = this._targetTransport; - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - return this._targetAuth; - } - prepareDefaultSwap() { - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport.close().catch((error) => this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(error)}`)); - this._targetTransport = this._defaultTransport; - this._targetAuth = this._defaultAuth; - this._swapTransport = true; - } - processStringMessage(message) { - const msg = JSON.parse(message, (key, value) => { - if (typeof value !== "string") { - return value; - } - if (value.length < this.dateMinLen) { - return value; - } - if (!value.startsWith(this.datePrefixFirstChar)) { - return value; - } - if (value.substring(0, this.datePrefixLen) !== this.datePrefix) { - return value; - } - try { - const milliseconds = parseInt(value.substring(this.datePrefixLen, value.length), 10); - if (isNaN(milliseconds)) { - return value; - } - return new Date(milliseconds); - } - catch (ex) { - return value; - } - }); - return { - msg, - msgType: msg.type, - }; - } - createStringMessage(message) { - const oldToJson = Date.prototype.toJSON; - try { - const datePrefix = this.datePrefix; - Date.prototype.toJSON = function () { - return datePrefix + this.getTime(); - }; - const result = JSON.stringify(message); - return result; - } - finally { - Date.prototype.toJSON = oldToJson; - } - } - processObjectMessage(message) { - if (!message.type) { - throw new Error("Object should have type property"); - } - return { - msg: message, - msgType: message.type, - }; - } - createObjectMessage(message) { - return message; - } - async loginCore(config, reconnect) { - this.loginConfig = config; - if (!this.loginConfig) { - this.loginConfig = { username: "", password: "" }; - } - this.shouldTryLogin = true; - const authentication = await this.setupAuthConfig(config, reconnect); - const helloMsg = { - type: "hello", - identity: this.settings.identity, - authentication - }; - if (config.sessionId) { - helloMsg.request_id = config.sessionId; - } - if (!this.globalDomain) { - this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [ - "welcome", - "token", - "authentication-request" - ]); - } - const sendOptions = { skipPeerId: true }; - if (this.initialLogin) { - sendOptions.retryInterval = this.settings.reconnectInterval; - sendOptions.maxRetries = this.settings.reconnectAttempts; - } - try { - const welcomeMsg = await this.tryAuthenticate(this.globalDomain, helloMsg, sendOptions, config); - this.logger.info("login successful with peerId " + welcomeMsg.peer_id); - this.peerId = welcomeMsg.peer_id; - this.resolvedIdentity = welcomeMsg.resolved_identity; - this.availableDomains = welcomeMsg.available_domains; - if (welcomeMsg.options) { - this.token = welcomeMsg.options.access_token; - this.info = welcomeMsg.options.info; - } - this.setLoggedIn(true); - return welcomeMsg.resolved_identity; - } - catch (err) { - this.logger.error("error sending hello message - " + (err.message || err.msg || err.reason || err), err); - throw err; - } - finally { - if (config?.flowCallback && config.sessionId) { - config.flowCallback(config.sessionId, null); - } - } - } - async tryAuthenticate(globalDomain, helloMsg, sendOptions, config) { - let welcomeMsg; - while (true) { - const msg = await globalDomain.send(helloMsg, undefined, sendOptions); - if (msg.type === "authentication-request") { - const token = Buffer.from(msg.authentication.token, "base64"); - if (config.flowCallback && config.sessionId) { - helloMsg.authentication.token = - (await config.flowCallback(config.sessionId, token)) - .data - .toString("base64"); - } - helloMsg.request_id = config.sessionId; - } - else if (msg.type === "welcome") { - welcomeMsg = msg; - break; - } - else if (msg.type === "error") { - throw new Error("Authentication failed: " + msg.reason); - } - else { - throw new Error("Unexpected message type during authentication: " + msg.type); - } - } - return welcomeMsg; - } - async setupAuthConfig(config, reconnect) { - const authentication = {}; - this.gatewayToken = config.gatewayToken; - if (config.gatewayToken) { - if (reconnect) { - try { - config.gatewayToken = await this.getNewGWToken(); - } - catch (e) { - this.logger.warn(`failed to get GW token when reconnecting ${e?.message || e}`); - } - } - authentication.method = "gateway-token"; - authentication.token = config.gatewayToken; - this.gatewayToken = config.gatewayToken; - } - else if (config.flowName === "sspi") { - authentication.provider = "win"; - authentication.method = "access-token"; - if (config.flowCallback && config.sessionId) { - authentication.token = - (await config.flowCallback(config.sessionId, null)) - .data - .toString("base64"); - } - else { - throw new Error("Invalid SSPI config"); - } - } - else if (config.token) { - authentication.method = "access-token"; - authentication.token = config.token; - } - else if (config.username) { - authentication.method = "secret"; - authentication.login = config.username; - authentication.secret = config.password; - } - else if (config.provider) { - authentication.provider = config.provider; - authentication.providerContext = config.providerContext; - } - else { - throw new Error("invalid auth message" + JSON.stringify(config)); - } - return authentication; - } - async logoutCore() { - this.logger.debug("core logging out..."); - this.shouldTryLogin = false; - if (this.pingTimer) { - clearTimeout(this.pingTimer); - } - const promises = this.sessions.map((session) => { - return session.leave(); - }); - await Promise.all(promises); - } - getNewGWToken() { - if (typeof window !== "undefined") { - const glue42gd = window.glue42gd; - if (glue42gd) { - return glue42gd.getGWToken(); - } - } - return Promise.reject(new Error("not running in GD")); - } - ping() { - if (!this.shouldTryLogin) { - return; - } - if (this._isLoggedIn) { - this.send({ type: "ping" }); - } - this.pingTimer = setTimeout(() => { - this.ping(); - }, 30 * 1000); - } - } - - const order = ["trace", "debug", "info", "warn", "error", "off"]; - class Logger { - name; - parent; - static Interop; - static InteropMethodName = "T42.AppLogger.Log"; - static Instance; - path; - subLoggers = []; - _consoleLevel; - _publishLevel; - loggerFullName; - includeTimeAndLevel; - logFn = console; - customLogFn = false; - constructor(name, parent, logFn) { - this.name = name; - this.parent = parent; - this.name = name; - if (parent) { - this.path = `${parent.path}.${name}`; - } - else { - this.path = name; - } - this.loggerFullName = `[${this.path}]`; - this.includeTimeAndLevel = !logFn; - if (logFn) { - this.logFn = logFn; - this.customLogFn = true; - } - } - subLogger(name) { - const existingSub = this.subLoggers.filter((subLogger) => { - return subLogger.name === name; - })[0]; - if (existingSub !== undefined) { - return existingSub; - } - Object.keys(this).forEach((key) => { - if (key === name) { - throw new Error("This sub logger name is not allowed."); - } - }); - const sub = new Logger(name, this, this.customLogFn ? this.logFn : undefined); - this.subLoggers.push(sub); - return sub; - } - publishLevel(level) { - if (level) { - this._publishLevel = level; - } - return this._publishLevel || this.parent?.publishLevel(); - } - consoleLevel(level) { - if (level) { - this._consoleLevel = level; - } - return this._consoleLevel || this.parent?.consoleLevel(); - } - log(message, level, error) { - this.publishMessage(level || "info", message, error); - } - trace(message) { - this.log(message, "trace"); - } - debug(message) { - this.log(message, "debug"); - } - info(message) { - this.log(message, "info"); - } - warn(message) { - this.log(message, "warn"); - } - error(message, err) { - this.log(message, "error", err); - } - canPublish(level, compareWith) { - const levelIdx = order.indexOf(level); - const restrictionIdx = order.indexOf(compareWith || this.consoleLevel() || "trace"); - return levelIdx >= restrictionIdx; - } - publishMessage(level, message, error) { - const loggerName = this.loggerFullName; - if (level === "error" && !error) { - const e = new Error(); - if (e.stack) { - message = - message + - "\n" + - e.stack - .split("\n") - .slice(4) - .join("\n"); - } - } - if (this.canPublish(level, this.publishLevel())) { - const interop = Logger.Interop; - if (interop) { - try { - if (interop.methods({ name: Logger.InteropMethodName }).length > 0) { - const args = { - msg: message, - logger: loggerName, - level - }; - if (error && error instanceof Error) { - args.error = { - message: error.message, - stack: error.stack ?? "" - }; - } - interop.invoke(Logger.InteropMethodName, args) - .catch((e) => { - this.logFn.error(`Unable to send log message to the platform: ${e.message}`, e); - }); - } - } - catch { - } - } - } - if (this.canPublish(level)) { - let prefix = ""; - if (this.includeTimeAndLevel) { - const date = new Date(); - const time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`; - prefix = `[${time}] [${level}] `; - } - const toPrint = `${prefix}${loggerName}: ${message}`; - switch (level) { - case "trace": - this.logFn.debug(toPrint); - break; - case "debug": - if (this.logFn.debug) { - this.logFn.debug(toPrint); - } - else { - this.logFn.log(toPrint); - } - break; - case "info": - this.logFn.info(toPrint); - break; - case "warn": - this.logFn.warn(toPrint); - break; - case "error": - if (error) { - this.logFn.error(toPrint, error); - } - else { - this.logFn.error(toPrint); - } - break; - } - } - } - } - - const GW_MESSAGE_CREATE_CONTEXT = "create-context"; - const GW_MESSAGE_ACTIVITY_CREATED = "created"; - const GW_MESSAGE_ACTIVITY_DESTROYED = "destroyed"; - const GW_MESSAGE_CONTEXT_CREATED = "context-created"; - const GW_MESSAGE_CONTEXT_ADDED = "context-added"; - const GW_MESSAGE_SUBSCRIBE_CONTEXT = "subscribe-context"; - const GW_MESSAGE_SUBSCRIBED_CONTEXT = "subscribed-context"; - const GW_MESSAGE_UNSUBSCRIBE_CONTEXT = "unsubscribe-context"; - const GW_MESSAGE_DESTROY_CONTEXT = "destroy-context"; - const GW_MESSAGE_CONTEXT_DESTROYED = "context-destroyed"; - const GW_MESSAGE_UPDATE_CONTEXT = "update-context"; - const GW_MESSAGE_CONTEXT_UPDATED = "context-updated"; - const GW_MESSAGE_JOINED_ACTIVITY = "joined"; - - const ContextMessageReplaySpec = { - get name() { - return "context"; - }, - get types() { - return [ - GW_MESSAGE_CREATE_CONTEXT, - GW_MESSAGE_ACTIVITY_CREATED, - GW_MESSAGE_ACTIVITY_DESTROYED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_SUBSCRIBE_CONTEXT, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - GW_MESSAGE_DESTROY_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_UPDATE_CONTEXT, - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_JOINED_ACTIVITY - ]; - } - }; - - var version = "6.8.1"; - - function prepareConfig (configuration, ext, glue42gd) { - let nodeStartingContext; - if (Utils.isNode()) { - const startingContextString = process.env._GD_STARTING_CONTEXT_; - if (startingContextString) { - try { - nodeStartingContext = JSON.parse(startingContextString); - } - catch { - } - } - } - function getConnection() { - const gwConfig = configuration.gateway; - const protocolVersion = gwConfig?.protocolVersion ?? 3; - const reconnectInterval = gwConfig?.reconnectInterval; - const reconnectAttempts = gwConfig?.reconnectAttempts; - const defaultWs = "ws://localhost:8385"; - let ws = gwConfig?.ws; - const sharedWorker = gwConfig?.sharedWorker; - const inproc = gwConfig?.inproc; - const webPlatform = gwConfig?.webPlatform ?? undefined; - if (glue42gd) { - ws = glue42gd.gwURL; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) { - ws = nodeStartingContext.gwURL; - } - if (!ws && !sharedWorker && !inproc) { - ws = defaultWs; - } - let instanceId; - let windowId; - let pid; - let environment; - let region; - const appName = getApplication(); - let uniqueAppName = appName; - if (typeof glue42gd !== "undefined") { - windowId = glue42gd.windowId; - pid = glue42gd.pid; - if (glue42gd.env) { - environment = glue42gd.env.env; - region = glue42gd.env.region; - } - uniqueAppName = glue42gd.application ?? "glue-app"; - instanceId = glue42gd.appInstanceId; - } - else if (Utils.isNode()) { - pid = process.pid; - if (nodeStartingContext) { - environment = nodeStartingContext.env; - region = nodeStartingContext.region; - instanceId = nodeStartingContext.instanceId; - } - } - else if (typeof window?.glue42electron !== "undefined") { - windowId = window?.glue42electron.instanceId; - pid = window?.glue42electron.pid; - environment = window?.glue42electron.env; - region = window?.glue42electron.region; - uniqueAppName = window?.glue42electron.application ?? "glue-app"; - instanceId = window?.glue42electron.instanceId; - } - else ; - const replaySpecs = configuration.gateway?.replaySpecs ?? []; - replaySpecs.push(ContextMessageReplaySpec); - let identity = { - application: uniqueAppName, - applicationName: appName, - windowId, - instance: instanceId, - process: pid, - region, - environment, - api: ext.version || version - }; - if (configuration.identity) { - identity = Object.assign(identity, configuration.identity); - } - return { - identity, - reconnectInterval, - ws, - sharedWorker, - webPlatform, - inproc, - protocolVersion, - reconnectAttempts, - replaySpecs, - }; - } - function getContexts() { - const defaultConfig = { - reAnnounceKnownContexts: true, - subscribeOnUpdate: true, - subscribeOnGet: true, - onlyReAnnounceSubscribedContexts: true - }; - if (typeof configuration.contexts === "undefined") { - return defaultConfig; - } - if (typeof configuration.contexts === "boolean" && configuration.contexts) { - return defaultConfig; - } - if (typeof configuration.contexts === "object") { - return { ...defaultConfig, ...configuration.contexts }; - } - return false; - } - function getApplication() { - if (configuration.application) { - return configuration.application; - } - if (glue42gd) { - return glue42gd.applicationName; - } - if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") { - return window.glue42electron.application; - } - const uid = nanoid(10); - if (Utils.isNode()) { - if (nodeStartingContext) { - return nodeStartingContext.applicationConfig.name; - } - return "NodeJS" + uid; - } - if (typeof window !== "undefined" && typeof document !== "undefined") { - return document.title + ` (${uid})`; - } - return uid; - } - function getAuth() { - if (typeof configuration.auth === "string") { - return { - token: configuration.auth - }; - } - if (configuration.auth) { - return configuration.auth; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) { - return { - gatewayToken: nodeStartingContext.gwToken - }; - } - if (configuration.gateway?.webPlatform) { - return { - username: "glue42", - password: "" - }; - } - } - function getLogger() { - let config = configuration.logger; - const defaultLevel = "warn"; - if (!config) { - config = defaultLevel; - } - let gdConsoleLevel; - if (glue42gd) { - gdConsoleLevel = glue42gd.consoleLogLevel; - } - if (typeof config === "string") { - return { console: gdConsoleLevel ?? config, publish: defaultLevel }; - } - return { - console: gdConsoleLevel ?? config.console ?? defaultLevel, - publish: config.publish ?? defaultLevel - }; - } - const connection = getConnection(); - let application = getApplication(); - if (typeof window !== "undefined") { - const windowAsAny = window; - const containerApplication = windowAsAny.htmlContainer ? - `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` : - windowAsAny?.glue42gd?.application; - if (containerApplication) { - application = containerApplication; - } - } - return { - bus: configuration.bus ?? false, - application, - auth: getAuth(), - logger: getLogger(), - connection, - metrics: configuration.metrics ?? true, - contexts: getContexts(), - version: ext.version || version, - libs: ext.libs ?? [], - customLogger: configuration.customLogger - }; - } - - class GW3ContextData { - name; - contextId; - context; - isAnnounced; - createdByUs; - joinedActivity; - updateCallbacks = {}; - activityId; - sentExplicitSubscription; - get hasReceivedSnapshot() { - return this.snapshotPromiseWrapper.resolved; - } - set hasReceivedSnapshot(has) { - if (has) { - this.snapshotPromiseWrapper.resolve(); - } - else { - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - } - get snapshotPromise() { - return this.snapshotPromiseWrapper.promise; - } - snapshotPromiseWrapper; - constructor(contextId, name, isAnnounced, activityId) { - this.contextId = contextId; - this.name = name; - this.isAnnounced = isAnnounced; - this.activityId = activityId; - this.context = {}; - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - hasCallbacks() { - return Object.keys(this.updateCallbacks).length > 0; - } - getState() { - if (this.isAnnounced && this.hasCallbacks()) { - return 3; - } - if (this.isAnnounced) { - return 2; - } - if (this.hasCallbacks()) { - return 1; - } - return 0; - } - } - - var lodash_clonedeep = {exports: {}}; - - /** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - lodash_clonedeep.exports; - - (function (module, exports) { - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** - * Adds the key-value `pair` to `map`. - * - * @private - * @param {Object} map The map to modify. - * @param {Array} pair The key-value pair to add. - * @returns {Object} Returns `map`. - */ - function addMapEntry(map, pair) { - // Don't return `map.set` because it's not chainable in IE 11. - map.set(pair[0], pair[1]); - return map; - } - - /** - * Adds `value` to `set`. - * - * @private - * @param {Object} set The set to modify. - * @param {*} value The value to add. - * @returns {Object} Returns `set`. - */ - function addSetEntry(set, value) { - // Don't return `set.add` because it's not chainable in IE 11. - set.add(value); - return set; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array ? array.length : 0; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array ? array.length : 0; - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ - function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var objectToString = objectProto.toString; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined, - Symbol = root.Symbol, - Uint8Array = root.Uint8Array, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeKeys = overArg(Object.keys, Object); - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'), - Map = getNative(root, 'Map'), - Promise = getNative(root, 'Promise'), - Set = getNative(root, 'Set'), - WeakMap = getNative(root, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - this.__data__ = new ListCache(entries); - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - return this.__data__['delete'](key); - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var cache = this.__data__; - if (cache instanceof ListCache) { - var pairs = cache.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - return this; - } - cache = this.__data__ = new MapCache(pairs); - } - cache.set(key, value); - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - - var length = result.length, - skipIndexes = !!length; - - for (var key in value) { - if ((hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {boolean} [isFull] Specify a clone including symbols. - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, isFull, customizer, key, object, stack) { - var result; - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - if (isHostObject(value)) { - return object ? value : {}; - } - result = initCloneObject(isFunc ? {} : value); - if (!isDeep) { - return copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, baseClone, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (!isArr) { - var props = isFull ? getAllKeys(value) : keys(value); - } - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(proto) { - return isObject(proto) ? objectCreate(proto) : {}; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - return objectToString.call(value); - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var result = new buffer.constructor(buffer.length); - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `map`. - * - * @private - * @param {Object} map The map to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned map. - */ - function cloneMap(map, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); - return arrayReduce(array, addMapEntry, new map.constructor); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of `set`. - * - * @private - * @param {Object} set The set to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned set. - */ - function cloneSet(set, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); - return arrayReduce(array, addSetEntry, new set.constructor); - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = undefined; - - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; - } - - /** - * Copies own symbol properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * Creates an array of the own enumerable symbol properties of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11, - // for data views in Edge < 14, and promises in Node.js. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = objectToString.call(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : undefined; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, cloneFunc, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return cloneMap(object, isDeep, cloneFunc); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return cloneSet(object, isDeep, cloneFunc); - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, true, true); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return !!value && typeof value == 'object'; - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - module.exports = cloneDeep; - } (lodash_clonedeep, lodash_clonedeep.exports)); - - var lodash_clonedeepExports = lodash_clonedeep.exports; - var cloneDeep = /*@__PURE__*/getDefaultExportFromCjs(lodash_clonedeepExports); - - function applyContextDelta(context, delta, logger) { - try { - if (logger?.canPublish("trace")) { - logger?.trace(`applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`); - } - if (!delta) { - return context; - } - if (delta.reset) { - context = { ...delta.reset }; - return context; - } - context = deepClone(context, undefined); - if (delta.commands) { - for (const command of delta.commands) { - if (command.type === "remove") { - deletePath(context, command.path); - } - else if (command.type === "set") { - setValueToPath(context, command.value, command.path); - } - } - return context; - } - const added = delta.added; - const updated = delta.updated; - const removed = delta.removed; - if (added) { - Object.keys(added).forEach((key) => { - context[key] = added[key]; - }); - } - if (updated) { - Object.keys(updated).forEach((key) => { - mergeObjectsProperties(key, context, updated); - }); - } - if (removed) { - removed.forEach((key) => { - delete context[key]; - }); - } - return context; - } - catch (e) { - logger?.error(`error applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`, e); - return context; - } - } - function deepClone(obj, hash) { - return cloneDeep(obj); - } - const mergeObjectsProperties = (key, what, withWhat) => { - const right = withWhat[key]; - if (right === undefined) { - return what; - } - const left = what[key]; - if (!left || !right) { - what[key] = right; - return what; - } - if (typeof left === "string" || - typeof left === "number" || - typeof left === "boolean" || - typeof right === "string" || - typeof right === "number" || - typeof right === "boolean" || - Array.isArray(left) || - Array.isArray(right)) { - what[key] = right; - return what; - } - what[key] = Object.assign({}, left, right); - return what; - }; - function deepEqual(x, y) { - if (x === y) { - return true; - } - if (!(x instanceof Object) || !(y instanceof Object)) { - return false; - } - if (x.constructor !== y.constructor) { - return false; - } - for (const p in x) { - if (!x.hasOwnProperty(p)) { - continue; - } - if (!y.hasOwnProperty(p)) { - return false; - } - if (x[p] === y[p]) { - continue; - } - if (typeof (x[p]) !== "object") { - return false; - } - if (!deepEqual(x[p], y[p])) { - return false; - } - } - for (const p in y) { - if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) { - return false; - } - } - return true; - } - function setValueToPath(obj, value, path) { - const pathArr = path.split("."); - const forbiddenKeys = ["__proto__", "constructor", "prototype"]; - let i; - for (i = 0; i < pathArr.length - 1; i++) { - const key = pathArr[i]; - if (forbiddenKeys.includes(key)) { - throw new Error(`The provided path ${path} is invalid. It cannot contain segment/key that is equal to one of the following values: ${forbiddenKeys}.`); - } - if (!obj[key]) { - obj[key] = {}; - } - if (typeof obj[key] !== "object") { - obj[key] = {}; - } - obj = obj[key]; - } - obj[pathArr[i]] = value; - } - function isSubset(superObj, subObj) { - return Object.keys(subObj).every((ele) => { - if (typeof subObj[ele] === "object") { - return isSubset(superObj?.[ele] || {}, subObj[ele] || {}); - } - return subObj[ele] === superObj?.[ele]; - }); - } - function deletePath(obj, path) { - const pathArr = path.split("."); - let i; - for (i = 0; i < pathArr.length - 1; i++) { - if (!obj[pathArr[i]]) { - return; - } - obj = obj[pathArr[i]]; - } - delete obj[pathArr[i]]; - } - - class GW3Bridge { - ERROR_URI_FAILURE = "global.errors.failure"; - ERROR_URI_INVALID_CONTEXT = "global.errors.invalid_context"; - _logger; - _connection; - _trackAllContexts; - _reAnnounceKnownContexts; - _subscribeOnUpdate; - _subscribeOnGet; - _onlyReAnnounceSubscribedContexts; - _gw3Session; - _contextNameToData = {}; - _gw3Subscriptions = []; - _nextCallbackSubscriptionNumber = 0; - _creationPromises = {}; - _contextNameToId = {}; - _contextIdToName = {}; - _protocolVersion = undefined; - _contextsTempCache = {}; - _contextsSubscriptionsCache = []; - _systemContextsSubKey; - get protocolVersion() { - if (!this._protocolVersion) { - const contextsDomainInfo = this._connection.availableDomains.find((d) => d.uri === "context"); - this._protocolVersion = contextsDomainInfo?.version ?? 1; - } - return this._protocolVersion; - } - get setPathSupported() { - return this.protocolVersion >= 2; - } - constructor(config) { - this._connection = config.connection; - this._logger = config.logger; - this._trackAllContexts = config.trackAllContexts; - this._reAnnounceKnownContexts = config.reAnnounceKnownContexts; - this._subscribeOnUpdate = config.subscribeOnUpdate ?? true; - this._subscribeOnGet = config.subscribeOnGet ?? true; - this._onlyReAnnounceSubscribedContexts = config.onlyReAnnounceSubscribedContexts ?? true; - this._gw3Session = this._connection.domain("global", [ - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_CONTEXT_UPDATED, - ]); - this._gw3Session.disconnected(this.resetState.bind(this)); - this._gw3Session.onJoined((wasReconnect) => { - if (!wasReconnect) { - return; - } - if (!this._reAnnounceKnownContexts) { - this._contextsTempCache = {}; - return this._connection.setLibReAnnounced({ name: "contexts" }); - } - this.reInitiateState() - .then(() => this._connection.setLibReAnnounced({ name: "contexts" })) - .catch((err) => { - this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(err)}`); - }); - }); - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - } - dispose() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - this._gw3Subscriptions.length = 0; - for (const contextName in this._contextNameToData) { - if (this._contextNameToId.hasOwnProperty(contextName)) { - delete this._contextNameToData[contextName]; - } - } - } - createContext(name, data) { - if (name in this._creationPromises) { - return this._creationPromises[name]; - } - this._creationPromises[name] = - this._gw3Session - .send({ - type: GW_MESSAGE_CREATE_CONTEXT, - domain: "global", - name, - data, - lifetime: "retained", - }) - .then((createContextMsg) => { - this._contextNameToId[name] = createContextMsg.context_id; - this._contextIdToName[createContextMsg.context_id] = name; - const contextData = this._contextNameToData[name] || new GW3ContextData(createContextMsg.context_id, name, true, undefined); - contextData.isAnnounced = true; - contextData.name = name; - contextData.contextId = createContextMsg.context_id; - contextData.context = createContextMsg.data || deepClone(data); - contextData.hasReceivedSnapshot = true; - this._contextNameToData[name] = contextData; - delete this._creationPromises[name]; - contextData.sentExplicitSubscription = true; - contextData.createdByUs = true; - this.subscribe(name, () => { }); - return createContextMsg.context_id; - }); - return this._creationPromises[name]; - } - all() { - return Object.keys(this._contextNameToData) - .filter((name) => this._contextNameToData[name].isAnnounced); - } - async update(name, delta) { - if (delta) { - delta = deepClone(delta); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - await this.createContext(name, delta); - return; - } - const currentContext = await this.get(contextData.name); - const calculatedDelta = this.setPathSupported ? - this.calculateContextDeltaV2(currentContext, delta) : - this.calculateContextDeltaV1(currentContext, delta); - if (!Object.keys(calculatedDelta.added).length - && !Object.keys(calculatedDelta.updated).length - && !calculatedDelta.removed.length - && !calculatedDelta.commands?.length) { - return Promise.resolve(); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: calculatedDelta, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, calculatedDelta, { - updaterId: gwResponse.peer_id - }); - } - } - async set(name, data) { - if (data) { - data = deepClone(data); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - return this.createContext(name, data); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { reset: data }, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - this.handleUpdated(contextData, { - reset: data, - added: {}, - removed: [], - updated: {} - }, { - updaterId: gwResponse.peer_id - }); - } - } - setPath(name, path, value) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later"); - } - return this.setPaths(name, [{ path, value }]); - } - async setPaths(name, pathValues) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later"); - } - if (pathValues) { - pathValues = deepClone(pathValues); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - const obj = {}; - for (const pathValue of pathValues) { - setValueToPath(obj, pathValue.value, pathValue.path); - } - return this.createContext(name, obj); - } - const commands = []; - for (const pathValue of pathValues) { - if (pathValue.value === null) { - commands.push({ type: "remove", path: pathValue.path }); - } - else { - commands.push({ type: "set", path: pathValue.path, value: pathValue.value }); - } - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { commands } - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, { - added: {}, - removed: [], - updated: {}, - commands - }, { - updaterId: gwResponse.peer_id - }); - } - } - async get(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - if (!contextData && this._subscribeOnGet) { - this.subscribe(name, () => { }); - } - return Promise.resolve({}); - } - if (contextData && !contextData.sentExplicitSubscription) { - return new Promise((resolve, reject) => { - this.subscribe(name, (data, _d, _r, un) => { - if (!this._subscribeOnGet) { - this.unsubscribe(un); - } - resolve(data); - }).catch((e) => { - if (this.isInvalidContextError(e)) { - resolve({}); - return; - } - reject(e); - }); - }); - } - await contextData.snapshotPromise; - const context = contextData?.context ?? {}; - return Promise.resolve(deepClone(context)); - } - isInvalidContextError(e) { - return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT - || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id")); - } - async subscribe(name, callback, subscriptionKey) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const thisCallbackSubscriptionNumber = typeof subscriptionKey === "undefined" ? this._nextCallbackSubscriptionNumber : subscriptionKey; - if (typeof subscriptionKey === "undefined") { - this._nextCallbackSubscriptionNumber += 1; - this._contextsSubscriptionsCache.push({ contextName: name, subKey: thisCallbackSubscriptionNumber, callback }); - } - let contextData = this._contextNameToData[name]; - if (!contextData || - !contextData.isAnnounced) { - contextData = contextData || new GW3ContextData(undefined, name, false, undefined); - this._contextNameToData[name] = contextData; - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - return Promise.resolve(thisCallbackSubscriptionNumber); - } - const hadCallbacks = contextData.hasCallbacks(); - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - if (!hadCallbacks) { - if (!contextData.joinedActivity && !contextData.createdByUs) { - if (contextData.context && contextData.sentExplicitSubscription) { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - return this.sendSubscribe(contextData) - .then(() => thisCallbackSubscriptionNumber, () => { - this.unsubscribe(thisCallbackSubscriptionNumber, true); - return thisCallbackSubscriptionNumber; - }); - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - unsubscribe(subscriptionKey, keepInSubscriptionsCache) { - if (!keepInSubscriptionsCache) { - this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter(x => x.subKey !== subscriptionKey); - } - for (const name of Object.keys(this._contextNameToData)) { - const contextData = this._contextNameToData[name]; - if (!contextData) { - continue; - } - const hadCallbacks = contextData.hasCallbacks(); - delete contextData.updateCallbacks[subscriptionKey]; - if (contextData.isAnnounced && - hadCallbacks && - !contextData.hasCallbacks() && - contextData.sentExplicitSubscription) { - contextData.hasReceivedSnapshot = false; - contextData.context = {}; - this.sendUnsubscribe(contextData).catch(() => { }); - } - if (!contextData.isAnnounced && - !contextData.hasCallbacks()) { - delete this._contextNameToData[name]; - delete this._contextNameToId[name]; - if (contextData.contextId) { - delete this._contextIdToName[contextData.contextId]; - } - } - } - } - async destroy(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - const contextId = contextData?.contextId; - if (!contextData || !contextId) { - return Promise.reject(`context with ${name} does not exist`); - } - return this._gw3Session - .send({ - type: GW_MESSAGE_DESTROY_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }).then(() => undefined); - } - handleUpdated(contextData, delta, extraData) { - const oldContext = contextData.context; - contextData.context = applyContextDelta(contextData.context, delta, this._logger); - if (this._contextNameToData[contextData.name] === contextData && - !deepEqual(oldContext, contextData.context)) { - this.invokeUpdateCallbacks(contextData, delta, extraData); - } - } - subscribeToContextCreatedMessages() { - const createdMessageTypes = [ - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_ACTIVITY_CREATED, - ]; - for (const createdMessageType of createdMessageTypes) { - const sub = this._connection.on(createdMessageType, this.handleContextCreatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextCreatedMessage(contextCreatedMsg) { - const createdMessageType = contextCreatedMsg.type; - if (createdMessageType === GW_MESSAGE_ACTIVITY_CREATED) { - this._contextNameToId[contextCreatedMsg.activity_id] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.activity_id; - } - else if (createdMessageType === GW_MESSAGE_CONTEXT_ADDED) { - this._contextNameToId[contextCreatedMsg.name] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.name; - } - else ; - const name = this._contextIdToName[contextCreatedMsg.context_id]; - if (!name) { - throw new Error("Received created event for context with unknown name: " + contextCreatedMsg.context_id); - } - if (!this._contextNameToId[name]) { - throw new Error("Received created event for context with unknown id: " + contextCreatedMsg.context_id); - } - let contextData = this._contextNameToData[name]; - if (contextData) { - if (contextData.isAnnounced) { - return; - } - else { - if (!contextData.hasCallbacks()) { - throw new Error("Assertion failure: contextData.hasCallbacks()"); - } - contextData.isAnnounced = true; - contextData.contextId = contextCreatedMsg.context_id; - contextData.activityId = contextCreatedMsg.activity_id; - if (!contextData.sentExplicitSubscription) { - this.sendSubscribe(contextData).catch(() => { }); - } - } - } - else { - this._contextNameToData[name] = contextData = - new GW3ContextData(contextCreatedMsg.context_id, name, true, contextCreatedMsg.activity_id); - if (this._trackAllContexts) { - this.subscribe(name, () => { }).then((subKey) => this._systemContextsSubKey = subKey); - } - } - } - subscribeToContextUpdatedMessages() { - const updatedMessageTypes = [ - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_JOINED_ACTIVITY, - ]; - for (const updatedMessageType of updatedMessageTypes) { - const sub = this._connection.on(updatedMessageType, this.handleContextUpdatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextUpdatedMessage(contextUpdatedMsg) { - const updatedMessageType = contextUpdatedMsg.type; - const contextId = contextUpdatedMsg.context_id; - let contextData = this._contextNameToData[this._contextIdToName[contextId]]; - const justSeen = !contextData || !contextData.isAnnounced; - if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - if (!contextData) { - contextData = - this._contextNameToData[contextUpdatedMsg.activity_id] || - new GW3ContextData(contextId, contextUpdatedMsg.activity_id, true, contextUpdatedMsg.activity_id); - } - this._contextNameToData[contextUpdatedMsg.activity_id] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.activity_id; - this._contextNameToId[contextUpdatedMsg.activity_id] = contextId; - contextData.contextId = contextId; - contextData.isAnnounced = true; - contextData.activityId = contextUpdatedMsg.activity_id; - contextData.joinedActivity = true; - } - else { - if (!contextData || !contextData.isAnnounced) { - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData = contextData || new GW3ContextData(contextId, contextUpdatedMsg.name, true, undefined); - contextData.sentExplicitSubscription = true; - this._contextNameToData[contextUpdatedMsg.name] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.name; - this._contextNameToId[contextUpdatedMsg.name] = contextId; - } - else { - this._logger.error(`Received 'update' for unknown context: ${contextId}`); - } - return; - } - } - const oldContext = contextData.context; - contextData.hasReceivedSnapshot = true; - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData.context = contextUpdatedMsg.data ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - contextData.context = contextUpdatedMsg.context_snapshot ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_CONTEXT_UPDATED) { - contextData.context = applyContextDelta(contextData.context, contextUpdatedMsg.delta, this._logger); - } - else { - throw new Error("Unrecognized context update message " + updatedMessageType); - } - if (justSeen || - !deepEqual(contextData.context, oldContext) || - updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta, { updaterId: contextUpdatedMsg.updater_id }); - } - } - invokeUpdateCallbacks(contextData, delta, extraData) { - delta = delta || { added: {}, updated: {}, reset: {}, removed: [] }; - if (delta.commands) { - delta.added = delta.updated = delta.reset = {}; - delta.removed = []; - for (const command of delta.commands) { - if (command.type === "remove") { - if (command.path.indexOf(".") === -1) { - delta.removed.push(command.path); - } - setValueToPath(delta.updated, null, command.path); - } - else if (command.type === "set") { - setValueToPath(delta.updated, command.value, command.path); - } - } - } - for (const updateCallbackIndex in contextData.updateCallbacks) { - if (contextData.updateCallbacks.hasOwnProperty(updateCallbackIndex)) { - try { - const updateCallback = contextData.updateCallbacks[updateCallbackIndex]; - updateCallback(deepClone(contextData.context), deepClone(Object.assign({}, delta.added || {}, delta.updated || {}, delta.reset || {})), delta.removed, parseInt(updateCallbackIndex, 10), extraData); - } - catch (err) { - this._logger.debug("callback error: " + JSON.stringify(err)); - } - } - } - } - subscribeToContextDestroyedMessages() { - const destroyedMessageTypes = [ - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_ACTIVITY_DESTROYED, - ]; - for (const destroyedMessageType of destroyedMessageTypes) { - const sub = this._connection.on(destroyedMessageType, this.handleContextDestroyedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextDestroyedMessage(destroyedMsg) { - const destroyedMessageType = destroyedMsg.type; - let contextId; - let name; - if (destroyedMessageType === GW_MESSAGE_ACTIVITY_DESTROYED) { - name = destroyedMsg.activity_id; - contextId = this._contextNameToId[name]; - if (!contextId) { - this._logger.error(`Received 'destroyed' for unknown activity: ${destroyedMsg.activity_id}`); - return; - } - } - else { - contextId = destroyedMsg.context_id; - name = this._contextIdToName[contextId]; - if (!name) { - this._logger.error(`Received 'destroyed' for unknown context: ${destroyedMsg.context_id}`); - return; - } - } - delete this._contextIdToName[contextId]; - delete this._contextNameToId[name]; - const contextData = this._contextNameToData[name]; - delete this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - this._logger.error(`Received 'destroyed' for unknown context: ${contextId}`); - return; - } - } - async sendSubscribe(contextData) { - contextData.sentExplicitSubscription = true; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_SUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = false; - throw error; - } - } - async sendUnsubscribe(contextData) { - const prev = contextData.sentExplicitSubscription; - contextData.sentExplicitSubscription = false; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = prev; - throw error; - } - } - calculateContextDeltaV1(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined }; - if (from) { - for (const x of Object.keys(from)) { - if (Object.keys(to).indexOf(x) !== -1 - && to[x] !== null - && !deepEqual(from[x], to[x])) { - delta.updated[x] = to[x]; - } - } - } - for (const x of Object.keys(to)) { - if (!from || (Object.keys(from).indexOf(x) === -1)) { - if (to[x] !== null) { - delta.added[x] = to[x]; - } - } - else if (to[x] === null) { - delta.removed.push(x); - } - } - return delta; - } - calculateContextDeltaV2(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined, commands: [] }; - for (const x of Object.keys(to)) { - if (to[x] !== null) { - const fromX = from ? from[x] : null; - if (!deepEqual(fromX, to[x])) { - delta.commands?.push({ type: "set", path: x, value: to[x] }); - } - } - else { - delta.commands?.push({ type: "remove", path: x }); - } - } - return delta; - } - resetState() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - if (this._systemContextsSubKey) { - this.unsubscribe(this._systemContextsSubKey, true); - delete this._systemContextsSubKey; - } - this._gw3Subscriptions = []; - this._contextNameToId = {}; - this._contextIdToName = {}; - delete this._protocolVersion; - this._contextsTempCache = Object.keys(this._contextNameToData).reduce((cacheSoFar, ctxName) => { - const contextData = this._contextNameToData[ctxName]; - const addToCache = !this._onlyReAnnounceSubscribedContexts || contextData.hasReceivedSnapshot; - if (addToCache) { - cacheSoFar[ctxName] = this._contextNameToData[ctxName].context; - } - return cacheSoFar; - }, {}); - this._contextNameToData = {}; - } - async reInitiateState() { - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - await Promise.all(this._contextsSubscriptionsCache.map((subscription) => this.subscribe(subscription.contextName, subscription.callback, subscription.subKey))); - await this.flushQueue(); - for (const ctxName in this._contextsTempCache) { - if (typeof this._contextsTempCache[ctxName] !== "object" || Object.keys(this._contextsTempCache[ctxName]).length === 0) { - continue; - } - const lastKnownData = this._contextsTempCache[ctxName]; - this._logger.info(`Re-announcing known context: ${ctxName}`); - await this.flushQueue(); - await this.update(ctxName, lastKnownData); - } - this._contextsTempCache = {}; - this._logger.info("Contexts are re-announced"); - } - flushQueue() { - return new Promise((resolve) => setTimeout(() => resolve(), 0)); - } - } - - class ContextsModule { - initTime; - initStartTime; - initEndTime; - _bridge; - constructor(config) { - this._bridge = new GW3Bridge(config); - } - all() { - return this._bridge.all(); - } - update(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.update(name, data); - } - set(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.set(name, data); - } - setPath(name, path, data) { - this.checkName(name); - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(data); - return this.set(name, data); - } - return this._bridge.setPath(name, path, data); - } - setPaths(name, paths) { - this.checkName(name); - if (!Array.isArray(paths)) { - throw new Error("Please provide the paths as an array of PathValues!"); - } - for (const { path, value } of paths) { - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(value); - } - } - return this._bridge.setPaths(name, paths); - } - subscribe(name, callback) { - this.checkName(name); - if (typeof callback !== "function") { - throw new Error("Please provide the callback as a function!"); - } - return this._bridge - .subscribe(name, (data, delta, removed, key, extraData) => callback(data, delta, removed, () => this._bridge.unsubscribe(key), extraData)) - .then((key) => () => { - this._bridge.unsubscribe(key); - }); - } - get(name) { - this.checkName(name); - return this._bridge.get(name); - } - ready() { - return Promise.resolve(this); - } - destroy(name) { - this.checkName(name); - return this._bridge.destroy(name); - } - get setPathSupported() { - return this._bridge.setPathSupported; - } - checkName(name) { - if (typeof name !== "string" || name === "") { - throw new Error("Please provide the name as a non-empty string!"); - } - } - checkPath(path) { - if (typeof path !== "string") { - throw new Error("Please provide the path as a dot delimited string!"); - } - } - checkData(data) { - if (typeof data !== "object") { - throw new Error("Please provide the data as an object!"); - } - } - } - - function promisify (promise, successCallback, errorCallback) { - if (typeof successCallback !== "function" && typeof errorCallback !== "function") { - return promise; - } - if (typeof successCallback !== "function") { - successCallback = () => { }; - } - else if (typeof errorCallback !== "function") { - errorCallback = () => { }; - } - return promise.then(successCallback, errorCallback); - } - - function rejectAfter(ms = 0, promise, error) { - let timeout; - const clearTimeoutIfThere = () => { - if (timeout) { - clearTimeout(timeout); - } - }; - promise - .then(() => { - clearTimeoutIfThere(); - }) - .catch(() => { - clearTimeoutIfThere(); - }); - return new Promise((resolve, reject) => { - timeout = setTimeout(() => reject(error), ms); - }); - } - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - Decoder.oneOf; - /** See `Decoder.union` */ - var union = Decoder.union; - /** See `Decoder.intersection` */ - Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - var fail$1 = Decoder.fail; - /** See `Decoder.lazy` */ - Decoder.lazy; - - const functionCheck = (input, propDescription) => { - const providedType = typeof input; - return providedType === "function" ? - anyJson() : - fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${typeof providedType}`); - }; - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number or 0"); - const methodDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - objectTypes: optional(array(nonEmptyStringDecoder)), - displayName: optional(nonEmptyStringDecoder), - accepts: optional(nonEmptyStringDecoder), - returns: optional(nonEmptyStringDecoder), - description: optional(nonEmptyStringDecoder), - version: optional(nonNegativeNumberDecoder), - supportsStreaming: optional(boolean()), - flags: optional(object()), - getServers: optional(anyJson().andThen((result) => functionCheck(result, "method definition getServers"))) - }); - const methodFilterDecoder = union(nonEmptyStringDecoder, methodDefinitionDecoder); - const instanceDecoder = object({ - application: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - pid: optional(nonNegativeNumberDecoder), - machine: optional(nonEmptyStringDecoder), - user: optional(nonEmptyStringDecoder), - environment: optional(nonEmptyStringDecoder), - region: optional(nonEmptyStringDecoder), - service: optional(nonEmptyStringDecoder), - instance: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - peerId: optional(nonEmptyStringDecoder), - isLocal: optional(boolean()), - api: optional(nonEmptyStringDecoder), - getMethods: optional(anyJson().andThen((result) => functionCheck(result, "instance getMethods"))), - getStreams: optional(anyJson().andThen((result) => functionCheck(result, "instance getStreams"))) - }); - const targetDecoder = union(constant("best"), constant("all"), constant("skipMine"), instanceDecoder, array(instanceDecoder)); - const invokeOptionsDecoder = object({ - waitTimeoutMs: optional(nonNegativeNumberDecoder), - methodResponseTimeoutMs: optional(nonNegativeNumberDecoder) - }); - - var InvokeStatus; - (function (InvokeStatus) { - InvokeStatus[InvokeStatus["Success"] = 0] = "Success"; - InvokeStatus[InvokeStatus["Error"] = 1] = "Error"; - })(InvokeStatus || (InvokeStatus = {})); - class Client { - protocol; - repo; - instance; - configuration; - constructor(protocol, repo, instance, configuration) { - this.protocol = protocol; - this.repo = repo; - this.instance = instance; - this.configuration = configuration; - } - subscribe(method, options, successCallback, errorCallback, existingSub) { - const callProtocolSubscribe = (targetServers, stream, successProxy, errorProxy) => { - options.methodResponseTimeout = options.methodResponseTimeout ?? options.waitTimeoutMs; - this.protocol.client.subscribe(stream, options, targetServers, successProxy, errorProxy, existingSub); - }; - const promise = new Promise((resolve, reject) => { - const successProxy = (sub) => { - resolve(sub); - }; - const errorProxy = (err) => { - reject(err); - }; - if (!method) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - let methodDef; - if (typeof method === "string") { - methodDef = { name: method }; - } - else { - methodDef = method; - } - if (!methodDef.name) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - if (options === undefined) { - options = {}; - } - let target = options.target; - if (target === undefined) { - target = "best"; - } - if (typeof target === "string" && target !== "all" && target !== "best") { - reject(new Error(`"${target}" is not a valid target. Valid targets are "all", "best", or an instance.`)); - return; - } - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = options.method_response_timeout; - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = this.configuration.methodResponseTimeout; - } - } - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = options.wait_for_method_timeout; - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - const delayStep = 500; - let delayTillNow = 0; - let currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - callProtocolSubscribe(currentServers, currentServers[0].methods[0], successProxy, errorProxy); - } - else { - const retry = () => { - if (!target || !(options.waitTimeoutMs)) { - return; - } - delayTillNow += delayStep; - currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - const streamInfo = currentServers[0].methods[0]; - callProtocolSubscribe(currentServers, streamInfo, successProxy, errorProxy); - } - else if (delayTillNow >= options.waitTimeoutMs) { - const def = typeof method === "string" ? { name: method } : method; - callProtocolSubscribe(currentServers, def, successProxy, errorProxy); - } - else { - setTimeout(retry, delayStep); - } - }; - setTimeout(retry, delayStep); - } - }); - return promisify(promise, successCallback, errorCallback); - } - servers(methodFilter) { - const filterCopy = methodFilter === undefined - ? undefined - : { ...methodFilter }; - return this.getServers(filterCopy).map((serverMethodMap) => { - return serverMethodMap.server.instance; - }); - } - methods(methodFilter) { - if (typeof methodFilter === "string") { - methodFilter = { name: methodFilter }; - } - else { - methodFilter = { ...methodFilter }; - } - return this.getMethods(methodFilter); - } - methodsForInstance(instance) { - return this.getMethodsForInstance(instance); - } - methodAdded(callback) { - return this.repo.onMethodAdded(callback); - } - methodRemoved(callback) { - return this.repo.onMethodRemoved(callback); - } - serverAdded(callback) { - return this.repo.onServerAdded(callback); - } - serverRemoved(callback) { - return this.repo.onServerRemoved((server, reason) => { - callback(server, reason); - }); - } - serverMethodAdded(callback) { - return this.repo.onServerMethodAdded((server, method) => { - callback({ server, method }); - }); - } - serverMethodRemoved(callback) { - return this.repo.onServerMethodRemoved((server, method) => { - callback({ server, method }); - }); - } - async invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - const getInvokePromise = async () => { - const methodDefinition = typeof methodFilter === "string" ? { name: methodFilter } : { ...methodFilter }; - if (!argumentObj) { - argumentObj = {}; - } - if (!target) { - target = "best"; - } - if (!additionalOptions) { - additionalOptions = {}; - } - const methodFilterDecoderResult = methodFilterDecoder.run(methodDefinition); - if (!methodFilterDecoderResult.ok) { - const message = `The provided 'method' argument is invalid. Error: ${JSON.stringify(methodFilterDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (typeof argumentObj !== "object") { - const message = "The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const targetDecoderResult = targetDecoder.run(target); - if (!targetDecoderResult.ok) { - const message = `The provided 'target' argument is invalid. Error: ${JSON.stringify(targetDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const invokeOptionsDecoderResult = invokeOptionsDecoder.run(additionalOptions); - if (!invokeOptionsDecoderResult.ok) { - const message = `The provided 'options' argument is invalid. Error: ${JSON.stringify(invokeOptionsDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (success && typeof success !== "function") { - const message = "The provided 'success' function is invalid. Error: The success should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (error && typeof error !== "function") { - const message = "The provided 'error' function is invalid. Error: The error should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = additionalOptions.method_response_timeout; - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = this.configuration.methodResponseTimeout; - } - } - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = additionalOptions.wait_for_method_timeout; - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - let serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length === 0) { - try { - serversMethodMap = await this.tryToAwaitForMethods(methodDefinition, target, additionalOptions); - } - catch (err) { - const message = `Can not find a method matching ${JSON.stringify(methodFilter)} with server filter ${JSON.stringify(target)}`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - } - const timeout = additionalOptions.methodResponseTimeoutMs; - const additionalOptionsCopy = additionalOptions; - const invokePromises = serversMethodMap.map((serversMethodPair) => { - const invId = nanoid(10); - const method = serversMethodPair.methods[0]; - const server = serversMethodPair.server; - const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy); - return Promise.race([ - invokePromise, - rejectAfter(timeout, invokePromise, { - invocationId: invId, - message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`, - status: InvokeStatus.Error, - }) - ]); - }); - const invocationMessages = await Promise.all(invokePromises); - const results = this.getInvocationResultObj(invocationMessages, methodDefinition, argumentObj); - const allRejected = invocationMessages.every((result) => result.status === InvokeStatus.Error); - if (allRejected) { - return Promise.reject(results); - } - return results; - }; - return promisify(getInvokePromise(), success, error); - } - generateInvalidInputInvocationResult(message, methodDefinition, argumentObj) { - const method = { - ...methodDefinition, - getServers: () => [], - supportsStreaming: false, - objectTypes: methodDefinition.objectTypes ?? [], - flags: methodDefinition.flags?.metadata ?? {} - }; - const invokeResultMessage = { - invocationId: nanoid(10), - status: InvokeStatus.Error, - message - }; - return this.getInvocationResultObj([invokeResultMessage], method, argumentObj); - } - getInvocationResultObj(invocationResults, method, calledWith) { - const all_return_values = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Success) - .reduce((allValues, currentValue) => { - allValues = [ - ...allValues, - { - executed_by: currentValue.instance, - returned: currentValue.result, - called_with: calledWith, - method, - message: currentValue.message, - status: currentValue.status, - } - ]; - return allValues; - }, []); - const all_errors = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Error) - .reduce((allErrors, currError) => { - allErrors = [ - ...allErrors, - { - executed_by: currError.instance, - called_with: calledWith, - name: method.name, - message: currError.message, - } - ]; - return allErrors; - }, []); - const invResult = invocationResults[0]; - const result = { - method, - called_with: calledWith, - returned: invResult.result, - executed_by: invResult.instance, - all_return_values, - all_errors, - message: invResult.message, - status: invResult.status - }; - return result; - } - tryToAwaitForMethods(methodDefinition, target, additionalOptions) { - return new Promise((resolve, reject) => { - if (additionalOptions.waitTimeoutMs === 0) { - reject(); - return; - } - const delayStep = 500; - let delayTillNow = 0; - const retry = () => { - delayTillNow += delayStep; - const serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length > 0) { - clearInterval(interval); - resolve(serversMethodMap); - } - else if (delayTillNow >= (additionalOptions.waitTimeoutMs || 10000)) { - clearInterval(interval); - reject(); - return; - } - }; - const interval = setInterval(retry, delayStep); - }); - } - filterByTarget(target, serverMethodMap) { - if (typeof target === "string") { - if (target === "all") { - return [...serverMethodMap]; - } - else if (target === "best") { - const localMachine = serverMethodMap - .find((s) => s.server.instance.isLocal); - if (localMachine) { - return [localMachine]; - } - if (serverMethodMap[0] !== undefined) { - return [serverMethodMap[0]]; - } - } - else if (target === "skipMine") { - return serverMethodMap.filter(({ server }) => server.instance.peerId !== this.instance.peerId); - } - } - else { - let targetArray; - if (!Array.isArray(target)) { - targetArray = [target]; - } - else { - targetArray = target; - } - const allServersMatching = targetArray.reduce((matches, filter) => { - const myMatches = serverMethodMap.filter((serverMethodPair) => { - return this.instanceMatch(filter, serverMethodPair.server.instance); - }); - return matches.concat(myMatches); - }, []); - return allServersMatching; - } - return []; - } - instanceMatch(instanceFilter, instanceDefinition) { - if (instanceFilter?.peerId && instanceFilter?.instance) { - instanceFilter = { ...instanceFilter }; - delete instanceFilter.peerId; - } - return this.containsProps(instanceFilter, instanceDefinition); - } - methodMatch(methodFilter, methodDefinition) { - return this.containsProps(methodFilter, methodDefinition); - } - containsProps(filter, repoMethod) { - const filterProps = Object.keys(filter) - .filter((prop) => { - return filter[prop] !== undefined - && filter[prop] !== null - && typeof filter[prop] !== "function" - && prop !== "object_types" - && prop !== "display_name" - && prop !== "id" - && prop !== "gatewayId" - && prop !== "identifier" - && prop[0] !== "_"; - }); - return filterProps.every((prop) => { - let isMatch; - const filterValue = filter[prop]; - const repoMethodValue = repoMethod[prop]; - switch (prop) { - case "objectTypes": - isMatch = (filterValue || []).every((filterValueEl) => { - return (repoMethodValue || []).includes(filterValueEl); - }); - break; - case "flags": - isMatch = isSubset(repoMethodValue || {}, filterValue || {}); - break; - default: - isMatch = String(filterValue).toLowerCase() === String(repoMethodValue).toLowerCase(); - } - return isMatch; - }); - } - getMethods(methodFilter) { - if (methodFilter === undefined) { - return this.repo.getMethods(); - } - const methods = this.repo.getMethods().filter((method) => { - return this.methodMatch(methodFilter, method); - }); - return methods; - } - getMethodsForInstance(instanceFilter) { - const allServers = this.repo.getServers(); - const matchingServers = allServers.filter((server) => { - return this.instanceMatch(instanceFilter, server.instance); - }); - if (matchingServers.length === 0) { - return []; - } - let resultMethodsObject = {}; - if (matchingServers.length === 1) { - resultMethodsObject = matchingServers[0].methods; - } - else { - matchingServers.forEach((server) => { - Object.keys(server.methods).forEach((methodKey) => { - const method = server.methods[methodKey]; - resultMethodsObject[method.identifier] = method; - }); - }); - } - return Object.keys(resultMethodsObject) - .map((key) => { - return resultMethodsObject[key]; - }); - } - getServers(methodFilter) { - const servers = this.repo.getServers(); - if (methodFilter === undefined) { - return servers.map((server) => { - return { server, methods: [] }; - }); - } - return servers.reduce((prev, current) => { - const methodsForServer = Object.values(current.methods); - const matchingMethods = methodsForServer.filter((method) => { - return this.methodMatch(methodFilter, method); - }); - if (matchingMethods.length > 0) { - prev.push({ server: current, methods: matchingMethods }); - } - return prev; - }, []); - } - getServerMethodsByFilterAndTarget(methodFilter, target) { - const serversMethodMap = this.getServers(methodFilter); - return this.filterByTarget(target, serversMethodMap); - } - } - - class ServerSubscription { - protocol; - repoMethod; - subscription; - constructor(protocol, repoMethod, subscription) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.subscription = subscription; - } - get stream() { - if (!this.repoMethod.stream) { - throw new Error("no stream"); - } - return this.repoMethod.stream; - } - get arguments() { return this.subscription.arguments || {}; } - get branchKey() { return this.subscription.branchKey; } - get instance() { - if (!this.subscription.instance) { - throw new Error("no instance"); - } - return this.subscription.instance; - } - close() { - this.protocol.server.closeSingleSubscription(this.repoMethod, this.subscription); - } - push(data) { - this.protocol.server.pushDataToSingle(this.repoMethod, this.subscription, data); - } - } - - class Request { - protocol; - repoMethod; - requestContext; - arguments; - instance; - constructor(protocol, repoMethod, requestContext) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.requestContext = requestContext; - this.arguments = requestContext.arguments; - this.instance = requestContext.instance; - } - accept() { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, ""); - } - acceptOnBranch(branch) { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, branch); - } - reject(reason) { - this.protocol.server.rejectRequest(this.requestContext, this.repoMethod, reason); - } - } - - let ServerStreaming$1 = class ServerStreaming { - protocol; - server; - constructor(protocol, server) { - this.protocol = protocol; - this.server = server; - protocol.server.onSubRequest((rc, rm) => this.handleSubRequest(rc, rm)); - protocol.server.onSubAdded((sub, rm) => this.handleSubAdded(sub, rm)); - protocol.server.onSubRemoved((sub, rm) => this.handleSubRemoved(sub, rm)); - } - handleSubRequest(requestContext, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRequestHandler === "function")) { - return; - } - const request = new Request(this.protocol, repoMethod, requestContext); - repoMethod.streamCallbacks.subscriptionRequestHandler(request); - } - handleSubAdded(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionAddedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionAddedHandler(sub); - } - handleSubRemoved(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRemovedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionRemovedHandler(sub); - } - }; - - class ServerBranch { - key; - protocol; - repoMethod; - constructor(key, protocol, repoMethod) { - this.key = key; - this.protocol = protocol; - this.repoMethod = repoMethod; - } - subscriptions() { - const subList = this.protocol.server.getSubscriptionList(this.repoMethod, this.key); - return subList.map((sub) => { - return new ServerSubscription(this.protocol, this.repoMethod, sub); - }); - } - close() { - this.protocol.server.closeAllSubscriptions(this.repoMethod, this.key); - } - push(data) { - this.protocol.server.pushData(this.repoMethod, data, [this.key]); - } - } - - class ServerStream { - _protocol; - _repoMethod; - _server; - name; - constructor(_protocol, _repoMethod, _server) { - this._protocol = _protocol; - this._repoMethod = _repoMethod; - this._server = _server; - this.name = this._repoMethod.definition.name; - } - branches(key) { - const bList = this._protocol.server.getBranchList(this._repoMethod); - if (key) { - if (bList.indexOf(key) > -1) { - return new ServerBranch(key, this._protocol, this._repoMethod); - } - return undefined; - } - else { - return bList.map((branchKey) => { - return new ServerBranch(branchKey, this._protocol, this._repoMethod); - }); - } - } - branch(key) { - return this.branches(key); - } - subscriptions() { - const subList = this._protocol.server.getSubscriptionList(this._repoMethod); - return subList.map((sub) => { - return new ServerSubscription(this._protocol, this._repoMethod, sub); - }); - } - get definition() { - const def2 = this._repoMethod.definition; - return { - accepts: def2.accepts, - description: def2.description, - displayName: def2.displayName, - name: def2.name, - objectTypes: def2.objectTypes, - returns: def2.returns, - supportsStreaming: def2.supportsStreaming, - flags: def2.flags?.metadata, - }; - } - close() { - this._protocol.server.closeAllSubscriptions(this._repoMethod); - this._server.unregister(this._repoMethod.definition, true); - } - push(data, branches) { - if (typeof branches !== "string" && !Array.isArray(branches) && branches !== undefined) { - throw new Error("invalid branches should be string or string array"); - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - this._protocol.server.pushData(this._repoMethod, data, branches); - } - updateRepoMethod(repoMethod) { - this._repoMethod = repoMethod; - } - } - - class Server { - protocol; - serverRepository; - streaming; - invocations = 0; - currentlyUnregistering = {}; - constructor(protocol, serverRepository) { - this.protocol = protocol; - this.serverRepository = serverRepository; - this.streaming = new ServerStreaming$1(protocol, this); - this.protocol.server.onInvoked(this.onMethodInvoked.bind(this)); - } - createStream(streamDef, callbacks, successCallback, errorCallback, existingStream) { - const promise = new Promise((resolve, reject) => { - if (!streamDef) { - reject("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream."); - return; - } - let streamMethodDefinition; - if (typeof streamDef === "string") { - streamMethodDefinition = { name: "" + streamDef }; - } - else { - streamMethodDefinition = { ...streamDef }; - } - if (!streamMethodDefinition.name) { - return reject(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(streamMethodDefinition)}`); - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === streamMethodDefinition.name); - if (nameAlreadyExists) { - return reject(`A stream with the name "${streamMethodDefinition.name}" already exists! Please, provide a unique name for the stream.`); - } - streamMethodDefinition.supportsStreaming = true; - if (!callbacks) { - callbacks = {}; - } - if (typeof callbacks.subscriptionRequestHandler !== "function") { - callbacks.subscriptionRequestHandler = (request) => { - request.accept(); - }; - } - const repoMethod = this.serverRepository.add({ - definition: streamMethodDefinition, - streamCallbacks: callbacks, - protocolState: {}, - }); - this.protocol.server.createStream(repoMethod) - .then(() => { - let streamUserObject; - if (existingStream) { - streamUserObject = existingStream; - existingStream.updateRepoMethod(repoMethod); - } - else { - streamUserObject = new ServerStream(this.protocol, repoMethod, this); - } - repoMethod.stream = streamUserObject; - resolve(streamUserObject); - }) - .catch((err) => { - if (repoMethod.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - reject(err); - }); - }); - return promisify(promise, successCallback, errorCallback); - } - register(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallbackFunction = async (context, resultCallback) => { - try { - const result = callback(context.args, context.instance); - if (result && typeof result.then === "function") { - const resultValue = await result; - resultCallback(undefined, resultValue); - } - else { - resultCallback(undefined, result); - } - } - catch (e) { - resultCallback(e ?? "", e ?? ""); - } - }; - wrappedCallbackFunction.userCallback = callback; - return this.registerCore(methodDefinition, wrappedCallbackFunction); - } - registerAsync(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallback = async (context, resultCallback) => { - try { - let resultCalled = false; - const success = (result) => { - if (!resultCalled) { - resultCallback(undefined, result); - } - resultCalled = true; - }; - const error = (e) => { - if (!resultCalled) { - if (!e) { - e = ""; - } - resultCallback(e, e); - } - resultCalled = true; - }; - const methodResult = callback(context.args, context.instance, success, error); - if (methodResult && typeof methodResult.then === "function") { - methodResult - .then(success) - .catch(error); - } - } - catch (e) { - resultCallback(e, undefined); - } - }; - wrappedCallback.userCallbackAsync = callback; - return this.registerCore(methodDefinition, wrappedCallback); - } - async unregister(methodFilter, forStream = false) { - if (methodFilter === undefined) { - return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property."); - } - if (typeof methodFilter === "function") { - await this.unregisterWithPredicate(methodFilter, forStream); - return; - } - let methodDefinition; - if (typeof methodFilter === "string") { - methodDefinition = { name: methodFilter }; - } - else { - methodDefinition = methodFilter; - } - if (methodDefinition.name === undefined) { - return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!"); - } - const methodToBeRemoved = this.serverRepository.getList().find((serverMethod) => { - return serverMethod.definition.name === methodDefinition.name - && (serverMethod.definition.supportsStreaming || false) === forStream; - }); - if (!methodToBeRemoved) { - return Promise.reject(`Method with a name "${methodDefinition.name}" does not exist or is not registered by your application!`); - } - await this.removeMethodsOrStreams([methodToBeRemoved]); - } - async unregisterWithPredicate(filterPredicate, forStream) { - const methodsOrStreamsToRemove = this.serverRepository.getList() - .filter((sm) => filterPredicate(sm.definition)) - .filter((serverMethod) => (serverMethod.definition.supportsStreaming || false) === forStream); - if (!methodsOrStreamsToRemove || methodsOrStreamsToRemove.length === 0) { - return Promise.reject(`Could not find a ${forStream ? "stream" : "method"} matching the specified condition!`); - } - await this.removeMethodsOrStreams(methodsOrStreamsToRemove); - } - removeMethodsOrStreams(methodsToRemove) { - const methodUnregPromises = []; - methodsToRemove.forEach((method) => { - const promise = this.protocol.server.unregister(method) - .then(() => { - if (method.repoId) { - this.serverRepository.remove(method.repoId); - } - }); - methodUnregPromises.push(promise); - this.addAsCurrentlyUnregistering(method.definition.name, promise); - }); - return Promise.all(methodUnregPromises); - } - async addAsCurrentlyUnregistering(methodName, promise) { - const timeout = new Promise((resolve) => setTimeout(resolve, 5000)); - this.currentlyUnregistering[methodName] = Promise.race([promise, timeout]).then(() => { - delete this.currentlyUnregistering[methodName]; - }); - } - async registerCore(method, theFunction) { - let methodDefinition; - if (typeof method === "string") { - methodDefinition = { name: "" + method }; - } - else { - methodDefinition = { ...method }; - } - if (!methodDefinition.name) { - return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(method)}`); - } - const unregisterInProgress = this.currentlyUnregistering[methodDefinition.name]; - if (typeof unregisterInProgress !== "undefined") { - await unregisterInProgress; - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === methodDefinition.name); - if (nameAlreadyExists) { - return Promise.reject(`A method with the name "${methodDefinition.name}" already exists! Please, provide a unique name for the method.`); - } - if (methodDefinition.supportsStreaming) { - return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${methodDefinition.name}” to be a stream, please use the “glue.interop.createStream()” method.`); - } - const repoMethod = this.serverRepository.add({ - definition: methodDefinition, - theFunction, - protocolState: {}, - }); - return this.protocol.server.register(repoMethod) - .catch((err) => { - if (repoMethod?.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - throw err; - }); - } - onMethodInvoked(methodToExecute, invocationId, invocationArgs) { - if (!methodToExecute || !methodToExecute.theFunction) { - return; - } - methodToExecute.theFunction(invocationArgs, (err, result) => { - if (err !== undefined && err !== null) { - if (err.message && typeof err.message === "string") { - err = err.message; - } - else if (typeof err !== "string") { - try { - err = JSON.stringify(err); - } - catch (unStrException) { - err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`; - } - } - } - if (!result) { - result = {}; - } - else if (typeof result !== "object" || Array.isArray(result)) { - result = { _value: result }; - } - this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result); - }); - } - } - - class InstanceWrapper { - wrapped = {}; - constructor(API, instance, connection) { - this.wrapped.getMethods = function () { - return API.methodsForInstance(this); - }; - this.wrapped.getStreams = function () { - return API.methodsForInstance(this).filter((m) => m.supportsStreaming); - }; - if (instance) { - this.refreshWrappedObject(instance); - } - if (connection) { - connection.loggedIn(() => { - this.refresh(connection); - }); - this.refresh(connection); - } - } - unwrap() { - return this.wrapped; - } - refresh(connection) { - if (!connection) { - return; - } - const resolvedIdentity = connection?.resolvedIdentity; - const instance = Object.assign({}, resolvedIdentity ?? {}, { peerId: connection?.peerId }); - this.refreshWrappedObject(instance); - } - refreshWrappedObject(resolvedIdentity) { - Object.keys(resolvedIdentity).forEach((key) => { - this.wrapped[key] = resolvedIdentity[key]; - }); - this.wrapped.user = resolvedIdentity.user; - this.wrapped.instance = resolvedIdentity.instance; - this.wrapped.application = resolvedIdentity.application ?? nanoid(10); - this.wrapped.applicationName = resolvedIdentity.applicationName; - this.wrapped.pid = resolvedIdentity.pid ?? resolvedIdentity.process ?? Math.floor(Math.random() * 10000000000); - this.wrapped.machine = resolvedIdentity.machine; - this.wrapped.environment = resolvedIdentity.environment; - this.wrapped.region = resolvedIdentity.region; - this.wrapped.windowId = resolvedIdentity.windowId; - this.wrapped.isLocal = resolvedIdentity.isLocal ?? true; - this.wrapped.api = resolvedIdentity.api; - this.wrapped.service = resolvedIdentity.service; - this.wrapped.peerId = resolvedIdentity.peerId; - } - } - - const hideMethodSystemFlags = (method) => { - return { - ...method, - flags: method.flags.metadata || {} - }; - }; - class ClientRepository { - logger; - API; - servers = {}; - myServer; - methodsCount = {}; - callbacks = CallbackRegistryFactory(); - constructor(logger, API) { - this.logger = logger; - this.API = API; - const peerId = this.API.instance.peerId; - this.myServer = { - id: peerId, - methods: {}, - instance: this.API.instance, - wrapper: this.API.unwrappedInstance, - }; - this.servers[peerId] = this.myServer; - } - addServer(info, serverId) { - this.logger.debug(`adding server ${serverId}`); - const current = this.servers[serverId]; - if (current) { - return current.id; - } - const wrapper = new InstanceWrapper(this.API, info); - const serverEntry = { - id: serverId, - methods: {}, - instance: wrapper.unwrap(), - wrapper, - }; - this.servers[serverId] = serverEntry; - this.callbacks.execute("onServerAdded", serverEntry.instance); - return serverId; - } - removeServerById(id, reason) { - const server = this.servers[id]; - if (!server) { - this.logger.warn(`not aware of server ${id}, my state ${JSON.stringify(Object.keys(this.servers))}`); - return; - } - else { - this.logger.debug(`removing server ${id}`); - } - Object.keys(server.methods).forEach((methodId) => { - this.removeServerMethod(id, methodId); - }); - delete this.servers[id]; - this.callbacks.execute("onServerRemoved", server.instance, reason); - } - addServerMethod(serverId, method) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - if (server.methods[method.id]) { - return; - } - const identifier = this.createMethodIdentifier(method); - const that = this; - const methodDefinition = { - identifier, - gatewayId: method.id, - name: method.name, - displayName: method.display_name, - description: method.description, - version: method.version, - objectTypes: method.object_types || [], - accepts: method.input_signature, - returns: method.result_signature, - supportsStreaming: typeof method.flags !== "undefined" ? method.flags.streaming : false, - flags: method.flags ?? {}, - getServers: () => { - return that.getServersByMethod(identifier); - } - }; - methodDefinition.object_types = methodDefinition.objectTypes; - methodDefinition.display_name = methodDefinition.displayName; - methodDefinition.version = methodDefinition.version; - server.methods[method.id] = methodDefinition; - const clientMethodDefinition = hideMethodSystemFlags(methodDefinition); - if (!this.methodsCount[identifier]) { - this.methodsCount[identifier] = 0; - this.callbacks.execute("onMethodAdded", clientMethodDefinition); - } - this.methodsCount[identifier] = this.methodsCount[identifier] + 1; - this.callbacks.execute("onServerMethodAdded", server.instance, clientMethodDefinition); - return methodDefinition; - } - removeServerMethod(serverId, methodId) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - const method = server.methods[methodId]; - delete server.methods[methodId]; - const clientMethodDefinition = hideMethodSystemFlags(method); - this.methodsCount[method.identifier] = this.methodsCount[method.identifier] - 1; - if (this.methodsCount[method.identifier] === 0) { - this.callbacks.execute("onMethodRemoved", clientMethodDefinition); - } - this.callbacks.execute("onServerMethodRemoved", server.instance, clientMethodDefinition); - } - getMethods() { - return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags); - } - getServers() { - return Object.values(this.servers).map(this.hideServerMethodSystemFlags); - } - onServerAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerAdded", callback); - const serversWithMethodsToReplay = this.getServers().map((s) => s.instance); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, serversWithMethodsToReplay, callback); - } - onMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodAdded", callback); - const methodsToReplay = this.getMethods(); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, methodsToReplay, callback); - } - onServerMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodAdded", callback); - let unsubCalled = false; - const servers = this.getServers(); - setTimeout(() => { - servers.forEach((server) => { - const methods = server.methods; - Object.keys(methods).forEach((methodId) => { - if (!unsubCalled) { - callback(server.instance, methods[methodId]); - } - }); - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - onMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodRemoved", callback); - return unsubscribeFunc; - } - onServerRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerRemoved", callback); - return unsubscribeFunc; - } - onServerMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodRemoved", callback); - return unsubscribeFunc; - } - getServerById(id) { - const server = this.servers[id]; - if (!server) { - return undefined; - } - return this.hideServerMethodSystemFlags(this.servers[id]); - } - reset() { - Object.keys(this.servers).forEach((key) => { - this.removeServerById(key, "reset"); - }); - this.servers = { - [this.myServer.id]: this.myServer - }; - this.methodsCount = {}; - } - createMethodIdentifier(methodInfo) { - const accepts = methodInfo.input_signature ?? ""; - const returns = methodInfo.result_signature ?? ""; - return (methodInfo.name + accepts + returns).toLowerCase(); - } - getServersByMethod(identifier) { - const allServers = []; - Object.values(this.servers).forEach((server) => { - Object.values(server.methods).forEach((method) => { - if (method.identifier === identifier) { - allServers.push(server.instance); - } - }); - }); - return allServers; - } - returnUnsubWithDelayedReplay(unsubscribeFunc, collectionToReplay, callback) { - let unsubCalled = false; - setTimeout(() => { - collectionToReplay.forEach((item) => { - if (!unsubCalled) { - callback(item); - } - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - hideServerMethodSystemFlags(server) { - const clientMethods = {}; - Object.entries(server.methods).forEach(([name, method]) => { - clientMethods[name] = hideMethodSystemFlags(method); - }); - return { - ...server, - methods: clientMethods - }; - } - extractMethodsFromServers(servers) { - const methods = Object.values(servers).reduce((clientMethods, server) => { - return [...clientMethods, ...Object.values(server.methods)]; - }, []); - return methods; - } - } - - class ServerRepository { - nextId = 0; - methods = []; - add(method) { - method.repoId = String(this.nextId); - this.nextId += 1; - this.methods.push(method); - return method; - } - remove(repoId) { - if (typeof repoId !== "string") { - return new TypeError("Expecting a string"); - } - this.methods = this.methods.filter((m) => { - return m.repoId !== repoId; - }); - } - getById(id) { - if (typeof id !== "string") { - return undefined; - } - return this.methods.find((m) => { - return m.repoId === id; - }); - } - getList() { - return this.methods.map((m) => m); - } - length() { - return this.methods.length; - } - reset() { - this.methods = []; - } - } - - const SUBSCRIPTION_REQUEST = "onSubscriptionRequest"; - const SUBSCRIPTION_ADDED = "onSubscriptionAdded"; - const SUBSCRIPTION_REMOVED = "onSubscriptionRemoved"; - class ServerStreaming { - session; - repository; - serverRepository; - logger; - ERR_URI_SUBSCRIPTION_FAILED = "com.tick42.agm.errors.subscription.failure"; - callbacks = CallbackRegistryFactory(); - nextStreamId = 0; - constructor(session, repository, serverRepository, logger) { - this.session = session; - this.repository = repository; - this.serverRepository = serverRepository; - this.logger = logger; - session.on("add-interest", (msg) => { - this.handleAddInterest(msg); - }); - session.on("remove-interest", (msg) => { - this.handleRemoveInterest(msg); - }); - } - acceptRequestOnBranch(requestContext, streamingMethod, branch) { - if (typeof branch !== "string") { - branch = ""; - } - if (typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - throw new TypeError("The streaming method is missing its subscriptions."); - } - if (!Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - throw new TypeError("The streaming method is missing its branches."); - } - const streamId = this.getStreamId(streamingMethod, branch); - const key = requestContext.msg.subscription_id; - const subscription = { - id: key, - arguments: requestContext.arguments, - instance: requestContext.instance, - branchKey: branch, - streamId, - subscribeMsg: requestContext.msg, - }; - streamingMethod.protocolState.subscriptionsMap[key] = subscription; - this.session.sendFireAndForget({ - type: "accepted", - subscription_id: key, - stream_id: streamId, - }).catch((err) => { - this.logger.warn(`Failed to send accepted message for subscription ${key}: ${JSON.stringify(err)}`); - }); - this.callbacks.execute(SUBSCRIPTION_ADDED, subscription, streamingMethod); - } - rejectRequest(requestContext, streamingMethod, reason) { - if (typeof reason !== "string") { - reason = ""; - } - this.sendSubscriptionFailed("Subscription rejected by user. " + reason, requestContext.msg.subscription_id); - } - pushData(streamingMethod, data, branches) { - if (typeof streamingMethod !== "object" || !Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - return; - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - if (typeof branches === "string") { - branches = [branches]; - } - else if (!Array.isArray(branches) || branches.length <= 0) { - branches = []; - } - const streamIdList = streamingMethod.protocolState.branchKeyToStreamIdMap - .filter((br) => { - if (!branches || branches.length === 0) { - return true; - } - return branches.indexOf(br.key) >= 0; - }).map((br) => { - return br.streamId; - }); - streamIdList.forEach((streamId) => { - const publishMessage = { - type: "publish", - stream_id: streamId, - data, - }; - this.session.sendFireAndForget(publishMessage) - .catch((err) => { - this.logger.warn(`Failed to send publish message for stream ${streamId}: ${JSON.stringify(err)}`); - }); - }); - } - pushDataToSingle(method, subscription, data) { - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - const postMessage = { - type: "post", - subscription_id: subscription.id, - data, - }; - this.session.sendFireAndForget(postMessage) - .catch((err) => { - this.logger.warn(`Failed to send post message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - } - closeSingleSubscription(streamingMethod, subscription) { - if (streamingMethod.protocolState.subscriptionsMap) { - delete streamingMethod.protocolState.subscriptionsMap[subscription.id]; - } - const dropSubscriptionMessage = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping a single subscription", - }; - this.session.sendFireAndForget(dropSubscriptionMessage) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - subscription.instance; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - closeMultipleSubscriptions(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object" || typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - let subscriptionsToClose = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey === "string") { - subscriptionsToClose = subscriptionsToClose.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - subscriptionsToClose.forEach((subscription) => { - delete subscriptionsMap[subscription.id]; - const drop = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping all subscriptions on stream_id: " + subscription.streamId, - }; - this.session.sendFireAndForget(drop) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - }); - } - getSubscriptionList(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object") { - return []; - } - let subscriptions = []; - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey !== "string") { - subscriptions = allSubscriptions; - } - else { - subscriptions = allSubscriptions.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - return subscriptions; - } - getBranchList(streamingMethod) { - if (typeof streamingMethod !== "object") { - return []; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - const result = []; - allSubscriptions.forEach((sub) => { - let branch = ""; - if (typeof sub === "object" && typeof sub.branchKey === "string") { - branch = sub.branchKey; - } - if (result.indexOf(branch) === -1) { - result.push(branch); - } - }); - return result; - } - onSubAdded(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED, callback); - } - onSubRequest(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST, callback); - } - onSubRemoved(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED, callback); - } - handleRemoveInterest(msg) { - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (typeof msg.subscription_id !== "string" || - typeof streamingMethod !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - if (typeof streamingMethod.protocolState.subscriptionsMap[msg.subscription_id] !== "object") { - return; - } - const subscription = streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - delete streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - onSubscriptionLifetimeEvent(eventName, handlerFunc) { - this.callbacks.add(eventName, handlerFunc); - } - getNextStreamId() { - return this.nextStreamId++ + ""; - } - handleAddInterest(msg) { - const caller = this.repository.getServerById(msg.caller_id); - const instance = caller?.instance ?? {}; - const requestContext = { - msg, - arguments: msg.arguments_kv || {}, - instance, - }; - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (streamingMethod === undefined) { - const errorMsg = "No method with id " + msg.method_id + " on this server."; - this.sendSubscriptionFailed(errorMsg, msg.subscription_id); - return; - } - if (streamingMethod.protocolState.subscriptionsMap && - streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]) { - this.sendSubscriptionFailed("A subscription with id " + msg.subscription_id + " already exists.", msg.subscription_id); - return; - } - this.callbacks.execute(SUBSCRIPTION_REQUEST, requestContext, streamingMethod); - } - sendSubscriptionFailed(reason, subscriptionId) { - const errorMessage = { - type: "error", - reason_uri: this.ERR_URI_SUBSCRIPTION_FAILED, - reason, - request_id: subscriptionId, - }; - this.session.sendFireAndForget(errorMessage) - .catch((err) => { - this.logger.warn(`Failed to send subscription failed message for subscription ${subscriptionId}: ${JSON.stringify(err)}`); - }); - } - getStreamId(streamingMethod, branchKey) { - if (typeof branchKey !== "string") { - branchKey = ""; - } - if (!streamingMethod.protocolState.branchKeyToStreamIdMap) { - throw new Error(`streaming ${streamingMethod.definition.name} method without protocol state`); - } - const needleBranch = streamingMethod.protocolState.branchKeyToStreamIdMap.filter((branch) => { - return branch.key === branchKey; - })[0]; - let streamId = (needleBranch ? needleBranch.streamId : undefined); - if (typeof streamId !== "string" || streamId === "") { - streamId = this.getNextStreamId(); - streamingMethod.protocolState.branchKeyToStreamIdMap.push({ key: branchKey, streamId }); - } - return streamId; - } - } - - class ServerProtocol { - session; - clientRepository; - serverRepository; - logger; - callbacks = CallbackRegistryFactory(); - streaming; - constructor(session, clientRepository, serverRepository, logger) { - this.session = session; - this.clientRepository = clientRepository; - this.serverRepository = serverRepository; - this.logger = logger; - this.streaming = new ServerStreaming(session, clientRepository, serverRepository, logger.subLogger("streaming")); - this.session.on("invoke", (msg) => this.handleInvokeMessage(msg)); - } - createStream(repoMethod) { - repoMethod.protocolState.subscriptionsMap = {}; - repoMethod.protocolState.branchKeyToStreamIdMap = []; - return this.register(repoMethod, true); - } - register(repoMethod, isStreaming) { - const methodDef = repoMethod.definition; - const flags = Object.assign({}, { metadata: methodDef.flags ?? {} }, { streaming: isStreaming || false }); - const registerMsg = { - type: "register", - methods: [{ - id: repoMethod.repoId, - name: methodDef.name, - display_name: methodDef.displayName, - description: methodDef.description, - version: methodDef.version, - flags, - object_types: methodDef.objectTypes || methodDef.object_types, - input_signature: methodDef.accepts, - result_signature: methodDef.returns, - restrictions: undefined, - }], - }; - return this.session.send(registerMsg, { methodId: repoMethod.repoId }) - .then(() => { - this.logger.debug("registered method " + repoMethod.definition.name + " with id " + repoMethod.repoId); - }) - .catch((msg) => { - this.logger.warn(`failed to register method ${repoMethod.definition.name} with id ${repoMethod.repoId} - ${JSON.stringify(msg)}`); - throw msg; - }); - } - onInvoked(callback) { - this.callbacks.add("onInvoked", callback); - } - methodInvocationResult(method, invocationId, err, result) { - let msg; - if (err || err === "") { - msg = { - type: "error", - request_id: invocationId, - reason_uri: "agm.errors.client_error", - reason: err, - context: result, - peer_id: undefined, - }; - } - else { - msg = { - type: "yield", - invocation_id: invocationId, - peer_id: this.session.peerId, - result, - request_id: undefined, - }; - } - this.session.sendFireAndForget(msg) - .catch((error => { - this.logger.warn(`Failed to send method invocation result for method ${method.definition.name} invocation ${invocationId} - ${JSON.stringify(error)}`); - })); - } - async unregister(method) { - const msg = { - type: "unregister", - methods: [method.repoId], - }; - await this.session.send(msg); - } - getBranchList(method) { - return this.streaming.getBranchList(method); - } - getSubscriptionList(method, branchKey) { - return this.streaming.getSubscriptionList(method, branchKey); - } - closeAllSubscriptions(method, branchKey) { - this.streaming.closeMultipleSubscriptions(method, branchKey); - } - pushData(method, data, branches) { - this.streaming.pushData(method, data, branches); - } - pushDataToSingle(method, subscription, data) { - this.streaming.pushDataToSingle(method, subscription, data); - } - closeSingleSubscription(method, subscription) { - this.streaming.closeSingleSubscription(method, subscription); - } - acceptRequestOnBranch(requestContext, method, branch) { - this.streaming.acceptRequestOnBranch(requestContext, method, branch); - } - rejectRequest(requestContext, method, reason) { - this.streaming.rejectRequest(requestContext, method, reason); - } - onSubRequest(callback) { - this.streaming.onSubRequest(callback); - } - onSubAdded(callback) { - this.streaming.onSubAdded(callback); - } - onSubRemoved(callback) { - this.streaming.onSubRemoved(callback); - } - handleInvokeMessage(msg) { - const invocationId = msg.invocation_id; - const callerId = msg.caller_id; - const methodId = msg.method_id; - const args = msg.arguments_kv; - const methodList = this.serverRepository.getList(); - const method = methodList.filter((m) => { - return m.repoId === methodId; - })[0]; - if (method === undefined) { - return; - } - const client = this.clientRepository.getServerById(callerId)?.instance; - const invocationArgs = { args, instance: client }; - this.callbacks.execute("onInvoked", method, invocationId, invocationArgs); - } - } - - class UserSubscription { - repository; - subscriptionData; - get requestArguments() { - return this.subscriptionData.params.arguments || {}; - } - get servers() { - return this.subscriptionData.trackedServers.reduce((servers, pair) => { - if (pair.subscriptionId) { - const server = this.repository.getServerById(pair.serverId)?.instance; - if (server) { - servers.push(server); - } - } - return servers; - }, []); - } - get serverInstance() { - return this.servers[0]; - } - get stream() { - return this.subscriptionData.method; - } - constructor(repository, subscriptionData) { - this.repository = repository; - this.subscriptionData = subscriptionData; - } - onData(dataCallback) { - if (typeof dataCallback !== "function") { - throw new TypeError("The data callback must be a function."); - } - this.subscriptionData.handlers.onData.push(dataCallback); - if (this.subscriptionData.handlers.onData.length === 1 && this.subscriptionData.queued.data.length > 0) { - this.subscriptionData.queued.data.forEach((dataItem) => { - dataCallback(dataItem); - }); - } - } - onClosed(closedCallback) { - if (typeof closedCallback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onClosed.push(closedCallback); - } - onFailed(callback) { - } - onConnected(callback) { - if (typeof callback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onConnected.push(callback); - } - close() { - this.subscriptionData.close(); - } - setNewSubscription(newSub) { - this.subscriptionData = newSub; - } - } - - class TimedCache { - config; - cache = []; - timeoutIds = []; - constructor(config) { - this.config = config; - } - add(element) { - const id = nanoid(10); - this.cache.push({ id, element }); - const timeoutId = setTimeout(() => { - const elementIdx = this.cache.findIndex((entry) => entry.id === id); - if (elementIdx < 0) { - return; - } - this.cache.splice(elementIdx, 1); - }, this.config.ELEMENT_TTL_MS); - this.timeoutIds.push(timeoutId); - } - flush() { - const elements = this.cache.map((entry) => entry.element); - this.timeoutIds.forEach((id) => clearInterval(id)); - this.cache = []; - this.timeoutIds = []; - return elements; - } - } - - const STATUS_AWAITING_ACCEPT = "awaitingAccept"; - const STATUS_SUBSCRIBED = "subscribed"; - const ERR_MSG_SUB_FAILED = "Subscription failed."; - const ERR_MSG_SUB_REJECTED = "Subscription rejected."; - const ON_CLOSE_MSG_SERVER_INIT = "ServerInitiated"; - const ON_CLOSE_MSG_CLIENT_INIT = "ClientInitiated"; - class ClientStreaming { - session; - repository; - logger; - subscriptionsList = {}; - timedCache = new TimedCache({ ELEMENT_TTL_MS: 10000 }); - subscriptionIdToLocalKeyMap = {}; - nextSubLocalKey = 0; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("subscribed", this.handleSubscribed); - session.on("event", this.handleEventData); - session.on("subscription-cancelled", this.handleSubscriptionCancelled); - } - subscribe(streamingMethod, params, targetServers, success, error, existingSub) { - if (targetServers.length === 0) { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " No available servers matched the target params.", - }); - return; - } - const subLocalKey = this.getNextSubscriptionLocalKey(); - const pendingSub = this.registerSubscription(subLocalKey, streamingMethod, params, success, error, params.methodResponseTimeout || 10000, existingSub); - if (typeof pendingSub !== "object") { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Unable to register the user callbacks.", - }); - return; - } - targetServers.forEach((target) => { - const serverId = target.server.id; - const method = target.methods.find((m) => m.name === streamingMethod.name); - if (!method) { - this.logger.error(`can not find method ${streamingMethod.name} for target ${target.server.id}`); - return; - } - pendingSub.trackedServers.push({ - serverId, - subscriptionId: undefined, - }); - const msg = { - type: "subscribe", - server_id: serverId, - method_id: method.gatewayId, - arguments_kv: params.arguments, - }; - this.session.send(msg, { serverId, subLocalKey }) - .then((m) => this.handleSubscribed(m)) - .catch((err) => this.handleErrorSubscribing(err)); - }); - } - drainSubscriptions() { - const existing = Object.values(this.subscriptionsList); - this.subscriptionsList = {}; - this.subscriptionIdToLocalKeyMap = {}; - return existing; - } - drainSubscriptionsCache() { - return this.timedCache.flush(); - } - getNextSubscriptionLocalKey() { - const current = this.nextSubLocalKey; - this.nextSubLocalKey += 1; - return current; - } - registerSubscription(subLocalKey, method, params, success, error, timeout, existingSub) { - const subsInfo = { - localKey: subLocalKey, - status: STATUS_AWAITING_ACCEPT, - method, - params, - success, - error, - trackedServers: [], - handlers: { - onData: existingSub?.handlers.onData || [], - onClosed: existingSub?.handlers.onClosed || [], - onConnected: existingSub?.handlers.onConnected || [], - }, - queued: { - data: [], - closers: [], - }, - timeoutId: undefined, - close: () => this.closeSubscription(subLocalKey), - subscription: existingSub?.subscription - }; - if (!existingSub) { - if (params.onData) { - subsInfo.handlers.onData.push(params.onData); - } - if (params.onClosed) { - subsInfo.handlers.onClosed.push(params.onClosed); - } - if (params.onConnected) { - subsInfo.handlers.onConnected.push(params.onConnected); - } - } - this.subscriptionsList[subLocalKey] = subsInfo; - subsInfo.timeoutId = setTimeout(() => { - if (this.subscriptionsList[subLocalKey] === undefined) { - return; - } - const pendingSub = this.subscriptionsList[subLocalKey]; - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - error({ - method, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Subscription attempt timed out after " + timeout + " ms.", - }); - delete this.subscriptionsList[subLocalKey]; - } - else if (pendingSub.status === STATUS_SUBSCRIBED && pendingSub.trackedServers.length > 0) { - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return (typeof server.subscriptionId !== "undefined"); - }); - delete pendingSub.timeoutId; - if (pendingSub.trackedServers.length <= 0) { - this.callOnClosedHandlers(pendingSub); - delete this.subscriptionsList[subLocalKey]; - } - } - }, timeout); - return subsInfo; - } - handleErrorSubscribing = (errorResponse) => { - const tag = errorResponse._tag; - const subLocalKey = tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return server.serverId !== tag.serverId; - }); - if (pendingSub.trackedServers.length <= 0) { - clearTimeout(pendingSub.timeoutId); - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - const reason = (typeof errorResponse.reason === "string" && errorResponse.reason !== "") ? - ' Publisher said "' + errorResponse.reason + '".' : - " No reason given."; - const callArgs = typeof pendingSub.params.arguments === "object" ? - JSON.stringify(pendingSub.params.arguments) : - "{}"; - pendingSub.error({ - message: ERR_MSG_SUB_REJECTED + reason + " Called with:" + callArgs, - called_with: pendingSub.params.arguments, - method: pendingSub.method, - }); - } - else if (pendingSub.status === STATUS_SUBSCRIBED) { - this.callOnClosedHandlers(pendingSub); - } - delete this.subscriptionsList[subLocalKey]; - } - }; - handleSubscribed = (msg) => { - const subLocalKey = msg._tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - const serverId = msg._tag.serverId; - const acceptingServer = pendingSub.trackedServers - .filter((server) => { - return server.serverId === serverId; - })[0]; - if (typeof acceptingServer !== "object") { - return; - } - acceptingServer.subscriptionId = msg.subscription_id; - this.subscriptionIdToLocalKeyMap[msg.subscription_id] = subLocalKey; - const isFirstResponse = (pendingSub.status === STATUS_AWAITING_ACCEPT); - pendingSub.status = STATUS_SUBSCRIBED; - if (isFirstResponse) { - let reconnect = false; - let sub = pendingSub.subscription; - if (sub) { - sub.setNewSubscription(pendingSub); - pendingSub.success(sub); - reconnect = true; - } - else { - sub = new UserSubscription(this.repository, pendingSub); - pendingSub.subscription = sub; - pendingSub.success(sub); - } - for (const handler of pendingSub.handlers.onConnected) { - try { - handler(sub.serverInstance, reconnect); - } - catch (e) { - } - } - } - }; - handleEventData = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const trackedServersFound = subscription.trackedServers.filter((s) => { - return s.subscriptionId === msg.subscription_id; - }); - if (trackedServersFound.length !== 1) { - return; - } - const isPrivateData = msg.oob; - const sendingServerId = trackedServersFound[0].serverId; - const server = this.repository.getServerById(sendingServerId); - const receivedStreamData = () => { - return { - data: msg.data, - server: server?.instance ?? {}, - requestArguments: subscription.params.arguments, - message: undefined, - private: isPrivateData, - }; - }; - const onDataHandlers = subscription.handlers.onData; - const queuedData = subscription.queued.data; - if (onDataHandlers.length > 0) { - onDataHandlers.forEach((callback) => { - if (typeof callback === "function") { - callback(receivedStreamData()); - } - }); - } - else { - queuedData.push(receivedStreamData()); - } - }; - handleSubscriptionCancelled = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const expectedNewLength = subscription.trackedServers.length - 1; - subscription.trackedServers = subscription.trackedServers.filter((server) => { - if (server.subscriptionId === msg.subscription_id) { - subscription.queued.closers.push(server.serverId); - return false; - } - else { - return true; - } - }); - if (subscription.trackedServers.length !== expectedNewLength) { - return; - } - if (subscription.trackedServers.length <= 0) { - this.timedCache.add(subscription); - clearTimeout(subscription.timeoutId); - this.callOnClosedHandlers(subscription); - delete this.subscriptionsList[subLocalKey]; - } - delete this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - }; - callOnClosedHandlers(subscription, reason) { - const closersCount = subscription.queued.closers.length; - const closingServerId = (closersCount > 0) ? subscription.queued.closers[closersCount - 1] : null; - let closingServer; - if (closingServerId !== undefined && typeof closingServerId === "string") { - closingServer = this.repository.getServerById(closingServerId)?.instance ?? {}; - } - subscription.handlers.onClosed.forEach((callback) => { - if (typeof callback !== "function") { - return; - } - callback({ - message: reason || ON_CLOSE_MSG_SERVER_INIT, - requestArguments: subscription.params.arguments || {}, - server: closingServer, - stream: subscription.method, - }); - }); - } - closeSubscription(subLocalKey) { - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - subscription.trackedServers.forEach((server) => { - if (typeof server.subscriptionId === "undefined") { - return; - } - subscription.queued.closers.push(server.serverId); - this.session.sendFireAndForget({ - type: "unsubscribe", - subscription_id: server.subscriptionId, - reason_uri: "", - reason: ON_CLOSE_MSG_CLIENT_INIT, - }).catch((err) => { - this.logger.warn(`Error sending unsubscribe for subscription id ${server.subscriptionId}: ${JSON.stringify(err)}`); - }); - delete this.subscriptionIdToLocalKeyMap[server.subscriptionId]; - }); - subscription.trackedServers = []; - this.callOnClosedHandlers(subscription, ON_CLOSE_MSG_CLIENT_INIT); - delete this.subscriptionsList[subLocalKey]; - } - } - - class ClientProtocol { - session; - repository; - logger; - streaming; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("peer-added", (msg) => this.handlePeerAdded(msg)); - session.on("peer-removed", (msg) => this.handlePeerRemoved(msg)); - session.on("methods-added", (msg) => this.handleMethodsAddedMessage(msg)); - session.on("methods-removed", (msg) => this.handleMethodsRemovedMessage(msg)); - this.streaming = new ClientStreaming(session, repository, logger); - } - subscribe(stream, options, targetServers, success, error, existingSub) { - this.streaming.subscribe(stream, options, targetServers, success, error, existingSub); - } - invoke(id, method, args, target) { - const serverId = target.id; - const methodId = method.gatewayId; - const msg = { - type: "call", - server_id: serverId, - method_id: methodId, - arguments_kv: args, - }; - return this.session.send(msg, { invocationId: id, serverId }) - .then((m) => this.handleResultMessage(m)) - .catch((err) => this.handleInvocationError(err)); - } - drainSubscriptions() { - return this.streaming.drainSubscriptions(); - } - drainSubscriptionsCache() { - return this.streaming.drainSubscriptionsCache(); - } - handlePeerAdded(msg) { - const newPeerId = msg.new_peer_id; - const remoteId = msg.identity; - const isLocal = msg.meta ? msg.meta.local : true; - const pid = Number(remoteId.process); - const serverInfo = { - machine: remoteId.machine, - pid: isNaN(pid) ? remoteId.process : pid, - instance: remoteId.instance, - application: remoteId.application, - applicationName: remoteId.applicationName, - environment: remoteId.environment, - region: remoteId.region, - user: remoteId.user, - windowId: remoteId.windowId, - peerId: newPeerId, - api: remoteId.api, - isLocal - }; - this.repository.addServer(serverInfo, newPeerId); - } - handlePeerRemoved(msg) { - const removedPeerId = msg.removed_id; - const reason = msg.reason; - this.repository.removeServerById(removedPeerId, reason); - } - handleMethodsAddedMessage(msg) { - const serverId = msg.server_id; - const methods = msg.methods; - methods.forEach((method) => { - this.repository.addServerMethod(serverId, method); - }); - } - handleMethodsRemovedMessage(msg) { - const serverId = msg.server_id; - const methodIdList = msg.methods; - const server = this.repository.getServerById(serverId); - if (server) { - const serverMethodKeys = Object.keys(server.methods); - serverMethodKeys.forEach((methodKey) => { - const method = server.methods[methodKey]; - if (methodIdList.indexOf(method.gatewayId) > -1) { - this.repository.removeServerMethod(serverId, methodKey); - } - }); - } - } - handleResultMessage(msg) { - const invocationId = msg._tag.invocationId; - const result = msg.result; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - return { - invocationId, - result, - instance: server?.instance, - status: InvokeStatus.Success, - message: "" - }; - } - handleInvocationError(msg) { - this.logger.debug(`handle invocation error ${JSON.stringify(msg)}`); - if ("_tag" in msg) { - const invocationId = msg._tag.invocationId; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - const message = msg.reason; - const context = msg.context; - return { - invocationId, - result: context, - instance: server?.instance, - status: InvokeStatus.Error, - message - }; - } - else { - return { - invocationId: "", - message: msg.message, - status: InvokeStatus.Error, - error: msg - }; - } - } - } - - function gW3ProtocolFactory (instance, connection, clientRepository, serverRepository, libConfig, interop) { - const logger = libConfig.logger.subLogger("gw3-protocol"); - let resolveReadyPromise; - const readyPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - const session = connection.domain("agm", ["subscribed"]); - const server = new ServerProtocol(session, clientRepository, serverRepository, logger.subLogger("server")); - const client = new ClientProtocol(session, clientRepository, logger.subLogger("client")); - async function handleReconnect() { - logger.info("reconnected - will replay registered methods and subscriptions"); - client.drainSubscriptionsCache().forEach((sub) => { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to soft-re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`soft-subscribing to method ${methodInfo.name} DONE`)).catch((error) => logger.warn(`subscribing to method ${methodInfo.name} failed: ${JSON.stringify(error)}}`)); - }); - const reconnectionPromises = []; - const existingSubscriptions = client.drainSubscriptions(); - for (const sub of existingSubscriptions) { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - reconnectionPromises.push(interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`subscribing to method ${methodInfo.name} DONE`))); - } - const registeredMethods = serverRepository.getList(); - serverRepository.reset(); - for (const method of registeredMethods) { - const def = method.definition; - if (method.stream) { - reconnectionPromises.push(interop.server.createStream(def, method.streamCallbacks, undefined, undefined, method.stream) - .then(() => logger.info(`subscribing to method ${def.name} DONE`)) - .catch(() => logger.warn(`subscribing to method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallback) { - reconnectionPromises.push(interop.register(def, method.theFunction.userCallback) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallbackAsync) { - reconnectionPromises.push(interop.registerAsync(def, method.theFunction.userCallbackAsync) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - } - await Promise.all(reconnectionPromises); - logger.info("Interop is re-announced"); - } - function handleInitialJoin() { - if (resolveReadyPromise) { - resolveReadyPromise({ - client, - server, - }); - resolveReadyPromise = undefined; - } - } - session.onJoined((reconnect) => { - clientRepository.addServer(instance, connection.peerId); - if (reconnect) { - handleReconnect().then(() => connection.setLibReAnnounced({ name: "interop" })).catch((error) => logger.warn(`Error while re-announcing interop: ${JSON.stringify(error)}`)); - } - else { - handleInitialJoin(); - } - }); - session.onLeft(() => { - clientRepository.reset(); - }); - session.join(); - return readyPromise; - } - - class Interop { - instance; - readyPromise; - client; - server; - unwrappedInstance; - protocol; - clientRepository; - serverRepository; - constructor(configuration) { - if (typeof configuration === "undefined") { - throw new Error("configuration is required"); - } - if (typeof configuration.connection === "undefined") { - throw new Error("configuration.connections is required"); - } - const connection = configuration.connection; - if (typeof configuration.methodResponseTimeout !== "number") { - configuration.methodResponseTimeout = 30 * 1000; - } - if (typeof configuration.waitTimeoutMs !== "number") { - configuration.waitTimeoutMs = 30 * 1000; - } - this.unwrappedInstance = new InstanceWrapper(this, undefined, connection); - this.instance = this.unwrappedInstance.unwrap(); - this.clientRepository = new ClientRepository(configuration.logger.subLogger("cRep"), this); - this.serverRepository = new ServerRepository(); - let protocolPromise; - if (connection.protocolVersion === 3) { - protocolPromise = gW3ProtocolFactory(this.instance, connection, this.clientRepository, this.serverRepository, configuration, this); - } - else { - throw new Error(`protocol ${connection.protocolVersion} not supported`); - } - this.readyPromise = protocolPromise.then((protocol) => { - this.protocol = protocol; - this.client = new Client(this.protocol, this.clientRepository, this.instance, configuration); - this.server = new Server(this.protocol, this.serverRepository); - return this; - }); - } - ready() { - return this.readyPromise; - } - serverRemoved(callback) { - return this.client.serverRemoved(callback); - } - serverAdded(callback) { - return this.client.serverAdded(callback); - } - serverMethodRemoved(callback) { - return this.client.serverMethodRemoved(callback); - } - serverMethodAdded(callback) { - return this.client.serverMethodAdded(callback); - } - methodRemoved(callback) { - return this.client.methodRemoved(callback); - } - methodAdded(callback) { - return this.client.methodAdded(callback); - } - methodsForInstance(instance) { - return this.client.methodsForInstance(instance); - } - methods(methodFilter) { - return this.client.methods(methodFilter); - } - servers(methodFilter) { - return this.client.servers(methodFilter); - } - subscribe(method, options, successCallback, errorCallback) { - return this.client.subscribe(method, options, successCallback, errorCallback); - } - createStream(streamDef, callbacks, successCallback, errorCallback) { - return this.server.createStream(streamDef, callbacks, successCallback, errorCallback); - } - unregister(methodFilter) { - return this.server.unregister(methodFilter); - } - registerAsync(methodDefinition, callback) { - return this.server.registerAsync(methodDefinition, callback); - } - register(methodDefinition, callback) { - return this.server.register(methodDefinition, callback); - } - invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - return this.client.invoke(methodFilter, argumentObj, target, additionalOptions, success, error); - } - waitForMethod(name) { - const pw = new PromiseWrapper(); - const unsubscribe = this.client.methodAdded((m) => { - if (m.name === name) { - unsubscribe(); - pw.resolve(m); - } - }); - return pw.promise; - } - } - - const successMessages = ["subscribed", "success"]; - class MessageBus { - connection; - logger; - peerId; - session; - subscriptions; - readyPromise; - constructor(connection, logger) { - this.connection = connection; - this.logger = logger; - this.peerId = connection.peerId; - this.subscriptions = []; - this.session = connection.domain("bus", successMessages); - this.readyPromise = this.session.join(); - this.readyPromise.then(() => { - this.watchOnEvent(); - }); - } - ready() { - return this.readyPromise; - } - publish = (topic, data, options) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "publish", - topic, - data, - peer_id: this.peerId, - routing_key: routingKey, - target_identity: target - }); - this.session.send(args) - .catch((err) => { - this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`); - }); - }; - subscribe = (topic, callback, options) => { - return new Promise((resolve, reject) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "subscribe", - topic, - peer_id: this.peerId, - routing_key: routingKey, - source: target - }); - this.session.send(args) - .then((response) => { - const { subscription_id } = response; - this.subscriptions.push({ subscription_id, topic, callback, source: target }); - resolve({ - unsubscribe: () => { - this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId }) - .then(() => { - this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id); - }).catch((err) => { - this.logger.warn(`Failed to send unsubscribe request for ${subscription_id}: ${JSON.stringify(err)}`); - }); - return Promise.resolve(); - } - }); - }) - .catch((error) => reject(error)); - }); - }; - watchOnEvent = () => { - this.session.on("event", (args) => { - const { data, subscription_id } = args; - const source = args["publisher-identity"]; - const subscription = this.subscriptions.find((s) => s.subscription_id === subscription_id); - if (subscription) { - if (!subscription.source) { - subscription.callback(data, subscription.topic, source); - } - else { - if (this.keysMatch(subscription.source, source)) { - subscription.callback(data, subscription.topic, source); - } - } - } - }); - }; - removeEmptyValues(obj) { - const cleaned = {}; - Object.keys(obj).forEach((key) => { - if (obj[key] !== undefined && obj[key] !== null) { - cleaned[key] = obj[key]; - } - }); - return cleaned; - } - keysMatch(obj1, obj2) { - const keysObj1 = Object.keys(obj1); - let allMatch = true; - keysObj1.forEach((key) => { - if (obj1[key] !== obj2[key]) { - allMatch = false; - } - }); - return allMatch; - } - } - - const IOConnectCoreFactory = (userConfig, ext) => { - const iodesktop = typeof window === "object" ? (window.iodesktop ?? window.glue42gd) : undefined; - const preloadPromise = typeof window === "object" ? (window.gdPreloadPromise ?? Promise.resolve()) : Promise.resolve(); - const glueInitTimer = timer("glue"); - userConfig = userConfig || {}; - ext = ext || {}; - const internalConfig = prepareConfig(userConfig, ext, iodesktop); - let _connection; - let _interop; - let _logger; - let _metrics; - let _contexts; - let _bus; - let _allowTrace; - const libs = {}; - function registerLib(name, inner, t) { - _allowTrace = _logger.canPublish("trace"); - if (_allowTrace) { - _logger.trace(`registering ${name} module`); - } - const done = (e) => { - inner.initTime = t.stop(); - inner.initEndTime = t.endTime; - inner.marks = t.marks; - if (!_allowTrace) { - return; - } - const traceMessage = e ? - `${name} failed - ${e.message}` : - `${name} is ready - ${t.endTime - t.startTime}`; - _logger.trace(traceMessage); - }; - inner.initStartTime = t.startTime; - if (inner.ready) { - inner.ready() - .then(() => { - done(); - }) - .catch((e) => { - const error = typeof e === "string" ? new Error(e) : e; - done(error); - }); - } - else { - done(); - } - if (!Array.isArray(name)) { - name = [name]; - } - name.forEach((n) => { - libs[n] = inner; - IOConnectCoreFactory[n] = inner; - }); - } - function setupConnection() { - const initTimer = timer("connection"); - _connection = new Connection(internalConfig.connection, _logger.subLogger("connection")); - let authPromise = Promise.resolve(internalConfig.auth); - if (internalConfig.connection && !internalConfig.auth) { - if (iodesktop) { - authPromise = iodesktop.getGWToken() - .then((token) => { - return { - gatewayToken: token - }; - }); - } - else if (typeof window !== "undefined" && window?.glue42electron) { - if (typeof window.glue42electron.gwToken === "string") { - authPromise = Promise.resolve({ - gatewayToken: window.glue42electron.gwToken - }); - } - } - else { - authPromise = Promise.reject("You need to provide auth information"); - } - } - return authPromise - .then((authConfig) => { - initTimer.mark("auth-promise-resolved"); - let authRequest; - if (Object.prototype.toString.call(authConfig) === "[object Object]") { - authRequest = authConfig; - } - else { - throw new Error("Invalid auth object - " + JSON.stringify(authConfig)); - } - return _connection.login(authRequest); - }) - .then(() => { - registerLib("connection", _connection, initTimer); - return internalConfig; - }) - .catch((e) => { - if (_connection) { - _connection.logout(); - } - throw e; - }); - } - function setupLogger() { - const initTimer = timer("logger"); - _logger = new Logger(`${internalConfig.connection.identity?.application}`, undefined, internalConfig.customLogger); - _logger.consoleLevel(internalConfig.logger.console); - _logger.publishLevel(internalConfig.logger.publish); - if (_logger.canPublish("debug")) { - _logger.debug("initializing glue..."); - } - registerLib("logger", _logger, initTimer); - return Promise.resolve(undefined); - } - function setupMetrics() { - const initTimer = timer("metrics"); - const config = internalConfig.metrics; - const metricsPublishingEnabledFunc = iodesktop?.getMetricsPublishingEnabled; - const identity = internalConfig.connection.identity; - const canUpdateMetric = metricsPublishingEnabledFunc ? metricsPublishingEnabledFunc : () => true; - const disableAutoAppSystem = (typeof config !== "boolean" && config.disableAutoAppSystem) ?? false; - _metrics = metrics({ - connection: config ? _connection : undefined, - logger: _logger.subLogger("metrics"), - canUpdateMetric, - system: "Glue42", - service: identity?.service ?? iodesktop?.applicationName ?? internalConfig.application, - instance: identity?.instance ?? identity?.windowId ?? nanoid(10), - disableAutoAppSystem, - pagePerformanceMetrics: typeof config !== "boolean" ? config?.pagePerformanceMetrics : undefined - }); - registerLib("metrics", _metrics, initTimer); - return Promise.resolve(); - } - function setupInterop() { - const initTimer = timer("interop"); - const agmConfig = { - connection: _connection, - logger: _logger.subLogger("interop"), - }; - _interop = new Interop(agmConfig); - Logger.Interop = _interop; - registerLib(["interop", "agm"], _interop, initTimer); - return Promise.resolve(); - } - function setupContexts() { - const hasActivities = (internalConfig.activities && _connection.protocolVersion === 3); - const needsContexts = internalConfig.contexts || hasActivities; - if (needsContexts) { - const initTimer = timer("contexts"); - _contexts = new ContextsModule({ - connection: _connection, - logger: _logger.subLogger("contexts"), - trackAllContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.trackAllContexts : false, - reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false, - subscribeOnGet: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnGet : true, - subscribeOnUpdate: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnUpdate : true, - onlyReAnnounceSubscribedContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.onlyReAnnounceSubscribedContexts : true - }); - registerLib("contexts", _contexts, initTimer); - } - else { - const replayer = _connection.replayer; - if (replayer) { - replayer.drain(ContextMessageReplaySpec.name); - } - } - return Promise.resolve(); - } - async function setupBus() { - if (!internalConfig.bus) { - return Promise.resolve(); - } - const initTimer = timer("bus"); - _bus = new MessageBus(_connection, _logger.subLogger("bus")); - registerLib("bus", _bus, initTimer); - return Promise.resolve(); - } - function setupExternalLibs(externalLibs) { - try { - externalLibs.forEach((lib) => { - setupExternalLib(lib.name, lib.create); - }); - return Promise.resolve(); - } - catch (e) { - return Promise.reject(e); - } - } - function setupExternalLib(name, createCallback) { - const initTimer = timer(name); - const lib = createCallback(libs); - if (lib) { - registerLib(name, lib, initTimer); - } - } - function waitForLibs() { - const libsReadyPromises = Object.keys(libs).map((key) => { - const lib = libs[key]; - return lib.ready ? - lib.ready() : Promise.resolve(); - }); - return Promise.all(libsReadyPromises); - } - function constructGlueObject() { - const feedbackFunc = (feedbackInfo) => { - if (!_interop) { - return; - } - _interop.invoke("T42.ACS.Feedback", feedbackInfo, "best"); - }; - const info = { - coreVersion: version, - version: internalConfig.version - }; - glueInitTimer.stop(); - const glue = { - feedback: feedbackFunc, - info, - logger: _logger, - interop: _interop, - agm: _interop, - connection: _connection, - metrics: _metrics, - contexts: _contexts, - bus: _bus, - version: internalConfig.version, - userConfig, - done: () => { - _logger?.info("done called by user..."); - return _connection.logout(); - } - }; - glue.performance = { - get glueVer() { - return internalConfig.version; - }, - get glueConfig() { - return JSON.stringify(userConfig); - }, - get browser() { - return window.performance.timing.toJSON(); - }, - get memory() { - return window.performance.memory; - }, - get initTimes() { - const all = getAllTimers(); - return Object.keys(all).map((key) => { - const t = all[key]; - return { - name: key, - duration: t.endTime - t.startTime, - marks: t.marks, - startTime: t.startTime, - endTime: t.endTime - }; - }); - } - }; - Object.keys(libs).forEach((key) => { - const lib = libs[key]; - glue[key] = lib; - }); - glue.config = {}; - Object.keys(internalConfig).forEach((k) => { - glue.config[k] = internalConfig[k]; - }); - if (ext && ext.extOptions) { - Object.keys(ext.extOptions).forEach((k) => { - glue.config[k] = ext?.extOptions[k]; - }); - } - if (ext?.enrichGlue) { - ext.enrichGlue(glue); - } - if (iodesktop && iodesktop.updatePerfData) { - iodesktop.updatePerfData(glue.performance); - } - if (glue.agm) { - const deprecatedDecorator = (fn, wrong, proper) => { - return function () { - glue.logger.warn(`glue.js - 'glue.agm.${wrong}' method is deprecated, use 'glue.interop.${proper}' instead.`); - return fn.apply(glue.agm, arguments); - }; - }; - const agmAny = glue.agm; - agmAny.method_added = deprecatedDecorator(glue.agm.methodAdded, "method_added", "methodAdded"); - agmAny.method_removed = deprecatedDecorator(glue.agm.methodRemoved, "method_removed", "methodRemoved"); - agmAny.server_added = deprecatedDecorator(glue.agm.serverAdded, "server_added", "serverAdded"); - agmAny.server_method_aded = deprecatedDecorator(glue.agm.serverMethodAdded, "server_method_aded", "serverMethodAdded"); - agmAny.server_method_removed = deprecatedDecorator(glue.agm.serverMethodRemoved, "server_method_removed", "serverMethodRemoved"); - } - return glue; - } - async function registerInstanceIfNeeded() { - const RegisterInstanceMethodName = "T42.ACS.RegisterInstance"; - if (Utils.isNode() && typeof process.env._GD_STARTING_CONTEXT_ === "undefined" && typeof userConfig?.application !== "undefined") { - const isMethodAvailable = _interop.methods({ name: RegisterInstanceMethodName }).length > 0; - if (isMethodAvailable) { - try { - await _interop.invoke(RegisterInstanceMethodName, { appName: userConfig?.application, pid: process.pid }); - } - catch (error) { - const typedError = error; - _logger.error(`Cannot register as an instance: ${JSON.stringify(typedError.message)}`); - } - } - } - } - return preloadPromise - .then(setupLogger) - .then(setupConnection) - .then(() => Promise.all([setupMetrics(), setupInterop(), setupContexts(), setupBus()])) - .then(() => _interop.readyPromise) - .then(() => registerInstanceIfNeeded()) - .then(() => { - return setupExternalLibs(internalConfig.libs || []); - }) - .then(waitForLibs) - .then(constructGlueObject) - .catch((err) => { - return Promise.reject({ - err, - libs - }); - }); - }; - if (typeof window !== "undefined") { - window.IOConnectCore = IOConnectCoreFactory; - } - IOConnectCoreFactory.version = version; - IOConnectCoreFactory.default = IOConnectCoreFactory; - - const iOConnectBrowserFactory = createFactoryFunction(IOConnectCoreFactory); - if (typeof window !== "undefined") { - const windowAny = window; - windowAny.IOBrowser = iOConnectBrowserFactory; - delete windowAny.GlueCore; - delete windowAny.IOConnectCore; - } - const legacyGlobal = window.glue42gd || window.glue42core; - const ioGlobal = window.iodesktop || window.iobrowser; - if (!legacyGlobal && !ioGlobal) { - window.iobrowser = { webStarted: false }; - } - if (!window.iodesktop && !window.iobrowser.system) { - window.iobrowser.system = setupGlobalSystem(); - } - iOConnectBrowserFactory.version = version$1; - - return iOConnectBrowserFactory; - -})); -//# sourceMappingURL=browser.umd.js.map diff --git a/javascript/solution/portfolio-downloader/package-lock.json b/javascript/solution/portfolio-downloader/package-lock.json new file mode 100644 index 0000000..bfbc981 --- /dev/null +++ b/javascript/solution/portfolio-downloader/package-lock.json @@ -0,0 +1,1279 @@ +{ + "name": "portfolio-downloader", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "portfolio-downloader", + "version": "1.0.0", + "dependencies": { + "@interopio/browser": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@interopio/browser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser/-/browser-4.2.4.tgz", + "integrity": "sha512-BPgkwH6N8HyGf7st99ZJwQ7arijz9j1bGu7pUAXBrtbv6cu4zH5GR7JKPGANZmFl0uefNPQyAQ4hc7C/i1i++A==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0", + "@interopio/search-api": "^3.2.1", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.2" + } + }, + "node_modules/@interopio/core": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@interopio/core/-/core-6.8.1.tgz", + "integrity": "sha512-WFWIV8JilNuAcxXaB+81IjL9j82sU73ABMUUEOWpvWoyqxhPlneOS+rSYViFX5gdk5pLH3fM6T/MmRGn3UFLwQ==", + "license": "MIT", + "dependencies": { + "callback-registry": "^2.7.2", + "ws": "^8.18.0" + } + }, + "node_modules/@interopio/desktop": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/@interopio/desktop/-/desktop-6.18.0.tgz", + "integrity": "sha512-YqRHRiCymbY2fOCT2HHJnLY4780JSRI1fUtaWEoIa5Z3djZk/3xRgVxIjOVw9Y/TAFGCwyIeW142a7HYnSGD5Q==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/schemas": "^10.1.0", + "@interopio/utils": "^1.4.2", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.1" + } + }, + "node_modules/@interopio/schemas": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@interopio/schemas/-/schemas-10.1.0.tgz", + "integrity": "sha512-8uDEoOAZenTr4a3O8vLq6JyS/LutkT/gh9EjuOrS9fOmHEUfJaS2u+qPo5em9/8MtjKgblZEJStSsW1gr34CtQ==", + "license": "ISC", + "dependencies": { + "ajv": "^6.12.6", + "ajv-keywords": "^3.4.1" + }, + "peerDependencies": { + "log4js": "^6.4.2" + }, + "peerDependenciesMeta": { + "log4js": { + "optional": true + } + } + }, + "node_modules/@interopio/search-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@interopio/search-api/-/search-api-3.2.1.tgz", + "integrity": "sha512-raUZzqBQoidm/6Mvgao2wFWlTDu9D4jghiX1dqor1LdsIfUpelJkkuFGeDl0z/3DWneaxDF8Vc/uoBtLz7qJLw==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1" + } + }, + "node_modules/@interopio/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@interopio/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-14Bb2WI9Cwf9zjhTurP4qP9AVY4cxR1AOrwrOtHrTGAeeHp88mALFWfMEv1QnRhlQ06To2vQcRgebNrPlHDZ8Q==", + "license": "ISC", + "dependencies": { + "decoder-validate": "^0.0.2" + } + }, + "node_modules/@interopio/workspaces-api": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@interopio/workspaces-api/-/workspaces-api-4.2.3.tgz", + "integrity": "sha512-5wrR1yhETKuX4txVrmS5q3G+8KI6GW4yOxsrVdf5qErO2HxN938XUdiAHIesarwlQoncrgnVx7uTn6IeOWUoXg==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/callback-registry": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/callback-registry/-/callback-registry-2.7.2.tgz", + "integrity": "sha512-VVrtF21DaH0VHeNMkLDd4VGuxsYM3V3l3lwYneKVMU/6X3TRtcQszUwlAcqj2HrLcbP1NyS12LsanUwCykaz/Q==", + "license": "ISC" + }, + "node_modules/decoder-validate": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/decoder-validate/-/decoder-validate-0.0.2.tgz", + "integrity": "sha512-9BsqAH9Zq6CvlxKHkSrZrH2iYlhuhHcrh6uTnDvcsa9P5YEweEzt1ci+X/9STgSCE7b9BA7/QIiwhfUDDWmjxw==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/javascript/solution/portfolio-downloader/package.json b/javascript/solution/portfolio-downloader/package.json new file mode 100644 index 0000000..28168ef --- /dev/null +++ b/javascript/solution/portfolio-downloader/package.json @@ -0,0 +1,13 @@ +{ + "name": "portfolio-downloader", + "version": "1.0.0", + "scripts": { + "start": "vite --port 9400" + }, + "dependencies": { + "@interopio/browser": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } +} diff --git a/javascript/solution/stocks/index.html b/javascript/solution/stocks/index.html index 0d34f89..d04d0e1 100644 --- a/javascript/solution/stocks/index.html +++ b/javascript/solution/stocks/index.html @@ -12,10 +12,8 @@ - - - + diff --git a/javascript/solution/stocks/index.js b/javascript/solution/stocks/index.js index f94e656..910516e 100644 --- a/javascript/solution/stocks/index.js +++ b/javascript/solution/stocks/index.js @@ -1,3 +1,6 @@ +import IOBrowser from '@interopio/browser'; +import IOWorkspaces from '@interopio/workspaces-api'; + let clientPortfolioStocks; let clientName; diff --git a/javascript/solution/stocks/lib/browser.umd.js b/javascript/solution/stocks/lib/browser.umd.js deleted file mode 100644 index a5e6fcb..0000000 --- a/javascript/solution/stocks/lib/browser.umd.js +++ /dev/null @@ -1,17399 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.browser = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs$1 (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) - }; - - function isNonNullObject(value) { - return !!value && typeof value === 'object' - } - - function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); - - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) - } - - // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 - var canUseSymbol = typeof Symbol === 'function' && Symbol.for; - var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; - - function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE - } - - function emptyTarget(val) { - return Array.isArray(val) ? [] : {} - } - - function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value - } - - function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) - } - - function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge - } - - function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return Object.propertyIsEnumerable.call(target, symbol) - }) - : [] - } - - function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) - } - - function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } - } - - // Protects from prototype poisoning and unexpected merging up the prototype chain. - function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. - } - - function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } - - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination - } - - function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; - - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } - } - - deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } - - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) - }; - - var deepmerge_1 = deepmerge; - - var cjs = deepmerge_1; - - var deepmerge$1 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$2 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$2 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$2 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$2 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$2 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$2 = function (f, r) { - return r.ok === true ? ok$2(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$2(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$2 = function (f, r) { - return r.ok === true ? r : err$2(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$2 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$2 = function() { - __assign$2 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - - function __rest$2(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$2(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$2(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$2(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$2 = function (json) { return Array.isArray(json); }; - var isJsonObject$2 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$2(json); - }; - var typeString$2 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$2 = function (expected, got) { - return "expected " + expected + ", got " + typeString$2(got); - }; - var printPath$2 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$2 = function (newAt, _a) { - var at = _a.at, rest = __rest$2(_a, ["at"]); - return (__assign$2({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$2 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$2(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$2(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$2(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$2(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$2(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$2(json) - : err$2({ message: expectedGot$2('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$2(json) - : err$2({ message: expectedGot$2('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$2(json) - : err$2({ message: expectedGot$2('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$2(json, value) - ? ok$2(value) - : err$2({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$2(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$2({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else if (isJsonObject$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$2(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$2(function (err$$1) { return prependAt$2("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$2([])); - } - else if (isJsonArray$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$2(json)) { - if (json.length !== decoders.length) { - return err$2({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$2(prependAt$2("[" + i + "]", nth.error)); - } - } - return ok$2(result); - } - else { - return err$2({ message: expectedGot$2("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$2(Object.assign, acc, decoder.decode(json)); }, ok$2({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$2(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$2(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$2(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$2(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$2({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$2(withDefault$2(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$2(function (error) { - return jsonAtPath === undefined - ? { at: printPath$2(paths), message: 'path does not exist' } - : prependAt$2(printPath$2(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$2(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$2({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$2 = Decoder$2.string; - /** See `Decoder.number` */ - var number$2 = Decoder$2.number; - /** See `Decoder.boolean` */ - var boolean$2 = Decoder$2.boolean; - /** See `Decoder.anyJson` */ - var anyJson$2 = Decoder$2.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$2.unknownJson; - /** See `Decoder.constant` */ - var constant$2 = Decoder$2.constant; - /** See `Decoder.object` */ - var object$2 = Decoder$2.object; - /** See `Decoder.array` */ - var array$2 = Decoder$2.array; - /** See `Decoder.tuple` */ - Decoder$2.tuple; - /** See `Decoder.dict` */ - Decoder$2.dict; - /** See `Decoder.optional` */ - var optional$2 = Decoder$2.optional; - /** See `Decoder.oneOf` */ - var oneOf$1 = Decoder$2.oneOf; - /** See `Decoder.union` */ - var union$1 = Decoder$2.union; - /** See `Decoder.intersection` */ - var intersection = Decoder$2.intersection; - /** See `Decoder.withDefault` */ - Decoder$2.withDefault; - /** See `Decoder.valueAt` */ - Decoder$2.valueAt; - /** See `Decoder.succeed` */ - Decoder$2.succeed; - /** See `Decoder.fail` */ - Decoder$2.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder$2.lazy; - - const defaultConfig = { - gateway: { webPlatform: {} }, - libraries: [], - exposeAPI: true, - }; - const defaultWidgetConfig = { - awaitFactory: true, - enable: false, - timeout: 5 * 1000, - restoreLastKnownPosition: true, - }; - const defaultModalsConfig = { - alerts: { - enabled: false - }, - dialogs: { - enabled: false - }, - awaitFactory: true, - timeout: 5 * 1000, - }; - const defaultIntentResolverConfig = { - enable: false, - timeout: 5 * 1000, - awaitFactory: true, - }; - - const Glue42CoreMessageTypes = { - platformUnload: { name: "platformUnload" }, - transportSwitchRequest: { name: "transportSwitchRequest" }, - transportSwitchResponse: { name: "transportSwitchResponse" }, - getCurrentTransport: { name: "getCurrentTransport" }, - getCurrentTransportResponse: { name: "getCurrentTransportResponse" }, - checkPreferredLogic: { name: "checkPreferredLogic" }, - checkPreferredConnection: { name: "checkPreferredConnection" }, - checkPreferredLogicResponse: { name: "checkPreferredLogicResponse" }, - checkPreferredConnectionResponse: { name: "checkPreferredConnectionResponse" } - }; - const webPlatformTransportName = "web-platform"; - const latestFDC3Type = "latest_fdc3_type"; - const errorChannel = new MessageChannel(); - const REQUEST_WIDGET_READY = "requestWidgetFactoryReady"; - const REQUEST_MODALS_UI_FACTORY_READY = "requestModalsUIFactoryReady"; - const MAX_SET_TIMEOUT_DELAY = 2147483647; - const REQUEST_INTENT_RESOLVER_UI_FACTORY_READY = "requestIntentResolverUIFactoryReady"; - const READONLY_PROPERTY_DESCRIPTOR = { - configurable: false, - enumerable: true, - writable: false, - }; - - const extractErrorMsg = (error) => { - if (typeof error === "string") { - return error; - } - if (error?.message) { - return typeof error.message === "string" ? error.message : JSON.stringify(error.message); - } - return JSON.stringify(error); - }; - const runDecoderWithIOError = (decoder, json) => { - try { - const result = decoder.runWithException(json); - return result; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const getSupportedOperationsNames = (operations) => { - return Object.keys(operations).filter((operation) => (operations)[operation].execute); - }; - const handleOperationCheck = (supportedOperations, operationName) => { - const isSupported = supportedOperations.some((operation) => operation.toLowerCase() === operationName.toLowerCase()); - return { isSupported }; - }; - const getSafeTimeoutDelay = (delay) => { - return Math.min(delay, MAX_SET_TIMEOUT_DELAY); - }; - const wrapPromise = () => { - let wrapperResolve; - let wrapperReject; - const promise = new Promise((resolve, reject) => { - wrapperResolve = resolve; - wrapperReject = reject; - }); - return { promise, resolve: wrapperResolve, reject: wrapperReject }; - }; - - class IOError { - raiseError(error, shouldThrowOriginalError) { - const errorMessage = extractErrorMsg(error); - errorChannel.port1.postMessage(errorMessage); - if (shouldThrowOriginalError) { - throw error; - } - throw new Error(errorMessage); - } - } - const ioError = new IOError(); - - const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"]; - const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"]; - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$1 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$1 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$1 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$1 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$1 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$1 = function (f, r) { - return r.ok === true ? ok$1(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$1 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$1(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$1 = function (f, r) { - return r.ok === true ? r : err$1(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$1 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$1 = function() { - __assign$1 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - - function __rest$1(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$1(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$1(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$1(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$1 = function (json) { return Array.isArray(json); }; - var isJsonObject$1 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$1(json); - }; - var typeString$1 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$1 = function (expected, got) { - return "expected " + expected + ", got " + typeString$1(got); - }; - var printPath$1 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$1 = function (newAt, _a) { - var at = _a.at, rest = __rest$1(_a, ["at"]); - return (__assign$1({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$1 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$1(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$1(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$1(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$1(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$1(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$1(json) - : err$1({ message: expectedGot$1('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$1(json) - : err$1({ message: expectedGot$1('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$1(json) - : err$1({ message: expectedGot$1('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$1(json, value) - ? ok$1(value) - : err$1({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$1(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$1({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else if (isJsonObject$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$1(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$1(function (err$$1) { return prependAt$1("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$1(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$1([])); - } - else if (isJsonArray$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$1(json)) { - if (json.length !== decoders.length) { - return err$1({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$1(prependAt$1("[" + i + "]", nth.error)); - } - } - return ok$1(result); - } - else { - return err$1({ message: expectedGot$1("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$1(Object.assign, acc, decoder.decode(json)); }, ok$1({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$1(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$1(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$1(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$1(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$1({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$1(withDefault$1(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$1(function (error) { - return jsonAtPath === undefined - ? { at: printPath$1(paths), message: 'path does not exist' } - : prependAt$1(printPath$1(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$1(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$1({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$1 = Decoder$1.string; - /** See `Decoder.number` */ - var number$1 = Decoder$1.number; - /** See `Decoder.boolean` */ - var boolean$1 = Decoder$1.boolean; - /** See `Decoder.anyJson` */ - var anyJson$1 = Decoder$1.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$1.unknownJson; - /** See `Decoder.constant` */ - var constant$1 = Decoder$1.constant; - /** See `Decoder.object` */ - var object$1 = Decoder$1.object; - /** See `Decoder.array` */ - var array$1 = Decoder$1.array; - /** See `Decoder.tuple` */ - Decoder$1.tuple; - /** See `Decoder.dict` */ - var dict = Decoder$1.dict; - /** See `Decoder.optional` */ - var optional$1 = Decoder$1.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder$1.oneOf; - /** See `Decoder.union` */ - Decoder$1.union; - /** See `Decoder.intersection` */ - Decoder$1.intersection; - /** See `Decoder.withDefault` */ - Decoder$1.withDefault; - /** See `Decoder.valueAt` */ - Decoder$1.valueAt; - /** See `Decoder.succeed` */ - Decoder$1.succeed; - /** See `Decoder.fail` */ - Decoder$1.fail; - /** See `Decoder.lazy` */ - Decoder$1.lazy; - - const nonEmptyStringDecoder$3 = string$1().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$3 = number$1().where((num) => num >= 0, "Expected a non-negative number"); - const regexDecoder = anyJson$1().andThen((value) => { - return value instanceof RegExp ? anyJson$1() : fail(`expected a regex, got a ${typeof value}`); - }); - - const intentDefinitionDecoder$1 = object$1({ - name: nonEmptyStringDecoder$3, - displayName: optional$1(string$1()), - contexts: optional$1(array$1(string$1())), - customConfig: optional$1(object$1()) - }); - const v2TypeDecoder = oneOf(constant$1("web"), constant$1("native"), constant$1("citrix"), constant$1("onlineNative"), constant$1("other")); - const v2DetailsDecoder = object$1({ - url: nonEmptyStringDecoder$3 - }); - const v2IconDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3) - }); - const v2ScreenshotDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3), - label: optional$1(nonEmptyStringDecoder$3) - }); - const v2ListensForIntentDecoder = object$1({ - contexts: array$1(nonEmptyStringDecoder$3), - displayName: optional$1(nonEmptyStringDecoder$3), - resultType: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(anyJson$1()) - }); - const v2IntentsDecoder = object$1({ - listensFor: optional$1(dict(v2ListensForIntentDecoder)), - raises: optional$1(dict(array$1(nonEmptyStringDecoder$3))) - }); - const v2UserChannelDecoder = object$1({ - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2AppChannelDecoder = object$1({ - name: nonEmptyStringDecoder$3, - description: optional$1(nonEmptyStringDecoder$3), - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2InteropDecoder = object$1({ - intents: optional$1(v2IntentsDecoder), - userChannels: optional$1(v2UserChannelDecoder), - appChannels: optional$1(array$1(v2AppChannelDecoder)) - }); - const glue42ApplicationDetailsDecoder = object$1({ - url: optional$1(nonEmptyStringDecoder$3), - top: optional$1(number$1()), - left: optional$1(number$1()), - width: optional$1(nonNegativeNumberDecoder$3), - height: optional$1(nonNegativeNumberDecoder$3) - }); - const glue42HostManifestsBrowserDecoder = object$1({ - name: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3.where((s) => s === "window", "Expected a value of window")), - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - customProperties: optional$1(anyJson$1()), - icon: optional$1(string$1()), - caption: optional$1(string$1()), - details: optional$1(glue42ApplicationDetailsDecoder), - intents: optional$1(array$1(intentDefinitionDecoder$1)), - hidden: optional$1(boolean$1()) - }); - const v1DefinitionDecoder = object$1({ - name: nonEmptyStringDecoder$3, - appId: nonEmptyStringDecoder$3, - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - manifest: nonEmptyStringDecoder$3, - manifestType: nonEmptyStringDecoder$3, - tooltip: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - images: optional$1(array$1(object$1({ url: optional$1(nonEmptyStringDecoder$3) }))), - icons: optional$1(array$1(object$1({ icon: optional$1(nonEmptyStringDecoder$3) }))), - customConfig: anyJson$1(), - intents: optional$1(array$1(intentDefinitionDecoder$1)) - }); - const v2LocalizedDefinitionDecoder = object$1({ - appId: optional$1(nonEmptyStringDecoder$3), - name: optional$1(nonEmptyStringDecoder$3), - details: optional$1(v2DetailsDecoder), - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder) - }); - const v2DefinitionDecoder = object$1({ - appId: nonEmptyStringDecoder$3, - name: optional$1(nonEmptyStringDecoder$3), - type: v2TypeDecoder, - details: v2DetailsDecoder, - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder), - localizedVersions: optional$1(dict(v2LocalizedDefinitionDecoder)) - }); - const allDefinitionsDecoder = oneOf(v1DefinitionDecoder, v2DefinitionDecoder); - - const parseDecoderErrorToStringMessage = (error) => { - return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`; - }; - - class FDC3Service { - fdc3ToDesktopDefinitionType = { - web: "window", - native: "exe", - citrix: "citrix", - onlineNative: "clickonce", - other: "window" - }; - toApi() { - return { - isFdc3Definition: this.isFdc3Definition.bind(this), - parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this), - parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this) - }; - } - isFdc3Definition(definition) { - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - return { isFdc3: false, reason: parseDecoderErrorToStringMessage(decodeRes.error) }; - } - if (definition.appId && definition.details) { - return { isFdc3: true, version: "2.0" }; - } - if (definition.manifest) { - return { isFdc3: true, version: "1.2" }; - } - return { isFdc3: false, reason: "The passed definition is not FDC3" }; - } - parseToBrowserBaseAppData(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - const userProperties = this.getUserPropertiesFromDefinition(definition, version); - const createOptions = { url: this.getUrl(definition, version) }; - const baseApplicationData = { - name: definition.appId, - type: "window", - createOptions, - userProperties: { - ...userProperties, - intents: version === "1.2" - ? userProperties.intents - : this.getIntentsFromV2AppDefinition(definition), - details: createOptions - }, - title: definition.title, - version: definition.version, - icon: this.getIconFromDefinition(definition, version), - caption: definition.description, - fdc3: version === "2.0" ? { ...definition, definitionVersion: "2.0" } : undefined, - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return baseApplicationData; - } - const ioDefinitionDecodeRes = glue42HostManifestsBrowserDecoder.run(ioConnectDefinition); - if (!ioDefinitionDecodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(ioDefinitionDecodeRes.error)}`); - } - if (!Object.keys(ioDefinitionDecodeRes.result).length) { - return baseApplicationData; - } - return this.mergeBaseAppDataWithGlueManifest(baseApplicationData, ioDefinitionDecodeRes.result); - } - parseToDesktopAppConfig(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - if (version === "1.2") { - const fdc3v1Definition = definition; - return { - name: fdc3v1Definition.appId, - type: "window", - details: { - url: this.getUrl(definition, version) - }, - version: fdc3v1Definition.version, - title: fdc3v1Definition.title, - tooltip: fdc3v1Definition.tooltip, - caption: fdc3v1Definition.description, - icon: fdc3v1Definition.icons?.[0].icon, - intents: fdc3v1Definition.intents, - customProperties: { - manifestType: fdc3v1Definition.manifestType, - images: fdc3v1Definition.images, - contactEmail: fdc3v1Definition.contactEmail, - supportEmail: fdc3v1Definition.supportEmail, - publisher: fdc3v1Definition.publisher, - icons: fdc3v1Definition.icons, - customConfig: fdc3v1Definition.customConfig - } - }; - } - const fdc3v2Definition = definition; - const desktopDefinition = { - name: fdc3v2Definition.appId, - type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type], - details: fdc3v2Definition.details, - version: fdc3v2Definition.version, - title: fdc3v2Definition.title, - tooltip: fdc3v2Definition.tooltip, - caption: fdc3v2Definition.description, - icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"), - intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition), - fdc3: { ...fdc3v2Definition, definitionVersion: "2.0" } - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return desktopDefinition; - } - if (typeof ioConnectDefinition !== "object" || Array.isArray(ioConnectDefinition)) { - throw new Error(`Invalid '${definition.hostManifests.ioConnect ? "hostManifests.ioConnect" : "hostManifests['Glue42']"}' key`); - } - return this.mergeDesktopConfigWithGlueManifest(desktopDefinition, ioConnectDefinition); - } - getUserPropertiesFromDefinition(definition, version) { - if (version === "1.2") { - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key))); - } - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key))); - } - getUrl(definition, version) { - let url; - if (version === "1.2") { - const parsedManifest = JSON.parse(definition.manifest); - url = parsedManifest.details?.url || parsedManifest.url; - } - else { - url = definition.details?.url; - } - if (!url || typeof url !== "string") { - throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`); - } - return url; - } - getIntentsFromV2AppDefinition(definition) { - const fdc3Intents = definition.interop?.intents?.listensFor; - if (!fdc3Intents) { - return; - } - const intents = Object.entries(fdc3Intents).map((fdc3Intent) => { - const [intentName, intentData] = fdc3Intent; - return { - name: intentName, - ...intentData - }; - }); - return intents; - } - getIconFromDefinition(definition, version) { - if (version === "1.2") { - return definition.icons?.find((iconDef) => iconDef.icon)?.icon || undefined; - } - return definition.icons?.find((iconDef) => iconDef.src)?.src || undefined; - } - mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) { - let baseApplicationDefinition = baseAppData; - if (hostManifestDefinition.customProperties) { - baseApplicationDefinition.userProperties = { ...baseAppData.userProperties, ...hostManifestDefinition.customProperties }; - } - if (hostManifestDefinition.details) { - const details = { ...baseAppData.createOptions, ...hostManifestDefinition.details }; - baseApplicationDefinition.createOptions = details; - baseApplicationDefinition.userProperties.details = details; - } - if (Array.isArray(hostManifestDefinition.intents)) { - baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents); - } - baseApplicationDefinition = { ...baseApplicationDefinition, ...hostManifestDefinition }; - delete baseApplicationDefinition.details; - delete baseApplicationDefinition.intents; - return baseApplicationDefinition; - } - mergeDesktopConfigWithGlueManifest(config, desktopDefinition) { - const appConfig = Object.assign({}, config, desktopDefinition, { details: { ...config.details, ...desktopDefinition.details } }); - if (Array.isArray(desktopDefinition.intents)) { - appConfig.intents = (config.intents || []).concat(desktopDefinition.intents); - } - return appConfig; - } - } - - const decoders$1 = { - common: { - nonEmptyStringDecoder: nonEmptyStringDecoder$3, - nonNegativeNumberDecoder: nonNegativeNumberDecoder$3, - regexDecoder - }, - fdc3: { - allDefinitionsDecoder, - v1DefinitionDecoder, - v2DefinitionDecoder - } - }; - - var INTENTS_ERRORS; - (function (INTENTS_ERRORS) { - INTENTS_ERRORS["USER_CANCELLED"] = "User Closed Intents Resolver UI without choosing a handler"; - INTENTS_ERRORS["CALLER_NOT_DEFINED"] = "Caller Id is not defined"; - INTENTS_ERRORS["TIMEOUT_HIT"] = "Timeout hit"; - INTENTS_ERRORS["INTENT_NOT_FOUND"] = "Cannot find Intent"; - INTENTS_ERRORS["HANDLER_NOT_FOUND"] = "Cannot find Intent Handler"; - INTENTS_ERRORS["TARGET_INSTANCE_UNAVAILABLE"] = "Cannot start Target Instance"; - INTENTS_ERRORS["INTENT_DELIVERY_FAILED"] = "Target Instance did not add a listener"; - INTENTS_ERRORS["RESOLVER_UNAVAILABLE"] = "Intents Resolver UI unavailable"; - INTENTS_ERRORS["RESOLVER_TIMEOUT"] = "User did not choose a handler"; - INTENTS_ERRORS["INVALID_RESOLVER_RESPONSE"] = "Intents Resolver UI returned invalid response"; - INTENTS_ERRORS["INTENT_HANDLER_REJECTION"] = "Intent Handler function processing the raised intent threw an error or rejected the promise it returned"; - })(INTENTS_ERRORS || (INTENTS_ERRORS = {})); - - let IoC$1 = class IoC { - _fdc3; - _decoders = decoders$1; - _errors = { - intents: INTENTS_ERRORS - }; - get fdc3() { - if (!this._fdc3) { - this._fdc3 = new FDC3Service().toApi(); - } - return this._fdc3; - } - get decoders() { - return this._decoders; - } - get errors() { - return this._errors; - } - }; - - const ioc = new IoC$1(); - ioc.fdc3; - const decoders = ioc.decoders; - ioc.errors; - - const nonEmptyStringDecoder$2 = string$2().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$2 = number$2().where((num) => num >= 0, "Expected a non-negative number"); - const optionalNonEmptyStringDecoder = optional$2(nonEmptyStringDecoder$2); - const libDomainDecoder = oneOf$1(constant$2("system"), constant$2("windows"), constant$2("appManager"), constant$2("layouts"), constant$2("intents"), constant$2("notifications"), constant$2("channels"), constant$2("extension"), constant$2("themes"), constant$2("prefs"), constant$2("ui")); - const windowOperationTypesDecoder = oneOf$1(constant$2("openWindow"), constant$2("windowHello"), constant$2("windowAdded"), constant$2("windowRemoved"), constant$2("getBounds"), constant$2("getFrameBounds"), constant$2("getUrl"), constant$2("moveResize"), constant$2("focus"), constant$2("close"), constant$2("getTitle"), constant$2("setTitle"), constant$2("focusChange"), constant$2("getChannel"), constant$2("notifyChannelsChanged"), constant$2("setZoomFactor"), constant$2("zoomFactorChange"), constant$2("refresh"), constant$2("operationCheck")); - const appManagerOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("appDirectoryStateChange"), constant$2("instanceStarted"), constant$2("instanceStopped"), constant$2("applicationStart"), constant$2("instanceStop"), constant$2("clear"), constant$2("operationCheck")); - const layoutsOperationTypesDecoder = oneOf$1(constant$2("layoutAdded"), constant$2("layoutChanged"), constant$2("layoutRemoved"), constant$2("layoutRenamed"), constant$2("get"), constant$2("getAll"), constant$2("export"), constant$2("import"), constant$2("remove"), constant$2("rename"), constant$2("clientSaveRequest"), constant$2("getGlobalPermissionState"), constant$2("checkGlobalActivated"), constant$2("requestGlobalPermission"), constant$2("getDefaultGlobal"), constant$2("setDefaultGlobal"), constant$2("clearDefaultGlobal"), constant$2("updateMetadata"), constant$2("operationCheck"), constant$2("getCurrent"), constant$2("defaultLayoutChanged"), constant$2("layoutRestored")); - const notificationsOperationTypesDecoder = oneOf$1(constant$2("raiseNotification"), constant$2("requestPermission"), constant$2("notificationShow"), constant$2("notificationClick"), constant$2("getPermission"), constant$2("list"), constant$2("notificationRaised"), constant$2("notificationClosed"), constant$2("click"), constant$2("clear"), constant$2("clearAll"), constant$2("configure"), constant$2("getConfiguration"), constant$2("configurationChanged"), constant$2("setState"), constant$2("clearOld"), constant$2("activeCountChange"), constant$2("stateChange"), constant$2("operationCheck"), constant$2("getActiveCount")); - const systemOperationTypesDecoder = oneOf$1(constant$2("getEnvironment"), constant$2("getBase"), constant$2("platformShutdown"), constant$2("isFdc3DataWrappingSupported"), constant$2("clientError"), constant$2("systemHello"), constant$2("operationCheck")); - const windowRelativeDirectionDecoder = oneOf$1(constant$2("top"), constant$2("left"), constant$2("right"), constant$2("bottom")); - const windowBoundsDecoder = object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }); - const windowOpenSettingsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - context: optional$2(anyJson$2()), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - windowId: optional$2(nonEmptyStringDecoder$2), - layoutComponentId: optional$2(nonEmptyStringDecoder$2) - })); - const openWindowConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2, - options: windowOpenSettingsDecoder - }); - const windowHelloDecoder = object$2({ - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const coreWindowDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleWindowDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const helloSuccessDecoder = object$2({ - windows: array$2(coreWindowDataDecoder), - isWorkspaceFrame: boolean$2() - }); - const windowTitleConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - title: string$2() - }); - const focusEventDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - hasFocus: boolean$2() - }); - const windowMoveResizeConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relative: optional$2(boolean$2()) - }); - const windowBoundsResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const frameWindowBoundsResultDecoder = object$2({ - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const windowUrlResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2 - }); - const windowZoomFactorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - factorIndex: nonNegativeNumberDecoder$2 - }); - const anyDecoder = anyJson$2(); - const boundsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2) - }); - const instanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - applicationName: nonEmptyStringDecoder$2 - }); - const iframePermissionsPolicyConfigDecoder = object$2({ - flags: string$2() - }); - const workspacesSandboxDecoder = object$2({ - flags: string$2() - }); - const requestChannelSelectorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelsNames: array$2(nonEmptyStringDecoder$2) - }); - const channelSelectorDecoder$1 = object$2({ - enabled: boolean$2(), - }); - const applicationDetailsDecoder = object$2({ - url: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - workspacesSandbox: optional$2(workspacesSandboxDecoder), - channelSelector: optional$2(channelSelectorDecoder$1), - iframePermissionsPolicy: optional$2(iframePermissionsPolicyConfigDecoder) - }); - const intentDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - displayName: optional$2(string$2()), - contexts: optional$2(array$2(string$2())), - customConfig: optional$2(object$2()), - resultType: optional$2(string$2()) - }); - const applicationDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - customProperties: optional$2(anyJson$2()), - icon: optional$2(string$2()), - caption: optional$2(string$2()), - details: applicationDetailsDecoder, - intents: optional$2(array$2(intentDefinitionDecoder)), - hidden: optional$2(boolean$2()), - fdc3: optional$2(decoders.fdc3.v2DefinitionDecoder) - }); - const appRemoveConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const appsExportOperationDecoder = object$2({ - definitions: array$2(applicationDefinitionDecoder) - }); - const applicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - instances: array$2(instanceDataDecoder), - userProperties: optional$2(anyJson$2()), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const baseApplicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - userProperties: anyJson$2(), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const appDirectoryStateChangeDecoder = object$2({ - appsAdded: array$2(baseApplicationDataDecoder), - appsChanged: array$2(baseApplicationDataDecoder), - appsRemoved: array$2(baseApplicationDataDecoder) - }); - const appHelloSuccessDecoder = object$2({ - apps: array$2(applicationDataDecoder), - initialChannelId: optional$2(nonEmptyStringDecoder$2) - }); - const basicInstanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const layoutTypeDecoder = oneOf$1(constant$2("Global"), constant$2("Activity"), constant$2("ApplicationDefault"), constant$2("Swimlane"), constant$2("Workspace")); - const componentTypeDecoder = oneOf$1(constant$2("application"), constant$2("activity")); - const windowComponentStateDecoder = object$2({ - context: optional$2(anyJson$2()), - bounds: windowBoundsDecoder, - createArgs: object$2({ - name: optional$2(nonEmptyStringDecoder$2), - url: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - instanceId: nonEmptyStringDecoder$2, - isCollapsed: optional$2(boolean$2()), - isSticky: optional$2(boolean$2()), - restoreSettings: object$2({ - groupId: optional$2(nonEmptyStringDecoder$2), - groupZOrder: optional$2(number$2()) - }), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const windowLayoutComponentDecoder = object$2({ - type: constant$2("window"), - componentType: optional$2(componentTypeDecoder), - application: nonEmptyStringDecoder$2, - state: windowComponentStateDecoder - }); - const windowLayoutItemDecoder = object$2({ - type: constant$2("window"), - config: object$2({ - appName: nonEmptyStringDecoder$2, - url: optional$2(nonEmptyStringDecoder$2), - title: optional$2(string$2()), - allowExtract: optional$2(boolean$2()), - allowReorder: optional$2(boolean$2()), - showCloseButton: optional$2(boolean$2()), - isMaximized: optional$2(boolean$2()) - }) - }); - const groupLayoutItemDecoder = object$2({ - type: constant$2("group"), - config: anyJson$2(), - children: array$2(oneOf$1(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object$2({ - type: constant$2("column"), - config: anyJson$2(), - children: array$2(oneOf$1(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object$2({ - type: constant$2("row"), - config: anyJson$2(), - children: array$2(oneOf$1(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutComponentStateDecoder = object$2({ - config: anyJson$2(), - context: anyJson$2(), - children: array$2(oneOf$1(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }); - const workspaceLayoutComponentDecoder = object$2({ - type: constant$2("Workspace"), - application: optional$2(nonEmptyStringDecoder$2), - state: workspaceLayoutComponentStateDecoder - }); - const workspaceFrameComponentStateDecoder = object$2({ - bounds: windowBoundsDecoder, - instanceId: nonEmptyStringDecoder$2, - selectedWorkspace: nonNegativeNumberDecoder$2, - workspaces: array$2(workspaceLayoutComponentStateDecoder), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }); - const workspaceFrameComponentDecoder = object$2({ - type: constant$2("workspaceFrame"), - application: nonEmptyStringDecoder$2, - componentType: optional$2(componentTypeDecoder), - state: workspaceFrameComponentStateDecoder - }); - const glueLayoutDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()) - }); - const renamedLayoutNotificationDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()), - prevName: nonEmptyStringDecoder$2 - }); - const newLayoutOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - instances: optional$2(array$2(nonEmptyStringDecoder$2)), - ignoreInstances: optional$2(array$2(nonEmptyStringDecoder$2)), - setAsCurrent: optional$2(boolean$2()), - ignoreContexts: optional$2(boolean$2()) - }); - const restoreOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - closeRunningInstance: optional$2(boolean$2()), - closeMe: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2) - }); - const layoutSummaryDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()) - }); - const simpleLayoutConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder - }); - const saveLayoutConfigDecoder = object$2({ - layout: newLayoutOptionsDecoder - }); - const renameLayoutConfigDecoder = object$2({ - layout: glueLayoutDecoder, - newName: nonEmptyStringDecoder$2 - }); - const layoutResultDecoder = object$2({ - status: nonEmptyStringDecoder$2 - }); - const updateLayoutMetadataConfigDecoder = object$2({ - layout: glueLayoutDecoder, - }); - const restoreLayoutConfigDecoder = object$2({ - layout: restoreOptionsDecoder - }); - const getAllLayoutsConfigDecoder = object$2({ - type: layoutTypeDecoder - }); - const allLayoutsFullConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder) - }); - const defaultGlobalChangedDecoder = optional$2(object$2({ - name: nonEmptyStringDecoder$2 - })); - const importModeDecoder = oneOf$1(constant$2("replace"), constant$2("merge")); - const layoutsImportConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder), - mode: importModeDecoder, - skipManagerRequest: optional$2(boolean$2()) - }); - const allLayoutsSummariesResultDecoder = object$2({ - summaries: array$2(layoutSummaryDecoder) - }); - const simpleLayoutResultDecoder = object$2({ - layout: glueLayoutDecoder - }); - const optionalSimpleLayoutResult = object$2({ - layout: optional$2(glueLayoutDecoder) - }); - const setDefaultGlobalConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const intentsOperationTypesDecoder = oneOf$1(constant$2("findIntent"), constant$2("getIntents"), constant$2("getIntentsByHandler"), constant$2("raise"), constant$2("filterHandlers")); - const intentHandlerDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2, - applicationTitle: optional$2(string$2()), - applicationDescription: optional$2(string$2()), - applicationIcon: optional$2(string$2()), - type: oneOf$1(constant$2("app"), constant$2("instance")), - displayName: optional$2(string$2()), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - instanceId: optional$2(string$2()), - instanceTitle: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - object$2({ - applicationName: string$2(), - applicationIcon: optional$2(string$2()), - instanceId: optional$2(string$2()), - }); - object$2({ - intent: nonEmptyStringDecoder$2, - handler: intentHandlerDecoder - }); - const intentDecoder = object$2({ - name: nonEmptyStringDecoder$2, - handlers: array$2(intentHandlerDecoder) - }); - const intentTargetDecoder = oneOf$1(constant$2("startNew"), constant$2("reuse"), object$2({ - app: optional$2(nonEmptyStringDecoder$2), - instance: optional$2(nonEmptyStringDecoder$2) - })); - const intentContextDecoder = object$2({ - type: optional$2(nonEmptyStringDecoder$2), - data: optional$2(anyJson$2()) - }); - const intentsDecoder = array$2(intentDecoder); - const wrappedIntentsDecoder = object$2({ - intents: intentsDecoder - }); - const intentFilterDecoder = object$2({ - name: optional$2(nonEmptyStringDecoder$2), - contextType: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const findFilterDecoder = oneOf$1(nonEmptyStringDecoder$2, intentFilterDecoder); - const wrappedIntentFilterDecoder = object$2({ - filter: optional$2(intentFilterDecoder) - }); - const applicationStartOptionsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const intentRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - target: optional$2(intentTargetDecoder), - context: optional$2(intentContextDecoder), - options: optional$2(applicationStartOptionsDecoder), - handlers: optional$2(array$2(intentHandlerDecoder)), - timeout: optional$2(nonNegativeNumberDecoder$2), - waitUserResponseIndefinitely: optional$2(boolean$2()), - clearSavedHandler: optional$2(boolean$2()) - }); - const originAppDecoder = object$2({ - interopInstance: nonEmptyStringDecoder$2, - name: optional$2(nonEmptyStringDecoder$2) - }); - const startReasonDecoder = object$2({ - originApp: originAppDecoder, - intentRequest: optional$2(intentRequestDecoder) - }); - const applicationStartConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - waitForAGMReady: boolean$2(), - id: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()), - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - forceChromeTab: optional$2(boolean$2()), - layoutComponentId: optional$2(nonEmptyStringDecoder$2), - channelId: optional$2(nonEmptyStringDecoder$2), - startReason: startReasonDecoder - }); - const raiseRequestDecoder = oneOf$1(nonEmptyStringDecoder$2, intentRequestDecoder); - const resolverConfigDecoder = object$2({ - enabled: boolean$2(), - appName: nonEmptyStringDecoder$2, - waitResponseTimeout: number$2() - }); - const handlerExclusionCriteriaApplicationNameDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaInstanceIdDecoder = object$2({ - instanceId: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaDecoder = oneOf$1(handlerExclusionCriteriaApplicationNameDecoder, handlerExclusionCriteriaInstanceIdDecoder); - const handlerFilterDecoder = object$2({ - title: optional$2(nonEmptyStringDecoder$2), - openResolver: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2), - intent: optional$2(nonEmptyStringDecoder$2), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - resultType: optional$2(nonEmptyStringDecoder$2), - applicationNames: optional$2(array$2(nonEmptyStringDecoder$2)), - excludeList: optional$2(array$2(handlerExclusionCriteriaDecoder)) - }); - const embeddedResolverConfigDecoder = object$2({ - enabled: boolean$2(), - initialCaller: object$2({ instanceId: nonEmptyStringDecoder$2 }), - }); - const raiseIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const intentResultDecoder = object$2({ - request: intentRequestDecoder, - handler: intentHandlerDecoder, - result: anyJson$2() - }); - const filterHandlersResultDecoder = object$2({ - handlers: array$2(intentHandlerDecoder) - }); - const filterHandlersWithResolverConfigDecoder = object$2({ - filterHandlersRequest: handlerFilterDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const AddIntentListenerRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - displayName: optional$2(string$2()), - icon: optional$2(string$2()), - description: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - const AddIntentListenerDecoder = oneOf$1(nonEmptyStringDecoder$2, AddIntentListenerRequestDecoder); - const intentInfoDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - description: optional$2(nonEmptyStringDecoder$2), - displayName: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const getIntentsResultDecoder = object$2({ - intents: array$2(intentInfoDecoder) - }); - const channelNameDecoder = (channelNames) => { - return nonEmptyStringDecoder$2.where(s => channelNames.includes(s), "Expected a valid channel name"); - }; - const fdc3OptionsDecoder = object$2({ - contextType: optional$2(nonEmptyStringDecoder$2) - }); - const publishOptionsDecoder = optional$2(oneOf$1(nonEmptyStringDecoder$2, object$2({ - name: optional$2(nonEmptyStringDecoder$2), - fdc3: optional$2(boolean$2()) - }))); - const leaveChannelsConfig = object$2({ - windowId: optionalNonEmptyStringDecoder, - channel: optionalNonEmptyStringDecoder - }); - const fdc3ContextDecoder = anyJson$2().where((value) => typeof value.type === "string", "Expected a valid FDC3 Context with compulsory 'type' field"); - const interopActionSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$2, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("all"), constant$2("best"))) - }); - const glue42NotificationActionDecoder = object$2({ - action: string$2(), - title: nonEmptyStringDecoder$2, - icon: optional$2(string$2()), - interop: optional$2(interopActionSettingsDecoder) - }); - const notificationStateDecoder = oneOf$1(constant$2("Active"), constant$2("Acknowledged"), constant$2("Seen"), constant$2("Closed"), constant$2("Stale"), constant$2("Snoozed"), constant$2("Processing")); - const activeNotificationsCountChangeDecoder = object$2({ - count: number$2() - }); - const notificationDefinitionDecoder = object$2({ - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())) - }); - const glue42NotificationOptionsDecoder = object$2({ - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const notificationSetStateRequestDecoder = object$2({ - id: nonEmptyStringDecoder$2, - state: notificationStateDecoder - }); - object$2().where((value) => value.fdc3 ? typeof value.fdc3.type === "string" : true, "Expected a valid FDC3 Context with compulsory 'type' field"); - const channelFDC3DisplayMetadataDecoder = object$2({ - color: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - name: optional$2(nonEmptyStringDecoder$2), - glyph: optional$2(nonEmptyStringDecoder$2) - }); - const channelFdc3MetaDecoder = object$2({ - id: nonEmptyStringDecoder$2, - displayMetadata: optional$2(channelFDC3DisplayMetadataDecoder) - }); - const channelMetaDecoder = object$2({ - color: nonEmptyStringDecoder$2, - fdc3: optional$2(channelFdc3MetaDecoder) - }); - const channelDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - meta: channelMetaDecoder, - data: optional$2(object$2()), - }); - const pathValueDecoder = object$2({ - path: nonEmptyStringDecoder$2, - value: anyJson$2() - }); - const pathsValueDecoder = array$2(pathValueDecoder); - const removeChannelDataDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const channelRestrictionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const channelRestrictionConfigWithWindowIdDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: nonEmptyStringDecoder$2 - }); - const restrictionConfigDataDecoder = object$2({ - config: channelRestrictionConfigWithWindowIdDecoder - }); - const restrictionsDecoder = object$2({ - channels: array$2(channelRestrictionsDecoder) - }); - const getRestrictionsDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const restrictionsConfigDecoder = object$2({ - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const restrictAllDataDecoder = object$2({ - restrictions: restrictionsConfigDecoder - }); - const raiseNotificationDecoder = object$2({ - settings: glue42NotificationOptionsDecoder, - id: nonEmptyStringDecoder$2 - }); - const raiseNotificationResultDecoder = object$2({ - settings: glue42NotificationOptionsDecoder - }); - const permissionRequestResultDecoder = object$2({ - permissionGranted: boolean$2() - }); - const permissionQueryResultDecoder = object$2({ - permission: oneOf$1(constant$2("default"), constant$2("granted"), constant$2("denied")) - }); - const notificationEventPayloadDecoder = object$2({ - definition: notificationDefinitionDecoder, - action: optional$2(string$2()), - id: optional$2(nonEmptyStringDecoder$2) - }); - const notificationFilterDecoder = object$2({ - allowed: optional$2(array$2(nonEmptyStringDecoder$2)), - blocked: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const notificationsConfigurationDecoder = object$2({ - enable: optional$2(boolean$2()), - enableToasts: optional$2(boolean$2()), - sourceFilter: optional$2(notificationFilterDecoder), - showNotificationBadge: optional$2(boolean$2()) - }); - const notificationsConfigurationProtocolDecoder = object$2({ - configuration: notificationsConfigurationDecoder - }); - const strictNotificationsConfigurationProtocolDecoder = object$2({ - configuration: object$2({ - enable: boolean$2(), - enableToasts: boolean$2(), - sourceFilter: object$2({ - allowed: array$2(nonEmptyStringDecoder$2), - blocked: array$2(nonEmptyStringDecoder$2) - }) - }) - }); - const platformSaveRequestConfigDecoder = object$2({ - layoutType: oneOf$1(constant$2("Global"), constant$2("Workspace")), - layoutName: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()) - }); - const saveRequestClientResponseDecoder = object$2({ - windowContext: optional$2(anyJson$2()), - }); - const permissionStateResultDecoder = object$2({ - state: oneOf$1(constant$2("prompt"), constant$2("denied"), constant$2("granted")) - }); - const simpleAvailabilityResultDecoder = object$2({ - isAvailable: boolean$2() - }); - const simpleItemIdDecoder = object$2({ - itemId: nonEmptyStringDecoder$2 - }); - const operationCheckResultDecoder = object$2({ - isSupported: boolean$2() - }); - const operationCheckConfigDecoder = object$2({ - operation: nonEmptyStringDecoder$2 - }); - const workspaceFrameBoundsResultDecoder = object$2({ - bounds: windowBoundsDecoder - }); - const themeDecoder = object$2({ - displayName: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleThemeResponseDecoder = object$2({ - theme: themeDecoder - }); - const allThemesResponseDecoder = object$2({ - themes: array$2(themeDecoder) - }); - const selectThemeConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const notificationsDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const simpleNotificationDataDecoder = object$2({ - notification: notificationsDataDecoder - }); - const allNotificationsDataDecoder = object$2({ - notifications: array$2(notificationsDataDecoder) - }); - const simpleNotificationSelectDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelResultDecoder = object$2({ - windowIds: array$2(nonEmptyStringDecoder$2) - }); - const channelsOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("addChannel"), constant$2("getMyChannel"), constant$2("getWindowIdsOnChannel"), constant$2("getWindowIdsWithChannels"), constant$2("joinChannel"), constant$2("restrict"), constant$2("getRestrictions"), constant$2("restrictAll"), constant$2("notifyChannelsChanged"), constant$2("leaveChannel"), constant$2("getMode"), constant$2("operationCheck")); - const modeDecoder = oneOf$1(constant$2("single"), constant$2("multi")); - const getChannelsModeDecoder = object$2({ - mode: modeDecoder - }); - const channelsAppHelloDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const channelsAppHelloSuccessDecoder = object$2({ - mode: modeDecoder, - channels: array$2(nonEmptyStringDecoder$2), - restrictions: array$2(channelRestrictionsDecoder) - }); - const getMyChanelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2) - }); - const windowWithChannelFilterDecoder = object$2({ - application: optional$2(nonEmptyStringDecoder$2), - channels: optional$2(array$2(nonEmptyStringDecoder$2)), - windowIds: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const wrappedWindowWithChannelFilterDecoder = object$2({ - filter: optional$2(windowWithChannelFilterDecoder) - }); - const getWindowIdsWithChannelsResultDecoder = object$2({ - windowIdsWithChannels: array$2(object$2({ - application: nonEmptyStringDecoder$2, - channel: optional$2(nonEmptyStringDecoder$2), - windowId: nonEmptyStringDecoder$2 - })) - }); - const startApplicationContextDecoder = optional$2(anyJson$2()); - const startApplicationOptionsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - reuseId: optional$2(nonEmptyStringDecoder$2), - originIntentRequest: optional$2(intentRequestDecoder) - })); - const joinChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2, - windowId: nonEmptyStringDecoder$2 - }); - const leaveChannelDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelName: optional$2(nonEmptyStringDecoder$2) - }); - const channelsChangedDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelNames: array$2(nonEmptyStringDecoder$2) - }); - const windowChannelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2), - }); - const prefsOperationTypesDecoder = oneOf$1(constant$2("clear"), constant$2("clearAll"), constant$2("get"), constant$2("getAll"), constant$2("set"), constant$2("update"), constant$2("prefsChanged"), constant$2("prefsHello"), constant$2("operationCheck"), constant$2("registerSubscriber")); - const appPreferencesDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - lastUpdate: optional$2(nonEmptyStringDecoder$2), - }); - const basePrefsConfigDecoder = object$2({ - app: nonEmptyStringDecoder$2, - }); - const getPrefsResultDecoder = object$2({ - prefs: appPreferencesDecoder, - }); - const getAllPrefsResultDecoder = object$2({ - all: array$2(appPreferencesDecoder), - }); - const subscriberRegisterConfigDecoder = object$2({ - interopId: nonEmptyStringDecoder$2, - appName: optional$2(nonEmptyStringDecoder$2) - }); - const changePrefsDataDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - }); - const prefsHelloSuccessDecoder = object$2({ - platform: object$2({ - app: nonEmptyStringDecoder$2, - }), - validNonExistentApps: optional$2(array$2(nonEmptyStringDecoder$2)), - }); - const clientErrorDataDecoder = object$2({ - message: nonEmptyStringDecoder$2 - }); - const systemHelloSuccessDecoder = object$2({ - isClientErrorOperationSupported: boolean$2() - }); - - const nonEmptyStringDecoder$1 = decoders.common.nonEmptyStringDecoder; - const nonNegativeNumberDecoder$1 = decoders.common.nonNegativeNumberDecoder; - const widgetSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const modalsSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const intentResolverSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const channelSelectorTypeDecoder = oneOf$1(constant$2("directional"), constant$2("default")); - const channelSelectorDecoder = object$2({ - type: optional$2(channelSelectorTypeDecoder), - enable: optional$2(boolean$2()) - }); - const positionDecoder = oneOf$1(constant$2("top-left"), constant$2("top-center"), constant$2("top-right"), constant$2("center-left"), constant$2("center-right"), constant$2("bottom-left"), constant$2("bottom-center"), constant$2("bottom-right")); - const displayModeDecoder = oneOf$1(constant$2("all"), constant$2("fdc3")); - const widgetChannelsDecoder = object$2({ - selector: optional$2(channelSelectorDecoder), - displayMode: optional$2(displayModeDecoder) - }); - const platformWidgetDefaultConfigDecoder = object$2({ - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const widgetConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const modalsConfigDecoder = object$2({ - alerts: optional$2(object$2({ - enabled: boolean$2() - })), - dialogs: optional$2(object$2({ - enabled: boolean$2() - })), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - }); - const uiOperationTypesDecoder = oneOf$1(constant$2("getResources"), constant$2("operationCheck"), constant$2("showAlert"), constant$2("showDialog"), constant$2("alertInteropAction"), constant$2("showResolver")); - const getResourcesDataDecoder = object$2({ - origin: nonEmptyStringDecoder$1 - }); - const blockedResourcesDecoder = object$2({ - blockedOrigin: constant$2(true) - }); - const availableWidgetResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - config: platformWidgetDefaultConfigDecoder, - sources: widgetSourcesDecoder - }); - const widgetResourcesDecoder = union$1(blockedResourcesDecoder, availableWidgetResourcesDecoder); - const availableModalsResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: modalsSourcesDecoder - }); - const modalsResourcesDecoder = union$1(blockedResourcesDecoder, availableModalsResourcesDecoder); - const availableIntentResolverResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: intentResolverSourcesDecoder - }); - const intentResolverResourcesDecoder = union$1(blockedResourcesDecoder, availableIntentResolverResourcesDecoder); - const resourcesDecoder = object$2({ - widget: optional$2(widgetResourcesDecoder), - modals: optional$2(modalsResourcesDecoder), - intentResolver: optional$2(intentResolverResourcesDecoder) - }); - const getResourcesResultDecoder = object$2({ - resources: resourcesDecoder, - }); - const alertsInteropSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$1, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("best"), constant$2("all"), nonEmptyStringDecoder$1)) - }); - const modalRequestTargetDecoder = oneOf$1(constant$2("Global"), constant$2("WindowContainer"), nonEmptyStringDecoder$1); - const modalRequestMessageTargetDecoder = object$2({ - instance: nonEmptyStringDecoder$1, - container: optional$2(oneOf$1(constant$2("Global"), constant$2("WindowContainer"))) - }); - const alertRequestConfigDecoder = object$2({ - variant: oneOf$1(constant$2("default"), constant$2("success"), constant$2("critical"), constant$2("info"), constant$2("warning")), - text: nonEmptyStringDecoder$1, - showCloseButton: optional$2(boolean$2()), - clickInterop: optional$2(alertsInteropSettingsDecoder), - onCloseInterop: optional$2(alertsInteropSettingsDecoder), - actions: optional$2(array$2(object$2({ - id: nonEmptyStringDecoder$1, - title: nonEmptyStringDecoder$1, - clickInterop: alertsInteropSettingsDecoder - }))), - data: optional$2(anyJson$2()), - ttl: optional$2(nonNegativeNumberDecoder$1), - target: optional$2(modalRequestTargetDecoder) - }); - const uiAlertRequestMessageDecoder = object$2({ - config: alertRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const dialogRequestConfigDecoder = object$2({ - templateName: nonEmptyStringDecoder$1, - variables: anyJson$2(), - target: optional$2(modalRequestTargetDecoder), - timer: optional$2(object$2({ - duration: nonNegativeNumberDecoder$1 - })), - size: optional$2(object$2({ - width: nonNegativeNumberDecoder$1, - height: nonNegativeNumberDecoder$1 - })), - movable: optional$2(boolean$2()), - transparent: optional$2(boolean$2()) - }); - const dialogResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - isEnterPressed: optional$2(boolean$2()), - responseButtonClicked: optional$2(object$2({ - id: nonEmptyStringDecoder$1, - text: nonEmptyStringDecoder$1 - })), - inputs: optional$2(array$2(object$2({ - type: oneOf$1(constant$2("checkbox"), constant$2("email"), constant$2("number"), constant$2("password"), constant$2("text")), - id: nonEmptyStringDecoder$1, - checked: optional$2(boolean$2()), - value: optional$2(string$2()) - }))) - }); - object$2({ - result: dialogResponseDecoder - }); - const uiDialogRequestMessageDecoder = object$2({ - config: dialogRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const openAlertResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const openDialogResultDecoder = object$2({ - id: nonEmptyStringDecoder$1, - responsePromise: anyJson$2() - }); - const dialogOnCompletionConfigDecoder = object$2({ - response: dialogResponseDecoder - }); - const alertInteropActionDecoder = object$2({ - name: nonEmptyStringDecoder$1, - settings: alertsInteropSettingsDecoder - }); - const alertOnClickConfigDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const alertInteropActionDataDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const intentResolverConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1) - }); - const openResolverResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const userSettingsDecoder = object$2({ - preserveChoice: boolean$2() - }); - const userChoiceResponseDecoder = object$2({ - intent: nonEmptyStringDecoder$1, - handler: intentHandlerDecoder, - userSettings: userSettingsDecoder - }); - const intentResolverResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - userChoice: optional$2(userChoiceResponseDecoder) - }); - const onUserResponseResponseDecoder = object$2({ - response: intentResolverResponseDecoder - }); - const openConfigWithIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder - }); - const openConfigWithHandlerFilterDecoder = object$2({ - handlerFilter: handlerFilterDecoder - }); - const intentResolverOpenConfigDecoder = union$1(openConfigWithIntentRequestDecoder, openConfigWithHandlerFilterDecoder); - const uiResolverRequestMessageConfigDecoder = intersection(intentResolverOpenConfigDecoder, object$2({ timeout: nonNegativeNumberDecoder$1 })); - const uiResolverRequestMessageDecoder = object$2({ - config: uiResolverRequestMessageConfigDecoder - }); - const uiResolverResponseMessageDecoder = object$2({ - result: intentResolverResponseDecoder - }); - - const parseConfig = (config = {}) => { - const isPlatformInternal = !!config?.gateway?.webPlatform?.port; - const decodedWidgetConfigResult = optional$2(widgetConfigDecoder).run(config.widget); - if (!decodedWidgetConfigResult.ok) { - throw ioError.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(decodedWidgetConfigResult.error)}`); - } - const decodedModalsConfigResult = optional$2(modalsConfigDecoder).run(config.modals); - if (!decodedModalsConfigResult.ok) { - throw ioError.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(decodedModalsConfigResult.error)}`); - } - const decodedIntentResolverConfigResult = optional$2(intentResolverConfigDecoder).run(config.intentResolver); - if (!decodedIntentResolverConfigResult.ok) { - throw ioError.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(decodedIntentResolverConfigResult.error)}`); - } - const combined = { - ...defaultConfig, - ...config, - isPlatformInternal, - logger: config.systemLogger?.level ?? "info", - customLogger: config.systemLogger?.customLogger, - widget: deepmerge$1(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}), - modals: deepmerge$1(defaultModalsConfig, decodedModalsConfigResult.result ?? {}), - intentResolver: deepmerge$1(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}), - }; - return combined; - }; - - const checkSingleton = () => { - const ioConnectBrowserNamespace = window.glue42core || window.iobrowser; - if (ioConnectBrowserNamespace && ioConnectBrowserNamespace.webStarted) { - return ioError.raiseError("IoConnect Browser has already been started for this application."); - } - if (!ioConnectBrowserNamespace) { - window.iobrowser = { webStarted: true }; - return; - } - ioConnectBrowserNamespace.webStarted = true; - }; - - const enterprise = (config) => { - const enterpriseConfig = { - windows: true, - layouts: "full", - appManager: "full", - channels: true, - libraries: config?.libraries ?? [], - logger: config?.systemLogger?.level ?? "warn" - }; - const injectedFactory = window.IODesktop || window.Glue; - return injectedFactory(enterpriseConfig); - }; - - const operations$a = { - openWindow: { name: "openWindow", dataDecoder: openWindowConfigDecoder, resultDecoder: coreWindowDataDecoder }, - windowHello: { name: "windowHello", dataDecoder: windowHelloDecoder, resultDecoder: helloSuccessDecoder }, - windowAdded: { name: "windowAdded", dataDecoder: coreWindowDataDecoder }, - windowRemoved: { name: "windowRemoved", dataDecoder: simpleWindowDecoder }, - getBounds: { name: "getBounds", dataDecoder: simpleWindowDecoder, resultDecoder: windowBoundsResultDecoder }, - getFrameBounds: { name: "getFrameBounds", dataDecoder: simpleWindowDecoder, resultDecoder: frameWindowBoundsResultDecoder }, - getUrl: { name: "getUrl", dataDecoder: simpleWindowDecoder, resultDecoder: windowUrlResultDecoder }, - moveResize: { name: "moveResize", dataDecoder: windowMoveResizeConfigDecoder }, - focus: { name: "focus", dataDecoder: simpleWindowDecoder }, - close: { name: "close", dataDecoder: simpleWindowDecoder }, - getTitle: { name: "getTitle", dataDecoder: simpleWindowDecoder, resultDecoder: windowTitleConfigDecoder }, - setTitle: { name: "setTitle", dataDecoder: windowTitleConfigDecoder }, - focusChange: { name: "focusChange", dataDecoder: focusEventDataDecoder }, - getChannel: { name: "getChannel", dataDecoder: simpleWindowDecoder, resultDecoder: windowChannelResultDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - setZoomFactor: { name: "setZoomFactor", dataDecoder: windowZoomFactorConfigDecoder }, - zoomFactorChange: { name: "zoomFactorChange", dataDecoder: windowZoomFactorConfigDecoder }, - refresh: { name: "refresh", dataDecoder: simpleWindowDecoder }, - operationCheck: { name: "operationCheck" } - }; - - function createRegistry$1(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry$1.default = createRegistry$1; - var lib$1 = createRegistry$1; - - - var CallbackRegistryFactory$1 = /*@__PURE__*/getDefaultExportFromCjs$1(lib$1); - - const ZOOM_FACTORS = Object.freeze({ - 0: 24, - 1: 33, - 2: 50, - 3: 67, - 4: 75, - 5: 80, - 6: 90, - 7: 100, - 8: 110, - 9: 125, - 10: 150, - 11: 175, - 12: 200, - 13: 250, - 14: 300, - 15: 400, - 16: 500 - }); - - class WebWindowModel { - _id; - _name; - _bridge; - _logger; - registry = CallbackRegistryFactory$1(); - myCtxKey; - ctxUnsubscribe; - zoomFactorIndex = 7; - me; - constructor(_id, _name, _bridge, _logger) { - this._id = _id; - this._name = _name; - this._bridge = _bridge; - this._logger = _logger; - this.myCtxKey = `___window___${this.id}`; - } - get id() { - return this._id.slice(); - } - get name() { - return this._name.slice(); - } - get zoomFactor() { - return ZOOM_FACTORS[this.zoomFactorIndex]; - } - clean() { - if (this.ctxUnsubscribe) { - this.ctxUnsubscribe(); - } - } - processSelfFocusEvent(hasFocus) { - this.me.isFocused = hasFocus; - this.registry.execute("focus-change", this.me); - } - processChannelsChangedEvent(channelNames) { - this.registry.execute("channels-changed", channelNames); - } - processSelfZoomFactorChangedEvent(factorIndex) { - this.zoomFactorIndex = factorIndex; - this.registry.execute("zoom-factor-changed", this.me); - } - async toApi() { - this.ctxUnsubscribe = await this._bridge.contextLib.subscribe(this.myCtxKey, (data) => this.registry.execute("context-updated", data)); - this.me = { - id: this.id, - name: this.name, - isFocused: false, - zoomFactor: this.zoomFactor, - getURL: this.getURL.bind(this), - moveResize: this.moveResize.bind(this), - resizeTo: this.resizeTo.bind(this), - moveTo: this.moveTo.bind(this), - focus: this.focus.bind(this), - close: this.close.bind(this), - getTitle: this.getTitle.bind(this), - setTitle: this.setTitle.bind(this), - getBounds: this.getBounds.bind(this), - getContext: this.getContext.bind(this), - updateContext: this.updateContext.bind(this), - setContext: this.setContext.bind(this), - refresh: this.refresh.bind(this), - onContextUpdated: this.onContextUpdated.bind(this), - onFocusChanged: this.onFocusChanged.bind(this), - getChannel: this.getChannel.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - zoomIn: this.zoomIn.bind(this), - zoomOut: this.zoomOut.bind(this), - setZoomFactor: this.setZoomFactor.bind(this), - onZoomFactorChanged: this.onZoomFactorChanged.bind(this), - }; - Object.defineProperties(this.me, { - id: READONLY_PROPERTY_DESCRIPTOR, - name: READONLY_PROPERTY_DESCRIPTOR, - zoomFactor: { - get: () => { - return this.zoomFactor; - }, - enumerable: true, - }, - }); - return this.me; - } - async getURL() { - const result = await this._bridge.send("windows", operations$a.getUrl, { windowId: this.id }); - return result.url; - } - onFocusChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - return this.registry.add("focus-change", callback); - } - async moveResize(dimension) { - const targetBounds = runDecoderWithIOError(boundsDecoder, dimension); - const commandArgs = Object.assign({}, targetBounds, { windowId: this.id, relative: false }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async resizeTo(width, height) { - if (typeof width === "undefined" && typeof height === "undefined") { - return this.me; - } - if (typeof width !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, width); - } - if (typeof height !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, height); - } - const commandArgs = Object.assign({}, { width, height }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async moveTo(top, left) { - if (typeof top === "undefined" && typeof left === "undefined") { - return this.me; - } - if (typeof top !== "undefined") { - runDecoderWithIOError(number$2(), top); - } - if (typeof left !== "undefined") { - runDecoderWithIOError(number$2(), left); - } - const commandArgs = Object.assign({}, { top, left }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async focus() { - if (this.name === "Platform") { - window.open(undefined, this.id); - } - else { - await this._bridge.send("windows", operations$a.focus, { windowId: this.id }); - } - return this.me; - } - async close() { - await this._bridge.send("windows", operations$a.close, { windowId: this.id }); - return this.me; - } - async getTitle() { - const result = await this._bridge.send("windows", operations$a.getTitle, { windowId: this.id }); - return result.title; - } - async setTitle(title) { - const ttl = runDecoderWithIOError(nonEmptyStringDecoder$2, title); - await this._bridge.send("windows", operations$a.setTitle, { windowId: this.id, title: ttl }); - return this.me; - } - async getBounds() { - const result = await this._bridge.send("windows", operations$a.getBounds, { windowId: this.id }); - return result.bounds; - } - async getContext() { - const ctx = await this._bridge.contextLib.get(this.myCtxKey); - const { ___io___, ...rest } = ctx; - return rest; - } - async updateContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - await this._bridge.contextLib.update(this.myCtxKey, ctx); - return this.me; - } - async setContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - const current = await this._bridge.contextLib.get(this.myCtxKey); - const newCtx = current.___io___ ? { ...ctx, ___io___: current.___io___ } : ctx; - await this._bridge.contextLib.set(this.myCtxKey, newCtx); - return this.me; - } - onContextUpdated(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - const wrappedCallback = (data) => { - const { ___io___, ...rest } = data; - callback(rest, this.me); - }; - return this.registry.add("context-updated", wrappedCallback); - } - async getChannel() { - const result = await this._bridge.send("windows", operations$a.getChannel, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return result.channel; - } - onChannelsChanged(callback) { - return this.registry.add("channels-changed", callback); - } - getClosestZoomFactorIndex(factor) { - const closestIndex = Object.entries(ZOOM_FACTORS).reduce((closestIndex, [currentIndex, currentValue]) => { - return (Math.abs(currentValue - factor) <= Math.abs(ZOOM_FACTORS[closestIndex] - factor) ? parseInt(currentIndex) : closestIndex); - }, 0); - const closestFactor = ZOOM_FACTORS[closestIndex]; - if (closestFactor !== factor) { - this._logger.warn(`Zoom factor ${factor} is not available, using closest value ${closestFactor} instead.`); - } - return closestIndex; - } - async zoom(factorIndex) { - if (factorIndex === this.zoomFactorIndex || !(factorIndex in ZOOM_FACTORS)) { - return; - } - await this._bridge.send("windows", operations$a.setZoomFactor, { windowId: this.id, factorIndex }, undefined, { includeOperationCheck: true }); - this.zoomFactorIndex = factorIndex; - } - async zoomIn() { - await this.zoom(this.zoomFactorIndex + 1); - return this.me; - } - async zoomOut() { - await this.zoom(this.zoomFactorIndex - 1); - return this.me; - } - async setZoomFactor(factor) { - const targetZoomFactor = runDecoderWithIOError(number$2(), factor); - const closestZoomFactorIndex = this.getClosestZoomFactorIndex(targetZoomFactor); - await this.zoom(closestZoomFactorIndex); - return this.me; - } - onZoomFactorChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"); - } - return this.registry.add("zoom-factor-changed", callback); - } - async refresh() { - await this._bridge.send("windows", operations$a.refresh, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return this.me; - } - } - - const commonOperations = { - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - getWorkspaceWindowFrameBounds: { name: "getWorkspaceWindowFrameBounds", resultDecoder: workspaceFrameBoundsResultDecoder, dataDecoder: simpleItemIdDecoder } - }; - - const PromiseWrap = (callback, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - callback() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - const PromisePlus$1 = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WindowsController { - supportedOperationsNames = []; - focusEventHandler; - registry = CallbackRegistryFactory$1(); - platformRegistration; - ioc; - bridge; - publicWindowId; - allWindowProjections = []; - me; - logger; - isWorkspaceFrame; - instanceId; - channelsController; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("windows.controller.web"); - this.logger.trace("starting the web windows controller"); - this.publicWindowId = ioc.publicWindowId; - this.addWindowOperationExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.instanceId = coreGlue.interop.instance.instance; - this.channelsController = ioc.channelsController; - this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`); - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - await this.initializeFocusTracking(); - this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning"); - const api = this.toApi(); - coreGlue.windows = api; - } - handlePlatformShutdown() { - this.registry.clear(); - this.allWindowProjections = []; - if (!this.focusEventHandler) { - return; - } - document.removeEventListener("visibilityChange", this.focusEventHandler); - window.removeEventListener("focus", this.focusEventHandler); - window.removeEventListener("blur", this.focusEventHandler); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(windowOperationTypesDecoder, args.operation); - const operation = operations$a[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async open(name, url, options) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(nonEmptyStringDecoder$2, url); - const settings = runDecoderWithIOError(windowOpenSettingsDecoder, options); - const windowSuccess = await this.bridge.send("windows", operations$a.openWindow, { name, url, options: settings }); - return this.waitForWindowAdded(windowSuccess.windowId); - } - list() { - return this.allWindowProjections.map((projection) => projection.api); - } - findById(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - return this.allWindowProjections.find((projection) => projection.id === id)?.api; - } - toApi() { - return { - open: this.open.bind(this), - my: this.my.bind(this), - list: this.list.bind(this), - findById: this.findById.bind(this), - onWindowAdded: this.onWindowAdded.bind(this), - onWindowRemoved: this.onWindowRemoved.bind(this), - onWindowGotFocus: this.onWindowGotFocus.bind(this), - onWindowLostFocus: this.onWindowLostFocus.bind(this) - }; - } - addWindowOperationExecutors() { - operations$a.focusChange.execute = this.handleFocusChangeEvent.bind(this); - operations$a.windowAdded.execute = this.handleWindowAdded.bind(this); - operations$a.windowRemoved.execute = this.handleWindowRemoved.bind(this); - operations$a.getBounds.execute = this.handleGetBounds.bind(this); - operations$a.getFrameBounds.execute = this.handleGetBounds.bind(this); - operations$a.getTitle.execute = this.handleGetTitle.bind(this); - operations$a.getUrl.execute = this.handleGetUrl.bind(this); - operations$a.moveResize.execute = this.handleMoveResize.bind(this); - operations$a.setTitle.execute = this.handleSetTitle.bind(this); - operations$a.getChannel.execute = this.handleGetChannel.bind(this); - operations$a.notifyChannelsChanged.execute = this.handleChannelsChanged.bind(this); - operations$a.setZoomFactor.execute = this.handleSetZoomFactor.bind(this); - operations$a.zoomFactorChange.execute = this.handleZoomFactorChanged.bind(this); - operations$a.refresh.execute = this.handleRefresh.bind(this); - operations$a.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$a); - } - my() { - return Object.assign({}, this.me); - } - onWindowAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"); - } - return this.registry.add("window-added", callback); - } - onWindowRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"); - } - return this.registry.add("window-removed", callback); - } - onWindowGotFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-got-focus", callback); - } - onWindowLostFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-lost-focus", callback); - } - async sayHello() { - const helloSuccess = await this.bridge.send("windows", operations$a.windowHello, { windowId: this.publicWindowId }); - return helloSuccess; - } - async registerWithPlatform() { - const { windows, isWorkspaceFrame } = await this.sayHello(); - this.isWorkspaceFrame = isWorkspaceFrame; - this.logger.trace("the platform responded to the hello message"); - if (!this.isWorkspaceFrame && this.publicWindowId) { - this.logger.trace("i am not treated as a workspace frame, setting my window"); - const myWindow = windows.find((w) => w.windowId === this.publicWindowId); - if (!myWindow) { - const windowsInfo = windows.map(w => `${w.windowId}:${w.name}`).join(", "); - return ioError.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${windowsInfo}`); - } - const myProjection = await this.ioc.buildWebWindow(this.publicWindowId, myWindow.name, this.logger); - this.me = myProjection.api; - this.allWindowProjections.push(myProjection); - } - const currentWindows = await Promise.all(windows - .filter((w) => w.windowId !== this.publicWindowId) - .map((w) => this.ioc.buildWebWindow(w.windowId, w.name, this.logger))); - this.logger.trace("all windows projections are completed, building the list collection"); - this.allWindowProjections.push(...currentWindows); - } - async handleFocusChangeEvent(focusData) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === focusData.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfFocusEvent(focusData.hasFocus); - const keyToExecute = focusData.hasFocus ? "window-got-focus" : "window-lost-focus"; - this.registry.execute(keyToExecute, foundProjection.api); - } - async handleWindowAdded(data) { - if (this.allWindowProjections.some((projection) => projection.id === data.windowId)) { - return; - } - const webWindowProjection = await this.ioc.buildWebWindow(data.windowId, data.name, this.logger); - this.allWindowProjections.push(webWindowProjection); - this.registry.execute("window-added", webWindowProjection.api); - } - async handleWindowRemoved(data) { - const removed = this.allWindowProjections.find((w) => w.id === data.windowId); - if (!removed) { - return; - } - this.allWindowProjections = this.allWindowProjections.filter((w) => w.id !== data.windowId); - removed.model.clean(); - this.registry.execute("window-removed", removed.api); - } - async handleGetBounds() { - if (!this.me && !this.isWorkspaceFrame) { - return ioError.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.isWorkspaceFrame ? "noop" : this.me.id, - bounds: { - top: window.screenTop, - left: window.screenLeft, - width: window.innerWidth, - height: window.innerHeight - } - }; - } - async handleGetTitle() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - title: document.title - }; - } - async handleGetUrl() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - url: window.location.href - }; - } - async handleMoveResize(config) { - const targetTop = typeof config.top === "number" ? config.top : - config.relative ? 0 : window.screenTop; - const targetLeft = typeof config.left === "number" ? config.left : - config.relative ? 0 : window.screenLeft; - const targetHeight = typeof config.height === "number" ? config.height : - config.relative ? 0 : window.innerHeight; - const targetWidth = typeof config.width === "number" ? config.width : - config.relative ? 0 : window.innerWidth; - const moveMethod = config.relative ? window.moveBy : window.moveTo; - const resizeMethod = config.relative ? window.resizeBy : window.resizeTo; - moveMethod(targetLeft, targetTop); - resizeMethod(targetWidth, targetHeight); - } - async handleSetTitle(config) { - document.title = config.title; - } - async initializeFocusTracking() { - if (this.isWorkspaceFrame) { - this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame"); - return; - } - try { - await this.bridge.send("windows", commonOperations.operationCheck, { operation: "focusChange" }); - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client."); - return; - } - const hasFocus = document.hasFocus(); - await this.transmitFocusChange(true); - if (!hasFocus) { - await this.transmitFocusChange(false); - } - this.defineEventListeners(); - } - processFocusEvent() { - const hasFocus = document.hasFocus(); - this.transmitFocusChange(hasFocus); - } - waitForWindowAdded(windowId) { - const foundWindow = this.allWindowProjections.find((projection) => projection.id === windowId); - if (foundWindow) { - return Promise.resolve(foundWindow.api); - } - return PromisePlus$1((resolve) => { - const unsubscribe = this.onWindowAdded((addedWindow) => { - if (addedWindow.id === windowId) { - unsubscribe(); - resolve(addedWindow); - } - }); - }, 30000, `Timed out waiting for ${windowId} to be announced`); - } - async transmitFocusChange(hasFocus) { - const eventData = { - windowId: this.me?.id || `iframe-${this.instanceId}`, - hasFocus - }; - if (this.me) { - this.me.isFocused = hasFocus; - } - await this.bridge.send("windows", operations$a.focusChange, eventData); - } - defineEventListeners() { - this.focusEventHandler = this.processFocusEvent.bind(this); - document.addEventListener("visibilityChange", this.focusEventHandler); - window.addEventListener("focus", this.focusEventHandler); - window.addEventListener("blur", this.focusEventHandler); - } - async handleGetChannel() { - if (!this.me) { - return ioError.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe"); - } - const channel = this.channelsController.my(); - return { - ...(channel ? { channel } : {}), - }; - } - async handleRefresh() { - if (!this.me) { - return ioError.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe"); - } - setTimeout(() => { - window.location.reload(); - }, 0); - } - async handleChannelsChanged(data) { - const windowProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - windowProjection?.model.processChannelsChangedEvent(data.channelNames); - } - async handleSetZoomFactor(config) { - if (!this.me) { - return ioError.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe"); - } - document.body.style.zoom = `${ZOOM_FACTORS[config.factorIndex]}%`; - } - async handleZoomFactorChanged(data) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfZoomFactorChangedEvent(data.factorIndex); - } - } - - const GlueWebPlatformControlName = "T42.Web.Platform.Control"; - const GlueWebPlatformStreamName = "T42.Web.Platform.Stream"; - const GlueClientControlName = "T42.Web.Client.Control"; - const GlueCorePlusThemesStream = "T42.Core.Plus.Themes.Stream"; - - class GlueBridge { - coreGlue; - communicationId; - platformMethodTimeoutMs = 10000; - controllers; - sub; - running; - constructor(coreGlue, communicationId) { - this.coreGlue = coreGlue; - this.communicationId = communicationId; - } - get contextLib() { - return this.coreGlue.contexts; - } - get interopInstance() { - return this.coreGlue.interop.instance.instance; - } - async stop() { - this.running = false; - this.sub.close(); - await this.coreGlue.interop.unregister(GlueClientControlName); - } - async start(controllers) { - this.running = true; - this.controllers = controllers; - await Promise.all([ - this.checkWaitMethod(GlueWebPlatformControlName), - this.checkWaitMethod(GlueWebPlatformStreamName) - ]); - const systemId = this.communicationId; - const [sub] = await Promise.all([ - this.coreGlue.interop.subscribe(GlueWebPlatformStreamName, systemId ? { target: { instance: this.communicationId } } : undefined), - this.coreGlue.interop.registerAsync(GlueClientControlName, (args, _, success, error) => this.passMessageController(args, success, error)) - ]); - this.sub = sub; - this.sub.onData((pkg) => this.passMessageController(pkg.data)); - } - getInteropInstance(windowId) { - const result = this.coreGlue.interop.servers().find((s) => s.windowId && s.windowId === windowId); - return { - application: result?.application, - applicationName: result?.applicationName, - peerId: result?.peerId, - instance: result?.instance, - windowId: result?.windowId - }; - } - async send(domain, operation, operationData, options, webOptions) { - if (operation.dataDecoder) { - try { - operation.dataDecoder.runWithException(operationData); - } - catch (error) { - return ioError.raiseError(`Unexpected Web->Platform outgoing validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - } - const operationSupported = webOptions?.includeOperationCheck ? - (await this.checkOperationSupported(domain, operation)).isSupported : - true; - if (!operationSupported) { - return ioError.raiseError(`Cannot complete operation: ${operation.name} for domain: ${domain} because this client is connected to a platform which does not support it`); - } - try { - const operationResult = await this.transmitMessage(domain, operation, operationData, options); - if (operation.resultDecoder) { - operation.resultDecoder.runWithException(operationResult); - } - return operationResult; - } - catch (error) { - if (error?.kind) { - return ioError.raiseError(`Unexpected Web<-Platform incoming validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - return ioError.raiseError(error); - } - } - async createNotificationsSteam() { - const streamExists = this.coreGlue.interop.methods().some((method) => method.name === GlueCorePlusThemesStream); - if (!streamExists) { - return ioError.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus."); - } - return this.coreGlue.interop.subscribe(GlueCorePlusThemesStream, this.communicationId ? { target: { instance: this.communicationId } } : undefined); - } - async checkOperationSupported(domain, operation) { - try { - const result = await this.send(domain, commonOperations.operationCheck, { operation: operation.name }); - return result; - } - catch (error) { - return { isSupported: false }; - } - } - checkWaitMethod(name) { - return PromisePlus$1((resolve) => { - const hasMethod = this.coreGlue.interop.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = this.communicationId ? - method.getServers().some((server) => server.instance === this.communicationId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - return resolve(); - } - const unSub = this.coreGlue.interop.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = this.communicationId ? - server.instance === this.communicationId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }, this.platformMethodTimeoutMs, `Cannot initiate Glue Web, because a system method's discovery timed out: ${name}`); - } - passMessageController(args, success, error) { - const decodeResult = libDomainDecoder.run(args.domain); - if (!decodeResult.ok) { - if (error) { - error(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(decodeResult.error)}`); - } - return; - } - const domain = decodeResult.result; - this.controllers[domain] - .handleBridgeMessage(args) - .then((resolutionData) => { - if (success) { - success(resolutionData); - } - }) - .catch((err) => { - if (error) { - error(err); - } - console.warn(err); - }); - } - async transmitMessage(domain, operation, data, options) { - const messageData = { domain, data, operation: operation.name }; - let invocationResult; - const baseErrorMessage = `Internal Platform Communication Error. Attempted operation: ${JSON.stringify(operation.name)} with data: ${JSON.stringify(data)}. `; - const systemId = this.communicationId; - try { - if (!this.running) { - throw new Error("Cannot send a control message, because the platform shut down"); - } - invocationResult = await this.coreGlue.interop.invoke(GlueWebPlatformControlName, messageData, systemId ? { instance: this.communicationId } : undefined, options); - if (!invocationResult) { - throw new Error("Received unsupported result from the platform - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from the platform - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - } - - const operations$9 = { - appHello: { name: "appHello", dataDecoder: windowHelloDecoder, resultDecoder: appHelloSuccessDecoder }, - appDirectoryStateChange: { name: "appDirectoryStateChange", dataDecoder: appDirectoryStateChangeDecoder }, - instanceStarted: { name: "instanceStarted", dataDecoder: instanceDataDecoder }, - instanceStopped: { name: "instanceStopped", dataDecoder: instanceDataDecoder }, - applicationStart: { name: "applicationStart", dataDecoder: applicationStartConfigDecoder, resultDecoder: instanceDataDecoder }, - instanceStop: { name: "instanceStop", dataDecoder: basicInstanceDataDecoder }, - import: { name: "import" }, - remove: { name: "remove", dataDecoder: appRemoveConfigDecoder }, - export: { name: "export", resultDecoder: appsExportOperationDecoder }, - clear: { name: "clear" }, - operationCheck: { name: "operationCheck" } - }; - - class AppManagerController { - me; - supportedOperationsNames = []; - baseApplicationsTimeoutMS = 60000; - appImportTimeoutMS = 20; - registry = CallbackRegistryFactory$1(); - ioc; - bridge; - publicWindowId; - applications = []; - instances = []; - platformRegistration; - logger; - channelsController; - interop; - initialChannelId; - handlePlatformShutdown() { - this.registry.clear(); - this.applications = []; - this.instances = []; - delete this.me; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("appManger.controller.web"); - this.logger.trace("starting the web appManager controller"); - this.publicWindowId = ioc.publicWindowId; - this.addOperationsExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.interop = coreGlue.interop; - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning"); - const api = this.toApi(); - coreGlue.appManager = api; - } - async postStart() { - if (!this.initialChannelId) { - return; - } - await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(appManagerOperationTypesDecoder, args.operation); - const operation = operations$9[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStarted requires a single argument of type function"); - } - return this.registry.add("instance-started", callback, this.instances); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStopped requires a single argument of type function"); - } - return this.registry.add("instance-stopped", callback); - } - async startApplication(appName, context, options) { - const channels = await this.channelsController.all(); - if (options?.channelId && !channels.includes(options.channelId)) { - return ioError.raiseError(`The channel with name "${options.channelId}" doesn't exist!`); - } - const startOptions = { - name: appName, - waitForAGMReady: options?.waitForAGMReady ?? true, - context, - top: options?.top, - left: options?.left, - width: options?.width, - height: options?.height, - relativeTo: options?.relativeTo, - relativeDirection: options?.relativeDirection, - id: options?.reuseId, - forceChromeTab: options?.forceTab, - layoutComponentId: options?.layoutComponentId, - channelId: options?.channelId, - startReason: { - originApp: { - name: this.me?.application.name, - interopInstance: this.interop.instance.instance - } - } - }; - if (options?.originIntentRequest) { - startOptions.startReason.intentRequest = options.originIntentRequest; - } - const openResult = await this.bridge.send("appManager", operations$9.applicationStart, startOptions); - const app = this.applications.find((a) => a.name === openResult.applicationName); - return this.ioc.buildInstance(openResult, app); - } - getApplication(name) { - const verifiedName = runDecoderWithIOError(nonEmptyStringDecoder$2, name); - return this.applications.find((app) => app.name === verifiedName); - } - getInstances() { - return this.instances.slice(); - } - onAppAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppAdded requires a single argument of type function"); - } - return this.registry.add("application-added", callback, this.applications); - } - onAppRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppRemoved requires a single argument of type function"); - } - return this.registry.add("application-removed", callback); - } - toApi() { - const api = { - myInstance: this.me, - inMemory: { - import: this.importApps.bind(this), - remove: this.remove.bind(this), - export: this.exportApps.bind(this), - clear: this.clear.bind(this) - }, - application: this.getApplication.bind(this), - applications: this.getApplications.bind(this), - instances: this.getInstances.bind(this), - onAppAdded: this.onAppAdded.bind(this), - onAppChanged: this.onAppChanged.bind(this), - onAppRemoved: this.onAppRemoved.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - return api; - } - addOperationsExecutors() { - operations$9.appDirectoryStateChange.execute = this.handleAppDirectoryStateChange.bind(this); - operations$9.instanceStarted.execute = this.handleInstanceStartedMessage.bind(this); - operations$9.instanceStopped.execute = this.handleInstanceStoppedMessage.bind(this); - operations$9.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$9); - } - async handleAppDirectoryStateChange(data) { - data.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)); - data.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)); - data.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this)); - } - onAppChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppChanged requires a single argument of type function"); - } - return this.registry.add("application-changed", callback); - } - async handleApplicationAddedMessage(appData) { - if (this.applications.some((app) => app.name === appData.name)) { - return; - } - const app = await this.ioc.buildApplication(appData, []); - const instances = this.instances.filter((instance) => instance.application.name === app.name); - app.instances.push(...instances); - this.applications.push(app); - this.registry.execute("application-added", app); - } - async handleApplicationRemovedMessage(appData) { - const appIndex = this.applications.findIndex((app) => app.name === appData.name); - if (appIndex < 0) { - return; - } - const app = this.applications[appIndex]; - this.applications.splice(appIndex, 1); - this.registry.execute("application-removed", app); - } - async handleApplicationChangedMessage(appData) { - const app = this.applications.find((app) => app.name === appData.name); - if (!app) { - return this.handleApplicationAddedMessage(appData); - } - app.title = appData.title; - app.version = appData.version; - app.icon = appData.icon; - app.caption = appData.caption; - app.userProperties = appData.userProperties; - this.registry.execute("application-changed", app); - } - async handleInstanceStartedMessage(instanceData) { - if (this.instances.some((instance) => instance.id === instanceData.id)) { - return; - } - const application = this.applications.find((app) => app.name === instanceData.applicationName); - if (!application) { - return ioError.raiseError(`Cannot add instance: ${instanceData.id}, because there is no application definition associated with it`); - } - const instance = this.ioc.buildInstance(instanceData, application); - this.instances.push(instance); - application.instances.push(instance); - this.registry.execute("instance-started", instance); - } - async handleInstanceStoppedMessage(instanceData) { - const instance = this.instances.find((i) => i.id === instanceData.id); - if (instance) { - const instIdx = this.instances.findIndex((inst) => inst.id === instanceData.id); - this.instances.splice(instIdx, 1); - } - const application = this.applications.find((app) => app.instances.some((inst) => inst.id === instanceData.id)); - if (application) { - const instIdxApps = application.instances.findIndex((inst) => inst.id === instanceData.id); - application.instances.splice(instIdxApps, 1); - } - if (!instance) { - return; - } - this.registry.execute("instance-stopped", instance); - } - async importApps(definitions, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(definitions)) { - return ioError.raiseError("Import must be called with an array of definitions"); - } - if (definitions.length > 10000) { - return ioError.raiseError("Cannot import more than 10000 app definitions in Glue42 Core."); - } - const parseResult = definitions.reduce((soFar, definition) => { - const { isValid, error } = this.isValidDefinition(definition); - if (!isValid) { - soFar.invalid.push({ app: definition?.name, error: error ?? `Provided definition is invalid ${JSON.stringify(definition)}` }); - } - else { - soFar.valid.push(definition); - } - return soFar; - }, { valid: [], invalid: [] }); - const responseTimeout = this.baseApplicationsTimeoutMS + this.appImportTimeoutMS * parseResult.valid.length; - await this.bridge.send("appManager", operations$9.import, { definitions: parseResult.valid, mode }, { methodResponseTimeoutMs: responseTimeout }); - return { - imported: parseResult.valid.map((valid) => valid.name), - errors: parseResult.invalid - }; - } - isValidDefinition(definition) { - const isFdc3V2Definition = definition?.appId && definition?.details; - if (isFdc3V2Definition) { - const decodeResult = decoders.fdc3.v2DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v2 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const isFdc3V1Definition = definition?.appId && definition?.manifest; - if (isFdc3V1Definition) { - const decodeResult = decoders.fdc3.v1DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v1 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const decodeResult = applicationDefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("appManager", operations$9.remove, { name }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async clear() { - await this.bridge.send("appManager", operations$9.clear, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async exportApps() { - const response = await this.bridge.send("appManager", operations$9.export, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - return response.definitions; - } - getApplications() { - return this.applications.slice(); - } - async registerWithPlatform() { - const result = await this.bridge.send("appManager", operations$9.appHello, { windowId: this.publicWindowId }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - this.logger.trace("the platform responded to the hello message with a full list of apps"); - this.applications = await Promise.all(result.apps.map((app) => this.ioc.buildApplication(app, app.instances))); - this.instances = this.applications.reduce((instancesSoFar, app) => { - instancesSoFar.push(...app.instances); - return instancesSoFar; - }, []); - this.me = this.findMyInstance(); - this.logger.trace(`all applications were parsed and saved. I am ${this.me ? "NOT a" : "a"} valid instance`); - this.initialChannelId = result.initialChannelId; - } - findMyInstance() { - for (const app of this.applications) { - const foundInstance = app.instances.find((instance) => instance.id === this.publicWindowId); - if (foundInstance) { - return foundInstance; - } - } - return undefined; - } - } - - class InstanceModel { - data; - bridge; - application; - me; - myCtxKey; - constructor(data, bridge, application) { - this.data = data; - this.bridge = bridge; - this.application = application; - this.myCtxKey = `___instance___${this.data.id}`; - } - toApi() { - const agm = this.bridge.getInteropInstance(this.data.id); - const api = { - id: this.data.id, - agm, - application: this.application, - stop: this.stop.bind(this), - getContext: this.getContext.bind(this) - }; - this.me = Object.freeze(api); - return this.me; - } - async getContext() { - return this.bridge.contextLib.get(this.myCtxKey); - } - async stop() { - await this.bridge.send("appManager", operations$9.instanceStop, { id: this.data.id }); - } - } - - class ApplicationModel { - data; - instances; - controller; - me; - constructor(data, instances, controller) { - this.data = data; - this.instances = instances; - this.controller = controller; - } - toApi() { - const api = { - name: this.data.name, - title: this.data.title, - version: this.data.version, - icon: this.data.icon, - caption: this.data.caption, - userProperties: this.data.userProperties, - instances: this.instances, - start: this.start.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - this.me = api; - return this.me; - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStarted((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStopped((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - async start(context, options) { - const verifiedContext = runDecoderWithIOError(startApplicationContextDecoder, context); - const verifiedOptions = runDecoderWithIOError(startApplicationOptionsDecoder, options); - return this.controller.startApplication(this.data.name, verifiedContext, verifiedOptions); - } - } - - const operations$8 = { - layoutAdded: { name: "layoutAdded", dataDecoder: glueLayoutDecoder }, - layoutChanged: { name: "layoutChanged", dataDecoder: glueLayoutDecoder }, - layoutRemoved: { name: "layoutRemoved", dataDecoder: glueLayoutDecoder }, - layoutRestored: { name: "layoutRestored", dataDecoder: glueLayoutDecoder }, - defaultLayoutChanged: { name: "defaultLayoutChanged", dataDecoder: defaultGlobalChangedDecoder }, - layoutRenamed: { name: "layoutRenamed", dataDecoder: renamedLayoutNotificationDecoder }, - get: { name: "get", dataDecoder: simpleLayoutConfigDecoder, resultDecoder: optionalSimpleLayoutResult }, - getAll: { name: "getAll", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsSummariesResultDecoder }, - export: { name: "export", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsFullConfigDecoder }, - import: { name: "import", dataDecoder: layoutsImportConfigDecoder }, - remove: { name: "remove", dataDecoder: simpleLayoutConfigDecoder }, - rename: { name: "rename", dataDecoder: renameLayoutConfigDecoder, resultDecoder: layoutResultDecoder }, - save: { name: "save", dataDecoder: saveLayoutConfigDecoder, resultDecoder: simpleLayoutResultDecoder }, - restore: { name: "restore", dataDecoder: restoreLayoutConfigDecoder }, - clientSaveRequest: { name: "clientSaveRequest", dataDecoder: platformSaveRequestConfigDecoder, resultDecoder: saveRequestClientResponseDecoder }, - getGlobalPermissionState: { name: "getGlobalPermissionState", resultDecoder: permissionStateResultDecoder }, - requestGlobalPermission: { name: "requestGlobalPermission", resultDecoder: simpleAvailabilityResultDecoder }, - checkGlobalActivated: { name: "checkGlobalActivated", resultDecoder: simpleAvailabilityResultDecoder }, - getDefaultGlobal: { name: "getDefaultGlobal", resultDecoder: optionalSimpleLayoutResult }, - setDefaultGlobal: { name: "setDefaultGlobal", dataDecoder: setDefaultGlobalConfigDecoder }, - clearDefaultGlobal: { name: "clearDefaultGlobal" }, - getCurrent: { name: "getCurrent", resultDecoder: optionalSimpleLayoutResult }, - updateMetadata: { name: "updateMetadata", dataDecoder: updateLayoutMetadataConfigDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class LayoutsController { - supportedOperationsNames = []; - defaultLayoutRestoreTimeoutMS = 120000; - registry = CallbackRegistryFactory$1(); - bridge; - logger; - windowsController; - saveRequestSubscription; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("layouts.controller.web"); - this.logger.trace("starting the web layouts controller"); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.addOperationsExecutors(); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"); - coreGlue.layouts = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(layoutsOperationTypesDecoder, args.operation); - const operation = operations$8[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - get: this.get.bind(this), - getAll: this.getAll.bind(this), - getCurrentLayout: this.getCurrentLayout.bind(this), - export: this.exportLayouts.bind(this), - import: this.importLayouts.bind(this), - save: this.save.bind(this), - restore: this.restore.bind(this), - remove: this.remove.bind(this), - onAdded: this.onAdded.bind(this), - onChanged: this.onChanged.bind(this), - onRemoved: this.onRemoved.bind(this), - onDefaultGlobalChanged: this.onDefaultGlobalChanged.bind(this), - onSaveRequested: this.subscribeOnSaveRequested.bind(this), - getMultiScreenPermissionState: this.getGlobalPermissionState.bind(this), - requestMultiScreenPermission: this.requestGlobalPermission.bind(this), - getGlobalTypeState: this.checkGlobalActivated.bind(this), - getDefaultGlobal: this.getDefaultGlobal.bind(this), - setDefaultGlobal: this.setDefaultGlobal.bind(this), - clearDefaultGlobal: this.clearDefaultGlobal.bind(this), - rename: this.rename.bind(this), - onRenamed: this.onRenamed.bind(this), - onRestored: this.onRestored.bind(this), - updateMetadata: this.updateMetadata.bind(this) - }; - return Object.freeze(api); - } - addOperationsExecutors() { - operations$8.layoutAdded.execute = this.handleOnAdded.bind(this); - operations$8.layoutChanged.execute = this.handleOnChanged.bind(this); - operations$8.layoutRemoved.execute = this.handleOnRemoved.bind(this); - operations$8.layoutRenamed.execute = this.handleOnRenamed.bind(this); - operations$8.layoutRestored.execute = this.handleOnRestored.bind(this); - operations$8.defaultLayoutChanged.execute = this.handleOnDefaultChanged.bind(this); - operations$8.clientSaveRequest.execute = this.handleSaveRequest.bind(this); - operations$8.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$8); - } - async get(name, type) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.get, { name, type }); - return result.layout; - } - async getCurrentLayout() { - const result = await this.bridge.send("layouts", operations$8.getCurrent, undefined); - return result.layout; - } - async getAll(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.getAll, { type }); - return result.summaries; - } - async exportLayouts(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.export, { type }); - return result.layouts; - } - async importLayouts(layouts, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(layouts)) { - return ioError.raiseError("Import must be called with an array of layouts"); - } - if (layouts.length > 1000) { - return ioError.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core."); - } - const parseResult = layouts.reduce((soFar, layout) => { - const decodeResult = glueLayoutDecoder.run(layout); - if (decodeResult.ok) { - soFar.valid.push(layout); - } - else { - this.logger.warn(`A layout with name: ${layout.name} was not imported, because of error: ${JSON.stringify(decodeResult.error)}`); - } - return soFar; - }, { valid: [] }); - const layoutsToImport = layouts.filter((layout) => parseResult.valid.some((validLayout) => validLayout.name === layout.name)); - await this.bridge.send("layouts", operations$8.import, { layouts: layoutsToImport, mode }); - } - async save(layout) { - runDecoderWithIOError(newLayoutOptionsDecoder, layout); - const saveResult = await this.bridge.send("layouts", operations$8.save, { layout }); - return saveResult.layout; - } - async restore(options) { - runDecoderWithIOError(restoreOptionsDecoder, options); - const invocationTimeout = options.timeout ? options.timeout * 2 : this.defaultLayoutRestoreTimeoutMS; - await this.bridge.send("layouts", operations$8.restore, { layout: options }, { methodResponseTimeoutMs: invocationTimeout }); - } - async remove(type, name) { - runDecoderWithIOError(layoutTypeDecoder, type); - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.remove, { type, name }); - } - async handleSaveRequest(config) { - const response = {}; - if (this.saveRequestSubscription) { - try { - const onSaveRequestResponse = this.saveRequestSubscription(config); - response.windowContext = onSaveRequestResponse?.windowContext; - } - catch (error) { - this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(error)}`); - } - } - return response; - } - async getGlobalPermissionState() { - const requestResult = await this.bridge.send("layouts", operations$8.getGlobalPermissionState, undefined); - return requestResult; - } - async requestGlobalPermission() { - const currentState = (await this.getGlobalPermissionState()).state; - if (currentState === "denied") { - return { permissionGranted: false }; - } - if (currentState === "granted") { - return { permissionGranted: true }; - } - const myWindow = this.windowsController.my(); - const globalNamespace = window.glue42core || window.iobrowser; - const amIWorkspaceFrame = globalNamespace.isPlatformFrame; - if (myWindow.name !== "Platform" && !amIWorkspaceFrame) { - return ioError.raiseError("Cannot request permission for multi-window placement from any app other than the Platform."); - } - const requestResult = await this.bridge.send("layouts", operations$8.requestGlobalPermission, undefined, { methodResponseTimeoutMs: 180000 }); - return { permissionGranted: requestResult.isAvailable }; - } - async checkGlobalActivated() { - const requestResult = await this.bridge.send("layouts", operations$8.checkGlobalActivated, undefined); - return { activated: requestResult.isAvailable }; - } - async getDefaultGlobal() { - const requestResult = await this.bridge.send("layouts", operations$8.getDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - return requestResult.layout; - } - async setDefaultGlobal(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.setDefaultGlobal, { name }, undefined, { includeOperationCheck: true }); - } - async clearDefaultGlobal() { - await this.bridge.send("layouts", operations$8.clearDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - } - async rename(layout, newName) { - runDecoderWithIOError(glueLayoutDecoder, layout); - runDecoderWithIOError(nonEmptyStringDecoder$2, newName); - const result = await this.bridge.send("layouts", operations$8.rename, { layout, newName }, undefined, { includeOperationCheck: true }); - return result; - } - async updateMetadata(layout) { - runDecoderWithIOError(glueLayoutDecoder, layout); - await this.bridge.send("layouts", operations$8.updateMetadata, { layout }, undefined, { includeOperationCheck: true }); - } - onAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"); - } - this.exportLayouts("Global").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - this.exportLayouts("Workspace").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - return this.registry.add(operations$8.layoutAdded.name, callback); - } - onChanged(callback) { - return this.registry.add(operations$8.layoutChanged.name, callback); - } - onDefaultGlobalChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"); - } - this.getDefaultGlobal().then((layout) => callback(layout ? { name: layout.name } : undefined)).catch(() => { }); - return this.registry.add(operations$8.defaultLayoutChanged.name, callback); - } - onRemoved(callback) { - return this.registry.add(operations$8.layoutRemoved.name, callback); - } - onRenamed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRenamed.name, callback); - } - onRestored(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRestored.name, callback); - } - subscribeOnSaveRequested(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."); - } - if (this.saveRequestSubscription) { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."); - } - this.saveRequestSubscription = callback; - return () => { - delete this.saveRequestSubscription; - }; - } - async handleOnAdded(layout) { - this.registry.execute(operations$8.layoutAdded.name, layout); - } - async handleOnChanged(layout) { - this.registry.execute(operations$8.layoutChanged.name, layout); - } - async handleOnDefaultChanged(layout) { - this.registry.execute(operations$8.defaultLayoutChanged.name, layout); - } - async handleOnRemoved(layout) { - this.registry.execute(operations$8.layoutRemoved.name, layout); - } - async handleOnRestored(layout) { - this.registry.execute(operations$8.layoutRestored.name, layout); - } - async handleOnRenamed(renamedData) { - const { prevName, ...layout } = renamedData; - this.registry.execute(operations$8.layoutRenamed.name, layout, { name: prevName }); - } - } - - const operations$7 = { - raiseNotification: { name: "raiseNotification", dataDecoder: raiseNotificationDecoder, resultDecoder: raiseNotificationResultDecoder }, - requestPermission: { name: "requestPermission", resultDecoder: permissionRequestResultDecoder }, - notificationShow: { name: "notificationShow", dataDecoder: notificationEventPayloadDecoder }, - notificationClick: { name: "notificationClick", dataDecoder: notificationEventPayloadDecoder }, - getPermission: { name: "getPermission", resultDecoder: permissionQueryResultDecoder }, - list: { name: "list", resultDecoder: allNotificationsDataDecoder }, - notificationRaised: { name: "notificationRaised", dataDecoder: simpleNotificationDataDecoder }, - notificationClosed: { name: "notificationClosed", dataDecoder: simpleNotificationSelectDecoder }, - click: { name: "click" }, - clear: { name: "clear" }, - clearAll: { name: "clearAll" }, - clearOld: { name: "clearOld" }, - configure: { name: "configure", dataDecoder: notificationsConfigurationProtocolDecoder }, - getConfiguration: { name: "getConfiguration", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - getActiveCount: { name: "getActiveCount", resultDecoder: activeNotificationsCountChangeDecoder }, - configurationChanged: { name: "configurationChanged", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - setState: { name: "setState", dataDecoder: notificationSetStateRequestDecoder }, - activeCountChange: { name: "activeCountChange", resultDecoder: activeNotificationsCountChangeDecoder }, - stateChange: { name: "stateChange", resultDecoder: notificationSetStateRequestDecoder }, - operationCheck: { name: "operationCheck" } - }; - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet$1 = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid$1 = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet$1[(Math.random() * 64) | 0]; - } - return id - }; - - class NotificationsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - bridge; - notificationsSettings; - notifications = {}; - coreGlue; - buildNotificationFunc; - notificationsConfiguration; - notificationsActiveCount = 0; - handlePlatformShutdown() { - this.notifications = {}; - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("notifications.controller.web"); - this.logger.trace("starting the web notifications controller"); - this.bridge = ioc.bridge; - this.coreGlue = coreGlue; - this.notificationsSettings = ioc.config.notifications; - this.buildNotificationFunc = ioc.buildNotification; - this.notificationsConfiguration = await this.getConfiguration(); - this.notificationsActiveCount = await this.getActiveCount(); - const api = this.toApi(); - this.addOperationExecutors(); - coreGlue.notifications = api; - this.logger.trace("notifications are ready"); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(notificationsOperationTypesDecoder, args.operation); - const operation = operations$7[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - requestPermission: this.requestPermission.bind(this), - getPermission: this.getPermission.bind(this), - list: this.list.bind(this), - onRaised: this.onRaised.bind(this), - onClosed: this.onClosed.bind(this), - click: this.click.bind(this), - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearOld: this.clearOld.bind(this), - configure: this.configure.bind(this), - getConfiguration: this.getConfiguration.bind(this), - getFilter: this.getFilter.bind(this), - setFilter: this.setFilter.bind(this), - setState: this.setState.bind(this), - onConfigurationChanged: this.onConfigurationChanged.bind(this), - onActiveCountChanged: this.onActiveCountChanged.bind(this), - onCounterChanged: this.onActiveCountChanged.bind(this), - onStateChanged: this.onStateChanged.bind(this) - }; - return Object.freeze(api); - } - async getPermission() { - const queryResult = await this.bridge.send("notifications", operations$7.getPermission, undefined); - return queryResult.permission; - } - async requestPermission() { - const permissionResult = await this.bridge.send("notifications", operations$7.requestPermission, undefined); - return permissionResult.permissionGranted; - } - async raise(options) { - const settings = runDecoderWithIOError(glue42NotificationOptionsDecoder, options); - settings.showToast = typeof settings.showToast === "boolean" ? settings.showToast : true; - settings.showInPanel = typeof settings.showInPanel === "boolean" ? settings.showInPanel : true; - const permissionGranted = await this.requestPermission(); - if (!permissionGranted) { - return ioError.raiseError("Cannot raise the notification, because the user has declined the permission request"); - } - const id = nanoid$1(10); - const raiseResult = await this.bridge.send("notifications", operations$7.raiseNotification, { settings, id }); - const notification = this.buildNotificationFunc(raiseResult.settings, id); - this.notifications[id] = notification; - return notification; - } - async list() { - const bridgeResponse = await this.bridge.send("notifications", operations$7.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.notifications; - } - onRaised(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onRaised expects a callback of type function"); - } - return this.registry.add("notification-raised", callback); - } - onClosed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onClosed expects a callback of type function"); - } - return this.registry.add("notification-closed", callback); - } - async click(id, action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - if (action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, action); - } - await this.bridge.send("notifications", operations$7.click, { id, action }, undefined, { includeOperationCheck: true }); - } - async clear(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - await this.bridge.send("notifications", operations$7.clear, { id }, undefined, { includeOperationCheck: true }); - } - async clearAll() { - await this.bridge.send("notifications", operations$7.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearOld() { - await this.bridge.send("notifications", operations$7.clearOld, undefined, undefined, { includeOperationCheck: true }); - } - async configure(config) { - const verifiedConfig = runDecoderWithIOError(notificationsConfigurationDecoder, config); - await this.bridge.send("notifications", operations$7.configure, { configuration: verifiedConfig }, undefined, { includeOperationCheck: true }); - } - async getConfiguration() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration; - } - async getActiveCount() { - try { - const response = await this.bridge.send("notifications", operations$7.getActiveCount, undefined, undefined, { includeOperationCheck: true }); - return response.count; - } - catch (error) { - console.warn("Failed to get accurate active notifications count", error); - return 0; - } - } - async getFilter() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration.sourceFilter; - } - async setFilter(filter) { - const verifiedFilter = runDecoderWithIOError(notificationFilterDecoder, filter); - await this.bridge.send("notifications", operations$7.configure, { configuration: { sourceFilter: verifiedFilter } }, undefined, { includeOperationCheck: true }); - return verifiedFilter; - } - async setState(id, state) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - runDecoderWithIOError(notificationStateDecoder, state); - await this.bridge.send("notifications", operations$7.setState, { id, state }, undefined, { includeOperationCheck: true }); - } - onConfigurationChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"); - } - setTimeout(() => callback(this.notificationsConfiguration), 0); - return this.registry.add("notifications-config-changed", callback); - } - onActiveCountChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"); - } - setTimeout(() => callback({ count: this.notificationsActiveCount }), 0); - return this.registry.add("notifications-active-count-changed", callback); - } - onStateChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"); - } - return this.registry.add("notification-state-changed", callback); - } - addOperationExecutors() { - operations$7.notificationShow.execute = this.handleNotificationShow.bind(this); - operations$7.notificationClick.execute = this.handleNotificationClick.bind(this); - operations$7.notificationRaised.execute = this.handleNotificationRaised.bind(this); - operations$7.notificationClosed.execute = this.handleNotificationClosed.bind(this); - operations$7.configurationChanged.execute = this.handleConfigurationChanged.bind(this); - operations$7.activeCountChange.execute = this.handleActiveCountChanged.bind(this); - operations$7.stateChange.execute = this.handleNotificationStateChanged.bind(this); - operations$7.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$7); - } - async handleConfigurationChanged(data) { - this.notificationsConfiguration = data.configuration; - this.registry.execute("notifications-config-changed", data.configuration); - } - async handleActiveCountChanged(data) { - this.notificationsActiveCount = data.count; - this.registry.execute("notifications-active-count-changed", data); - } - async handleNotificationStateChanged(data) { - this.registry.execute("notification-state-changed", { id: data.id }, data.state); - } - async handleNotificationShow(data) { - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onshow) { - notification.onshow(); - } - } - async handleNotificationClick(data) { - if (!data.action && this.notificationsSettings?.defaultClick) { - this.notificationsSettings.defaultClick(this.coreGlue, data.definition); - } - if (data.action && this.notificationsSettings?.actionClicks?.some((actionDef) => actionDef.action === data.action)) { - const foundHandler = this.notificationsSettings?.actionClicks?.find((actionDef) => actionDef.action === data.action); - foundHandler.handler(this.coreGlue, data.definition); - } - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onclick) { - notification.onclick(); - delete this.notifications[data.id]; - } - } - async handleNotificationRaised(data) { - this.registry.execute("notification-raised", data.notification); - } - async handleNotificationClosed(data) { - this.registry.execute("notification-closed", data); - } - } - - const operations$6 = { - getIntents: { name: "getIntents", resultDecoder: wrappedIntentsDecoder }, - findIntent: { name: "findIntent", dataDecoder: wrappedIntentFilterDecoder, resultDecoder: wrappedIntentsDecoder }, - raise: { name: "raise", dataDecoder: raiseIntentRequestDecoder, resultDecoder: intentResultDecoder }, - filterHandlers: { name: "filterHandlers", dataDecoder: filterHandlersWithResolverConfigDecoder, resultDecoder: filterHandlersResultDecoder }, - getIntentsByHandler: { name: "getIntentsByHandler", dataDecoder: intentHandlerDecoder, resultDecoder: getIntentsResultDecoder } - }; - - const GLUE42_FDC3_INTENTS_METHOD_PREFIX = "Tick42.FDC3.Intents."; - const INTENTS_RESOLVER_APP_NAME = "intentsResolver"; - const DEFAULT_RESOLVER_RESPONSE_TIMEOUT = 60 * 1000; - const ADDITIONAL_BRIDGE_OPERATION_TIMEOUT = 30 * 1000; - const DEFAULT_PICK_HANDLER_BY_TIMEOUT = 90 * 1000; - - class IntentsController { - bridge; - logger; - interop; - appManagerController; - windowsController; - myIntents = new Set(); - prefsController; - uiController; - useIntentsResolverUI = true; - intentsResolverAppName; - intentResolverResponseTimeout = DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - unregisterIntentPromises = []; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("intents.controller.web"); - this.logger.trace("starting the web intents controller"); - this.bridge = ioc.bridge; - this.interop = coreGlue.interop; - this.appManagerController = ioc.appManagerController; - this.windowsController = ioc.windowsController; - this.prefsController = ioc.prefsController; - this.uiController = ioc.uiController; - this.checkIfIntentsResolverIsEnabled(ioc.config); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"); - coreGlue.intents = api; - } - handlePlatformShutdown() { - this.myIntents = new Set(); - this.unregisterIntentPromises = []; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(intentsOperationTypesDecoder, args.operation); - const operation = operations$6[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - all: this.all.bind(this), - addIntentListener: this.addIntentListener.bind(this), - register: this.register.bind(this), - find: this.find.bind(this), - filterHandlers: this.filterHandlers.bind(this), - getIntents: this.getIntentsByHandler.bind(this), - clearSavedHandlers: this.clearSavedHandlers.bind(this), - onHandlerAdded: this.onHandlerAdded.bind(this), - onHandlerRemoved: this.onHandlerRemoved.bind(this) - }; - return api; - } - async raise(request) { - const validatedIntentRequest = runDecoderWithIOError(raiseRequestDecoder, request); - const intentRequest = typeof validatedIntentRequest === "string" - ? { intent: validatedIntentRequest } - : validatedIntentRequest; - await Promise.all(this.unregisterIntentPromises); - if (intentRequest.clearSavedHandler) { - this.logger.trace(`User removes saved handler for intent ${intentRequest.intent}`); - await this.removeRememberedHandler(intentRequest.intent); - } - const resultFromRememberedHandler = await this.checkHandleRaiseWithRememberedHandler(intentRequest); - if (resultFromRememberedHandler) { - return resultFromRememberedHandler; - } - const requestWithResolverInfo = { - intentRequest, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - const methodResponseTimeoutMs = intentRequest.waitUserResponseIndefinitely - ? MAX_SET_TIMEOUT_DELAY - : (intentRequest.timeout || this.intentResolverResponseTimeout) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(request)} and method response timeout of ${methodResponseTimeoutMs}ms`); - const response = await this.bridge.send("intents", operations$6.raise, requestWithResolverInfo, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }); - this.logger.trace(`Raise operation completed with response: ${JSON.stringify(response)}`); - return response; - } - getLegacyResolverConfigByRequest(filter) { - if (filter.handlerFilter) { - return { - enabled: typeof filter.handlerFilter?.openResolver === "boolean" ? filter.handlerFilter?.openResolver : this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout: filter.handlerFilter?.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT - }; - } - const waitResponseTimeout = filter.intentRequest?.waitUserResponseIndefinitely ? MAX_SET_TIMEOUT_DELAY : this.intentResolverResponseTimeout; - return { - enabled: this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout - }; - } - getEmbeddedResolverConfig() { - return { - enabled: this.uiController.isIntentResolverEnabled(), - initialCaller: { instanceId: this.interop.instance.instance } - }; - } - async all() { - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.getIntents, undefined); - return result.intents; - } - addIntentListener(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - let registerPromise; - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - const result = { - unsubscribe: () => { - this.myIntents.delete(intentName); - registerPromise - .then(() => this.interop.unregister(methodName)) - .catch((err) => this.logger.trace(`Unregistration of a method with name ${methodName} failed with reason: ${err}`)); - } - }; - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - registerPromise = this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - return handler(rest); - } - }); - registerPromise.catch(err => { - this.myIntents.delete(intentName); - this.logger.warn(`Registration of a method with name ${methodName} failed with reason: ${err}`); - }); - return result; - } - async register(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - await Promise.all(this.unregisterIntentPromises); - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - try { - await this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - const caller = this.interop.servers().find((server) => server.instance === _initialCallerId); - return handler(rest, caller); - } - }); - } - catch (err) { - this.myIntents.delete(intentName); - return ioError.raiseError(`Registration of a method with name ${methodName} failed with reason: ${JSON.stringify(err)}`); - } - return { - unsubscribe: () => this.unsubscribeIntent(intentName) - }; - } - async find(intentFilter) { - let data = undefined; - if (typeof intentFilter !== "undefined") { - const intentFilterObj = runDecoderWithIOError(findFilterDecoder, intentFilter); - if (typeof intentFilterObj === "string") { - data = { - filter: { - name: intentFilterObj - } - }; - } - else if (typeof intentFilterObj === "object") { - data = { - filter: intentFilterObj - }; - } - } - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.findIntent, data); - return result.intents; - } - onHandlerAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!"); - } - const unOnAppAdded = this.subscribeForAppEvent("onAppAdded", callback); - const unOnServerMethodAdded = this.subscribeForServerMethodEvent("serverMethodAdded", callback); - return () => { - unOnAppAdded(); - unOnServerMethodAdded(); - }; - } - onHandlerRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!"); - } - const unOnAppRemoved = this.subscribeForAppEvent("onAppRemoved", callback); - const unOnServerMethodRemoved = this.subscribeForServerMethodEvent("serverMethodRemoved", callback); - return () => { - unOnAppRemoved(); - unOnServerMethodRemoved(); - }; - } - subscribeForAppEvent(method, callback) { - return this.appManagerController[method]((app) => { - const appIntents = app.userProperties.intents; - if (!appIntents?.length) { - return; - } - appIntents.forEach((intent) => { - const handler = this.buildIntentHandlerFromApp(app, intent); - callback(handler, intent.name); - }); - }); - } - subscribeForServerMethodEvent(eventMethod, callback) { - return this.interop[eventMethod](async ({ server, method }) => { - if (!method.name.startsWith(GLUE42_FDC3_INTENTS_METHOD_PREFIX)) { - return; - } - const intentName = method.name.replace(GLUE42_FDC3_INTENTS_METHOD_PREFIX, ""); - const handler = await this.buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName); - callback(handler, intentName); - }); - } - buildIntentHandlerFromApp(app, intent) { - const handler = { - applicationName: app.name, - type: "app", - applicationDescription: app.caption, - applicationIcon: app.icon, - applicationTitle: app.title, - contextTypes: intent.contexts, - displayName: intent.displayName, - resultType: intent.resultType, - customConfig: intent.customConfig - }; - return handler; - } - async buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName) { - const info = method.flags.intent; - const app = this.appManagerController.getApplication(server.application || server.applicationName); - let title; - if (eventMethod === "serverMethodAdded" && server.windowId) { - title = await (this.windowsController.findById(server.windowId))?.getTitle(); - } - const appIntent = app?.userProperties?.intents?.find((intent) => intent.name === intentName); - const handler = { - applicationName: server.application || server.applicationName || "", - instanceId: server.windowId || server.instance, - type: "instance", - applicationIcon: info?.icon || app?.icon, - applicationTitle: app?.title, - applicationDescription: info?.description || app?.caption, - contextTypes: info?.contextTypes || appIntent?.contexts, - instanceTitle: title, - displayName: info?.displayName || appIntent?.displayName, - resultType: info?.resultType || appIntent?.resultType, - customConfig: info?.customConfig - }; - return handler; - } - async clearSavedHandlers() { - this.logger.trace("Removing all saved handlers from prefs storage for current app"); - await this.prefsController.update({ intents: undefined }); - } - checkIfIntentsResolverIsEnabled(options) { - this.useIntentsResolverUI = typeof options.intents?.enableIntentsResolverUI === "boolean" - ? options.intents.enableIntentsResolverUI - : true; - this.intentsResolverAppName = options.intents?.intentsResolverAppName ?? INTENTS_RESOLVER_APP_NAME; - this.intentResolverResponseTimeout = options.intents?.methodResponseTimeoutMs ?? DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - } - clearUnregistrationPromise(promiseToRemove) { - this.unregisterIntentPromises = this.unregisterIntentPromises.filter(promise => promise !== promiseToRemove); - } - buildInteropMethodName(intentName) { - return `${GLUE42_FDC3_INTENTS_METHOD_PREFIX}${intentName}`; - } - unsubscribeIntent(intentName) { - this.myIntents.delete(intentName); - const methodName = this.buildInteropMethodName(intentName); - const unregisterPromise = this.interop.unregister(methodName); - this.unregisterIntentPromises.push(unregisterPromise); - unregisterPromise - .then(() => { - this.clearUnregistrationPromise(unregisterPromise); - }) - .catch((err) => { - this.logger.error(`Unregistration of a method with name ${methodName} failed with reason: ${err}`); - this.clearUnregistrationPromise(unregisterPromise); - }); - } - async filterHandlers(handlerFilter) { - runDecoderWithIOError(handlerFilterDecoder, handlerFilter); - this.checkIfAtLeastOneFilterIsPresent(handlerFilter); - const embeddedResolverConfig = this.getEmbeddedResolverConfig(); - if (handlerFilter.openResolver && !this.useIntentsResolverUI && !embeddedResolverConfig.enabled) { - return ioError.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled"); - } - const methodResponseTimeoutMs = (handlerFilter.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - const filterHandlersRequestWithResolverConfig = { - filterHandlersRequest: handlerFilter, - resolverConfig: this.getLegacyResolverConfigByRequest({ handlerFilter }), - embeddedResolverConfig - }; - const result = await this.bridge.send("intents", operations$6.filterHandlers, filterHandlersRequestWithResolverConfig, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }, { includeOperationCheck: true }); - return result; - } - checkIfAtLeastOneFilterIsPresent(filter) { - const errorMsg = "Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'"; - if (!Object.keys(filter).length) { - return ioError.raiseError(errorMsg); - } - const { intent, resultType, contextTypes, applicationNames } = filter; - const existingValidContextTypes = contextTypes?.length; - const existingValidApplicationNames = applicationNames?.length; - if (!intent && !resultType && !existingValidContextTypes && !existingValidApplicationNames) { - return ioError.raiseError(errorMsg); - } - } - async getIntentsByHandler(handler) { - runDecoderWithIOError(intentHandlerDecoder, handler); - const result = await this.bridge.send("intents", operations$6.getIntentsByHandler, handler, undefined, { includeOperationCheck: true }); - return result; - } - async removeRememberedHandler(intentName) { - this.logger.trace(`Removing saved handler from prefs storage for intent ${intentName}`); - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const intentPrefs = prefs.data?.intents; - if (!intentPrefs) { - this.logger.trace("No app prefs found for current app"); - return; - } - delete intentPrefs[intentName]; - const updatedPrefs = { - ...prefs.data, - intents: intentPrefs - }; - try { - await this.prefsController.update(updatedPrefs); - } - catch (error) { - this.logger.warn(`prefs.update() threw the following error: ${error}`); - return; - } - this.logger.trace(`Handler saved choice for intent ${intentName} removed successfully`); - } - async checkForRememberedHandler(intentRequest) { - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const prefsForIntent = prefs.data?.intents?.[intentRequest.intent]; - return prefsForIntent?.handler; - } - async checkHandleRaiseWithRememberedHandler(intentRequest) { - if (intentRequest.target) { - return; - } - const rememberedHandler = await this.checkForRememberedHandler(intentRequest); - if (!rememberedHandler) { - return; - } - const operationData = { - intentRequest: { - ...intentRequest, - target: { - app: rememberedHandler.applicationName, - instance: rememberedHandler.instanceId - } - }, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - try { - const response = await this.bridge.send("intents", operations$6.raise, operationData); - return response; - } - catch (error) { - this.logger.trace(`Could not raise intent to remembered handler. Reason: ${error}. Removing it from Prefs store`); - await this.removeRememberedHandler(intentRequest.intent); - } - } - } - - const operations$5 = { - appHello: { name: "appHello", dataDecoder: channelsAppHelloDataDecoder, resultDecoder: channelsAppHelloSuccessDecoder }, - addChannel: { name: "addChannel", dataDecoder: channelDefinitionDecoder }, - removeChannel: { name: "removeChannel", dataDecoder: removeChannelDataDecoder }, - getMyChannel: { name: "getMyChannel", resultDecoder: getMyChanelResultDecoder }, - getWindowIdsOnChannel: { name: "getWindowIdsOnChannel", dataDecoder: getWindowIdsOnChannelDataDecoder, resultDecoder: getWindowIdsOnChannelResultDecoder }, - getWindowIdsWithChannels: { name: "getWindowIdsWithChannels", dataDecoder: wrappedWindowWithChannelFilterDecoder, resultDecoder: getWindowIdsWithChannelsResultDecoder }, - joinChannel: { name: "joinChannel", dataDecoder: joinChannelDataDecoder }, - restrict: { name: "restrict", dataDecoder: restrictionConfigDataDecoder }, - getRestrictions: { name: "getRestrictions", dataDecoder: getRestrictionsDataDecoder, resultDecoder: restrictionsDecoder }, - restrictAll: { name: "restrictAll", dataDecoder: restrictAllDataDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - leaveChannel: { name: "leaveChannel", dataDecoder: leaveChannelDataDecoder }, - requestChannelSelector: { name: "requestChannelSelector", dataDecoder: requestChannelSelectorConfigDecoder }, - getMode: { name: "getMode", resultDecoder: getChannelsModeDecoder }, - operationCheck: { name: "operationCheck" }, - }; - - const DEFAULT_MODE = "single"; - const CHANNELS_PREFIX = "___channel___"; - const SUBS_KEY = "subs"; - const CHANGED_KEY = "changed"; - const CHANNELS_CHANGED = "channels_changed"; - const STORAGE_NAMESPACE = "io_connect_channels"; - const DEFAULT_STORAGE_MODE = "inMemory"; - - class ChannelsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - contexts; - interop; - bridge; - windowsController; - _mode; - myWindowId; - storage; - handlePlatformShutdown() { - this.registry.clear(); - this.storage.clear(); - } - addOperationsExecutors() { - operations$5.getMyChannel.execute = this.handleGetMyChannel.bind(this); - operations$5.joinChannel.execute = this.handleJoinChannel.bind(this); - operations$5.leaveChannel.execute = this.handleLeaveChannel.bind(this); - operations$5.restrict.execute = this.handleRestrict.bind(this); - operations$5.getRestrictions.execute = ({ windowId }) => this.getRestrictions(windowId); - operations$5.restrictAll.execute = this.handleRestrictAll.bind(this); - operations$5.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$5); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("channels.controller.web"); - this.logger.trace("starting the web channels controller"); - this.contexts = coreGlue.contexts; - this.interop = coreGlue.interop; - this.addOperationsExecutors(); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.storage = ioc.channelsStorage; - this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"); - this.myWindowId = this.windowsController.my().id ?? this.interop.instance.instance; - await this.initialize(); - const api = this.toApi(); - coreGlue.channels = api; - } - async postStart(io, ioc) { - try { - await this.requestChannelSelector(io.appManager.myInstance); - } - catch (error) { - this.logger.warn(`Failed to display channel selector: ${extractErrorMsg(error)}`); - } - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(channelsOperationTypesDecoder, args.operation); - const operation = operations$5[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async list() { - const channelNames = this.getAllChannelNames(); - const channelContexts = await Promise.all(channelNames.map((channelName) => this.get(channelName))); - return channelContexts; - } - my() { - return this.current(); - } - async handleGetMyChannel() { - const channel = this.my(); - return channel ? { channel } : {}; - } - async join(name, windowId) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const joinData = { channel: name, windowId: windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.joinChannel, joinData, undefined, { includeOperationCheck: true }); - } - handleJoinChannel({ channel }) { - if (this._mode === "single") { - return this.switchToChannel(channel); - } - return this.joinAdditionalChannel(channel); - } - onChanged(callback) { - return this.changed(callback); - } - async leave(config = {}) { - runDecoderWithIOError(leaveChannelsConfig, config); - if (config.channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.channel); - } - const leaveData = { channelName: config.channel, windowId: config.windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.leaveChannel, leaveData, undefined, { includeOperationCheck: true }); - } - async handleAppManagerInitialChannelId(channel) { - if (this.storage.mode === "inMemory") { - return; - } - if (this.storage.getSessionStorageData()) { - return; - } - return this.handleJoinChannel({ channel, windowId: this.myWindowId }); - } - async handleLeaveChannel({ channelName }) { - const channelNamesToLeave = channelName ? [channelName] : this.storage.channels; - channelNamesToLeave.forEach((name) => this.storage.invokeUnsubscribes(name)); - this.storage.channels = this.storage.channels.filter((channelName) => !channelNamesToLeave.includes(channelName)); - this.executeChangedEvents(); - await this.notifyChannelsChanged(); - } - toApi() { - const api = { - mode: this._mode, - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - publish: this.publish.bind(this), - all: this.all.bind(this), - list: this.list.bind(this), - get: this.get.bind(this), - getMyChannels: this.getMyChannels.bind(this), - myChannels: this.myChannels.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - join: this.join.bind(this), - leave: this.leave.bind(this), - current: this.current.bind(this), - my: this.my.bind(this), - changed: this.changed.bind(this), - onChanged: this.onChanged.bind(this), - add: this.add.bind(this), - remove: this.remove.bind(this), - getMy: this.getMy.bind(this), - getWindowsOnChannel: this.getWindowsOnChannel.bind(this), - getWindowsWithChannels: this.getWindowsWithChannels.bind(this), - restrict: this.restrict.bind(this), - getRestrictions: this.getRestrictions.bind(this), - restrictAll: this.restrictAll.bind(this), - clearChannelData: this.clearChannelData.bind(this), - setPath: this.setPath.bind(this), - setPaths: this.setPaths.bind(this) - }; - return Object.freeze(api); - } - createContextName(channelName) { - return `${CHANNELS_PREFIX}${channelName}`; - } - getAllChannelNames() { - const contextNames = this.contexts.all(); - const channelContextNames = contextNames.filter((contextName) => contextName.startsWith(CHANNELS_PREFIX)); - const channelNames = channelContextNames.map((channelContextName) => channelContextName.replace(CHANNELS_PREFIX, "")); - return channelNames; - } - async joinAdditionalChannel(name) { - if (this.storage.channels.includes(name)) { - return; - } - this.storage.channels = [...this.storage.channels, name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - async switchToChannel(name) { - const currentChannel = this.storage.channels[0]; - if (name === currentChannel) { - return; - } - this.storage.invokeUnsubscribes(currentChannel); - this.storage.channels = [name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - executeChangedEvents(name) { - this.registry.execute(CHANGED_KEY, name); - this.registry.execute(CHANNELS_CHANGED, this.storage.channels); - } - async notifyChannelsChanged() { - const windowId = this.windowsController.my().id; - if (!windowId) { - return; - } - try { - await this.bridge.send("channels", operations$5.notifyChannelsChanged, { channelNames: this.storage.channels, windowId }, undefined, { includeOperationCheck: true }); - } - catch (error) { - this.logger.warn(`Failed to notify channel changed: ${extractErrorMsg(error)}`); - } - } - async updateData(name, data) { - const contextName = this.createContextName(name); - const fdc3Type = this.getFDC3Type(data); - if (this.contexts.setPathSupported) { - const pathValues = Object.keys(data).map((key) => { - return { - path: `data.${key}`, - value: data[key] - }; - }); - if (fdc3Type) { - pathValues.push({ path: latestFDC3Type, value: fdc3Type }); - } - await this.contexts.setPaths(contextName, pathValues); - } - else { - if (fdc3Type) { - data[latestFDC3Type] = fdc3Type; - } - await this.contexts.update(contextName, { data }); - } - } - getFDC3Type(data) { - const fdc3PropsArr = Object.keys(data).filter((key) => key.indexOf("fdc3_") === 0); - if (fdc3PropsArr.length === 0) { - return; - } - if (fdc3PropsArr.length > 1) { - return ioError.raiseError("FDC3 does not support updating of multiple context keys"); - } - return fdc3PropsArr[0].split("_").slice(1).join("_"); - } - subscribe(callback, options) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels, because the provided callback is not a function!"); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const currentChannel = this.current(); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - if (currentChannel) { - this.replaySubscribe(wrappedCallback, currentChannel); - } - return this.registry.add(SUBS_KEY, wrappedCallback); - } - async subscribeFor(name, callback, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (typeof callback !== "function") { - return ioError.raiseError(`Cannot subscribe to channel ${name}, because the provided callback is not a function!`); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - wrappedCallback(context.data, context, delta, extraData?.updaterId); - }); - } - async publish(data, options) { - if (typeof data !== "object") { - return ioError.raiseError("Cannot publish to channel, because the provided data is not an object!"); - } - runDecoderWithIOError(publishOptionsDecoder, options); - if (typeof options === "object") { - return this.publishWithOptions(data, options); - } - if (typeof options === "string") { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options); - } - if (!options && this.storage.channels.length > 1) { - return this.publishOnMultipleChannels(data); - } - const channelName = typeof options === "string" ? options : this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - return this.updateData(channelName, data); - } - async all() { - const channelNames = this.getAllChannelNames(); - return channelNames; - } - async get(name, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const channelContext = await this.contexts.get(contextName); - if (options?.contextType) { - return this.getContextForFdc3Type(channelContext, options.contextType); - } - if (channelContext.latest_fdc3_type) { - return this.getContextWithFdc3Data(channelContext); - } - return channelContext; - } - async getMyChannels() { - return Promise.all(this.storage.channels.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.get(contextName); - })); - } - myChannels() { - return this.storage.channels; - } - getContextForFdc3Type(channelContext, searchedType) { - const encodedType = `fdc3_${searchedType.split(".").join("&")}`; - if (!channelContext.data[encodedType]) { - return { - name: channelContext.name, - meta: channelContext.meta, - data: {} - }; - } - const fdc3Context = { type: searchedType, ...channelContext.data[encodedType] }; - return { - name: channelContext.name, - meta: channelContext.meta, - data: { fdc3: fdc3Context } - }; - } - getContextWithFdc3Data(channelContext) { - const { latest_fdc3_type, ...rest } = channelContext; - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Context = { type: parsedType, ...rest.data[`fdc3_${latest_fdc3_type}`] }; - delete rest.data[`fdc3_${latest_fdc3_type}`]; - const context = { - name: channelContext.name, - meta: channelContext.meta, - data: { - ...rest.data, - fdc3: fdc3Context - } - }; - return context; - } - current() { - return this.storage.channels[0]; - } - changed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"); - } - return this.registry.add(CHANGED_KEY, callback); - } - async add(info) { - const channelContext = runDecoderWithIOError(channelDefinitionDecoder, info); - const channelWithSuchNameExists = this.getAllChannelNames().includes(channelContext.name); - if (channelWithSuchNameExists) { - return ioError.raiseError("There's an already existing channel with such name"); - } - await this.bridge.send("channels", operations$5.addChannel, channelContext); - return { - name: channelContext.name, - meta: channelContext.meta, - data: channelContext.data || {} - }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - const channelWithSuchNameExists = this.getAllChannelNames().includes(name); - if (!channelWithSuchNameExists) { - return ioError.raiseError("There's no channel with such name"); - } - await this.bridge.send("channels", operations$5.removeChannel, { name }, undefined, { includeOperationCheck: true }); - } - replaySubscribe = (callback, channelId) => { - this.get(channelId) - .then((channelContext) => { - if (!channelContext) { - return undefined; - } - const contextName = this.createContextName(channelContext.name); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - callback(context.data, context, delta, extraData?.updaterId); - }); - }) - .then((un) => un?.()) - .catch(err => this.logger.trace(err)); - }; - async getMy(options) { - if (!this.storage.channels.length) { - return; - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - return this.get(this.storage.channels[this.storage.channels.length - 1], options); - } - async getWindowsOnChannel(channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), channel); - const { windowIds } = await this.bridge.send("channels", operations$5.getWindowIdsOnChannel, { channel }, undefined, { includeOperationCheck: true }); - const result = windowIds.reduce((windows, windowId) => { - const window = this.windowsController.findById(windowId); - return window ? [...windows, window] : windows; - }, []); - return result; - } - async getWindowsWithChannels(filter) { - const operationData = filter !== undefined - ? { filter: runDecoderWithIOError(windowWithChannelFilterDecoder, filter) } - : {}; - const { windowIdsWithChannels } = await this.bridge.send("channels", operations$5.getWindowIdsWithChannels, operationData, undefined, { includeOperationCheck: true }); - const result = windowIdsWithChannels.reduce((windowsWithChannels, { application, channel, windowId }) => { - const window = this.windowsController.findById(windowId); - return window ? [...windowsWithChannels, { application, channel, window }] : windowsWithChannels; - }, []); - return result; - } - async clearChannelData(name) { - const paths = [ - { path: "data", value: {} }, - { path: "latest_fdc3_type", value: null }, - ]; - await this.handleSetPaths("clearChannelData", paths, name); - } - async restrict(config) { - runDecoderWithIOError(channelRestrictionsDecoder, config); - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.name); - const configData = { - config: { - ...config, - windowId: config.windowId ?? this.myWindowId - } - }; - await this.bridge.send("channels", operations$5.restrict, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrict({ config }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateRestriction(config); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateRestriction(config); - const isForCurrentChannel = config.name === currentChannel.name; - if (!isForCurrentChannel || prevReadAllowed || !config.read) { - return; - } - this.replaySubscribeCallback(config.name); - } - updateRestriction(config) { - const exists = this.storage.restrictions.some((r) => r.name === config.name); - this.storage.restrictions = exists - ? this.storage.restrictions.map((restriction) => restriction.name === config.name ? config : restriction) - : this.storage.restrictions.concat(config); - } - updateAllRestrictions(config) { - const allChannelNames = this.getAllChannelNames(); - this.storage.restrictions = allChannelNames.map((name) => ({ name, ...config })); - } - async getRestrictions(windowId) { - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const forAnotherClient = windowId && windowId !== this.interop.instance.instance; - if (windowId && forAnotherClient) { - return this.bridge.send("channels", operations$5.getRestrictions, { windowId }, undefined, { includeOperationCheck: true }); - } - return { channels: this.storage.restrictions }; - } - async restrictAll(restrictions) { - runDecoderWithIOError(restrictionsConfigDecoder, restrictions); - const configData = { - restrictions: { - ...restrictions, - windowId: restrictions.windowId ?? this.myWindowId - } - }; - return this.bridge.send("channels", operations$5.restrictAll, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrictAll({ restrictions }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateAllRestrictions(restrictions); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateAllRestrictions(restrictions); - if (prevReadAllowed || !restrictions.read) { - return; - } - this.replaySubscribeCallback(currentChannel.name); - } - async setPath(path, name) { - const validatedPath = runDecoderWithIOError(pathValueDecoder, path); - const paths = [{ path: `data.${validatedPath.path}`, value: validatedPath.value }]; - await this.handleSetPaths("setPath", paths, name); - } - async setPaths(paths, name) { - const validatedPaths = runDecoderWithIOError(pathsValueDecoder, paths); - const dataPaths = validatedPaths.map(({ path, value }) => ({ path: `data.${path}`, value })); - await this.handleSetPaths("setPaths", dataPaths, name); - } - async handleSetPaths(operation, paths, name) { - const channelNamesToUpdate = name ? [name] : this.storage.channels; - if (!channelNamesToUpdate.length) { - return ioError.raiseError(`Cannot complete ${operation} operation, because channel is not specified. Either join one or pass a channel name as second argument!`); - } - this.validateChannelNames(channelNamesToUpdate); - const { allowed, forbidden } = this.groupChannelsByPermission("write", channelNamesToUpdate); - if (channelNamesToUpdate.length === forbidden.length) { - return ioError.raiseError(`Cannot complete ${operation} operation due to write restrictions to the following channels: ${channelNamesToUpdate.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Cannot set paths on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} due to write restrictions`); - } - await Promise.all(allowed.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.setPaths(contextName, paths); - })); - } - validateChannelNames(names) { - const allChannelNames = this.getAllChannelNames(); - names.forEach((name) => runDecoderWithIOError(channelNameDecoder(allChannelNames), name)); - } - groupChannelsByPermission(action, channelNames) { - return channelNames.reduce((byFar, channelName) => { - const isAllowed = this.isAllowedByRestrictions(channelName, action); - if (isAllowed) { - byFar.allowed.push(channelName); - } - else { - byFar.forbidden.push(channelName); - } - return byFar; - }, { allowed: [], forbidden: [] }); - } - isAllowedByRestrictions(channelName, action) { - const restriction = this.storage.restrictions.find((restriction) => restriction.name === channelName); - return restriction ? restriction[action] : true; - } - replaySubscribeCallback(channelName) { - const contextName = this.createContextName(channelName); - this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }).then((unsub) => { - if (unsub && typeof unsub === "function") { - unsub(); - } - }).catch(err => this.logger.error(err)); - } - async publishWithOptions(data, options) { - if (options.name) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options.name); - } - const publishOnMultipleChannels = options.name ? false : this.storage.channels.length > 1; - if (publishOnMultipleChannels) { - return this.publishOnMultipleChannels(data, options.fdc3); - } - const channelName = options.name || this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - if (!options.fdc3) { - return this.updateData(channelName, data); - } - return this.publishFdc3Data(channelName, data); - } - async publishOnMultipleChannels(data, isFdc3) { - const { allowed, forbidden } = this.groupChannelsByPermission("write", this.storage.channels); - if (this.storage.channels.length === forbidden.length) { - return ioError.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Data on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} won't be published due to write restrictions`); - } - const publishMethod = isFdc3 ? this.publishFdc3Data.bind(this) : this.updateData.bind(this); - await Promise.all(allowed.map((channelName) => publishMethod(channelName, data))); - } - async publishFdc3Data(channelName, data) { - runDecoderWithIOError(fdc3ContextDecoder, data); - const { type, ...rest } = data; - const parsedType = type.split(".").join("&"); - const fdc3DataToPublish = { [`fdc3_${parsedType}`]: rest }; - return this.updateData(channelName, fdc3DataToPublish); - } - getWrappedSubscribeCallback(callback) { - const wrappedCallback = (channelData, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const latestTypePropName = `fdc3_${latest_fdc3_type}`; - if (!latest_fdc3_type || (delta.data && !delta.data[latestTypePropName])) { - callback(channelData, context, updaterId); - return; - } - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Data = { type: parsedType, ...data[latestTypePropName] }; - const { [latestTypePropName]: latestFDC3Type, ...rest } = channelData; - callback({ ...rest, fdc3: fdc3Data }, context, updaterId); - }; - return wrappedCallback; - } - getWrappedSubscribeCallbackWithFdc3Type(callback, fdc3Type) { - const didReplay = { replayed: false }; - const wrappedCallback = (_, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const searchedType = `fdc3_${fdc3Type.split(".").join("&")}`; - if (!data[searchedType] || (delta.data && !delta.data[searchedType])) { - return; - } - if (didReplay.replayed) { - return this.parseDataAndInvokeSubscribeCallback({ latestFdc3TypeEncoded: latest_fdc3_type, searchedType: fdc3Type, callback, context, updaterId }); - } - const fdc3Data = { type: fdc3Type, ...data[searchedType] }; - callback({ fdc3: fdc3Data }, context, updaterId); - didReplay.replayed = true; - }; - return wrappedCallback; - } - parseDataAndInvokeSubscribeCallback(args) { - const { latestFdc3TypeEncoded, searchedType, callback, context, updaterId } = args; - const latestPublishedType = latestFdc3TypeEncoded.split("&").join("."); - if (latestPublishedType !== searchedType) { - return; - } - const fdc3Data = { type: searchedType, ...context.data[`fdc3_${latestFdc3TypeEncoded}`] }; - callback({ fdc3: fdc3Data }, context, updaterId); - } - async requestChannelSelector(myInstance) { - if (!myInstance) { - return; - } - const myApplicationData = myInstance.application; - const myAppDetails = myApplicationData.userProperties?.details; - if (!myAppDetails) { - return; - } - if (!myAppDetails?.channelSelector?.enabled) { - return; - } - const windowId = myInstance.id; - const requestChannelSelectorConfig = { windowId, channelsNames: this.storage.channels }; - await this.bridge.send("channels", operations$5.requestChannelSelector, requestChannelSelectorConfig, undefined, { includeOperationCheck: true }); - } - async getPlatformChannelsMode() { - try { - const result = await this.bridge.send("channels", operations$5.getMode, {}, undefined, { includeOperationCheck: true }); - return result.mode; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - return DEFAULT_MODE; - } - } - onChannelsChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"); - } - return this.registry.add(CHANNELS_CHANGED, callback); - } - async initialize() { - const isAppHelloSupported = await this.checkIfAppHelloSupported(); - if (!isAppHelloSupported) { - return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions"); - } - const { success, error } = await this.sendAppHello(); - if (error) { - return this.handleAppHelloFailure(error); - } - this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(success)}`); - const { mode, channels, restrictions } = success; - this.storage.mode = "inMemory"; - this._mode = mode; - this.storage.channels = channels; - this.storage.restrictions = restrictions; - } - async handleAppHelloFailure(errorMsg) { - this.logger.trace(errorMsg); - this.storage.mode = "sessionStorage"; - this._mode = await this.getPlatformChannelsMode(); - } - async sendAppHello() { - try { - const result = await this.bridge.send("channels", operations$5.appHello, { windowId: this.myWindowId }, undefined, { includeOperationCheck: true }); - return { success: result, error: undefined }; - } - catch (error) { - return { error: `Failed to get initial state from platform. Error: ${extractErrorMsg(error)}`, success: undefined }; - } - } - async checkIfAppHelloSupported() { - try { - const { isSupported } = await this.bridge.send("channels", operations$5.operationCheck, { operation: operations$5.appHello.name }, undefined, { includeOperationCheck: true }); - return isSupported; - } - catch (error) { - this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${extractErrorMsg(error)}`); - return false; - } - } - } - - const operations$4 = { - getEnvironment: { name: "getEnvironment", resultDecoder: anyDecoder }, - getBase: { name: "getBase", resultDecoder: anyDecoder }, - platformShutdown: { name: "platformShutdown" }, - isFdc3DataWrappingSupported: { name: "isFdc3DataWrappingSupported" }, - clientError: { name: "clientError", dataDecoder: clientErrorDataDecoder }, - systemHello: { name: "systemHello", resultDecoder: systemHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class SystemController { - supportedOperationsNames = []; - bridge; - ioc; - logger; - errorPort = errorChannel.port2; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("system.controller.web"); - this.logger.trace("starting the web system controller"); - this.bridge = ioc.bridge; - this.ioc = ioc; - this.addOperationsExecutors(); - let isClientErrorOperationSupported = false; - try { - const systemHelloSuccess = await this.bridge.send("system", operations$4.systemHello, undefined, undefined, { includeOperationCheck: true }); - isClientErrorOperationSupported = systemHelloSuccess.isClientErrorOperationSupported; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support some system operations."); - } - this.errorPort.onmessage = async (event) => { - if (!isClientErrorOperationSupported) { - return; - } - await this.bridge.send("system", operations$4.clientError, { message: event.data }, undefined, { includeOperationCheck: true }); - }; - await this.setEnvironment(); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(systemOperationTypesDecoder, args.operation); - const operation = operations$4[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async processPlatformShutdown() { - Object.values(this.ioc.controllers).forEach((controller) => controller.handlePlatformShutdown ? controller.handlePlatformShutdown() : null); - this.ioc.preferredConnectionController.stop(); - this.ioc.eventsDispatcher.stop(); - await this.bridge.stop(); - } - async setEnvironment() { - const environment = await this.bridge.send("system", operations$4.getEnvironment, undefined); - const base = await this.bridge.send("system", operations$4.getBase, undefined); - const globalNamespace = window.glue42core || window.iobrowser; - const globalNamespaceName = window.glue42core ? "glue42core" : "iobrowser"; - const globalObj = Object.assign({}, globalNamespace, base, { environment }); - window[globalNamespaceName] = globalObj; - } - addOperationsExecutors() { - operations$4.platformShutdown.execute = this.processPlatformShutdown.bind(this); - operations$4.isFdc3DataWrappingSupported.execute = this.handleIsFdc3DataWrappingSupported.bind(this); - operations$4.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$4); - } - async handleIsFdc3DataWrappingSupported() { - return { isSupported: true }; - } - } - - class Notification { - onclick = () => { }; - onshow = () => { }; - id; - title; - badge; - body; - data; - dir; - icon; - image; - lang; - renotify; - requireInteraction; - silent; - tag; - timestamp; - vibrate; - clickInterop; - actions; - focusPlatformOnDefaultClick; - severity; - showToast; - showInPanel; - state; - constructor(config, id) { - this.id = id; - this.badge = config.badge; - this.body = config.body; - this.data = config.data; - this.dir = config.dir; - this.icon = config.icon; - this.image = config.image; - this.lang = config.lang; - this.renotify = config.renotify; - this.requireInteraction = config.requireInteraction; - this.silent = config.silent; - this.tag = config.tag; - this.timestamp = config.timestamp; - this.vibrate = config.vibrate; - this.title = config.title; - this.clickInterop = config.clickInterop; - this.actions = config.actions; - this.focusPlatformOnDefaultClick = config.focusPlatformOnDefaultClick; - this.severity = config.severity; - this.showToast = config.showToast; - this.showInPanel = config.showInPanel; - this.state = config.state; - } - } - - oneOf$1(constant$2("clientHello")); - const extensionConfigDecoder = object$2({ - widget: object$2({ - inject: boolean$2() - }) - }); - - const operations$3 = { - clientHello: { name: "clientHello", resultDecoder: extensionConfigDecoder } - }; - - class ExtController { - windowId; - logger; - bridge; - eventsDispatcher; - channelsController; - config; - channels = []; - unsubFuncs = []; - contentCommands = { - widgetVisualizationPermission: { name: "widgetVisualizationPermission", handle: this.handleWidgetVisualizationPermission.bind(this) }, - changeChannel: { name: "changeChannel", handle: this.handleChangeChannel.bind(this) } - }; - handlePlatformShutdown() { - this.unsubFuncs.forEach((unsub) => unsub()); - this.channels = []; - this.unsubFuncs = []; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("extension.controller.web"); - this.windowId = ioc.publicWindowId; - this.logger.trace("starting the extension web controller"); - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.eventsDispatcher = ioc.eventsDispatcher; - try { - await this.registerWithPlatform(); - } - catch (error) { - return; - } - this.channels = await this.channelsController.list(); - const unsubDispatcher = this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)); - const unsubChannels = this.channelsController.onChanged((channel) => { - this.eventsDispatcher.sendContentMessage({ command: "channelChange", newChannel: channel }); - }); - this.unsubFuncs.push(unsubDispatcher); - this.unsubFuncs.push(unsubChannels); - } - async handleBridgeMessage(_) { - } - handleContentMessage(message) { - if (!message || typeof message.command !== "string") { - return; - } - const foundHandler = this.contentCommands[message.command]; - if (!foundHandler) { - return; - } - foundHandler.handle(message); - } - async registerWithPlatform() { - this.logger.trace("registering with the platform"); - this.config = await this.bridge.send("extension", operations$3.clientHello, { windowId: this.windowId }); - this.logger.trace("the platform responded to the hello message with a valid extension config"); - } - async handleWidgetVisualizationPermission() { - if (!this.config?.widget.inject) { - return this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: false }); - } - const currentChannel = this.channels.find((channel) => channel.name === this.channelsController.my()); - this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: true, channels: this.channels, currentChannel }); - } - async handleChangeChannel(message) { - if (message.name === "no-channel") { - await this.channelsController.leave(); - return; - } - await this.channelsController.join(message.name); - } - } - - class EventsDispatcher { - config; - glue; - registry = CallbackRegistryFactory$1(); - glue42EventName = "Glue42"; - _handleMessage; - _resolveWidgetReadyPromise; - _resolveModalsUIFactoryReadyPromise; - _resolveIntentResolverUIFactoryReadyPromise; - constructor(config) { - this.config = config; - } - events = { - notifyStarted: { name: "notifyStarted", handle: this.handleNotifyStarted.bind(this) }, - contentInc: { name: "contentInc", handle: this.handleContentInc.bind(this) }, - requestGlue: { name: "requestGlue", handle: this.handleRequestGlue.bind(this) }, - widgetFactoryReady: { name: "widgetFactoryReady", handle: this.handleWidgetReady.bind(this) }, - modalsUIFactoryReady: { name: "modalsUIFactoryReady", handle: this.handleModalsUIFactoryReady.bind(this) }, - intentResolverUIFactoryReady: { name: "intentResolverUIFactoryReady", handle: this.handleIntentResolverUIFactoryReady.bind(this) }, - }; - stop() { - window.removeEventListener(this.glue42EventName, this._handleMessage); - } - start(glue) { - this.glue = glue; - this.wireCustomEventListener(); - this.announceStarted(); - } - sendContentMessage(message) { - this.send("contentOut", "glue42core", message); - } - onContentMessage(callback) { - return this.registry.add("content-inc", callback); - } - async widgetReady() { - const widgetReadyPromise = new Promise((resolve) => { - this._resolveWidgetReadyPromise = resolve; - }); - this.requestWidgetReady(); - return widgetReadyPromise; - } - async modalsUIFactoryReady() { - const modalsUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveModalsUIFactoryReadyPromise = resolve; - }); - this.requestModalsUIFactoryReady(); - return modalsUIFactoryReadyPromise; - } - async intentResolverUIFactoryReady() { - const intentResolverUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveIntentResolverUIFactoryReadyPromise = resolve; - }); - this.requestIntentResolverUIFactoryReady(); - return intentResolverUIFactoryReadyPromise; - } - wireCustomEventListener() { - this._handleMessage = this.handleMessage.bind(this); - window.addEventListener(this.glue42EventName, this._handleMessage); - } - handleMessage(event) { - const data = event.detail; - const namespace = data?.glue42 ?? data?.glue42core; - if (!namespace) { - return; - } - const glue42Event = namespace.event; - const foundHandler = this.events[glue42Event]; - if (!foundHandler) { - return; - } - foundHandler.handle(namespace.message); - } - announceStarted() { - this.send("start", "glue42"); - } - handleRequestGlue() { - if (!this.config.exposeAPI) { - this.send("requestGlueResponse", "glue42", { error: "Will not give access to the underlying Glue API, because it was explicitly denied upon initialization." }); - return; - } - this.send("requestGlueResponse", "glue42", { glue: this.glue }); - } - handleNotifyStarted() { - this.announceStarted(); - } - handleContentInc(message) { - this.registry.execute("content-inc", message); - } - requestWidgetReady() { - this.send(REQUEST_WIDGET_READY, "glue42"); - } - handleWidgetReady() { - this._resolveWidgetReadyPromise?.(); - } - requestModalsUIFactoryReady() { - this.send(REQUEST_MODALS_UI_FACTORY_READY, "glue42"); - } - handleModalsUIFactoryReady() { - this._resolveModalsUIFactoryReadyPromise?.(); - } - requestIntentResolverUIFactoryReady() { - this.send(REQUEST_INTENT_RESOLVER_UI_FACTORY_READY, "glue42"); - } - handleIntentResolverUIFactoryReady() { - this._resolveIntentResolverUIFactoryReadyPromise?.(); - } - send(eventName, namespace, message) { - const payload = {}; - payload[namespace] = { event: eventName, message }; - const event = new CustomEvent(this.glue42EventName, { detail: payload }); - window.dispatchEvent(event); - } - } - - class PreferredConnectionController { - coreGlue; - transactionTimeout = 15000; - transactionLocks = {}; - webPlatformTransport; - webPlatformMessagesUnsubscribe; - reconnectCounter = 0; - logger; - constructor(coreGlue) { - this.coreGlue = coreGlue; - this.logger = this.coreGlue.logger.subLogger("web.preferred.connection.controller"); - } - stop() { - if (!this.webPlatformMessagesUnsubscribe) { - return; - } - this.webPlatformMessagesUnsubscribe(); - } - async start(coreConfig) { - if (coreConfig.isPlatformInternal) { - this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic."); - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - if (!isConnectedToPlatform) { - return ioError.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport."); - } - if (!this.coreGlue.connection.transport.isPreferredActivated) { - this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization."); - return; - } - this.webPlatformTransport = this.coreGlue.connection.transport; - this.webPlatformMessagesUnsubscribe = this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this)); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - handleWebPlatformMessage(msg) { - if (typeof msg === "string") { - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - const type = msg.type; - const args = msg.args; - const transactionId = msg.transactionId; - if (type === Glue42CoreMessageTypes.transportSwitchRequest.name) { - return this.handleTransportSwitchRequest(args, transactionId); - } - if (type === Glue42CoreMessageTypes.platformUnload.name && !isConnectedToPlatform) { - return this.handlePlatformUnload(); - } - if (type === Glue42CoreMessageTypes.getCurrentTransportResponse.name) { - return this.handleGetCurrentTransportResponse(args, transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredLogic.name) { - return this.handleCheckPreferredLogic(transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredConnection.name) { - return this.handleCheckPreferredConnection(args, transactionId); - } - } - async reEstablishPlatformPort() { - try { - await this.webPlatformTransport.connect(); - } - catch (error) { - this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(error)}`); - --this.reconnectCounter; - if (this.reconnectCounter > 0) { - return this.reEstablishPlatformPort(); - } - this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform."); - } - this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."); - this.reconnectCounter = 0; - this.webPlatformTransport.close(); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - async checkSwitchTransport(config) { - const myCurrentTransportName = this.coreGlue.connection.transport.name(); - if (myCurrentTransportName === config.transportName) { - this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary"); - return; - } - this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${myCurrentTransportName}, but it should reconnect to ${JSON.stringify(config)}`); - const result = await this.coreGlue.connection.switchTransport(config); - this.setConnected(); - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - } - async getCurrentPlatformTransportState() { - this.logger.trace("Requesting the current transport state of the platform."); - const transaction = this.setTransaction(Glue42CoreMessageTypes.getCurrentTransport.name); - this.sendPlatformMessage(Glue42CoreMessageTypes.getCurrentTransport.name, transaction.id); - const transportState = await transaction.lock; - this.logger.trace(`The platform responded with transport state: ${JSON.stringify(transportState)}`); - return transportState; - } - setTransaction(operation) { - const transaction = {}; - const transactionId = nanoid$1(10); - const transactionLock = new Promise((resolve, reject) => { - let transactionLive = true; - transaction.lift = (args) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - resolve(args); - }; - transaction.fail = (reason) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - reject(reason); - }; - setTimeout(() => { - if (!transactionLive) { - return; - } - transactionLive = false; - this.logger.warn(`Transaction for operation: ${operation} timed out.`); - delete this.transactionLocks[transactionId]; - reject(`Transaction for operation: ${operation} timed out.`); - }, this.transactionTimeout); - }); - transaction.lock = transactionLock; - transaction.id = transactionId; - this.transactionLocks[transactionId] = transaction; - return transaction; - } - sendPlatformMessage(type, transactionId, args) { - this.logger.trace(`Sending a platform message of type: ${type}, id: ${transactionId} and args: ${JSON.stringify(args)}`); - this.webPlatformTransport.sendObject({ - glue42core: { type, args, transactionId } - }); - } - handleTransportSwitchRequest(args, transactionId) { - this.logger.trace(`Received a transport switch request with id: ${transactionId} and data: ${JSON.stringify(args)}`); - this.coreGlue.connection.switchTransport(args.switchSettings) - .then((result) => { - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - this.setConnected(); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: result.success }); - }) - .catch((error) => { - this.logger.error(error); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: false }); - }); - } - handlePlatformUnload() { - this.reconnectCounter = 5; - this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."); - this.reEstablishPlatformPort(); - } - handleGetCurrentTransportResponse(args, transactionId) { - this.logger.trace(`Got a current transport response from the platform with id: ${transactionId} and data: ${JSON.stringify(args)}`); - const transportState = args.transportState; - const transaction = this.transactionLocks[transactionId]; - transaction?.lift(transportState); - } - handleCheckPreferredLogic(transactionId) { - setTimeout(() => this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredLogicResponse.name, transactionId), 0); - } - handleCheckPreferredConnection(args, transactionId) { - const url = args.url; - this.logger.trace(`Testing the possible connection to: ${url}`); - this.checkPreferredConnection(url) - .then((result) => { - this.logger.trace(`The connection to ${url} is possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, result); - }) - .catch((error) => { - this.logger.trace(`The connection to ${url} is not possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, { error }); - }); - } - checkPreferredConnection(url) { - return new Promise((resolve) => { - const ws = new WebSocket(url); - ws.onerror = () => resolve({ live: false }); - ws.onopen = () => { - ws.close(); - resolve({ live: true }); - }; - }); - } - setConnected() { - this.webPlatformTransport.manualSetReadyState(); - } - } - - const operations$2 = { - getCurrent: { name: "getCurrent", resultDecoder: simpleThemeResponseDecoder }, - list: { name: "list", resultDecoder: allThemesResponseDecoder }, - select: { name: "select", dataDecoder: selectThemeConfigDecoder } - }; - - class ThemesController { - logger; - bridge; - registry = CallbackRegistryFactory$1(); - themesSubscription; - activeThemeSubs = 0; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("themes.controller.web"); - this.logger.trace("starting the web themes controller"); - this.bridge = ioc.bridge; - const api = this.toApi(); - coreGlue.themes = api; - this.logger.trace("themes are ready"); - } - handlePlatformShutdown() { - this.registry.clear(); - this.activeThemeSubs = 0; - this.themesSubscription?.close(); - delete this.themesSubscription; - } - async handleBridgeMessage() { - } - toApi() { - const api = { - getCurrent: this.getCurrent.bind(this), - list: this.list.bind(this), - select: this.select.bind(this), - onChanged: this.onChanged.bind(this) - }; - return Object.freeze(api); - } - async getCurrent() { - const bridgeResponse = await this.bridge.send("themes", operations$2.getCurrent, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.theme; - } - async list() { - const bridgeResponse = await this.bridge.send("themes", operations$2.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.themes; - } - async select(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("themes", operations$2.select, { name }, undefined, { includeOperationCheck: true }); - } - async onChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onChanged requires a callback of type function"); - } - const subReady = this.themesSubscription ? - Promise.resolve() : - this.configureThemeSubscription(); - await subReady; - ++this.activeThemeSubs; - const unsubFunc = this.registry.add("on-theme-change", callback); - return () => this.themeUnsub(unsubFunc); - } - async configureThemeSubscription() { - if (this.themesSubscription) { - return; - } - this.themesSubscription = await this.bridge.createNotificationsSteam(); - this.themesSubscription.onData((data) => { - const eventData = data.data; - const validation = simpleThemeResponseDecoder.run(eventData); - if (!validation.ok) { - this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`); - return; - } - const themeChanged = validation.result; - this.registry.execute("on-theme-change", themeChanged.theme); - }); - this.themesSubscription.onClosed(() => { - this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"); - this.registry.clear(); - this.activeThemeSubs = 0; - delete this.themesSubscription; - }); - } - themeUnsub(registryUnsub) { - registryUnsub(); - --this.activeThemeSubs; - if (this.activeThemeSubs) { - return; - } - this.themesSubscription?.close(); - delete this.themesSubscription; - } - } - - class ChannelsStorage { - sessionStorage = window.sessionStorage; - _mode = DEFAULT_STORAGE_MODE; - inMemoryChannels = []; - inMemoryRestrictions = []; - _unsubscribeDict = {}; - clear() { - this._mode = DEFAULT_STORAGE_MODE; - this.inMemoryChannels = []; - this.inMemoryRestrictions = []; - this._unsubscribeDict = {}; - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify([])); - } - get mode() { - return this._mode; - } - set mode(mode) { - this._mode = mode; - } - get channels() { - if (this.mode === "inMemory") { - return this.inMemoryChannels.slice(); - } - return this.getSessionStorageData()?.channels ?? []; - } - set channels(channels) { - if (this.mode === "inMemory") { - this.inMemoryChannels = channels; - } - this.setSessionStorageChannels(channels); - } - get restrictions() { - if (this.mode === "inMemory") { - return this.inMemoryRestrictions.slice(); - } - return this.getSessionStorageData()?.restrictions ?? []; - } - set restrictions(restrictions) { - if (this.mode === "inMemory") { - this.inMemoryRestrictions = restrictions; - } - this.setSessionStorageRestrictions(restrictions); - } - getSessionStorageData() { - return JSON.parse(this.sessionStorage.getItem(STORAGE_NAMESPACE) || "null"); - } - addUnsubscribe(channel, unsubscribe) { - this._unsubscribeDict[channel] = unsubscribe; - } - invokeUnsubscribes(channel) { - if (channel) { - this._unsubscribeDict[channel]?.(); - delete this._unsubscribeDict[channel]; - return; - } - Object.values(this._unsubscribeDict).forEach((unsub) => unsub()); - this._unsubscribeDict = {}; - } - setSessionStorageChannels(channels) { - const data = this.getSessionStorageData(); - if (data?.channels) { - data.channels = channels; - return this.setSessionStorageData(data); - } - const newData = { channels, restrictions: data?.restrictions ?? [] }; - return this.setSessionStorageData(newData); - } - setSessionStorageRestrictions(restrictions) { - const data = this.getSessionStorageData(); - if (data?.restrictions) { - data.restrictions = restrictions; - return this.setSessionStorageData(data); - } - const newData = { channels: data?.channels ?? [], restrictions }; - return this.setSessionStorageData(newData); - } - setSessionStorageData(data) { - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify(data)); - } - } - - const operations$1 = { - clear: { name: "clear", dataDecoder: basePrefsConfigDecoder }, - clearAll: { name: "clearAll" }, - get: { name: "get", dataDecoder: basePrefsConfigDecoder, resultDecoder: getPrefsResultDecoder }, - getAll: { name: "getAll", resultDecoder: getAllPrefsResultDecoder }, - set: { name: "set", dataDecoder: changePrefsDataDecoder }, - update: { name: "update", dataDecoder: changePrefsDataDecoder }, - prefsChanged: { name: "prefsChanged", dataDecoder: getPrefsResultDecoder }, - prefsHello: { name: "prefsHello", resultDecoder: prefsHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" }, - registerSubscriber: { name: "registerSubscriber", dataDecoder: subscriberRegisterConfigDecoder }, - }; - - class PrefsController { - supportedOperationsNames = []; - bridge; - config; - logger; - appManagerController; - platformAppName; - registry = CallbackRegistryFactory$1(); - validNonExistentApps; - signaledSubscription = false; - interopId; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("prefs.controller.web"); - this.logger.trace("starting the web prefs controller"); - this.addOperationsExecutors(); - this.interopId = coreGlue.interop.instance.instance; - this.bridge = ioc.bridge; - this.config = ioc.config; - this.appManagerController = ioc.appManagerController; - try { - const prefsHelloSuccess = await this.bridge.send("prefs", operations$1.prefsHello, undefined, undefined, { includeOperationCheck: true }); - this.platformAppName = prefsHelloSuccess.platform.app; - this.validNonExistentApps = prefsHelloSuccess.validNonExistentApps ?? []; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support Prefs API."); - return; - } - this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning"); - const api = this.toApi(); - coreGlue.prefs = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(prefsOperationTypesDecoder, args.operation); - const operation = operations$1[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async get(app) { - const verifiedApp = app === undefined || app === null ? this.getMyAppName() : runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const { prefs } = await this.bridge.send("prefs", operations$1.get, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - return prefs; - } - async update(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.updateFor(app, data); - } - addOperationsExecutors() { - operations$1.prefsChanged.execute = this.handleOnChanged.bind(this); - operations$1.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$1); - } - toApi() { - const api = { - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearFor: this.clearFor.bind(this), - get: this.get.bind(this), - getAll: this.getAll.bind(this), - set: this.set.bind(this), - setFor: this.setFor.bind(this), - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - update: this.update.bind(this), - updateFor: this.updateFor.bind(this), - }; - return api; - } - async clear() { - const app = this.getMyAppName(); - await this.clearFor(app); - } - async clearAll() { - await this.bridge.send("prefs", operations$1.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearFor(app) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - await this.bridge.send("prefs", operations$1.clear, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - } - async getAll() { - const result = await this.bridge.send("prefs", operations$1.getAll, undefined, undefined, { includeOperationCheck: true }); - return result; - } - async set(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.setFor(app, data); - } - async setFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.set, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - subscribe(callback) { - const app = this.getMyAppName(); - return this.subscribeFor(app, callback); - } - subscribeFor(app, callback) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const applications = this.appManagerController.getApplications(); - const isValidApp = verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp); - if (!isValidApp) { - return ioError.raiseError(`The provided app name "${app}" is not valid.`); - } - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!"); - } - if (!this.signaledSubscription) { - this.bridge.send("prefs", operations$1.registerSubscriber, { interopId: this.interopId, appName: verifiedApp }, undefined, { includeOperationCheck: true }) - .catch((error) => { - this.logger.warn("Failed to register subscriber for prefs"); - this.logger.error(error); - }); - this.signaledSubscription = true; - } - const subscriptionKey = this.getSubscriptionKey(verifiedApp); - this.get(verifiedApp).then(callback); - return this.registry.add(subscriptionKey, callback); - } - async updateFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.update, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - getMyAppName() { - const myAppName = this.config.isPlatformInternal ? this.platformAppName : this.appManagerController.me?.application.name; - if (!myAppName) { - return ioError.raiseError("App Preferences operations can not be executed for windows that do not have app!"); - } - return myAppName; - } - getSubscriptionKey(app) { - return `prefs-changed-${app}`; - } - async handleOnChanged({ prefs }) { - const subscriptionKey = this.getSubscriptionKey(prefs.app); - this.registry.execute(subscriptionKey, prefs); - } - } - - const operations = { - getResources: { name: "getResources", dataDecoder: getResourcesDataDecoder, resultDecoder: getResourcesResultDecoder }, - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - showAlert: { name: "showAlert", dataDecoder: uiAlertRequestMessageDecoder }, - showDialog: { name: "showDialog", dataDecoder: uiDialogRequestMessageDecoder }, - alertInteropAction: { name: "alertInteropAction", dataDecoder: alertInteropActionDataDecoder }, - showResolver: { name: "showResolver", dataDecoder: uiResolverRequestMessageDecoder, resultDecoder: uiResolverResponseMessageDecoder }, - }; - - const DEFAULT_ALERT_TTL = 5 * 1000; - const MODALS_SHADOW_HOST_ID = "io-modals-shadow-host"; - const MODALS_ROOT_ELEMENT_ID = "io-modals-root"; - const WIDGET_SHADOW_HOST_ID = "io-widget-shadow-host"; - const WIDGET_ROOT_ELEMENT_ID = "io-widget-root"; - const INTENT_RESOLVER_SHADOW_HOST_ID = "io-intent-resolver-shadow-host"; - const INTENT_RESOLVER_ROOT_ELEMENT_ID = "io-intent-resolver-root"; - const SHADOW_ROOT_ELEMENT_CLASSNAME = "io-body io-variables"; - - class UIController { - ioc; - supportedOperationsNames = []; - logger; - bridge; - config; - zIndexDictionary = { - [WIDGET_SHADOW_HOST_ID]: "100", - [MODALS_SHADOW_HOST_ID]: "101", - [INTENT_RESOLVER_SHADOW_HOST_ID]: "100" - }; - widgetResources; - modalsResources; - intentResolverResources; - modalsUiApi; - isDialogOpen = false; - intentResolverUiApi; - isIntentResolverOpen = false; - constructor(ioc) { - this.ioc = ioc; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("ui.controller.web"); - this.logger.trace("starting the ui controller"); - this.bridge = ioc.bridge; - this.config = ioc.config; - this.addOperationsExecutors(); - const resources = await this.getResources(); - if (!resources) { - this.logger.trace("No UI elements to display - platform is not initialized with any UI resources"); - return; - } - this.logger.trace(`Received UI resources from platform: ${JSON.stringify(resources)}`); - this.setResources(resources); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(uiOperationTypesDecoder, args.operation); - const operation = operations[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async showComponents(io) { - const initializeWidgetPromise = this.widgetResources ? this.initializeWidget(io, this.widgetResources) : Promise.resolve(); - const initializeModalsPromise = this.modalsResources ? this.initializeModalsUi(io, this.modalsResources) : Promise.resolve(); - const initializeIntentResolverPromise = this.intentResolverResources ? this.initializeIntentResolverUI(io, this.intentResolverResources) : Promise.resolve(); - await Promise.all([ - this.config.widget.awaitFactory ? initializeWidgetPromise : Promise.resolve(), - this.config.modals.awaitFactory ? initializeModalsPromise : Promise.resolve(), - this.config.intentResolver.awaitFactory ? initializeIntentResolverPromise : Promise.resolve(), - ]); - } - isIntentResolverEnabled() { - return !!this.intentResolverResources && this.config.intentResolver.enable; - } - addOperationsExecutors() { - operations.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - operations.showAlert.execute = this.handleShowAlert.bind(this); - operations.showDialog.execute = this.handleShowDialog.bind(this); - operations.showResolver.execute = this.handleShowResolver.bind(this); - this.supportedOperationsNames = getSupportedOperationsNames(operations); - } - async handleShowAlert({ config }) { - if (!this.config.modals.alerts.enabled) { - return ioError.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showAlert operation because modalsUiApi is missing."); - } - const { promise: closePromise, resolve: resolveClosePromise } = wrapPromise(); - const onClick = (config) => { - const decodedConfig = alertOnClickConfigDecoder.run(config); - if (!decodedConfig.ok) { - this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(decodedConfig.error)}.`); - return; - } - const { interopAction } = decodedConfig.result; - this.bridge.send("ui", operations.alertInteropAction, { interopAction }, undefined, { includeOperationCheck: true }) - .catch((error) => this.logger.warn(extractErrorMsg(error))); - }; - let result; - try { - this.logger.trace(`Open alert with config: ${JSON.stringify(config)}`); - result = modalsUiApi.alerts.open({ ...config, onClick, onClose: resolveClosePromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openAlertResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - const timeoutId = setTimeout(() => { - resolveClosePromise(); - }, getSafeTimeoutDelay(config.ttl ?? DEFAULT_ALERT_TTL)); - closePromise.then(() => { - clearTimeout(timeoutId); - try { - modalsUiApi.alerts.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close alert with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - }); - } - async handleShowDialog({ config }) { - if (!this.config.modals.dialogs.enabled) { - return ioError.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showDialog operation because modalsUiApi is missing."); - } - if (this.isDialogOpen) { - return ioError.raiseError("Cannot open a dialog because another one is already open."); - } - const { promise: completionPromise, resolve: resolveCompletionPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open dialog with config: ${JSON.stringify(config)}`); - result = modalsUiApi.dialogs.open({ ...config, onCompletion: resolveCompletionPromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openDialogResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - this.isDialogOpen = true; - let timeoutId; - if (config.timer) { - timeoutId = setTimeout(() => { - resolveCompletionPromise({ response: { isExpired: true } }); - }, getSafeTimeoutDelay(config.timer.duration)); - } - const response = await completionPromise; - clearTimeout(timeoutId); - this.isDialogOpen = false; - try { - modalsUiApi.dialogs.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close dialog with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodeResponse = dialogOnCompletionConfigDecoder.run(response); - if (!decodeResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodeResponse.error)}.`); - } - return { result: decodeResponse.result.response }; - } - async handleShowResolver({ config }) { - this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(config)}`); - if (!this.config.intentResolver.enable) { - return ioError.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config."); - } - const intentResolverApi = this.intentResolverUiApi; - if (!intentResolverApi) { - return ioError.raiseError("Unable to perform showResolver operation because intentResolverApi is missing."); - } - if (this.isIntentResolverOpen) { - return ioError.raiseError("Cannot open the intent resolver because another one is already open."); - } - const { promise: completionPromise, resolve: resolveIntentResolverPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open intent resolver with config: ${JSON.stringify(config)}`); - result = intentResolverApi.open({ ...config, onUserResponse: resolveIntentResolverPromise }); - } - catch (error) { - return ioError.raiseError(`intentResolverUI.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodedOpenResult = openResolverResultDecoder.run(result); - if (!decodedOpenResult.ok) { - return ioError.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(decodedOpenResult.error)}.`); - } - const timer = setTimeout(() => resolveIntentResolverPromise({ response: { isExpired: true } }), getSafeTimeoutDelay(config.timeout)); - const response = await completionPromise; - clearTimeout(timer); - this.isIntentResolverOpen = false; - try { - intentResolverApi.close({ id: decodedOpenResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close intent resolver with id ${decodedOpenResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodedResponse = onUserResponseResponseDecoder.run(response); - if (!decodedResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodedResponse.error)}.`); - } - return { result: decodedResponse.result.response }; - } - async getResources() { - const data = { - origin: window.origin - }; - try { - const result = await this.bridge.send("ui", operations.getResources, data, undefined, { includeOperationCheck: true }); - return result.resources; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - } - } - appendModalsResources(resources) { - this.logger.trace("Appending modals resources"); - return this.appendResources(MODALS_SHADOW_HOST_ID, MODALS_ROOT_ELEMENT_ID, resources.sources); - } - appendWidgetResources(resources) { - this.logger.trace("Appending widget resources"); - return this.appendResources(WIDGET_SHADOW_HOST_ID, WIDGET_ROOT_ELEMENT_ID, resources.sources); - } - appendIntentResolverResources(resources) { - this.logger.trace("Appending intent resolver resources"); - return this.appendResources(INTENT_RESOLVER_SHADOW_HOST_ID, INTENT_RESOLVER_ROOT_ELEMENT_ID, resources.sources); - } - appendResources(shadowHostId, rootElementId, sources) { - const { bundle, fonts = [], styles } = sources; - const shadowHost = document.createElement("div"); - shadowHost.id = shadowHostId; - shadowHost.style.position = "fixed"; - shadowHost.style.zIndex = this.zIndexDictionary[shadowHostId]; - const shadowRoot = shadowHost.attachShadow({ mode: "open" }); - const script = document.createElement("script"); - script.src = bundle; - script.type = "module"; - shadowRoot.appendChild(script); - const rootElement = document.createElement("div"); - rootElement.id = rootElementId; - rootElement.className = SHADOW_ROOT_ELEMENT_CLASSNAME; - shadowRoot.appendChild(rootElement); - styles.forEach((style) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = style; - shadowRoot.appendChild(link); - }); - fonts.forEach((font) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = font; - document.head.insertBefore(link, document.head.firstChild); - }); - document.body.appendChild(shadowHost); - return { rootElement }; - } - async initializeWidget(io, resources) { - this.logger.trace("Initializing IOBrowserWidget."); - const { rootElement } = this.appendWidgetResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...deepmerge$1(resources.config, this.config.widget), - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.widgetReady(); - this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(config)}`); - await window.IOBrowserWidget(io, config); - this.logger.trace("IOBrowserWidget was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserWidget to initialize.`); - } - async initializeModalsUi(io, resources) { - this.logger.trace("Initializing IOBrowserModalsUI."); - const { rootElement } = this.appendModalsResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.modals, - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.modalsUIFactoryReady(); - this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.modalsUiApi = await window.IOBrowserModalsUI(io, config); - this.logger.trace("IOBrowserModalsUI was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`); - } - async initializeIntentResolverUI(io, resources) { - this.logger.trace("Initializing IOBrowserIntentResolverUI."); - const { rootElement } = this.appendIntentResolverResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.intentResolver, - rootElement - }; - const timeout = config.timeout; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(); - this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.intentResolverUiApi = await window.IOBrowserIntentResolverUI(io, config); - this.logger.trace("IOBrowserIntentResolverUI initialized successfully."); - }, timeout, `Timeout of ${timeout}ms hit waiting for IOBrowserIntentResolverUI to initialize.`); - } - setResources(resources) { - this.setWidgetResources(resources.widget); - this.setModalsUiResources(resources.modals); - this.setIntentResolverResources(resources.intentResolver); - } - setWidgetResources(resources) { - const baseMsg = "Widget won't be displayed. Reason: "; - const decodedConfig = widgetConfigDecoder.run(this.config.widget); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid widget config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.widget.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'widget: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`); - return; - } - this.widgetResources = resources; - } - setModalsUiResources(resources) { - const baseMsg = "Modals won't be displayed. Reason: "; - const decodedConfig = modalsConfigDecoder.run(this.config.modals); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid modals config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.modals.alerts.enabled && !this.config.modals.dialogs.enabled) { - this.logger.trace(`${baseMsg} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`); - return; - } - this.modalsResources = resources; - } - setIntentResolverResources(resources) { - const baseMsg = "Intent Resolver UI won't be displayed. Reason: "; - const decodedConfig = intentResolverConfigDecoder.run(this.config.intentResolver); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid intent resolver config. Error: ${JSON.stringify(decodedConfig.error)}`); - return; - } - if (!this.config.intentResolver.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'intentResolver: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`); - return; - } - this.intentResolverResources = resources; - } - subscribeForThemeChanges(io, element) { - const themesApi = io.themes; - if (!themesApi) { - return; - } - const changeTheme = async (theme) => { - if (element.classList.contains(theme.name)) { - return; - } - const allThemes = await themesApi.list(); - element.classList.remove(...allThemes.map(({ name }) => name)); - element.classList.add(theme.name); - }; - themesApi.onChanged(changeTheme); - themesApi.getCurrent().then(changeTheme); - } - } - - class IoC { - _coreGlue; - _communicationId; - _publicWindowId; - _webConfig; - _windowsControllerInstance; - _appManagerControllerInstance; - _layoutsControllerInstance; - _notificationsControllerInstance; - _intentsControllerInstance; - _channelsControllerInstance; - _themesControllerInstance; - _extensionController; - _systemControllerInstance; - _bridgeInstance; - _eventsDispatcher; - _preferredConnectionController; - _channelsStorage; - _prefsControllerInstance; - _uiController; - controllers = { - windows: this.windowsController, - appManager: this.appManagerController, - layouts: this.layoutsController, - notifications: this.notificationsController, - intents: this.intentsController, - channels: this.channelsController, - system: this.systemController, - extension: this.extensionController, - themes: this.themesController, - prefs: this.prefsController, - ui: this.uiController - }; - get communicationId() { - return this._communicationId; - } - get publicWindowId() { - return this._publicWindowId; - } - get windowsController() { - if (!this._windowsControllerInstance) { - this._windowsControllerInstance = new WindowsController(); - } - return this._windowsControllerInstance; - } - get uiController() { - if (!this._uiController) { - this._uiController = new UIController(this); - } - return this._uiController; - } - get appManagerController() { - if (!this._appManagerControllerInstance) { - this._appManagerControllerInstance = new AppManagerController(); - } - return this._appManagerControllerInstance; - } - get layoutsController() { - if (!this._layoutsControllerInstance) { - this._layoutsControllerInstance = new LayoutsController(); - } - return this._layoutsControllerInstance; - } - get themesController() { - if (!this._themesControllerInstance) { - this._themesControllerInstance = new ThemesController(); - } - return this._themesControllerInstance; - } - get notificationsController() { - if (!this._notificationsControllerInstance) { - this._notificationsControllerInstance = new NotificationsController(); - } - return this._notificationsControllerInstance; - } - get intentsController() { - if (!this._intentsControllerInstance) { - this._intentsControllerInstance = new IntentsController(); - } - return this._intentsControllerInstance; - } - get systemController() { - if (!this._systemControllerInstance) { - this._systemControllerInstance = new SystemController(); - } - return this._systemControllerInstance; - } - get channelsController() { - if (!this._channelsControllerInstance) { - this._channelsControllerInstance = new ChannelsController(); - } - return this._channelsControllerInstance; - } - get prefsController() { - if (!this._prefsControllerInstance) { - this._prefsControllerInstance = new PrefsController(); - } - return this._prefsControllerInstance; - } - get extensionController() { - if (!this._extensionController) { - this._extensionController = new ExtController(); - } - return this._extensionController; - } - get eventsDispatcher() { - if (!this._eventsDispatcher) { - this._eventsDispatcher = new EventsDispatcher(this.config); - } - return this._eventsDispatcher; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new GlueBridge(this._coreGlue, this.communicationId); - } - return this._bridgeInstance; - } - get preferredConnectionController() { - if (!this._preferredConnectionController) { - this._preferredConnectionController = new PreferredConnectionController(this._coreGlue); - } - return this._preferredConnectionController; - } - get channelsStorage() { - if (!this._channelsStorage) { - this._channelsStorage = new ChannelsStorage(); - } - return this._channelsStorage; - } - get config() { - return this._webConfig; - } - defineGlue(coreGlue) { - this._coreGlue = coreGlue; - this._publicWindowId = coreGlue.connection.transport.publicWindowId; - const globalNamespace = window.glue42core || window.iobrowser; - this._communicationId = coreGlue.connection.transport.communicationId || globalNamespace.communicationId; - } - defineConfig(config) { - this._webConfig = config; - } - async buildWebWindow(id, name, logger) { - const model = new WebWindowModel(id, name, this.bridge, logger); - const api = await model.toApi(); - return { id, model, api }; - } - buildNotification(config, id) { - return new Notification(config, id); - } - async buildApplication(app, applicationInstances) { - const application = (new ApplicationModel(app, [], this.appManagerController)).toApi(); - const instances = applicationInstances.map((instanceData) => this.buildInstance(instanceData, application)); - application.instances.push(...instances); - return application; - } - buildInstance(instanceData, app) { - return (new InstanceModel(instanceData, this.bridge, app)).toApi(); - } - } - - var version$1 = "4.2.4"; - - const setupGlobalSystem = (io, bridge) => { - return { - getContainerInfo: async () => { - if (window === window.parent) { - return; - } - if (window.name.includes("#wsp")) { - return { - workspaceFrame: { - id: "N/A" - } - }; - } - return window.parent === window.top ? - { top: {} } : - { parent: {} }; - }, - getProfileData: async () => { - if (!bridge) { - throw new Error("Bridge is not available and cannot fetch the profile data"); - } - const data = await bridge.send("system", { name: "getProfileData" }, undefined); - return data; - } - }; - }; - - const createFactoryFunction = (coreFactoryFunction) => { - let cachedApiPromise; - const initAPI = async (config) => { - const ioc = new IoC(); - const glue = await PromiseWrap(() => coreFactoryFunction(config, { version: version$1 }), 30000, "Glue Web initialization timed out, because core didn't resolve"); - const logger = glue.logger.subLogger("web.main.controller"); - ioc.defineGlue(glue); - await ioc.preferredConnectionController.start(config); - await ioc.bridge.start(ioc.controllers); - ioc.defineConfig(config); - logger.trace("the bridge has been started, initializing all controllers"); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.start(glue, ioc))); - logger.trace("all controllers reported started, starting all additional libraries"); - try { - await Promise.all(config.libraries.map((lib) => lib(glue, config))); - logger.trace("all libraries were started"); - ioc.eventsDispatcher.start(glue); - logger.trace("start event dispatched, glue is ready, returning it"); - await ioc.uiController.showComponents(glue).catch((err) => logger.warn(err?.message ? err.message : JSON.stringify(err))); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.postStart ? controller.postStart(glue, ioc) : Promise.resolve())); - window.iobrowser.system = setupGlobalSystem(glue, ioc.bridge); - window.iobrowser = Object.freeze({ ...window.iobrowser }); - return glue; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const factory = (userConfig) => { - if (window.glue42gd || window.iodesktop) { - return enterprise(userConfig); - } - const config = parseConfig(userConfig); - try { - checkSingleton(); - } - catch (error) { - return typeof cachedApiPromise === "undefined" ? Promise.reject(new Error(error)) : cachedApiPromise; - } - const apiPromise = initAPI(config); - cachedApiPromise = userConfig?.memoizeAPI ? apiPromise : undefined; - return apiPromise; - }; - return factory; - }; - - var MetricTypes = { - STRING: 1, - NUMBER: 2, - TIMESTAMP: 3, - OBJECT: 4 - }; - - function getMetricTypeByValue(metric) { - if (metric.type === MetricTypes.TIMESTAMP) { - return "timestamp"; - } - else if (metric.type === MetricTypes.NUMBER) { - return "number"; - } - else if (metric.type === MetricTypes.STRING) { - return "string"; - } - else if (metric.type === MetricTypes.OBJECT) { - return "object"; - } - return "unknown"; - } - function getTypeByValue(value) { - if (value.constructor === Date) { - return "timestamp"; - } - else if (typeof value === "number") { - return "number"; - } - else if (typeof value === "string") { - return "string"; - } - else if (typeof value === "object") { - return "object"; - } - else { - return "string"; - } - } - function serializeMetric(metric) { - const serializedMetrics = {}; - const type = getMetricTypeByValue(metric); - if (type === "object") { - const values = Object.keys(metric.value).reduce((memo, key) => { - const innerType = getTypeByValue(metric.value[key]); - if (innerType === "object") { - const composite = defineNestedComposite(metric.value[key]); - memo[key] = { - type: "object", - description: "", - context: {}, - composite, - }; - } - else { - memo[key] = { - type: innerType, - description: "", - context: {}, - }; - } - return memo; - }, {}); - serializedMetrics.composite = values; - } - serializedMetrics.name = normalizeMetricName(metric.path.join("/") + "/" + metric.name); - serializedMetrics.type = type; - serializedMetrics.description = metric.description; - serializedMetrics.context = {}; - return serializedMetrics; - } - function defineNestedComposite(values) { - return Object.keys(values).reduce((memo, key) => { - const type = getTypeByValue(values[key]); - if (type === "object") { - memo[key] = { - type: "object", - description: "", - context: {}, - composite: defineNestedComposite(values[key]), - }; - } - else { - memo[key] = { - type, - description: "", - context: {}, - }; - } - return memo; - }, {}); - } - function normalizeMetricName(name) { - if (typeof name !== "undefined" && name.length > 0 && name[0] !== "/") { - return "/" + name; - } - else { - return name; - } - } - function getMetricValueByType(metric) { - const type = getMetricTypeByValue(metric); - if (type === "timestamp") { - return Date.now(); - } - else { - return publishNestedComposite(metric.value); - } - } - function publishNestedComposite(values) { - if (typeof values !== "object") { - return values; - } - return Object.keys(values).reduce((memo, key) => { - const value = values[key]; - if (typeof value === "object" && value.constructor !== Date) { - memo[key] = publishNestedComposite(value); - } - else if (value.constructor === Date) { - memo[key] = new Date(value).getTime(); - } - else if (value.constructor === Boolean) { - memo[key] = value.toString(); - } - else { - memo[key] = value; - } - return memo; - }, {}); - } - function flatten(arr) { - return arr.reduce((flat, toFlatten) => { - return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); - }, []); - } - function getHighestState(arr) { - return arr.sort((a, b) => { - if (!a.state) { - return 1; - } - if (!b.state) { - return -1; - } - return b.state - a.state; - })[0]; - } - function aggregateDescription(arr) { - let msg = ""; - arr.forEach((m, idx, a) => { - const path = m.path.join("."); - if (idx === a.length - 1) { - msg += path + "." + m.name + ": " + m.description; - } - else { - msg += path + "." + m.name + ": " + m.description + ","; - } - }); - if (msg.length > 100) { - return msg.slice(0, 100) + "..."; - } - else { - return msg; - } - } - function composeMsgForRootStateMetric(system) { - const aggregatedState = system.root.getAggregateState(); - const merged = flatten(aggregatedState); - const highestState = getHighestState(merged); - const aggregateDesc = aggregateDescription(merged); - return { - description: aggregateDesc, - value: highestState.state, - }; - } - - function gw3 (connection, config) { - if (!connection || typeof connection !== "object") { - throw new Error("Connection is required parameter"); - } - let joinPromise; - let session; - const init = (repo) => { - let resolveReadyPromise; - joinPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - session = connection.domain("metrics"); - session.onJoined((reconnect) => { - if (!reconnect && resolveReadyPromise) { - resolveReadyPromise(); - resolveReadyPromise = undefined; - } - const rootStateMetric = { - name: "/State", - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const defineRootMetricsMsg = { - type: "define", - metrics: [rootStateMetric], - }; - session.sendFireAndForget(defineRootMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(err)}`); - }); - if (reconnect) { - replayRepo(repo); - } - }); - session.join({ - system: config.system, - service: config.service, - instance: config.instance - }); - }; - const replayRepo = (repo) => { - replaySystem(repo.root); - }; - const replaySystem = (system) => { - createSystem(system); - system.metrics.forEach((m) => { - createMetric(m); - }); - system.subSystems.forEach((ss) => { - replaySystem(ss); - }); - }; - const createSystem = async (system) => { - if (system.parent === undefined) { - return; - } - await joinPromise; - const metric = { - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const createMetricsMsg = { - type: "define", - metrics: [metric], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const updateSystem = async (system, state) => { - await joinPromise; - const shadowedUpdateMetric = { - type: "publish", - values: [{ - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - value: { - Description: state.description, - Value: state.state, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(shadowedUpdateMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - const stateObj = composeMsgForRootStateMetric(system); - const rootMetric = { - type: "publish", - peer_id: connection.peerId, - values: [{ - name: "/State", - value: { - Description: stateObj.description, - Value: stateObj.value, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(rootMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for root state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const createMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - const m = serializeMetric(metricClone); - const createMetricsMsg = { - type: "define", - metrics: [m], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for metric ${metric.name}: ${JSON.stringify(err)}`); - }); - if (typeof metricClone.value !== "undefined") { - updateMetricCore(metricClone); - } - }; - const updateMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - updateMetricCore(metricClone); - }; - const updateMetricCore = (metric) => { - if (canUpdate()) { - const value = getMetricValueByType(metric); - const publishMetricsMsg = { - type: "publish", - values: [{ - name: normalizeMetricName(metric.path.join("/") + "/" + metric.name), - value, - timestamp: Date.now(), - }], - }; - return session.sendFireAndForget(publishMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to publish metric ${metric.name}: ${JSON.stringify(err)}`); - }); - } - return Promise.resolve(); - }; - const cloneMetric = (metric) => { - const metricClone = { ...metric }; - if (typeof metric.value === "object" && metric.value !== null) { - metricClone.value = { ...metric.value }; - } - return metricClone; - }; - const canUpdate = () => { - try { - const func = config.canUpdateMetric ?? (() => true); - return func(); - } - catch { - return true; - } - }; - return { - init, - createSystem, - updateSystem, - createMetric, - updateMetric, - }; - } - - var Helpers = { - validate: (definition, parent, transport) => { - if (definition === null || typeof definition !== "object") { - throw new Error("Missing definition"); - } - if (parent === null || typeof parent !== "object") { - throw new Error("Missing parent"); - } - if (transport === null || typeof transport !== "object") { - throw new Error("Missing transport"); - } - }, - }; - - class BaseMetric { - definition; - system; - transport; - value; - type; - path = []; - name; - description; - get repo() { - return this.system?.repo; - } - get id() { return `${this.system.path}/${name}`; } - constructor(definition, system, transport, value, type) { - this.definition = definition; - this.system = system; - this.transport = transport; - this.value = value; - this.type = type; - Helpers.validate(definition, system, transport); - this.path = system.path.slice(0); - this.path.push(system.name); - this.name = definition.name; - this.description = definition.description; - transport.createMetric(this); - } - update(newValue) { - this.value = newValue; - return this.transport.updateMetric(this); - } - } - - class NumberMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.NUMBER); - } - incrementBy(num) { - this.update(this.value + num); - } - increment() { - this.incrementBy(1); - } - decrement() { - this.incrementBy(-1); - } - decrementBy(num) { - this.incrementBy(num * -1); - } - } - - class ObjectMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.OBJECT); - } - update(newValue) { - this.mergeValues(newValue); - return this.transport.updateMetric(this); - } - mergeValues(values) { - return Object.keys(this.value).forEach((k) => { - if (typeof values[k] !== "undefined") { - this.value[k] = values[k]; - } - }); - } - } - - class StringMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.STRING); - } - } - - class TimestampMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.TIMESTAMP); - } - now() { - this.update(new Date()); - } - } - - function system(name, repo, protocol, parent, description) { - if (!repo) { - throw new Error("Repository is required"); - } - if (!protocol) { - throw new Error("Transport is required"); - } - const _transport = protocol; - const _name = name; - const _description = description || ""; - const _repo = repo; - const _parent = parent; - const _path = _buildPath(parent); - let _state = {}; - const id = _arrayToString(_path, "/") + name; - const root = repo.root; - const _subSystems = []; - const _metrics = []; - function subSystem(nameSystem, descriptionSystem) { - if (!nameSystem || nameSystem.length === 0) { - throw new Error("name is required"); - } - const match = _subSystems.filter((s) => s.name === nameSystem); - if (match.length > 0) { - return match[0]; - } - const _system = system(nameSystem, _repo, _transport, me, descriptionSystem); - _subSystems.push(_system); - return _system; - } - function setState(state, stateDescription) { - _state = { state, description: stateDescription }; - _transport.updateSystem(me, _state); - } - function stringMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.STRING, value, (metricDef) => new StringMetric(metricDef, me, _transport, value)); - } - function numberMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.NUMBER, value, (metricDef) => new NumberMetric(metricDef, me, _transport, value)); - } - function objectMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.OBJECT, value, (metricDef) => new ObjectMetric(metricDef, me, _transport, value)); - } - function timestampMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.TIMESTAMP, value, (metricDef) => new TimestampMetric(metricDef, me, _transport, value)); - } - function _getOrCreateMetric(metricObject, expectedType, value, createMetric) { - let metricDef = { name: "" }; - if (typeof metricObject === "string") { - metricDef = { name: metricObject }; - } - else { - metricDef = metricObject; - } - const matching = _metrics.filter((shadowedMetric) => shadowedMetric.name === metricDef.name); - if (matching.length > 0) { - const existing = matching[0]; - if (existing.type !== expectedType) { - throw new Error(`A metric named ${metricDef.name} is already defined with different type.`); - } - if (typeof value !== "undefined") { - existing - .update(value) - .catch(() => { }); - } - return existing; - } - const metric = createMetric(metricDef); - _metrics.push(metric); - return metric; - } - function _buildPath(shadowedSystem) { - if (!shadowedSystem || !shadowedSystem.parent) { - return []; - } - const path = _buildPath(shadowedSystem.parent); - path.push(shadowedSystem.name); - return path; - } - function _arrayToString(path, separator) { - return ((path && path.length > 0) ? path.join(separator) : ""); - } - function getAggregateState() { - const aggState = []; - if (Object.keys(_state).length > 0) { - aggState.push({ - name: _name, - path: _path, - state: _state.state, - description: _state.description, - }); - } - _subSystems.forEach((shadowedSubSystem) => { - const result = shadowedSubSystem.getAggregateState(); - if (result.length > 0) { - aggState.push(...result); - } - }); - return aggState; - } - const me = { - get name() { - return _name; - }, - get description() { - return _description; - }, - get repo() { - return _repo; - }, - get parent() { - return _parent; - }, - path: _path, - id, - root, - get subSystems() { - return _subSystems; - }, - get metrics() { - return _metrics; - }, - subSystem, - getState: () => { - return _state; - }, - setState, - stringMetric, - timestampMetric, - objectMetric, - numberMetric, - getAggregateState, - }; - _transport.createSystem(me); - return me; - } - - class Repository { - root; - constructor(options, protocol) { - protocol.init(this); - this.root = system("", this, protocol); - this.addSystemMetrics(this.root, options.clickStream || options.clickStream === undefined); - } - addSystemMetrics(rootSystem, useClickStream) { - if (typeof navigator !== "undefined") { - rootSystem.stringMetric("UserAgent", navigator.userAgent); - } - if (useClickStream && typeof document !== "undefined") { - const clickStream = rootSystem.subSystem("ClickStream"); - const documentClickHandler = (e) => { - if (!e.target) { - return; - } - const target = e.target; - const className = target ? target.getAttribute("class") ?? "" : ""; - clickStream.objectMetric("LastBrowserEvent", { - type: "click", - timestamp: new Date(), - target: { - className, - id: target.id, - type: "<" + target.tagName.toLowerCase() + ">", - href: target.href || "", - }, - }); - }; - clickStream.objectMetric("Page", { - title: document.title, - page: window.location.href, - }); - if (document.addEventListener) { - document.addEventListener("click", documentClickHandler); - } - else { - document.attachEvent("onclick", documentClickHandler); - } - } - rootSystem.stringMetric("StartTime", (new Date()).toString()); - const urlMetric = rootSystem.stringMetric("StartURL", ""); - const appNameMetric = rootSystem.stringMetric("AppName", ""); - if (typeof window !== "undefined") { - if (typeof window.location !== "undefined") { - const startUrl = window.location.href; - urlMetric.update(startUrl); - } - if (typeof window.glue42gd !== "undefined") { - appNameMetric.update(window.glue42gd.appName); - } - } - } - } - - class NullProtocol { - init(repo) { - } - createSystem(system) { - return Promise.resolve(); - } - updateSystem(metric, state) { - return Promise.resolve(); - } - createMetric(metric) { - return Promise.resolve(); - } - updateMetric(metric) { - return Promise.resolve(); - } - } - - class PerfTracker { - api; - lastCount = 0; - initialPublishTimeout = 10 * 1000; - publishInterval = 60 * 1000; - system; - constructor(api, initialPublishTimeout, publishInterval) { - this.api = api; - this.initialPublishTimeout = initialPublishTimeout ?? this.initialPublishTimeout; - this.publishInterval = publishInterval ?? this.publishInterval; - this.scheduleCollection(); - this.system = this.api.subSystem("performance", "Performance data published by the web application"); - } - scheduleCollection() { - setTimeout(() => { - this.collect(); - setInterval(() => { - this.collect(); - }, this.publishInterval); - }, this.initialPublishTimeout); - } - collect() { - try { - this.collectMemory(); - this.collectEntries(); - } - catch { - } - } - collectMemory() { - const memory = window.performance.memory; - this.system.stringMetric("memory", JSON.stringify({ - totalJSHeapSize: memory.totalJSHeapSize, - usedJSHeapSize: memory.usedJSHeapSize - })); - } - collectEntries() { - const allEntries = window.performance.getEntries(); - if (allEntries.length <= this.lastCount) { - return; - } - this.lastCount = allEntries.length; - const jsonfiedEntries = allEntries.map((i) => i.toJSON()); - this.system.stringMetric("entries", JSON.stringify(jsonfiedEntries)); - } - } - - var metrics = (options) => { - let protocol; - if (!options.connection || typeof options.connection !== "object") { - protocol = new NullProtocol(); - } - else { - protocol = gw3(options.connection, options); - } - const repo = new Repository(options, protocol); - let rootSystem = repo.root; - if (!options.disableAutoAppSystem) { - rootSystem = rootSystem.subSystem("App"); - } - const api = addFAVSupport(rootSystem); - initPerf(api, options.pagePerformanceMetrics); - return api; - }; - function initPerf(api, config) { - if (typeof window === "undefined") { - return; - } - const perfConfig = window?.glue42gd?.metrics?.pagePerformanceMetrics; - if (perfConfig) { - config = perfConfig; - } - if (config?.enabled) { - new PerfTracker(api, config.initialPublishTimeout, config.publishInterval); - } - } - function addFAVSupport(system) { - const reportingSystem = system.subSystem("reporting"); - const def = { - name: "features" - }; - let featureMetric; - const featureMetricFunc = (name, action, payload) => { - if (typeof name === "undefined" || name === "") { - throw new Error("name is mandatory"); - } - else if (typeof action === "undefined" || action === "") { - throw new Error("action is mandatory"); - } - else if (typeof payload === "undefined" || payload === "") { - throw new Error("payload is mandatory"); - } - if (!featureMetric) { - featureMetric = reportingSystem.objectMetric(def, { name, action, payload }); - } - else { - featureMetric.update({ - name, - action, - payload - }); - } - }; - system.featureMetric = featureMetricFunc; - return system; - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackRegistryFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - class InProcTransport { - gw; - registry = CallbackRegistryFactory(); - client; - constructor(settings, logger) { - this.gw = settings.facade; - this.gw.connect((_client, message) => { - this.messageHandler(message); - }).then((client) => { - this.client = client; - }); - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - if (this.client) { - this.client.send(msg); - return Promise.resolve(undefined); - } - else { - return Promise.reject(`not connected`); - } - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "in-memory"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class SharedWorkerTransport { - logger; - worker; - registry = CallbackRegistryFactory(); - constructor(workerFile, logger) { - this.logger = logger; - this.worker = new SharedWorker(workerFile); - this.worker.port.onmessage = (e) => { - this.messageHandler(e.data); - }; - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - this.worker.port.postMessage(msg); - return Promise.resolve(); - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "shared-worker"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class Utils { - static isNode() { - if (typeof Utils._isNode !== "undefined") { - return Utils._isNode; - } - if (typeof window !== "undefined") { - Utils._isNode = false; - return false; - } - try { - Utils._isNode = Object.prototype.toString.call(global.process) === "[object process]"; - } - catch (e) { - Utils._isNode = false; - } - return Utils._isNode; - } - static _isNode; - } - - class PromiseWrapper { - static delay(time) { - return new Promise((resolve) => setTimeout(resolve, time)); - } - resolve; - reject; - promise; - rejected = false; - resolved = false; - get ended() { - return this.rejected || this.resolved; - } - constructor() { - this.promise = new Promise((resolve, reject) => { - this.resolve = (t) => { - this.resolved = true; - resolve(t); - }; - this.reject = (err) => { - this.rejected = true; - reject(err); - }; - }); - } - } - - const timers = {}; - function getAllTimers() { - return timers; - } - function timer (timerName) { - const existing = timers[timerName]; - if (existing) { - return existing; - } - const marks = []; - function now() { - return new Date().getTime(); - } - const startTime = now(); - mark("start", startTime); - let endTime; - let period; - function stop() { - endTime = now(); - mark("end", endTime); - period = endTime - startTime; - return period; - } - function mark(name, time) { - const currentTime = time ?? now(); - let diff = 0; - if (marks.length > 0) { - diff = currentTime - marks[marks.length - 1].time; - } - marks.push({ name, time: currentTime, diff }); - } - const timerObj = { - get startTime() { - return startTime; - }, - get endTime() { - return endTime; - }, - get period() { - return period; - }, - stop, - mark, - marks - }; - timers[timerName] = timerObj; - return timerObj; - } - - const WebSocketConstructor = Utils.isNode() ? null : window.WebSocket; - class WS { - ws; - logger; - settings; - startupTimer = timer("connection"); - _running = true; - _registry = CallbackRegistryFactory(); - wsRequests = []; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - if (!this.settings.ws) { - throw new Error("ws is missing"); - } - } - onMessage(callback) { - return this._registry.add("onMessage", callback); - } - send(msg, options) { - return new Promise((resolve, reject) => { - this.waitForSocketConnection(() => { - try { - this.ws?.send(msg); - resolve(); - } - catch (e) { - reject(e); - } - }, reject); - }); - } - open() { - this.logger.info("opening ws..."); - this._running = true; - return new Promise((resolve, reject) => { - this.waitForSocketConnection(resolve, reject); - }); - } - close() { - this._running = false; - if (this.ws) { - this.ws.close(); - } - return Promise.resolve(); - } - onConnectedChanged(callback) { - return this._registry.add("onConnectedChanged", callback); - } - name() { - return this.settings.ws; - } - reconnect() { - this.ws?.close(); - const pw = new PromiseWrapper(); - this.waitForSocketConnection(() => { - pw.resolve(); - }); - return pw.promise; - } - waitForSocketConnection(callback, failed) { - failed = failed ?? (() => { }); - if (!this._running) { - failed(`wait for socket on ${this.settings.ws} failed - socket closed by user`); - return; - } - if (this.ws?.readyState === 1) { - callback(); - return; - } - this.wsRequests.push({ callback, failed }); - if (this.wsRequests.length > 1) { - return; - } - this.openSocket(); - } - async openSocket(retryInterval, retriesLeft) { - this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${retryInterval}, retriesLeft: ${retriesLeft}...`); - this.startupTimer.mark("opening-socket"); - if (retryInterval === undefined) { - retryInterval = this.settings.reconnectInterval; - } - if (typeof retriesLeft === "undefined") { - retriesLeft = this.settings.reconnectAttempts; - } - if (retriesLeft !== undefined) { - if (retriesLeft === 0) { - this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`); - return; - } - this.logger.debug(`will retry ${retriesLeft} more times (every ${retryInterval} ms)`); - } - try { - await this.initiateSocket(); - this.startupTimer.mark("socket-initiated"); - this.notifyForSocketState(); - } - catch { - setTimeout(() => { - const retries = retriesLeft === undefined ? undefined : retriesLeft - 1; - this.openSocket(retryInterval, retries); - }, retryInterval); - } - } - initiateSocket() { - const pw = new PromiseWrapper(); - this.logger.debug(`initiating ws to ${this.settings.ws}...`); - this.ws = new WebSocketConstructor(this.settings.ws ?? ""); - let wasOpen = false; - this.ws.onerror = (err) => { - let reason; - try { - reason = JSON.stringify(err); - } - catch (error) { - const seen = new WeakSet(); - const replacer = (key, value) => { - if (typeof value === "object" && value !== null) { - if (seen.has(value)) { - return; - } - seen.add(value); - } - if (value instanceof Error) { - return { - message: value.message, - name: value.name, - stack: value.stack - }; - } - return value; - }; - reason = JSON.stringify(err, replacer); - } - this.logger.info(`ws error - reason: ${reason}`); - pw.reject("error"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("error"); - } - this.notifyStatusChanged(false, reason); - }; - this.ws.onclose = (err) => { - this.logger.info(`ws closed - code: ${err?.code} reason: ${err?.reason}`); - pw.reject("closed"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("closed"); - } - this.notifyStatusChanged(false); - }; - this.ws.onopen = () => { - this.startupTimer.mark("ws-opened"); - this.logger.info(`ws opened ${this.settings.identity?.application}`); - pw.resolve(); - wasOpen = true; - this.notifyStatusChanged(true); - }; - this.ws.onmessage = (message) => { - this._registry.execute("onMessage", message.data); - }; - return pw.promise; - } - notifyForSocketState(error) { - this.wsRequests.forEach((wsRequest) => { - if (error) { - if (wsRequest.failed) { - wsRequest.failed(error); - } - } - else { - wsRequest.callback(); - } - }); - this.wsRequests = []; - } - notifyStatusChanged(status, reason) { - this._registry.execute("onConnectedChanged", status, reason); - } - } - - class MessageReplayerImpl { - specs; - specsNames = []; - messages = {}; - isDone; - subs = {}; - subsRefCount = {}; - connection; - constructor(specs) { - this.specs = {}; - for (const spec of specs) { - this.specs[spec.name] = spec; - this.specsNames.push(spec.name); - } - } - init(connection) { - this.connection = connection; - for (const name of this.specsNames) { - for (const type of this.specs[name].types) { - let refCount = this.subsRefCount[type]; - if (!refCount) { - refCount = 0; - } - refCount += 1; - this.subsRefCount[type] = refCount; - if (refCount > 1) { - continue; - } - const sub = connection.on(type, (msg) => this.processMessage(type, msg)); - this.subs[type] = sub; - } - } - } - processMessage(type, msg) { - if (this.isDone || !msg) { - return; - } - for (const name of this.specsNames) { - if (this.specs[name].types.indexOf(type) !== -1) { - const messages = this.messages[name] || []; - this.messages[name] = messages; - messages.push(msg); - } - } - } - drain(name, callback) { - if (callback) { - (this.messages[name] || []).forEach(callback); - } - delete this.messages[name]; - for (const type of this.specs[name].types) { - this.subsRefCount[type] -= 1; - if (this.subsRefCount[type] <= 0) { - this.connection?.off(this.subs[type]); - delete this.subs[type]; - delete this.subsRefCount[type]; - } - } - delete this.specs[name]; - if (!this.specs.length) { - this.isDone = true; - } - } - } - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet[(Math.random() * 64) | 0]; - } - return id - }; - - const PromisePlus = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WebPlatformTransport { - settings; - logger; - identity; - isPreferredActivated; - _connectionProtocolVersion; - _communicationId; - publicWindowId; - selfAssignedWindowId; - iAmConnected = false; - parentReady = false; - rejected = false; - parentPingResolve; - parentPingInterval; - connectionResolve; - extConnectionResolve; - extConnectionReject; - connectionReject; - port; - myClientId; - extContentAvailable = false; - extContentConnecting = false; - extContentConnected = false; - parentWindowId; - parentInExtMode = false; - webNamespace = "g42_core_web"; - parent; - parentType; - parentPingTimeout = 5000; - connectionRequestTimeout = 7000; - defaultTargetString = "*"; - registry = CallbackRegistryFactory(); - messages = { - connectionAccepted: { name: "connectionAccepted", handle: this.handleConnectionAccepted.bind(this) }, - connectionRejected: { name: "connectionRejected", handle: this.handleConnectionRejected.bind(this) }, - connectionRequest: { name: "connectionRequest", handle: this.handleConnectionRequest.bind(this) }, - parentReady: { - name: "parentReady", handle: () => { - } - }, - parentPing: { name: "parentPing", handle: this.handleParentPing.bind(this) }, - platformPing: { name: "platformPing", handle: this.handlePlatformPing.bind(this) }, - platformReady: { name: "platformReady", handle: this.handlePlatformReady.bind(this) }, - clientUnload: { name: "clientUnload", handle: () => { } }, - manualUnload: { name: "manualUnload", handle: this.handleManualUnload.bind(this) }, - extConnectionResponse: { name: "extConnectionResponse", handle: this.handleExtConnectionResponse.bind(this) }, - extSetupRequest: { name: "extSetupRequest", handle: this.handleExtSetupRequest.bind(this) }, - gatewayDisconnect: { name: "gatewayDisconnect", handle: this.handleGatewayDisconnect.bind(this) }, - gatewayInternalConnect: { name: "gatewayInternalConnect", handle: this.handleGatewayInternalConnect.bind(this) } - }; - constructor(settings, logger, identity) { - this.settings = settings; - this.logger = logger; - this.identity = identity; - this.extContentAvailable = !!window.glue42ext; - this.setUpMessageListener(); - this.setUpUnload(); - this.setupPlatformUnloadListener(); - this.parentType = window.name.includes("#wsp") ? "workspace" : undefined; - } - manualSetReadyState() { - this.iAmConnected = true; - this.parentReady = true; - } - get transportWindowId() { - return this.publicWindowId; - } - get communicationId() { - return this._communicationId; - } - async sendObject(msg) { - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: msg }, window.origin); - } - if (!this.port) { - throw new Error("Cannot send message, because the port was not opened yet"); - } - this.port.postMessage(msg); - } - get isObjectBasedTransport() { - return true; - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - send() { - return Promise.reject("not supported"); - } - onConnectedChanged(callback) { - return this.registry.add("onConnectedChanged", callback); - } - async open() { - this.logger.debug("opening a connection to the web platform gateway."); - await this.connect(); - this.notifyStatusChanged(true); - } - close() { - this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId || "unknown"}, client connected: ${this.iAmConnected}`); - const message = { - glue42core: { - type: this.messages.gatewayDisconnect.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.port?.postMessage(message); - this.parentReady = false; - this.notifyStatusChanged(false, "manual reconnection"); - return Promise.resolve(); - } - name() { - return "web-platform"; - } - async reconnect() { - await this.close(); - return Promise.resolve(); - } - initiateInternalConnection() { - return new Promise((resolve, reject) => { - this.logger.debug("opening an internal web platform connection"); - this.port = this.settings.port; - if (this.iAmConnected) { - this.logger.warn("cannot open a new connection, because this client is currently connected"); - return; - } - this.port.onmessage = (event) => { - if (this.iAmConnected && !event.data?.glue42core) { - this.registry.execute("onMessage", event.data); - return; - } - const data = event.data?.glue42core; - if (!data) { - return; - } - if (data.type === this.messages.gatewayInternalConnect.name && data.success) { - this.publicWindowId = this.settings.windowId; - if (this.identity && this.publicWindowId) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.publicWindowId; - } - resolve(); - } - if (data.type === this.messages.gatewayInternalConnect.name && data.error) { - reject(data.error); - } - }; - this.port.postMessage({ - glue42core: { - type: this.messages.gatewayInternalConnect.name - } - }); - }); - } - initiateRemoteConnection(target) { - return PromisePlus((resolve, reject) => { - this.connectionResolve = resolve; - this.connectionReject = reject; - this.myClientId = this.myClientId ?? nanoid(10); - const bridgeInstanceId = this.getMyWindowId() || nanoid(10); - const request = { - glue42core: { - type: this.messages.connectionRequest.name, - clientId: this.myClientId, - clientType: "child", - bridgeInstanceId, - selfAssignedWindowId: this.selfAssignedWindowId - } - }; - this.logger.debug(`sending connection request - clientId: ${this.myClientId}`); - if (this.extContentConnecting) { - request.glue42core.clientType = "child"; - request.glue42core.bridgeInstanceId = this.myClientId; - request.glue42core.parentWindowId = this.parentWindowId; - return window.postMessage(request, window.origin); - } - if (!target) { - throw new Error("Cannot send a connection request, because no glue target was specified!"); - } - target.postMessage(request, this.defaultTargetString); - }, this.connectionRequestTimeout, "The connection to the target glue window timed out"); - } - async isParentCheckSuccess(parentCheck) { - try { - await parentCheck; - return { success: true }; - } - catch (error) { - return { success: false }; - } - } - setUpMessageListener() { - if (this.settings.port) { - this.logger.debug("skipping generic message listener, because this is an internal client"); - return; - } - this.logger.debug("setting up window message listener"); - window.addEventListener("message", (event) => { - const data = event.data?.glue42core; - if (!data || this.rejected) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - if (!this.checkMessageTypeValid(data.type)) { - this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${data.type}`); - return; - } - const messageType = data.type; - this.logger.debug(`received valid glue42core message of type: ${messageType}`); - this.messages[messageType].handle(event); - }); - } - setUpUnload() { - if (this.settings.port) { - this.logger.debug("skipping unload event listener, because this is an internal client"); - return; - } - this.logger.debug("setting up unload event listeners"); - window.addEventListener("beforeunload", () => { - if (this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - window.addEventListener("pagehide", () => { - if (!this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - } - signalClientDisappearing() { - if (this.extContentConnected) { - return; - } - this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.parent?.postMessage(message, this.defaultTargetString); - this.port?.postMessage(message); - } - handlePlatformReady(event) { - this.logger.debug("the web platform gave the ready signal"); - this.parentReady = true; - if (this.parentPingResolve) { - this.parentPingResolve(); - delete this.parentPingResolve; - } - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - this.parent = event.source; - this.parentType = window.name.includes("#wsp") ? "workspace" : "window"; - } - handleConnectionAccepted(event) { - const data = event.data?.glue42core; - if (this.myClientId !== data.clientId) { - return this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${data.clientId}`); - } - return this.handleAcceptanceOfMyRequest(data); - } - handleAcceptanceOfMyRequest(data) { - this.logger.debug("handling a connection accepted signal targeted at me."); - this.isPreferredActivated = data.isPreferredActivated; - if (this.extContentConnecting) { - return this.processExtContentConnection(data); - } - if (!data.port) { - this.logger.error("cannot set up my connection, because I was not provided with a port"); - return; - } - this._connectionProtocolVersion = data.connectionProtocolVersion; - this.publicWindowId = this.getMyWindowId(); - if (this.identity) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.identity.instance ? this.identity.instance : this.publicWindowId || nanoid(10); - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - this._communicationId = data.communicationId; - this.port = data.port; - this.port.onmessage = (e) => this.registry.execute("onMessage", e.data); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - this.logger.error("unable to call the connection resolve, because no connection promise was found"); - } - processExtContentConnection(data) { - this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."); - this.extContentConnecting = false; - this.extContentConnected = true; - this.publicWindowId = this.parentWindowId || this.myClientId; - if (this.extContentConnecting && this.identity) { - this.identity.windowId = this.publicWindowId; - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - window.addEventListener("message", (event) => { - const extData = event.data?.glue42ExtInc; - if (!extData) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - this.registry.execute("onMessage", extData); - }); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - } - handleConnectionRejected(event) { - this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"); - if (!this.connectionReject) { - return; - } - const errorMsg = typeof event.data.glue42core?.error === "string" - ? `Connection was rejected. ${event.data.glue42core?.error}` - : "The platform connection was rejected. Most likely because this window was not created by a glue API call"; - this.connectionReject(errorMsg); - delete this.connectionReject; - } - handleConnectionRequest() { - if (this.extContentConnecting) { - this.logger.debug("This connection request event is targeted at the extension content"); - return; - } - } - handleParentPing(event) { - if (!this.parentReady) { - this.logger.debug("my parent is not ready, I am ignoring the parent ping"); - return; - } - if (!this.iAmConnected) { - this.logger.debug("i am not fully connected yet, I am ignoring the parent ping"); - return; - } - const message = { - glue42core: { - type: this.messages.parentReady.name - } - }; - if (this.extContentConnected) { - message.glue42core.extMode = { windowId: this.myClientId }; - } - const source = event.source; - this.logger.debug("responding to a parent ping with a ready message"); - source.postMessage(message, event.origin); - } - setupPlatformUnloadListener() { - this.logger.debug("setting up platform unload listener"); - this.onMessage((msg) => { - if (msg.type === "platformUnload") { - this.logger.debug("detected a web platform unload"); - this.parentReady = false; - this.notifyStatusChanged(false, "Gateway unloaded"); - } - }); - } - handleManualUnload() { - this.logger.debug("handling manual unload"); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: message }, window.origin); - } - this.port?.postMessage(message); - } - handlePlatformPing() { - return; - } - notifyStatusChanged(status, reason) { - this.logger.debug(`status changed - connected: ${status}, reason: ${reason || "none"}`); - this.iAmConnected = status; - this.registry.execute("onConnectedChanged", status, reason); - } - checkMessageTypeValid(typeToValidate) { - return typeof typeToValidate === "string" && !!this.messages[typeToValidate]; - } - requestConnectionPermissionFromExt() { - return this.waitForContentScript() - .then(() => PromisePlus((resolve, reject) => { - this.extConnectionResolve = resolve; - this.extConnectionReject = reject; - const message = { - glue42core: { - type: "extSetupRequest" - } - }; - this.logger.debug("permission request to the extension content script was sent"); - window.postMessage(message, window.origin); - }, this.parentPingTimeout, "Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")); - } - handleExtConnectionResponse(event) { - const data = event.data?.glue42core; - if (!data.approved) { - return this.extConnectionReject ? this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected") : undefined; - } - if (this.extConnectionResolve) { - this.extConnectionResolve(); - delete this.extConnectionResolve; - } - this.extContentConnecting = true; - this.parentType = "extension"; - this.logger.debug("The extension connection was approved, proceeding."); - } - handleExtSetupRequest() { - return; - } - handleGatewayDisconnect() { - return; - } - handleGatewayInternalConnect() { - return; - } - waitForContentScript() { - const contentReady = !!window.glue42ext?.content; - if (contentReady) { - return Promise.resolve(); - } - return PromisePlus((resolve) => { - window.addEventListener("Glue42EXTReady", () => { - resolve(); - }); - }, this.connectionRequestTimeout, "The content script was available, but was never heard to be ready"); - } - async connect() { - if (this.settings.port) { - await this.initiateInternalConnection(); - this.logger.debug("internal web platform connection completed"); - return; - } - this.logger.debug("opening a client web platform connection"); - await this.findParent(); - await this.initiateRemoteConnection(this.parent); - this.logger.debug("the client is connected"); - } - async findParent() { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const myInsideParents = this.getPossibleParentsInWindow(window); - const myOutsideParents = this.getPossibleParentsOutsideWindow(window.top?.opener, window.top); - const uniqueParents = new Set([...myInsideParents, ...myOutsideParents]); - if (!uniqueParents.size && !this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - if (!uniqueParents.size && this.extContentAvailable) { - await this.requestConnectionPermissionFromExt(); - return; - } - const defaultParentCheck = await this.isParentCheckSuccess(this.confirmParent(Array.from(uniqueParents))); - if (defaultParentCheck.success) { - this.logger.debug("The default parent was found!"); - return; - } - if (!this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - await this.requestConnectionPermissionFromExt(); - } - getPossibleParentsInWindow(currentWindow) { - return (!currentWindow?.parent || currentWindow === currentWindow.parent) ? [] : [currentWindow.parent, ...this.getPossibleParentsInWindow(currentWindow.parent)]; - } - getPossibleParentsOutsideWindow(opener, current) { - return (!opener || !current || opener === current) ? [] : [opener, ...this.getPossibleParentsInWindow(opener), ...this.getPossibleParentsOutsideWindow(opener.opener, opener)]; - } - confirmParent(targets) { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const parentCheck = PromisePlus((resolve) => { - this.parentPingResolve = resolve; - const message = { - glue42core: { - type: this.messages.platformPing.name - } - }; - this.parentPingInterval = setInterval(() => { - targets.forEach((target) => { - target.postMessage(message, this.defaultTargetString); - }); - }, 1000); - }, this.parentPingTimeout, connectionNotPossibleMsg); - parentCheck.catch(() => { - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - }); - return parentCheck; - } - getMyWindowId() { - if (this.parentType === "workspace") { - return window.name.substring(0, window.name.indexOf("#wsp")); - } - if (window !== window.top) { - return; - } - if (window.name?.includes("g42")) { - return window.name; - } - this.selfAssignedWindowId = this.selfAssignedWindowId || `g42-${nanoid(10)}`; - return this.selfAssignedWindowId; - } - } - - const waitForInvocations = (invocations, callback) => { - let left = invocations; - return () => { - left--; - if (left === 0) { - callback(); - } - }; - }; - - class AsyncSequelizer { - minSequenceInterval; - queue = []; - isExecutingQueue = false; - constructor(minSequenceInterval = 0) { - this.minSequenceInterval = minSequenceInterval; - } - enqueue(action) { - return new Promise((resolve, reject) => { - this.queue.push({ action, resolve, reject }); - this.executeQueue(); - }); - } - async executeQueue() { - if (this.isExecutingQueue) { - return; - } - this.isExecutingQueue = true; - while (this.queue.length) { - const operation = this.queue.shift(); - if (!operation) { - this.isExecutingQueue = false; - return; - } - try { - const actionResult = await operation.action(); - operation.resolve(actionResult); - } - catch (error) { - operation.reject(error); - } - await this.intervalBreak(); - } - this.isExecutingQueue = false; - } - intervalBreak() { - return new Promise((res) => setTimeout(res, this.minSequenceInterval)); - } - } - - function domainSession (domain, connection, logger, successMessages, errorMessages) { - if (domain == null) { - domain = "global"; - } - successMessages = successMessages ?? ["success"]; - errorMessages = errorMessages ?? ["error"]; - let isJoined = domain === "global"; - let tryReconnecting = false; - let _latestOptions; - let _connectionOn = false; - const callbacks = CallbackRegistryFactory(); - connection.disconnected(handleConnectionDisconnected); - connection.loggedIn(handleConnectionLoggedIn); - connection.on("success", (msg) => handleSuccessMessage(msg)); - connection.on("error", (msg) => handleErrorMessage(msg)); - connection.on("result", (msg) => handleSuccessMessage(msg)); - if (successMessages) { - successMessages.forEach((sm) => { - connection.on(sm, (msg) => handleSuccessMessage(msg)); - }); - } - if (errorMessages) { - errorMessages.forEach((sm) => { - connection.on(sm, (msg) => handleErrorMessage(msg)); - }); - } - const requestsMap = {}; - function join(options) { - _latestOptions = options; - return new Promise((resolve, reject) => { - if (isJoined) { - resolve({}); - return; - } - let joinPromise; - if (domain === "global") { - joinPromise = _connectionOn ? Promise.resolve({}) : Promise.reject("not connected to gateway"); - } - else { - logger.debug(`joining domain ${domain}`); - const joinMsg = { - type: "join", - destination: domain, - domain: "global", - options, - }; - joinPromise = send(joinMsg); - } - joinPromise - .then(() => { - handleJoined(); - resolve({}); - }) - .catch((err) => { - logger.debug("error joining " + domain + " domain: " + JSON.stringify(err)); - reject(err); - }); - }); - } - function leave() { - if (domain === "global") { - return Promise.resolve(); - } - logger.debug("stopping session " + domain + "..."); - const leaveMsg = { - type: "leave", - destination: domain, - domain: "global", - }; - tryReconnecting = false; - return send(leaveMsg) - .then(() => { - isJoined = false; - callbacks.execute("onLeft"); - }) - .catch(() => { - isJoined = false; - callbacks.execute("onLeft"); - }); - } - function handleJoined() { - logger.debug("did join " + domain); - isJoined = true; - const wasReconnect = tryReconnecting; - tryReconnecting = false; - callbacks.execute("onJoined", wasReconnect); - } - function handleConnectionDisconnected() { - logger.debug("connection is down"); - _connectionOn = false; - isJoined = false; - tryReconnecting = true; - Object.keys(requestsMap).forEach(requestId => { - const request = requestsMap[requestId]; - if (request) { - logger.trace(`failing pending request ${requestId} due to connection lost`); - request.error({ - err: "Connection lost - gateway connection was disconnected" - }); - } - }); - callbacks.execute("onLeft", { disconnected: true }); - } - async function handleConnectionLoggedIn() { - _connectionOn = true; - if (tryReconnecting) { - logger.debug("connection is now up - trying to reconnect..."); - try { - await join(_latestOptions); - } - catch { - logger.trace(`failed to reconnect`); - } - } - } - function onJoined(callback) { - if (isJoined) { - callback(false); - } - return callbacks.add("onJoined", callback); - } - function onLeft(callback) { - if (!isJoined) { - callback(); - } - return callbacks.add("onLeft", callback); - } - function handleErrorMessage(msg) { - if (domain !== msg.domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.error(msg); - } - function handleSuccessMessage(msg) { - if (msg.domain !== domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.success(msg); - } - function getNextRequestId() { - return nanoid(10); - } - let queuedCalls = []; - function send(msg, tag, options) { - const ignore = ["hello", "join"]; - if (msg.type && ignore.indexOf(msg.type) === -1) { - if (!isJoined) { - console.warn(`trying to send a message (${msg.domain} ${msg.type}) but not connected, will queue`); - const pw = new PromiseWrapper(); - queuedCalls.push({ msg, tag, options, pw }); - if (queuedCalls.length === 1) { - const unsubscribe = onJoined(() => { - logger.info(`joined - will now send queued messages (${queuedCalls.length} -> [${queuedCalls.map((m) => m.msg.type)}])`); - queuedCalls.forEach((qm) => { - send(qm.msg, qm.tag, qm.options) - .then((t) => qm.pw.resolve(t)) - .catch((e) => qm.pw.reject(e)); - }); - queuedCalls = []; - unsubscribe(); - }); - } - return pw.promise; - } - } - options = options ?? {}; - msg.request_id = msg.request_id ?? getNextRequestId(); - msg.domain = msg.domain ?? domain; - if (!options.skipPeerId) { - msg.peer_id = connection.peerId; - } - const requestId = msg.request_id; - return new Promise((resolve, reject) => { - requestsMap[requestId] = { - success: (successMsg) => { - delete requestsMap[requestId]; - successMsg._tag = tag; - resolve(successMsg); - }, - error: (errorMsg) => { - console.warn(`Gateway error - ${JSON.stringify(errorMsg)}`); - delete requestsMap[requestId]; - errorMsg._tag = tag; - reject(errorMsg); - }, - }; - connection - .send(msg, options) - .catch((err) => { - requestsMap[requestId]?.error({ err }); - }); - }); - } - function sendFireAndForget(msg) { - msg.request_id = msg.request_id ? msg.request_id : getNextRequestId(); - msg.domain = msg.domain ?? domain; - msg.peer_id = connection.peerId; - return connection.send(msg); - } - return { - join, - leave, - onJoined, - onLeft, - send, - sendFireAndForget, - on: (type, callback) => { - connection.on(type, (msg) => { - if (msg.domain !== domain) { - return; - } - try { - callback(msg); - } - catch (e) { - logger.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(msg)}`, e); - } - }); - }, - loggedIn: (callback) => connection.loggedIn(callback), - connected: (callback) => connection.connected(callback), - disconnected: (callback) => connection.disconnected(callback), - get peerId() { - return connection.peerId; - }, - get domain() { - return domain; - }, - }; - } - - class Connection { - settings; - logger; - protocolVersion = 3; - peerId; - token; - info; - resolvedIdentity; - availableDomains; - gatewayToken; - replayer; - messageHandlers = {}; - ids = 1; - registry = CallbackRegistryFactory(); - _connected = false; - isTrace = false; - transport; - _defaultTransport; - _defaultAuth; - _targetTransport; - _targetAuth; - _swapTransport = false; - _switchInProgress = false; - _transportSubscriptions = []; - datePrefix = "#T42_DATE#"; - datePrefixLen = this.datePrefix.length; - dateMinLen = this.datePrefixLen + 1; - datePrefixFirstChar = this.datePrefix[0]; - _sequelizer = new AsyncSequelizer(); - _isLoggedIn = false; - shouldTryLogin = true; - pingTimer; - sessions = []; - globalDomain; - initialLogin = true; - initialLoginAttempts = 3; - loginConfig; - loginRetryInProgress = false; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - settings = settings || {}; - settings.reconnectAttempts = settings.reconnectAttempts ?? 10; - settings.reconnectInterval = settings.reconnectInterval ?? 1000; - if (settings.inproc) { - this.transport = new InProcTransport(settings.inproc, logger.subLogger("inMemory")); - } - else if (settings.sharedWorker) { - this.transport = new SharedWorkerTransport(settings.sharedWorker, logger.subLogger("shared-worker")); - } - else if (settings.webPlatform) { - this.transport = new WebPlatformTransport(settings.webPlatform, logger.subLogger("web-platform"), settings.identity); - } - else if (settings.ws !== undefined) { - this.transport = new WS(settings, logger.subLogger("ws")); - } - else { - throw new Error("No connection information specified"); - } - this.isTrace = logger.canPublish("trace"); - logger.debug(`starting with ${this.transport.name()} transport`); - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - this._defaultTransport = this.transport; - this.ping(); - } - async switchTransport(settings) { - return this._sequelizer.enqueue(async () => { - if (!settings || typeof settings !== "object") { - throw new Error("Cannot switch transports, because the settings are missing or invalid."); - } - if (typeof settings.type === "undefined") { - throw new Error("Cannot switch the transport, because the type is not defined"); - } - this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(settings)}`); - const switchTargetTransport = settings.type === "secondary" ? this.getNewSecondaryTransport(settings) : this._defaultTransport; - this._targetTransport = switchTargetTransport; - this._targetAuth = settings.type === "secondary" ? this.getNewSecondaryAuth(settings) : this._defaultAuth; - const verifyPromise = this.verifyConnection(); - this._swapTransport = true; - this._switchInProgress = true; - this.logger.trace("The new transport has been set, closing the current transport"); - await this.transport.close(); - try { - await verifyPromise; - const isSwitchSuccess = this.transport === switchTargetTransport; - this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${isSwitchSuccess}`); - this._switchInProgress = false; - return { success: isSwitchSuccess }; - } - catch (error) { - this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."); - this.switchTransport({ type: "default" }); - this._switchInProgress = false; - return { success: false }; - } - }); - } - onLibReAnnounced(callback) { - return this.registry.add("libReAnnounced", callback); - } - setLibReAnnounced(lib) { - this.registry.execute("libReAnnounced", lib); - } - send(message, options) { - if (this.transport.sendObject && - this.transport.isObjectBasedTransport) { - const msg = this.createObjectMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${JSON.stringify(msg)}`); - } - return this.transport.sendObject(msg, options); - } - else { - const strMessage = this.createStringMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${strMessage}`); - } - return this.transport.send(strMessage, options); - } - } - on(type, messageHandler) { - type = type.toLowerCase(); - if (this.messageHandlers[type] === undefined) { - this.messageHandlers[type] = {}; - } - const id = this.ids++; - this.messageHandlers[type][id] = messageHandler; - return { - type, - id, - }; - } - off(info) { - delete this.messageHandlers[info.type.toLowerCase()][info.id]; - } - get isConnected() { - return this._isLoggedIn; - } - connected(callback) { - return this.loggedIn(() => { - const currentServer = this.transport.name(); - callback(currentServer); - }); - } - disconnected(callback) { - return this.registry.add("disconnected", callback); - } - async login(authRequest, reconnect) { - this.logger.debug(`Login initiated - reconnect: ${reconnect}, transport: ${this.transport.name()}`); - if (!this._defaultAuth) { - this._defaultAuth = authRequest; - } - if (this._swapTransport) { - this.logger.trace("Detected a transport swap, swapping transports"); - const newAuth = this.transportSwap(); - authRequest = newAuth ?? authRequest; - } - try { - await this.transport.open(); - this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`); - timer("connection").mark("transport-opened"); - const identity = await this.loginCore(authRequest, reconnect); - this.logger.debug(`Logged in with identity: ${JSON.stringify(identity)}`); - timer("connection").mark("protocol-logged-in"); - return identity; - } - catch (error) { - if (this._switchInProgress) { - this.logger.debug("An error while logging in after a transport swap, preparing a default swap."); - this.prepareDefaultSwap(); - } - throw new Error(error); - } - } - async logout() { - await this.logoutCore(); - await this.transport.close(); - } - loggedIn(callback) { - if (this._isLoggedIn) { - callback(); - } - return this.registry.add("onLoggedIn", callback); - } - domain(domain, successMessages, errorMessages) { - let session = this.sessions.find((s) => s.domain === domain); - if (!session) { - session = domainSession(domain, this, this.logger.subLogger(`domain=${domain}`), successMessages, errorMessages); - this.sessions.push(session); - } - return session; - } - authToken() { - const createTokenReq = { - domain: "global", - type: "create-token" - }; - if (!this.globalDomain) { - return Promise.reject(new Error("no global domain session")); - } - return this.globalDomain.send(createTokenReq) - .then((res) => { - return res.token; - }); - } - reconnect() { - return this.transport.reconnect(); - } - setLoggedIn(value) { - this._isLoggedIn = value; - if (this._isLoggedIn) { - this.initialLogin = false; - this.registry.execute("onLoggedIn"); - } - } - distributeMessage(message, type) { - const handlers = this.messageHandlers[type.toLowerCase()]; - if (handlers !== undefined) { - Object.keys(handlers).forEach((handlerId) => { - const handler = handlers[handlerId]; - if (handler !== undefined) { - try { - handler(message); - } - catch (error) { - try { - this.logger.error(`Message handler failed with ${error.stack}`, error); - } - catch (loggerError) { - console.log("Message handler failed", error); - } - } - } - }); - } - } - handleConnectionChanged(connected) { - if (this._connected === connected) { - this.logger.trace("connection state unchanged, skipping"); - return; - } - this.logger.info(`connection state changed to ${connected ? "connected" : "disconnected"}`); - this._connected = connected; - if (connected) { - if (this.settings?.replaySpecs?.length) { - this.replayer = new MessageReplayerImpl(this.settings.replaySpecs); - this.replayer.init(this); - } - this.registry.execute("connected"); - } - else { - this.setLoggedIn(false); - if (this.shouldTryLogin) { - this.attemptLoginWithRetry(); - } - this.registry.execute("disconnected"); - } - } - async attemptLoginWithRetry() { - if (!this.loginConfig) { - throw new Error("no login info"); - } - if (this.loginRetryInProgress) { - this.logger.debug("login attempt already in progress, ignoring request..."); - return; - } - if (this._isLoggedIn) { - this.logger.debug("already logged in, ignoring request..."); - return; - } - if (this.initialLogin) { - this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`); - if (this.initialLoginAttempts <= 0) { - this.logger.info("maximum initial login attempts reached, will not try to login again"); - return; - } - this.initialLoginAttempts--; - } - try { - this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`); - this.loginRetryInProgress = true; - await this.login(this.loginConfig, true); - } - catch (e) { - this.logger.error(`error trying to login: ${e?.message}`, e); - setTimeout(this.attemptLoginWithRetry.bind(this), this.settings.reconnectInterval ?? 1000); - } - finally { - this.loginRetryInProgress = false; - } - } - handleTransportMessage(msg) { - let msgObj; - if (typeof msg === "string") { - msgObj = this.processStringMessage(msg); - } - else { - msgObj = this.processObjectMessage(msg); - } - if (this.isTrace) { - this.logger.trace(`<< ${JSON.stringify(msgObj)}`); - } - this.distributeMessage(msgObj.msg, msgObj.msgType); - } - verifyConnection() { - return PromisePlus((resolve) => { - let unsub; - const ready = waitForInvocations(2, () => { - if (unsub) { - unsub(); - } - resolve(); - }); - unsub = this.onLibReAnnounced((lib) => { - if (lib.name === "interop") { - return ready(); - } - if (lib.name === "contexts") { - return ready(); - } - }); - }, 10000, "Transport switch timed out waiting for all libraries to be re-announced"); - } - getNewSecondaryTransport(settings) { - if (!settings.transportConfig?.url) { - throw new Error("Missing secondary transport URL."); - } - return new WS(Object.assign({}, this.settings, { ws: settings.transportConfig.url, reconnectAttempts: 1 }), this.logger.subLogger("ws-secondary")); - } - getNewSecondaryAuth(settings) { - if (!settings.transportConfig?.auth) { - throw new Error("Missing secondary transport auth information."); - } - return settings.transportConfig.auth; - } - transportSwap() { - this._swapTransport = false; - if (!this._targetTransport || !this._targetAuth) { - this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`); - return; - } - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport = this._targetTransport; - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - return this._targetAuth; - } - prepareDefaultSwap() { - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport.close().catch((error) => this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(error)}`)); - this._targetTransport = this._defaultTransport; - this._targetAuth = this._defaultAuth; - this._swapTransport = true; - } - processStringMessage(message) { - const msg = JSON.parse(message, (key, value) => { - if (typeof value !== "string") { - return value; - } - if (value.length < this.dateMinLen) { - return value; - } - if (!value.startsWith(this.datePrefixFirstChar)) { - return value; - } - if (value.substring(0, this.datePrefixLen) !== this.datePrefix) { - return value; - } - try { - const milliseconds = parseInt(value.substring(this.datePrefixLen, value.length), 10); - if (isNaN(milliseconds)) { - return value; - } - return new Date(milliseconds); - } - catch (ex) { - return value; - } - }); - return { - msg, - msgType: msg.type, - }; - } - createStringMessage(message) { - const oldToJson = Date.prototype.toJSON; - try { - const datePrefix = this.datePrefix; - Date.prototype.toJSON = function () { - return datePrefix + this.getTime(); - }; - const result = JSON.stringify(message); - return result; - } - finally { - Date.prototype.toJSON = oldToJson; - } - } - processObjectMessage(message) { - if (!message.type) { - throw new Error("Object should have type property"); - } - return { - msg: message, - msgType: message.type, - }; - } - createObjectMessage(message) { - return message; - } - async loginCore(config, reconnect) { - this.loginConfig = config; - if (!this.loginConfig) { - this.loginConfig = { username: "", password: "" }; - } - this.shouldTryLogin = true; - const authentication = await this.setupAuthConfig(config, reconnect); - const helloMsg = { - type: "hello", - identity: this.settings.identity, - authentication - }; - if (config.sessionId) { - helloMsg.request_id = config.sessionId; - } - if (!this.globalDomain) { - this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [ - "welcome", - "token", - "authentication-request" - ]); - } - const sendOptions = { skipPeerId: true }; - if (this.initialLogin) { - sendOptions.retryInterval = this.settings.reconnectInterval; - sendOptions.maxRetries = this.settings.reconnectAttempts; - } - try { - const welcomeMsg = await this.tryAuthenticate(this.globalDomain, helloMsg, sendOptions, config); - this.logger.info("login successful with peerId " + welcomeMsg.peer_id); - this.peerId = welcomeMsg.peer_id; - this.resolvedIdentity = welcomeMsg.resolved_identity; - this.availableDomains = welcomeMsg.available_domains; - if (welcomeMsg.options) { - this.token = welcomeMsg.options.access_token; - this.info = welcomeMsg.options.info; - } - this.setLoggedIn(true); - return welcomeMsg.resolved_identity; - } - catch (err) { - this.logger.error("error sending hello message - " + (err.message || err.msg || err.reason || err), err); - throw err; - } - finally { - if (config?.flowCallback && config.sessionId) { - config.flowCallback(config.sessionId, null); - } - } - } - async tryAuthenticate(globalDomain, helloMsg, sendOptions, config) { - let welcomeMsg; - while (true) { - const msg = await globalDomain.send(helloMsg, undefined, sendOptions); - if (msg.type === "authentication-request") { - const token = Buffer.from(msg.authentication.token, "base64"); - if (config.flowCallback && config.sessionId) { - helloMsg.authentication.token = - (await config.flowCallback(config.sessionId, token)) - .data - .toString("base64"); - } - helloMsg.request_id = config.sessionId; - } - else if (msg.type === "welcome") { - welcomeMsg = msg; - break; - } - else if (msg.type === "error") { - throw new Error("Authentication failed: " + msg.reason); - } - else { - throw new Error("Unexpected message type during authentication: " + msg.type); - } - } - return welcomeMsg; - } - async setupAuthConfig(config, reconnect) { - const authentication = {}; - this.gatewayToken = config.gatewayToken; - if (config.gatewayToken) { - if (reconnect) { - try { - config.gatewayToken = await this.getNewGWToken(); - } - catch (e) { - this.logger.warn(`failed to get GW token when reconnecting ${e?.message || e}`); - } - } - authentication.method = "gateway-token"; - authentication.token = config.gatewayToken; - this.gatewayToken = config.gatewayToken; - } - else if (config.flowName === "sspi") { - authentication.provider = "win"; - authentication.method = "access-token"; - if (config.flowCallback && config.sessionId) { - authentication.token = - (await config.flowCallback(config.sessionId, null)) - .data - .toString("base64"); - } - else { - throw new Error("Invalid SSPI config"); - } - } - else if (config.token) { - authentication.method = "access-token"; - authentication.token = config.token; - } - else if (config.username) { - authentication.method = "secret"; - authentication.login = config.username; - authentication.secret = config.password; - } - else if (config.provider) { - authentication.provider = config.provider; - authentication.providerContext = config.providerContext; - } - else { - throw new Error("invalid auth message" + JSON.stringify(config)); - } - return authentication; - } - async logoutCore() { - this.logger.debug("core logging out..."); - this.shouldTryLogin = false; - if (this.pingTimer) { - clearTimeout(this.pingTimer); - } - const promises = this.sessions.map((session) => { - return session.leave(); - }); - await Promise.all(promises); - } - getNewGWToken() { - if (typeof window !== "undefined") { - const glue42gd = window.glue42gd; - if (glue42gd) { - return glue42gd.getGWToken(); - } - } - return Promise.reject(new Error("not running in GD")); - } - ping() { - if (!this.shouldTryLogin) { - return; - } - if (this._isLoggedIn) { - this.send({ type: "ping" }); - } - this.pingTimer = setTimeout(() => { - this.ping(); - }, 30 * 1000); - } - } - - const order = ["trace", "debug", "info", "warn", "error", "off"]; - class Logger { - name; - parent; - static Interop; - static InteropMethodName = "T42.AppLogger.Log"; - static Instance; - path; - subLoggers = []; - _consoleLevel; - _publishLevel; - loggerFullName; - includeTimeAndLevel; - logFn = console; - customLogFn = false; - constructor(name, parent, logFn) { - this.name = name; - this.parent = parent; - this.name = name; - if (parent) { - this.path = `${parent.path}.${name}`; - } - else { - this.path = name; - } - this.loggerFullName = `[${this.path}]`; - this.includeTimeAndLevel = !logFn; - if (logFn) { - this.logFn = logFn; - this.customLogFn = true; - } - } - subLogger(name) { - const existingSub = this.subLoggers.filter((subLogger) => { - return subLogger.name === name; - })[0]; - if (existingSub !== undefined) { - return existingSub; - } - Object.keys(this).forEach((key) => { - if (key === name) { - throw new Error("This sub logger name is not allowed."); - } - }); - const sub = new Logger(name, this, this.customLogFn ? this.logFn : undefined); - this.subLoggers.push(sub); - return sub; - } - publishLevel(level) { - if (level) { - this._publishLevel = level; - } - return this._publishLevel || this.parent?.publishLevel(); - } - consoleLevel(level) { - if (level) { - this._consoleLevel = level; - } - return this._consoleLevel || this.parent?.consoleLevel(); - } - log(message, level, error) { - this.publishMessage(level || "info", message, error); - } - trace(message) { - this.log(message, "trace"); - } - debug(message) { - this.log(message, "debug"); - } - info(message) { - this.log(message, "info"); - } - warn(message) { - this.log(message, "warn"); - } - error(message, err) { - this.log(message, "error", err); - } - canPublish(level, compareWith) { - const levelIdx = order.indexOf(level); - const restrictionIdx = order.indexOf(compareWith || this.consoleLevel() || "trace"); - return levelIdx >= restrictionIdx; - } - publishMessage(level, message, error) { - const loggerName = this.loggerFullName; - if (level === "error" && !error) { - const e = new Error(); - if (e.stack) { - message = - message + - "\n" + - e.stack - .split("\n") - .slice(4) - .join("\n"); - } - } - if (this.canPublish(level, this.publishLevel())) { - const interop = Logger.Interop; - if (interop) { - try { - if (interop.methods({ name: Logger.InteropMethodName }).length > 0) { - const args = { - msg: message, - logger: loggerName, - level - }; - if (error && error instanceof Error) { - args.error = { - message: error.message, - stack: error.stack ?? "" - }; - } - interop.invoke(Logger.InteropMethodName, args) - .catch((e) => { - this.logFn.error(`Unable to send log message to the platform: ${e.message}`, e); - }); - } - } - catch { - } - } - } - if (this.canPublish(level)) { - let prefix = ""; - if (this.includeTimeAndLevel) { - const date = new Date(); - const time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`; - prefix = `[${time}] [${level}] `; - } - const toPrint = `${prefix}${loggerName}: ${message}`; - switch (level) { - case "trace": - this.logFn.debug(toPrint); - break; - case "debug": - if (this.logFn.debug) { - this.logFn.debug(toPrint); - } - else { - this.logFn.log(toPrint); - } - break; - case "info": - this.logFn.info(toPrint); - break; - case "warn": - this.logFn.warn(toPrint); - break; - case "error": - if (error) { - this.logFn.error(toPrint, error); - } - else { - this.logFn.error(toPrint); - } - break; - } - } - } - } - - const GW_MESSAGE_CREATE_CONTEXT = "create-context"; - const GW_MESSAGE_ACTIVITY_CREATED = "created"; - const GW_MESSAGE_ACTIVITY_DESTROYED = "destroyed"; - const GW_MESSAGE_CONTEXT_CREATED = "context-created"; - const GW_MESSAGE_CONTEXT_ADDED = "context-added"; - const GW_MESSAGE_SUBSCRIBE_CONTEXT = "subscribe-context"; - const GW_MESSAGE_SUBSCRIBED_CONTEXT = "subscribed-context"; - const GW_MESSAGE_UNSUBSCRIBE_CONTEXT = "unsubscribe-context"; - const GW_MESSAGE_DESTROY_CONTEXT = "destroy-context"; - const GW_MESSAGE_CONTEXT_DESTROYED = "context-destroyed"; - const GW_MESSAGE_UPDATE_CONTEXT = "update-context"; - const GW_MESSAGE_CONTEXT_UPDATED = "context-updated"; - const GW_MESSAGE_JOINED_ACTIVITY = "joined"; - - const ContextMessageReplaySpec = { - get name() { - return "context"; - }, - get types() { - return [ - GW_MESSAGE_CREATE_CONTEXT, - GW_MESSAGE_ACTIVITY_CREATED, - GW_MESSAGE_ACTIVITY_DESTROYED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_SUBSCRIBE_CONTEXT, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - GW_MESSAGE_DESTROY_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_UPDATE_CONTEXT, - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_JOINED_ACTIVITY - ]; - } - }; - - var version = "6.8.1"; - - function prepareConfig (configuration, ext, glue42gd) { - let nodeStartingContext; - if (Utils.isNode()) { - const startingContextString = process.env._GD_STARTING_CONTEXT_; - if (startingContextString) { - try { - nodeStartingContext = JSON.parse(startingContextString); - } - catch { - } - } - } - function getConnection() { - const gwConfig = configuration.gateway; - const protocolVersion = gwConfig?.protocolVersion ?? 3; - const reconnectInterval = gwConfig?.reconnectInterval; - const reconnectAttempts = gwConfig?.reconnectAttempts; - const defaultWs = "ws://localhost:8385"; - let ws = gwConfig?.ws; - const sharedWorker = gwConfig?.sharedWorker; - const inproc = gwConfig?.inproc; - const webPlatform = gwConfig?.webPlatform ?? undefined; - if (glue42gd) { - ws = glue42gd.gwURL; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) { - ws = nodeStartingContext.gwURL; - } - if (!ws && !sharedWorker && !inproc) { - ws = defaultWs; - } - let instanceId; - let windowId; - let pid; - let environment; - let region; - const appName = getApplication(); - let uniqueAppName = appName; - if (typeof glue42gd !== "undefined") { - windowId = glue42gd.windowId; - pid = glue42gd.pid; - if (glue42gd.env) { - environment = glue42gd.env.env; - region = glue42gd.env.region; - } - uniqueAppName = glue42gd.application ?? "glue-app"; - instanceId = glue42gd.appInstanceId; - } - else if (Utils.isNode()) { - pid = process.pid; - if (nodeStartingContext) { - environment = nodeStartingContext.env; - region = nodeStartingContext.region; - instanceId = nodeStartingContext.instanceId; - } - } - else if (typeof window?.glue42electron !== "undefined") { - windowId = window?.glue42electron.instanceId; - pid = window?.glue42electron.pid; - environment = window?.glue42electron.env; - region = window?.glue42electron.region; - uniqueAppName = window?.glue42electron.application ?? "glue-app"; - instanceId = window?.glue42electron.instanceId; - } - else ; - const replaySpecs = configuration.gateway?.replaySpecs ?? []; - replaySpecs.push(ContextMessageReplaySpec); - let identity = { - application: uniqueAppName, - applicationName: appName, - windowId, - instance: instanceId, - process: pid, - region, - environment, - api: ext.version || version - }; - if (configuration.identity) { - identity = Object.assign(identity, configuration.identity); - } - return { - identity, - reconnectInterval, - ws, - sharedWorker, - webPlatform, - inproc, - protocolVersion, - reconnectAttempts, - replaySpecs, - }; - } - function getContexts() { - const defaultConfig = { - reAnnounceKnownContexts: true, - subscribeOnUpdate: true, - subscribeOnGet: true, - onlyReAnnounceSubscribedContexts: true - }; - if (typeof configuration.contexts === "undefined") { - return defaultConfig; - } - if (typeof configuration.contexts === "boolean" && configuration.contexts) { - return defaultConfig; - } - if (typeof configuration.contexts === "object") { - return { ...defaultConfig, ...configuration.contexts }; - } - return false; - } - function getApplication() { - if (configuration.application) { - return configuration.application; - } - if (glue42gd) { - return glue42gd.applicationName; - } - if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") { - return window.glue42electron.application; - } - const uid = nanoid(10); - if (Utils.isNode()) { - if (nodeStartingContext) { - return nodeStartingContext.applicationConfig.name; - } - return "NodeJS" + uid; - } - if (typeof window !== "undefined" && typeof document !== "undefined") { - return document.title + ` (${uid})`; - } - return uid; - } - function getAuth() { - if (typeof configuration.auth === "string") { - return { - token: configuration.auth - }; - } - if (configuration.auth) { - return configuration.auth; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) { - return { - gatewayToken: nodeStartingContext.gwToken - }; - } - if (configuration.gateway?.webPlatform) { - return { - username: "glue42", - password: "" - }; - } - } - function getLogger() { - let config = configuration.logger; - const defaultLevel = "warn"; - if (!config) { - config = defaultLevel; - } - let gdConsoleLevel; - if (glue42gd) { - gdConsoleLevel = glue42gd.consoleLogLevel; - } - if (typeof config === "string") { - return { console: gdConsoleLevel ?? config, publish: defaultLevel }; - } - return { - console: gdConsoleLevel ?? config.console ?? defaultLevel, - publish: config.publish ?? defaultLevel - }; - } - const connection = getConnection(); - let application = getApplication(); - if (typeof window !== "undefined") { - const windowAsAny = window; - const containerApplication = windowAsAny.htmlContainer ? - `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` : - windowAsAny?.glue42gd?.application; - if (containerApplication) { - application = containerApplication; - } - } - return { - bus: configuration.bus ?? false, - application, - auth: getAuth(), - logger: getLogger(), - connection, - metrics: configuration.metrics ?? true, - contexts: getContexts(), - version: ext.version || version, - libs: ext.libs ?? [], - customLogger: configuration.customLogger - }; - } - - class GW3ContextData { - name; - contextId; - context; - isAnnounced; - createdByUs; - joinedActivity; - updateCallbacks = {}; - activityId; - sentExplicitSubscription; - get hasReceivedSnapshot() { - return this.snapshotPromiseWrapper.resolved; - } - set hasReceivedSnapshot(has) { - if (has) { - this.snapshotPromiseWrapper.resolve(); - } - else { - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - } - get snapshotPromise() { - return this.snapshotPromiseWrapper.promise; - } - snapshotPromiseWrapper; - constructor(contextId, name, isAnnounced, activityId) { - this.contextId = contextId; - this.name = name; - this.isAnnounced = isAnnounced; - this.activityId = activityId; - this.context = {}; - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - hasCallbacks() { - return Object.keys(this.updateCallbacks).length > 0; - } - getState() { - if (this.isAnnounced && this.hasCallbacks()) { - return 3; - } - if (this.isAnnounced) { - return 2; - } - if (this.hasCallbacks()) { - return 1; - } - return 0; - } - } - - var lodash_clonedeep = {exports: {}}; - - /** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - lodash_clonedeep.exports; - - (function (module, exports) { - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** - * Adds the key-value `pair` to `map`. - * - * @private - * @param {Object} map The map to modify. - * @param {Array} pair The key-value pair to add. - * @returns {Object} Returns `map`. - */ - function addMapEntry(map, pair) { - // Don't return `map.set` because it's not chainable in IE 11. - map.set(pair[0], pair[1]); - return map; - } - - /** - * Adds `value` to `set`. - * - * @private - * @param {Object} set The set to modify. - * @param {*} value The value to add. - * @returns {Object} Returns `set`. - */ - function addSetEntry(set, value) { - // Don't return `set.add` because it's not chainable in IE 11. - set.add(value); - return set; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array ? array.length : 0; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array ? array.length : 0; - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ - function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var objectToString = objectProto.toString; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined, - Symbol = root.Symbol, - Uint8Array = root.Uint8Array, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeKeys = overArg(Object.keys, Object); - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'), - Map = getNative(root, 'Map'), - Promise = getNative(root, 'Promise'), - Set = getNative(root, 'Set'), - WeakMap = getNative(root, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - this.__data__ = new ListCache(entries); - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - return this.__data__['delete'](key); - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var cache = this.__data__; - if (cache instanceof ListCache) { - var pairs = cache.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - return this; - } - cache = this.__data__ = new MapCache(pairs); - } - cache.set(key, value); - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - - var length = result.length, - skipIndexes = !!length; - - for (var key in value) { - if ((hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {boolean} [isFull] Specify a clone including symbols. - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, isFull, customizer, key, object, stack) { - var result; - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - if (isHostObject(value)) { - return object ? value : {}; - } - result = initCloneObject(isFunc ? {} : value); - if (!isDeep) { - return copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, baseClone, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (!isArr) { - var props = isFull ? getAllKeys(value) : keys(value); - } - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(proto) { - return isObject(proto) ? objectCreate(proto) : {}; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - return objectToString.call(value); - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var result = new buffer.constructor(buffer.length); - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `map`. - * - * @private - * @param {Object} map The map to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned map. - */ - function cloneMap(map, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); - return arrayReduce(array, addMapEntry, new map.constructor); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of `set`. - * - * @private - * @param {Object} set The set to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned set. - */ - function cloneSet(set, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); - return arrayReduce(array, addSetEntry, new set.constructor); - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = undefined; - - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; - } - - /** - * Copies own symbol properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * Creates an array of the own enumerable symbol properties of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11, - // for data views in Edge < 14, and promises in Node.js. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = objectToString.call(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : undefined; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, cloneFunc, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return cloneMap(object, isDeep, cloneFunc); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return cloneSet(object, isDeep, cloneFunc); - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, true, true); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return !!value && typeof value == 'object'; - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - module.exports = cloneDeep; - } (lodash_clonedeep, lodash_clonedeep.exports)); - - var lodash_clonedeepExports = lodash_clonedeep.exports; - var cloneDeep = /*@__PURE__*/getDefaultExportFromCjs(lodash_clonedeepExports); - - function applyContextDelta(context, delta, logger) { - try { - if (logger?.canPublish("trace")) { - logger?.trace(`applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`); - } - if (!delta) { - return context; - } - if (delta.reset) { - context = { ...delta.reset }; - return context; - } - context = deepClone(context, undefined); - if (delta.commands) { - for (const command of delta.commands) { - if (command.type === "remove") { - deletePath(context, command.path); - } - else if (command.type === "set") { - setValueToPath(context, command.value, command.path); - } - } - return context; - } - const added = delta.added; - const updated = delta.updated; - const removed = delta.removed; - if (added) { - Object.keys(added).forEach((key) => { - context[key] = added[key]; - }); - } - if (updated) { - Object.keys(updated).forEach((key) => { - mergeObjectsProperties(key, context, updated); - }); - } - if (removed) { - removed.forEach((key) => { - delete context[key]; - }); - } - return context; - } - catch (e) { - logger?.error(`error applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`, e); - return context; - } - } - function deepClone(obj, hash) { - return cloneDeep(obj); - } - const mergeObjectsProperties = (key, what, withWhat) => { - const right = withWhat[key]; - if (right === undefined) { - return what; - } - const left = what[key]; - if (!left || !right) { - what[key] = right; - return what; - } - if (typeof left === "string" || - typeof left === "number" || - typeof left === "boolean" || - typeof right === "string" || - typeof right === "number" || - typeof right === "boolean" || - Array.isArray(left) || - Array.isArray(right)) { - what[key] = right; - return what; - } - what[key] = Object.assign({}, left, right); - return what; - }; - function deepEqual(x, y) { - if (x === y) { - return true; - } - if (!(x instanceof Object) || !(y instanceof Object)) { - return false; - } - if (x.constructor !== y.constructor) { - return false; - } - for (const p in x) { - if (!x.hasOwnProperty(p)) { - continue; - } - if (!y.hasOwnProperty(p)) { - return false; - } - if (x[p] === y[p]) { - continue; - } - if (typeof (x[p]) !== "object") { - return false; - } - if (!deepEqual(x[p], y[p])) { - return false; - } - } - for (const p in y) { - if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) { - return false; - } - } - return true; - } - function setValueToPath(obj, value, path) { - const pathArr = path.split("."); - const forbiddenKeys = ["__proto__", "constructor", "prototype"]; - let i; - for (i = 0; i < pathArr.length - 1; i++) { - const key = pathArr[i]; - if (forbiddenKeys.includes(key)) { - throw new Error(`The provided path ${path} is invalid. It cannot contain segment/key that is equal to one of the following values: ${forbiddenKeys}.`); - } - if (!obj[key]) { - obj[key] = {}; - } - if (typeof obj[key] !== "object") { - obj[key] = {}; - } - obj = obj[key]; - } - obj[pathArr[i]] = value; - } - function isSubset(superObj, subObj) { - return Object.keys(subObj).every((ele) => { - if (typeof subObj[ele] === "object") { - return isSubset(superObj?.[ele] || {}, subObj[ele] || {}); - } - return subObj[ele] === superObj?.[ele]; - }); - } - function deletePath(obj, path) { - const pathArr = path.split("."); - let i; - for (i = 0; i < pathArr.length - 1; i++) { - if (!obj[pathArr[i]]) { - return; - } - obj = obj[pathArr[i]]; - } - delete obj[pathArr[i]]; - } - - class GW3Bridge { - ERROR_URI_FAILURE = "global.errors.failure"; - ERROR_URI_INVALID_CONTEXT = "global.errors.invalid_context"; - _logger; - _connection; - _trackAllContexts; - _reAnnounceKnownContexts; - _subscribeOnUpdate; - _subscribeOnGet; - _onlyReAnnounceSubscribedContexts; - _gw3Session; - _contextNameToData = {}; - _gw3Subscriptions = []; - _nextCallbackSubscriptionNumber = 0; - _creationPromises = {}; - _contextNameToId = {}; - _contextIdToName = {}; - _protocolVersion = undefined; - _contextsTempCache = {}; - _contextsSubscriptionsCache = []; - _systemContextsSubKey; - get protocolVersion() { - if (!this._protocolVersion) { - const contextsDomainInfo = this._connection.availableDomains.find((d) => d.uri === "context"); - this._protocolVersion = contextsDomainInfo?.version ?? 1; - } - return this._protocolVersion; - } - get setPathSupported() { - return this.protocolVersion >= 2; - } - constructor(config) { - this._connection = config.connection; - this._logger = config.logger; - this._trackAllContexts = config.trackAllContexts; - this._reAnnounceKnownContexts = config.reAnnounceKnownContexts; - this._subscribeOnUpdate = config.subscribeOnUpdate ?? true; - this._subscribeOnGet = config.subscribeOnGet ?? true; - this._onlyReAnnounceSubscribedContexts = config.onlyReAnnounceSubscribedContexts ?? true; - this._gw3Session = this._connection.domain("global", [ - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_CONTEXT_UPDATED, - ]); - this._gw3Session.disconnected(this.resetState.bind(this)); - this._gw3Session.onJoined((wasReconnect) => { - if (!wasReconnect) { - return; - } - if (!this._reAnnounceKnownContexts) { - this._contextsTempCache = {}; - return this._connection.setLibReAnnounced({ name: "contexts" }); - } - this.reInitiateState() - .then(() => this._connection.setLibReAnnounced({ name: "contexts" })) - .catch((err) => { - this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(err)}`); - }); - }); - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - } - dispose() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - this._gw3Subscriptions.length = 0; - for (const contextName in this._contextNameToData) { - if (this._contextNameToId.hasOwnProperty(contextName)) { - delete this._contextNameToData[contextName]; - } - } - } - createContext(name, data) { - if (name in this._creationPromises) { - return this._creationPromises[name]; - } - this._creationPromises[name] = - this._gw3Session - .send({ - type: GW_MESSAGE_CREATE_CONTEXT, - domain: "global", - name, - data, - lifetime: "retained", - }) - .then((createContextMsg) => { - this._contextNameToId[name] = createContextMsg.context_id; - this._contextIdToName[createContextMsg.context_id] = name; - const contextData = this._contextNameToData[name] || new GW3ContextData(createContextMsg.context_id, name, true, undefined); - contextData.isAnnounced = true; - contextData.name = name; - contextData.contextId = createContextMsg.context_id; - contextData.context = createContextMsg.data || deepClone(data); - contextData.hasReceivedSnapshot = true; - this._contextNameToData[name] = contextData; - delete this._creationPromises[name]; - contextData.sentExplicitSubscription = true; - contextData.createdByUs = true; - this.subscribe(name, () => { }); - return createContextMsg.context_id; - }); - return this._creationPromises[name]; - } - all() { - return Object.keys(this._contextNameToData) - .filter((name) => this._contextNameToData[name].isAnnounced); - } - async update(name, delta) { - if (delta) { - delta = deepClone(delta); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - await this.createContext(name, delta); - return; - } - const currentContext = await this.get(contextData.name); - const calculatedDelta = this.setPathSupported ? - this.calculateContextDeltaV2(currentContext, delta) : - this.calculateContextDeltaV1(currentContext, delta); - if (!Object.keys(calculatedDelta.added).length - && !Object.keys(calculatedDelta.updated).length - && !calculatedDelta.removed.length - && !calculatedDelta.commands?.length) { - return Promise.resolve(); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: calculatedDelta, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, calculatedDelta, { - updaterId: gwResponse.peer_id - }); - } - } - async set(name, data) { - if (data) { - data = deepClone(data); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - return this.createContext(name, data); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { reset: data }, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - this.handleUpdated(contextData, { - reset: data, - added: {}, - removed: [], - updated: {} - }, { - updaterId: gwResponse.peer_id - }); - } - } - setPath(name, path, value) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later"); - } - return this.setPaths(name, [{ path, value }]); - } - async setPaths(name, pathValues) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later"); - } - if (pathValues) { - pathValues = deepClone(pathValues); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - const obj = {}; - for (const pathValue of pathValues) { - setValueToPath(obj, pathValue.value, pathValue.path); - } - return this.createContext(name, obj); - } - const commands = []; - for (const pathValue of pathValues) { - if (pathValue.value === null) { - commands.push({ type: "remove", path: pathValue.path }); - } - else { - commands.push({ type: "set", path: pathValue.path, value: pathValue.value }); - } - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { commands } - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, { - added: {}, - removed: [], - updated: {}, - commands - }, { - updaterId: gwResponse.peer_id - }); - } - } - async get(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - if (!contextData && this._subscribeOnGet) { - this.subscribe(name, () => { }); - } - return Promise.resolve({}); - } - if (contextData && !contextData.sentExplicitSubscription) { - return new Promise((resolve, reject) => { - this.subscribe(name, (data, _d, _r, un) => { - if (!this._subscribeOnGet) { - this.unsubscribe(un); - } - resolve(data); - }).catch((e) => { - if (this.isInvalidContextError(e)) { - resolve({}); - return; - } - reject(e); - }); - }); - } - await contextData.snapshotPromise; - const context = contextData?.context ?? {}; - return Promise.resolve(deepClone(context)); - } - isInvalidContextError(e) { - return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT - || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id")); - } - async subscribe(name, callback, subscriptionKey) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const thisCallbackSubscriptionNumber = typeof subscriptionKey === "undefined" ? this._nextCallbackSubscriptionNumber : subscriptionKey; - if (typeof subscriptionKey === "undefined") { - this._nextCallbackSubscriptionNumber += 1; - this._contextsSubscriptionsCache.push({ contextName: name, subKey: thisCallbackSubscriptionNumber, callback }); - } - let contextData = this._contextNameToData[name]; - if (!contextData || - !contextData.isAnnounced) { - contextData = contextData || new GW3ContextData(undefined, name, false, undefined); - this._contextNameToData[name] = contextData; - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - return Promise.resolve(thisCallbackSubscriptionNumber); - } - const hadCallbacks = contextData.hasCallbacks(); - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - if (!hadCallbacks) { - if (!contextData.joinedActivity && !contextData.createdByUs) { - if (contextData.context && contextData.sentExplicitSubscription) { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - return this.sendSubscribe(contextData) - .then(() => thisCallbackSubscriptionNumber, () => { - this.unsubscribe(thisCallbackSubscriptionNumber, true); - return thisCallbackSubscriptionNumber; - }); - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - unsubscribe(subscriptionKey, keepInSubscriptionsCache) { - if (!keepInSubscriptionsCache) { - this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter(x => x.subKey !== subscriptionKey); - } - for (const name of Object.keys(this._contextNameToData)) { - const contextData = this._contextNameToData[name]; - if (!contextData) { - continue; - } - const hadCallbacks = contextData.hasCallbacks(); - delete contextData.updateCallbacks[subscriptionKey]; - if (contextData.isAnnounced && - hadCallbacks && - !contextData.hasCallbacks() && - contextData.sentExplicitSubscription) { - contextData.hasReceivedSnapshot = false; - contextData.context = {}; - this.sendUnsubscribe(contextData).catch(() => { }); - } - if (!contextData.isAnnounced && - !contextData.hasCallbacks()) { - delete this._contextNameToData[name]; - delete this._contextNameToId[name]; - if (contextData.contextId) { - delete this._contextIdToName[contextData.contextId]; - } - } - } - } - async destroy(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - const contextId = contextData?.contextId; - if (!contextData || !contextId) { - return Promise.reject(`context with ${name} does not exist`); - } - return this._gw3Session - .send({ - type: GW_MESSAGE_DESTROY_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }).then(() => undefined); - } - handleUpdated(contextData, delta, extraData) { - const oldContext = contextData.context; - contextData.context = applyContextDelta(contextData.context, delta, this._logger); - if (this._contextNameToData[contextData.name] === contextData && - !deepEqual(oldContext, contextData.context)) { - this.invokeUpdateCallbacks(contextData, delta, extraData); - } - } - subscribeToContextCreatedMessages() { - const createdMessageTypes = [ - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_ACTIVITY_CREATED, - ]; - for (const createdMessageType of createdMessageTypes) { - const sub = this._connection.on(createdMessageType, this.handleContextCreatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextCreatedMessage(contextCreatedMsg) { - const createdMessageType = contextCreatedMsg.type; - if (createdMessageType === GW_MESSAGE_ACTIVITY_CREATED) { - this._contextNameToId[contextCreatedMsg.activity_id] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.activity_id; - } - else if (createdMessageType === GW_MESSAGE_CONTEXT_ADDED) { - this._contextNameToId[contextCreatedMsg.name] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.name; - } - else ; - const name = this._contextIdToName[contextCreatedMsg.context_id]; - if (!name) { - throw new Error("Received created event for context with unknown name: " + contextCreatedMsg.context_id); - } - if (!this._contextNameToId[name]) { - throw new Error("Received created event for context with unknown id: " + contextCreatedMsg.context_id); - } - let contextData = this._contextNameToData[name]; - if (contextData) { - if (contextData.isAnnounced) { - return; - } - else { - if (!contextData.hasCallbacks()) { - throw new Error("Assertion failure: contextData.hasCallbacks()"); - } - contextData.isAnnounced = true; - contextData.contextId = contextCreatedMsg.context_id; - contextData.activityId = contextCreatedMsg.activity_id; - if (!contextData.sentExplicitSubscription) { - this.sendSubscribe(contextData).catch(() => { }); - } - } - } - else { - this._contextNameToData[name] = contextData = - new GW3ContextData(contextCreatedMsg.context_id, name, true, contextCreatedMsg.activity_id); - if (this._trackAllContexts) { - this.subscribe(name, () => { }).then((subKey) => this._systemContextsSubKey = subKey); - } - } - } - subscribeToContextUpdatedMessages() { - const updatedMessageTypes = [ - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_JOINED_ACTIVITY, - ]; - for (const updatedMessageType of updatedMessageTypes) { - const sub = this._connection.on(updatedMessageType, this.handleContextUpdatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextUpdatedMessage(contextUpdatedMsg) { - const updatedMessageType = contextUpdatedMsg.type; - const contextId = contextUpdatedMsg.context_id; - let contextData = this._contextNameToData[this._contextIdToName[contextId]]; - const justSeen = !contextData || !contextData.isAnnounced; - if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - if (!contextData) { - contextData = - this._contextNameToData[contextUpdatedMsg.activity_id] || - new GW3ContextData(contextId, contextUpdatedMsg.activity_id, true, contextUpdatedMsg.activity_id); - } - this._contextNameToData[contextUpdatedMsg.activity_id] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.activity_id; - this._contextNameToId[contextUpdatedMsg.activity_id] = contextId; - contextData.contextId = contextId; - contextData.isAnnounced = true; - contextData.activityId = contextUpdatedMsg.activity_id; - contextData.joinedActivity = true; - } - else { - if (!contextData || !contextData.isAnnounced) { - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData = contextData || new GW3ContextData(contextId, contextUpdatedMsg.name, true, undefined); - contextData.sentExplicitSubscription = true; - this._contextNameToData[contextUpdatedMsg.name] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.name; - this._contextNameToId[contextUpdatedMsg.name] = contextId; - } - else { - this._logger.error(`Received 'update' for unknown context: ${contextId}`); - } - return; - } - } - const oldContext = contextData.context; - contextData.hasReceivedSnapshot = true; - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData.context = contextUpdatedMsg.data ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - contextData.context = contextUpdatedMsg.context_snapshot ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_CONTEXT_UPDATED) { - contextData.context = applyContextDelta(contextData.context, contextUpdatedMsg.delta, this._logger); - } - else { - throw new Error("Unrecognized context update message " + updatedMessageType); - } - if (justSeen || - !deepEqual(contextData.context, oldContext) || - updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta, { updaterId: contextUpdatedMsg.updater_id }); - } - } - invokeUpdateCallbacks(contextData, delta, extraData) { - delta = delta || { added: {}, updated: {}, reset: {}, removed: [] }; - if (delta.commands) { - delta.added = delta.updated = delta.reset = {}; - delta.removed = []; - for (const command of delta.commands) { - if (command.type === "remove") { - if (command.path.indexOf(".") === -1) { - delta.removed.push(command.path); - } - setValueToPath(delta.updated, null, command.path); - } - else if (command.type === "set") { - setValueToPath(delta.updated, command.value, command.path); - } - } - } - for (const updateCallbackIndex in contextData.updateCallbacks) { - if (contextData.updateCallbacks.hasOwnProperty(updateCallbackIndex)) { - try { - const updateCallback = contextData.updateCallbacks[updateCallbackIndex]; - updateCallback(deepClone(contextData.context), deepClone(Object.assign({}, delta.added || {}, delta.updated || {}, delta.reset || {})), delta.removed, parseInt(updateCallbackIndex, 10), extraData); - } - catch (err) { - this._logger.debug("callback error: " + JSON.stringify(err)); - } - } - } - } - subscribeToContextDestroyedMessages() { - const destroyedMessageTypes = [ - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_ACTIVITY_DESTROYED, - ]; - for (const destroyedMessageType of destroyedMessageTypes) { - const sub = this._connection.on(destroyedMessageType, this.handleContextDestroyedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextDestroyedMessage(destroyedMsg) { - const destroyedMessageType = destroyedMsg.type; - let contextId; - let name; - if (destroyedMessageType === GW_MESSAGE_ACTIVITY_DESTROYED) { - name = destroyedMsg.activity_id; - contextId = this._contextNameToId[name]; - if (!contextId) { - this._logger.error(`Received 'destroyed' for unknown activity: ${destroyedMsg.activity_id}`); - return; - } - } - else { - contextId = destroyedMsg.context_id; - name = this._contextIdToName[contextId]; - if (!name) { - this._logger.error(`Received 'destroyed' for unknown context: ${destroyedMsg.context_id}`); - return; - } - } - delete this._contextIdToName[contextId]; - delete this._contextNameToId[name]; - const contextData = this._contextNameToData[name]; - delete this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - this._logger.error(`Received 'destroyed' for unknown context: ${contextId}`); - return; - } - } - async sendSubscribe(contextData) { - contextData.sentExplicitSubscription = true; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_SUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = false; - throw error; - } - } - async sendUnsubscribe(contextData) { - const prev = contextData.sentExplicitSubscription; - contextData.sentExplicitSubscription = false; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = prev; - throw error; - } - } - calculateContextDeltaV1(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined }; - if (from) { - for (const x of Object.keys(from)) { - if (Object.keys(to).indexOf(x) !== -1 - && to[x] !== null - && !deepEqual(from[x], to[x])) { - delta.updated[x] = to[x]; - } - } - } - for (const x of Object.keys(to)) { - if (!from || (Object.keys(from).indexOf(x) === -1)) { - if (to[x] !== null) { - delta.added[x] = to[x]; - } - } - else if (to[x] === null) { - delta.removed.push(x); - } - } - return delta; - } - calculateContextDeltaV2(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined, commands: [] }; - for (const x of Object.keys(to)) { - if (to[x] !== null) { - const fromX = from ? from[x] : null; - if (!deepEqual(fromX, to[x])) { - delta.commands?.push({ type: "set", path: x, value: to[x] }); - } - } - else { - delta.commands?.push({ type: "remove", path: x }); - } - } - return delta; - } - resetState() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - if (this._systemContextsSubKey) { - this.unsubscribe(this._systemContextsSubKey, true); - delete this._systemContextsSubKey; - } - this._gw3Subscriptions = []; - this._contextNameToId = {}; - this._contextIdToName = {}; - delete this._protocolVersion; - this._contextsTempCache = Object.keys(this._contextNameToData).reduce((cacheSoFar, ctxName) => { - const contextData = this._contextNameToData[ctxName]; - const addToCache = !this._onlyReAnnounceSubscribedContexts || contextData.hasReceivedSnapshot; - if (addToCache) { - cacheSoFar[ctxName] = this._contextNameToData[ctxName].context; - } - return cacheSoFar; - }, {}); - this._contextNameToData = {}; - } - async reInitiateState() { - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - await Promise.all(this._contextsSubscriptionsCache.map((subscription) => this.subscribe(subscription.contextName, subscription.callback, subscription.subKey))); - await this.flushQueue(); - for (const ctxName in this._contextsTempCache) { - if (typeof this._contextsTempCache[ctxName] !== "object" || Object.keys(this._contextsTempCache[ctxName]).length === 0) { - continue; - } - const lastKnownData = this._contextsTempCache[ctxName]; - this._logger.info(`Re-announcing known context: ${ctxName}`); - await this.flushQueue(); - await this.update(ctxName, lastKnownData); - } - this._contextsTempCache = {}; - this._logger.info("Contexts are re-announced"); - } - flushQueue() { - return new Promise((resolve) => setTimeout(() => resolve(), 0)); - } - } - - class ContextsModule { - initTime; - initStartTime; - initEndTime; - _bridge; - constructor(config) { - this._bridge = new GW3Bridge(config); - } - all() { - return this._bridge.all(); - } - update(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.update(name, data); - } - set(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.set(name, data); - } - setPath(name, path, data) { - this.checkName(name); - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(data); - return this.set(name, data); - } - return this._bridge.setPath(name, path, data); - } - setPaths(name, paths) { - this.checkName(name); - if (!Array.isArray(paths)) { - throw new Error("Please provide the paths as an array of PathValues!"); - } - for (const { path, value } of paths) { - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(value); - } - } - return this._bridge.setPaths(name, paths); - } - subscribe(name, callback) { - this.checkName(name); - if (typeof callback !== "function") { - throw new Error("Please provide the callback as a function!"); - } - return this._bridge - .subscribe(name, (data, delta, removed, key, extraData) => callback(data, delta, removed, () => this._bridge.unsubscribe(key), extraData)) - .then((key) => () => { - this._bridge.unsubscribe(key); - }); - } - get(name) { - this.checkName(name); - return this._bridge.get(name); - } - ready() { - return Promise.resolve(this); - } - destroy(name) { - this.checkName(name); - return this._bridge.destroy(name); - } - get setPathSupported() { - return this._bridge.setPathSupported; - } - checkName(name) { - if (typeof name !== "string" || name === "") { - throw new Error("Please provide the name as a non-empty string!"); - } - } - checkPath(path) { - if (typeof path !== "string") { - throw new Error("Please provide the path as a dot delimited string!"); - } - } - checkData(data) { - if (typeof data !== "object") { - throw new Error("Please provide the data as an object!"); - } - } - } - - function promisify (promise, successCallback, errorCallback) { - if (typeof successCallback !== "function" && typeof errorCallback !== "function") { - return promise; - } - if (typeof successCallback !== "function") { - successCallback = () => { }; - } - else if (typeof errorCallback !== "function") { - errorCallback = () => { }; - } - return promise.then(successCallback, errorCallback); - } - - function rejectAfter(ms = 0, promise, error) { - let timeout; - const clearTimeoutIfThere = () => { - if (timeout) { - clearTimeout(timeout); - } - }; - promise - .then(() => { - clearTimeoutIfThere(); - }) - .catch(() => { - clearTimeoutIfThere(); - }); - return new Promise((resolve, reject) => { - timeout = setTimeout(() => reject(error), ms); - }); - } - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - Decoder.oneOf; - /** See `Decoder.union` */ - var union = Decoder.union; - /** See `Decoder.intersection` */ - Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - var fail$1 = Decoder.fail; - /** See `Decoder.lazy` */ - Decoder.lazy; - - const functionCheck = (input, propDescription) => { - const providedType = typeof input; - return providedType === "function" ? - anyJson() : - fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${typeof providedType}`); - }; - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number or 0"); - const methodDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - objectTypes: optional(array(nonEmptyStringDecoder)), - displayName: optional(nonEmptyStringDecoder), - accepts: optional(nonEmptyStringDecoder), - returns: optional(nonEmptyStringDecoder), - description: optional(nonEmptyStringDecoder), - version: optional(nonNegativeNumberDecoder), - supportsStreaming: optional(boolean()), - flags: optional(object()), - getServers: optional(anyJson().andThen((result) => functionCheck(result, "method definition getServers"))) - }); - const methodFilterDecoder = union(nonEmptyStringDecoder, methodDefinitionDecoder); - const instanceDecoder = object({ - application: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - pid: optional(nonNegativeNumberDecoder), - machine: optional(nonEmptyStringDecoder), - user: optional(nonEmptyStringDecoder), - environment: optional(nonEmptyStringDecoder), - region: optional(nonEmptyStringDecoder), - service: optional(nonEmptyStringDecoder), - instance: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - peerId: optional(nonEmptyStringDecoder), - isLocal: optional(boolean()), - api: optional(nonEmptyStringDecoder), - getMethods: optional(anyJson().andThen((result) => functionCheck(result, "instance getMethods"))), - getStreams: optional(anyJson().andThen((result) => functionCheck(result, "instance getStreams"))) - }); - const targetDecoder = union(constant("best"), constant("all"), constant("skipMine"), instanceDecoder, array(instanceDecoder)); - const invokeOptionsDecoder = object({ - waitTimeoutMs: optional(nonNegativeNumberDecoder), - methodResponseTimeoutMs: optional(nonNegativeNumberDecoder) - }); - - var InvokeStatus; - (function (InvokeStatus) { - InvokeStatus[InvokeStatus["Success"] = 0] = "Success"; - InvokeStatus[InvokeStatus["Error"] = 1] = "Error"; - })(InvokeStatus || (InvokeStatus = {})); - class Client { - protocol; - repo; - instance; - configuration; - constructor(protocol, repo, instance, configuration) { - this.protocol = protocol; - this.repo = repo; - this.instance = instance; - this.configuration = configuration; - } - subscribe(method, options, successCallback, errorCallback, existingSub) { - const callProtocolSubscribe = (targetServers, stream, successProxy, errorProxy) => { - options.methodResponseTimeout = options.methodResponseTimeout ?? options.waitTimeoutMs; - this.protocol.client.subscribe(stream, options, targetServers, successProxy, errorProxy, existingSub); - }; - const promise = new Promise((resolve, reject) => { - const successProxy = (sub) => { - resolve(sub); - }; - const errorProxy = (err) => { - reject(err); - }; - if (!method) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - let methodDef; - if (typeof method === "string") { - methodDef = { name: method }; - } - else { - methodDef = method; - } - if (!methodDef.name) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - if (options === undefined) { - options = {}; - } - let target = options.target; - if (target === undefined) { - target = "best"; - } - if (typeof target === "string" && target !== "all" && target !== "best") { - reject(new Error(`"${target}" is not a valid target. Valid targets are "all", "best", or an instance.`)); - return; - } - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = options.method_response_timeout; - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = this.configuration.methodResponseTimeout; - } - } - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = options.wait_for_method_timeout; - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - const delayStep = 500; - let delayTillNow = 0; - let currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - callProtocolSubscribe(currentServers, currentServers[0].methods[0], successProxy, errorProxy); - } - else { - const retry = () => { - if (!target || !(options.waitTimeoutMs)) { - return; - } - delayTillNow += delayStep; - currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - const streamInfo = currentServers[0].methods[0]; - callProtocolSubscribe(currentServers, streamInfo, successProxy, errorProxy); - } - else if (delayTillNow >= options.waitTimeoutMs) { - const def = typeof method === "string" ? { name: method } : method; - callProtocolSubscribe(currentServers, def, successProxy, errorProxy); - } - else { - setTimeout(retry, delayStep); - } - }; - setTimeout(retry, delayStep); - } - }); - return promisify(promise, successCallback, errorCallback); - } - servers(methodFilter) { - const filterCopy = methodFilter === undefined - ? undefined - : { ...methodFilter }; - return this.getServers(filterCopy).map((serverMethodMap) => { - return serverMethodMap.server.instance; - }); - } - methods(methodFilter) { - if (typeof methodFilter === "string") { - methodFilter = { name: methodFilter }; - } - else { - methodFilter = { ...methodFilter }; - } - return this.getMethods(methodFilter); - } - methodsForInstance(instance) { - return this.getMethodsForInstance(instance); - } - methodAdded(callback) { - return this.repo.onMethodAdded(callback); - } - methodRemoved(callback) { - return this.repo.onMethodRemoved(callback); - } - serverAdded(callback) { - return this.repo.onServerAdded(callback); - } - serverRemoved(callback) { - return this.repo.onServerRemoved((server, reason) => { - callback(server, reason); - }); - } - serverMethodAdded(callback) { - return this.repo.onServerMethodAdded((server, method) => { - callback({ server, method }); - }); - } - serverMethodRemoved(callback) { - return this.repo.onServerMethodRemoved((server, method) => { - callback({ server, method }); - }); - } - async invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - const getInvokePromise = async () => { - const methodDefinition = typeof methodFilter === "string" ? { name: methodFilter } : { ...methodFilter }; - if (!argumentObj) { - argumentObj = {}; - } - if (!target) { - target = "best"; - } - if (!additionalOptions) { - additionalOptions = {}; - } - const methodFilterDecoderResult = methodFilterDecoder.run(methodDefinition); - if (!methodFilterDecoderResult.ok) { - const message = `The provided 'method' argument is invalid. Error: ${JSON.stringify(methodFilterDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (typeof argumentObj !== "object") { - const message = "The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const targetDecoderResult = targetDecoder.run(target); - if (!targetDecoderResult.ok) { - const message = `The provided 'target' argument is invalid. Error: ${JSON.stringify(targetDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const invokeOptionsDecoderResult = invokeOptionsDecoder.run(additionalOptions); - if (!invokeOptionsDecoderResult.ok) { - const message = `The provided 'options' argument is invalid. Error: ${JSON.stringify(invokeOptionsDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (success && typeof success !== "function") { - const message = "The provided 'success' function is invalid. Error: The success should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (error && typeof error !== "function") { - const message = "The provided 'error' function is invalid. Error: The error should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = additionalOptions.method_response_timeout; - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = this.configuration.methodResponseTimeout; - } - } - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = additionalOptions.wait_for_method_timeout; - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - let serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length === 0) { - try { - serversMethodMap = await this.tryToAwaitForMethods(methodDefinition, target, additionalOptions); - } - catch (err) { - const message = `Can not find a method matching ${JSON.stringify(methodFilter)} with server filter ${JSON.stringify(target)}`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - } - const timeout = additionalOptions.methodResponseTimeoutMs; - const additionalOptionsCopy = additionalOptions; - const invokePromises = serversMethodMap.map((serversMethodPair) => { - const invId = nanoid(10); - const method = serversMethodPair.methods[0]; - const server = serversMethodPair.server; - const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy); - return Promise.race([ - invokePromise, - rejectAfter(timeout, invokePromise, { - invocationId: invId, - message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`, - status: InvokeStatus.Error, - }) - ]); - }); - const invocationMessages = await Promise.all(invokePromises); - const results = this.getInvocationResultObj(invocationMessages, methodDefinition, argumentObj); - const allRejected = invocationMessages.every((result) => result.status === InvokeStatus.Error); - if (allRejected) { - return Promise.reject(results); - } - return results; - }; - return promisify(getInvokePromise(), success, error); - } - generateInvalidInputInvocationResult(message, methodDefinition, argumentObj) { - const method = { - ...methodDefinition, - getServers: () => [], - supportsStreaming: false, - objectTypes: methodDefinition.objectTypes ?? [], - flags: methodDefinition.flags?.metadata ?? {} - }; - const invokeResultMessage = { - invocationId: nanoid(10), - status: InvokeStatus.Error, - message - }; - return this.getInvocationResultObj([invokeResultMessage], method, argumentObj); - } - getInvocationResultObj(invocationResults, method, calledWith) { - const all_return_values = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Success) - .reduce((allValues, currentValue) => { - allValues = [ - ...allValues, - { - executed_by: currentValue.instance, - returned: currentValue.result, - called_with: calledWith, - method, - message: currentValue.message, - status: currentValue.status, - } - ]; - return allValues; - }, []); - const all_errors = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Error) - .reduce((allErrors, currError) => { - allErrors = [ - ...allErrors, - { - executed_by: currError.instance, - called_with: calledWith, - name: method.name, - message: currError.message, - } - ]; - return allErrors; - }, []); - const invResult = invocationResults[0]; - const result = { - method, - called_with: calledWith, - returned: invResult.result, - executed_by: invResult.instance, - all_return_values, - all_errors, - message: invResult.message, - status: invResult.status - }; - return result; - } - tryToAwaitForMethods(methodDefinition, target, additionalOptions) { - return new Promise((resolve, reject) => { - if (additionalOptions.waitTimeoutMs === 0) { - reject(); - return; - } - const delayStep = 500; - let delayTillNow = 0; - const retry = () => { - delayTillNow += delayStep; - const serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length > 0) { - clearInterval(interval); - resolve(serversMethodMap); - } - else if (delayTillNow >= (additionalOptions.waitTimeoutMs || 10000)) { - clearInterval(interval); - reject(); - return; - } - }; - const interval = setInterval(retry, delayStep); - }); - } - filterByTarget(target, serverMethodMap) { - if (typeof target === "string") { - if (target === "all") { - return [...serverMethodMap]; - } - else if (target === "best") { - const localMachine = serverMethodMap - .find((s) => s.server.instance.isLocal); - if (localMachine) { - return [localMachine]; - } - if (serverMethodMap[0] !== undefined) { - return [serverMethodMap[0]]; - } - } - else if (target === "skipMine") { - return serverMethodMap.filter(({ server }) => server.instance.peerId !== this.instance.peerId); - } - } - else { - let targetArray; - if (!Array.isArray(target)) { - targetArray = [target]; - } - else { - targetArray = target; - } - const allServersMatching = targetArray.reduce((matches, filter) => { - const myMatches = serverMethodMap.filter((serverMethodPair) => { - return this.instanceMatch(filter, serverMethodPair.server.instance); - }); - return matches.concat(myMatches); - }, []); - return allServersMatching; - } - return []; - } - instanceMatch(instanceFilter, instanceDefinition) { - if (instanceFilter?.peerId && instanceFilter?.instance) { - instanceFilter = { ...instanceFilter }; - delete instanceFilter.peerId; - } - return this.containsProps(instanceFilter, instanceDefinition); - } - methodMatch(methodFilter, methodDefinition) { - return this.containsProps(methodFilter, methodDefinition); - } - containsProps(filter, repoMethod) { - const filterProps = Object.keys(filter) - .filter((prop) => { - return filter[prop] !== undefined - && filter[prop] !== null - && typeof filter[prop] !== "function" - && prop !== "object_types" - && prop !== "display_name" - && prop !== "id" - && prop !== "gatewayId" - && prop !== "identifier" - && prop[0] !== "_"; - }); - return filterProps.every((prop) => { - let isMatch; - const filterValue = filter[prop]; - const repoMethodValue = repoMethod[prop]; - switch (prop) { - case "objectTypes": - isMatch = (filterValue || []).every((filterValueEl) => { - return (repoMethodValue || []).includes(filterValueEl); - }); - break; - case "flags": - isMatch = isSubset(repoMethodValue || {}, filterValue || {}); - break; - default: - isMatch = String(filterValue).toLowerCase() === String(repoMethodValue).toLowerCase(); - } - return isMatch; - }); - } - getMethods(methodFilter) { - if (methodFilter === undefined) { - return this.repo.getMethods(); - } - const methods = this.repo.getMethods().filter((method) => { - return this.methodMatch(methodFilter, method); - }); - return methods; - } - getMethodsForInstance(instanceFilter) { - const allServers = this.repo.getServers(); - const matchingServers = allServers.filter((server) => { - return this.instanceMatch(instanceFilter, server.instance); - }); - if (matchingServers.length === 0) { - return []; - } - let resultMethodsObject = {}; - if (matchingServers.length === 1) { - resultMethodsObject = matchingServers[0].methods; - } - else { - matchingServers.forEach((server) => { - Object.keys(server.methods).forEach((methodKey) => { - const method = server.methods[methodKey]; - resultMethodsObject[method.identifier] = method; - }); - }); - } - return Object.keys(resultMethodsObject) - .map((key) => { - return resultMethodsObject[key]; - }); - } - getServers(methodFilter) { - const servers = this.repo.getServers(); - if (methodFilter === undefined) { - return servers.map((server) => { - return { server, methods: [] }; - }); - } - return servers.reduce((prev, current) => { - const methodsForServer = Object.values(current.methods); - const matchingMethods = methodsForServer.filter((method) => { - return this.methodMatch(methodFilter, method); - }); - if (matchingMethods.length > 0) { - prev.push({ server: current, methods: matchingMethods }); - } - return prev; - }, []); - } - getServerMethodsByFilterAndTarget(methodFilter, target) { - const serversMethodMap = this.getServers(methodFilter); - return this.filterByTarget(target, serversMethodMap); - } - } - - class ServerSubscription { - protocol; - repoMethod; - subscription; - constructor(protocol, repoMethod, subscription) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.subscription = subscription; - } - get stream() { - if (!this.repoMethod.stream) { - throw new Error("no stream"); - } - return this.repoMethod.stream; - } - get arguments() { return this.subscription.arguments || {}; } - get branchKey() { return this.subscription.branchKey; } - get instance() { - if (!this.subscription.instance) { - throw new Error("no instance"); - } - return this.subscription.instance; - } - close() { - this.protocol.server.closeSingleSubscription(this.repoMethod, this.subscription); - } - push(data) { - this.protocol.server.pushDataToSingle(this.repoMethod, this.subscription, data); - } - } - - class Request { - protocol; - repoMethod; - requestContext; - arguments; - instance; - constructor(protocol, repoMethod, requestContext) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.requestContext = requestContext; - this.arguments = requestContext.arguments; - this.instance = requestContext.instance; - } - accept() { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, ""); - } - acceptOnBranch(branch) { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, branch); - } - reject(reason) { - this.protocol.server.rejectRequest(this.requestContext, this.repoMethod, reason); - } - } - - let ServerStreaming$1 = class ServerStreaming { - protocol; - server; - constructor(protocol, server) { - this.protocol = protocol; - this.server = server; - protocol.server.onSubRequest((rc, rm) => this.handleSubRequest(rc, rm)); - protocol.server.onSubAdded((sub, rm) => this.handleSubAdded(sub, rm)); - protocol.server.onSubRemoved((sub, rm) => this.handleSubRemoved(sub, rm)); - } - handleSubRequest(requestContext, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRequestHandler === "function")) { - return; - } - const request = new Request(this.protocol, repoMethod, requestContext); - repoMethod.streamCallbacks.subscriptionRequestHandler(request); - } - handleSubAdded(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionAddedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionAddedHandler(sub); - } - handleSubRemoved(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRemovedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionRemovedHandler(sub); - } - }; - - class ServerBranch { - key; - protocol; - repoMethod; - constructor(key, protocol, repoMethod) { - this.key = key; - this.protocol = protocol; - this.repoMethod = repoMethod; - } - subscriptions() { - const subList = this.protocol.server.getSubscriptionList(this.repoMethod, this.key); - return subList.map((sub) => { - return new ServerSubscription(this.protocol, this.repoMethod, sub); - }); - } - close() { - this.protocol.server.closeAllSubscriptions(this.repoMethod, this.key); - } - push(data) { - this.protocol.server.pushData(this.repoMethod, data, [this.key]); - } - } - - class ServerStream { - _protocol; - _repoMethod; - _server; - name; - constructor(_protocol, _repoMethod, _server) { - this._protocol = _protocol; - this._repoMethod = _repoMethod; - this._server = _server; - this.name = this._repoMethod.definition.name; - } - branches(key) { - const bList = this._protocol.server.getBranchList(this._repoMethod); - if (key) { - if (bList.indexOf(key) > -1) { - return new ServerBranch(key, this._protocol, this._repoMethod); - } - return undefined; - } - else { - return bList.map((branchKey) => { - return new ServerBranch(branchKey, this._protocol, this._repoMethod); - }); - } - } - branch(key) { - return this.branches(key); - } - subscriptions() { - const subList = this._protocol.server.getSubscriptionList(this._repoMethod); - return subList.map((sub) => { - return new ServerSubscription(this._protocol, this._repoMethod, sub); - }); - } - get definition() { - const def2 = this._repoMethod.definition; - return { - accepts: def2.accepts, - description: def2.description, - displayName: def2.displayName, - name: def2.name, - objectTypes: def2.objectTypes, - returns: def2.returns, - supportsStreaming: def2.supportsStreaming, - flags: def2.flags?.metadata, - }; - } - close() { - this._protocol.server.closeAllSubscriptions(this._repoMethod); - this._server.unregister(this._repoMethod.definition, true); - } - push(data, branches) { - if (typeof branches !== "string" && !Array.isArray(branches) && branches !== undefined) { - throw new Error("invalid branches should be string or string array"); - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - this._protocol.server.pushData(this._repoMethod, data, branches); - } - updateRepoMethod(repoMethod) { - this._repoMethod = repoMethod; - } - } - - class Server { - protocol; - serverRepository; - streaming; - invocations = 0; - currentlyUnregistering = {}; - constructor(protocol, serverRepository) { - this.protocol = protocol; - this.serverRepository = serverRepository; - this.streaming = new ServerStreaming$1(protocol, this); - this.protocol.server.onInvoked(this.onMethodInvoked.bind(this)); - } - createStream(streamDef, callbacks, successCallback, errorCallback, existingStream) { - const promise = new Promise((resolve, reject) => { - if (!streamDef) { - reject("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream."); - return; - } - let streamMethodDefinition; - if (typeof streamDef === "string") { - streamMethodDefinition = { name: "" + streamDef }; - } - else { - streamMethodDefinition = { ...streamDef }; - } - if (!streamMethodDefinition.name) { - return reject(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(streamMethodDefinition)}`); - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === streamMethodDefinition.name); - if (nameAlreadyExists) { - return reject(`A stream with the name "${streamMethodDefinition.name}" already exists! Please, provide a unique name for the stream.`); - } - streamMethodDefinition.supportsStreaming = true; - if (!callbacks) { - callbacks = {}; - } - if (typeof callbacks.subscriptionRequestHandler !== "function") { - callbacks.subscriptionRequestHandler = (request) => { - request.accept(); - }; - } - const repoMethod = this.serverRepository.add({ - definition: streamMethodDefinition, - streamCallbacks: callbacks, - protocolState: {}, - }); - this.protocol.server.createStream(repoMethod) - .then(() => { - let streamUserObject; - if (existingStream) { - streamUserObject = existingStream; - existingStream.updateRepoMethod(repoMethod); - } - else { - streamUserObject = new ServerStream(this.protocol, repoMethod, this); - } - repoMethod.stream = streamUserObject; - resolve(streamUserObject); - }) - .catch((err) => { - if (repoMethod.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - reject(err); - }); - }); - return promisify(promise, successCallback, errorCallback); - } - register(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallbackFunction = async (context, resultCallback) => { - try { - const result = callback(context.args, context.instance); - if (result && typeof result.then === "function") { - const resultValue = await result; - resultCallback(undefined, resultValue); - } - else { - resultCallback(undefined, result); - } - } - catch (e) { - resultCallback(e ?? "", e ?? ""); - } - }; - wrappedCallbackFunction.userCallback = callback; - return this.registerCore(methodDefinition, wrappedCallbackFunction); - } - registerAsync(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallback = async (context, resultCallback) => { - try { - let resultCalled = false; - const success = (result) => { - if (!resultCalled) { - resultCallback(undefined, result); - } - resultCalled = true; - }; - const error = (e) => { - if (!resultCalled) { - if (!e) { - e = ""; - } - resultCallback(e, e); - } - resultCalled = true; - }; - const methodResult = callback(context.args, context.instance, success, error); - if (methodResult && typeof methodResult.then === "function") { - methodResult - .then(success) - .catch(error); - } - } - catch (e) { - resultCallback(e, undefined); - } - }; - wrappedCallback.userCallbackAsync = callback; - return this.registerCore(methodDefinition, wrappedCallback); - } - async unregister(methodFilter, forStream = false) { - if (methodFilter === undefined) { - return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property."); - } - if (typeof methodFilter === "function") { - await this.unregisterWithPredicate(methodFilter, forStream); - return; - } - let methodDefinition; - if (typeof methodFilter === "string") { - methodDefinition = { name: methodFilter }; - } - else { - methodDefinition = methodFilter; - } - if (methodDefinition.name === undefined) { - return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!"); - } - const methodToBeRemoved = this.serverRepository.getList().find((serverMethod) => { - return serverMethod.definition.name === methodDefinition.name - && (serverMethod.definition.supportsStreaming || false) === forStream; - }); - if (!methodToBeRemoved) { - return Promise.reject(`Method with a name "${methodDefinition.name}" does not exist or is not registered by your application!`); - } - await this.removeMethodsOrStreams([methodToBeRemoved]); - } - async unregisterWithPredicate(filterPredicate, forStream) { - const methodsOrStreamsToRemove = this.serverRepository.getList() - .filter((sm) => filterPredicate(sm.definition)) - .filter((serverMethod) => (serverMethod.definition.supportsStreaming || false) === forStream); - if (!methodsOrStreamsToRemove || methodsOrStreamsToRemove.length === 0) { - return Promise.reject(`Could not find a ${forStream ? "stream" : "method"} matching the specified condition!`); - } - await this.removeMethodsOrStreams(methodsOrStreamsToRemove); - } - removeMethodsOrStreams(methodsToRemove) { - const methodUnregPromises = []; - methodsToRemove.forEach((method) => { - const promise = this.protocol.server.unregister(method) - .then(() => { - if (method.repoId) { - this.serverRepository.remove(method.repoId); - } - }); - methodUnregPromises.push(promise); - this.addAsCurrentlyUnregistering(method.definition.name, promise); - }); - return Promise.all(methodUnregPromises); - } - async addAsCurrentlyUnregistering(methodName, promise) { - const timeout = new Promise((resolve) => setTimeout(resolve, 5000)); - this.currentlyUnregistering[methodName] = Promise.race([promise, timeout]).then(() => { - delete this.currentlyUnregistering[methodName]; - }); - } - async registerCore(method, theFunction) { - let methodDefinition; - if (typeof method === "string") { - methodDefinition = { name: "" + method }; - } - else { - methodDefinition = { ...method }; - } - if (!methodDefinition.name) { - return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(method)}`); - } - const unregisterInProgress = this.currentlyUnregistering[methodDefinition.name]; - if (typeof unregisterInProgress !== "undefined") { - await unregisterInProgress; - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === methodDefinition.name); - if (nameAlreadyExists) { - return Promise.reject(`A method with the name "${methodDefinition.name}" already exists! Please, provide a unique name for the method.`); - } - if (methodDefinition.supportsStreaming) { - return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${methodDefinition.name}” to be a stream, please use the “glue.interop.createStream()” method.`); - } - const repoMethod = this.serverRepository.add({ - definition: methodDefinition, - theFunction, - protocolState: {}, - }); - return this.protocol.server.register(repoMethod) - .catch((err) => { - if (repoMethod?.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - throw err; - }); - } - onMethodInvoked(methodToExecute, invocationId, invocationArgs) { - if (!methodToExecute || !methodToExecute.theFunction) { - return; - } - methodToExecute.theFunction(invocationArgs, (err, result) => { - if (err !== undefined && err !== null) { - if (err.message && typeof err.message === "string") { - err = err.message; - } - else if (typeof err !== "string") { - try { - err = JSON.stringify(err); - } - catch (unStrException) { - err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`; - } - } - } - if (!result) { - result = {}; - } - else if (typeof result !== "object" || Array.isArray(result)) { - result = { _value: result }; - } - this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result); - }); - } - } - - class InstanceWrapper { - wrapped = {}; - constructor(API, instance, connection) { - this.wrapped.getMethods = function () { - return API.methodsForInstance(this); - }; - this.wrapped.getStreams = function () { - return API.methodsForInstance(this).filter((m) => m.supportsStreaming); - }; - if (instance) { - this.refreshWrappedObject(instance); - } - if (connection) { - connection.loggedIn(() => { - this.refresh(connection); - }); - this.refresh(connection); - } - } - unwrap() { - return this.wrapped; - } - refresh(connection) { - if (!connection) { - return; - } - const resolvedIdentity = connection?.resolvedIdentity; - const instance = Object.assign({}, resolvedIdentity ?? {}, { peerId: connection?.peerId }); - this.refreshWrappedObject(instance); - } - refreshWrappedObject(resolvedIdentity) { - Object.keys(resolvedIdentity).forEach((key) => { - this.wrapped[key] = resolvedIdentity[key]; - }); - this.wrapped.user = resolvedIdentity.user; - this.wrapped.instance = resolvedIdentity.instance; - this.wrapped.application = resolvedIdentity.application ?? nanoid(10); - this.wrapped.applicationName = resolvedIdentity.applicationName; - this.wrapped.pid = resolvedIdentity.pid ?? resolvedIdentity.process ?? Math.floor(Math.random() * 10000000000); - this.wrapped.machine = resolvedIdentity.machine; - this.wrapped.environment = resolvedIdentity.environment; - this.wrapped.region = resolvedIdentity.region; - this.wrapped.windowId = resolvedIdentity.windowId; - this.wrapped.isLocal = resolvedIdentity.isLocal ?? true; - this.wrapped.api = resolvedIdentity.api; - this.wrapped.service = resolvedIdentity.service; - this.wrapped.peerId = resolvedIdentity.peerId; - } - } - - const hideMethodSystemFlags = (method) => { - return { - ...method, - flags: method.flags.metadata || {} - }; - }; - class ClientRepository { - logger; - API; - servers = {}; - myServer; - methodsCount = {}; - callbacks = CallbackRegistryFactory(); - constructor(logger, API) { - this.logger = logger; - this.API = API; - const peerId = this.API.instance.peerId; - this.myServer = { - id: peerId, - methods: {}, - instance: this.API.instance, - wrapper: this.API.unwrappedInstance, - }; - this.servers[peerId] = this.myServer; - } - addServer(info, serverId) { - this.logger.debug(`adding server ${serverId}`); - const current = this.servers[serverId]; - if (current) { - return current.id; - } - const wrapper = new InstanceWrapper(this.API, info); - const serverEntry = { - id: serverId, - methods: {}, - instance: wrapper.unwrap(), - wrapper, - }; - this.servers[serverId] = serverEntry; - this.callbacks.execute("onServerAdded", serverEntry.instance); - return serverId; - } - removeServerById(id, reason) { - const server = this.servers[id]; - if (!server) { - this.logger.warn(`not aware of server ${id}, my state ${JSON.stringify(Object.keys(this.servers))}`); - return; - } - else { - this.logger.debug(`removing server ${id}`); - } - Object.keys(server.methods).forEach((methodId) => { - this.removeServerMethod(id, methodId); - }); - delete this.servers[id]; - this.callbacks.execute("onServerRemoved", server.instance, reason); - } - addServerMethod(serverId, method) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - if (server.methods[method.id]) { - return; - } - const identifier = this.createMethodIdentifier(method); - const that = this; - const methodDefinition = { - identifier, - gatewayId: method.id, - name: method.name, - displayName: method.display_name, - description: method.description, - version: method.version, - objectTypes: method.object_types || [], - accepts: method.input_signature, - returns: method.result_signature, - supportsStreaming: typeof method.flags !== "undefined" ? method.flags.streaming : false, - flags: method.flags ?? {}, - getServers: () => { - return that.getServersByMethod(identifier); - } - }; - methodDefinition.object_types = methodDefinition.objectTypes; - methodDefinition.display_name = methodDefinition.displayName; - methodDefinition.version = methodDefinition.version; - server.methods[method.id] = methodDefinition; - const clientMethodDefinition = hideMethodSystemFlags(methodDefinition); - if (!this.methodsCount[identifier]) { - this.methodsCount[identifier] = 0; - this.callbacks.execute("onMethodAdded", clientMethodDefinition); - } - this.methodsCount[identifier] = this.methodsCount[identifier] + 1; - this.callbacks.execute("onServerMethodAdded", server.instance, clientMethodDefinition); - return methodDefinition; - } - removeServerMethod(serverId, methodId) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - const method = server.methods[methodId]; - delete server.methods[methodId]; - const clientMethodDefinition = hideMethodSystemFlags(method); - this.methodsCount[method.identifier] = this.methodsCount[method.identifier] - 1; - if (this.methodsCount[method.identifier] === 0) { - this.callbacks.execute("onMethodRemoved", clientMethodDefinition); - } - this.callbacks.execute("onServerMethodRemoved", server.instance, clientMethodDefinition); - } - getMethods() { - return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags); - } - getServers() { - return Object.values(this.servers).map(this.hideServerMethodSystemFlags); - } - onServerAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerAdded", callback); - const serversWithMethodsToReplay = this.getServers().map((s) => s.instance); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, serversWithMethodsToReplay, callback); - } - onMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodAdded", callback); - const methodsToReplay = this.getMethods(); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, methodsToReplay, callback); - } - onServerMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodAdded", callback); - let unsubCalled = false; - const servers = this.getServers(); - setTimeout(() => { - servers.forEach((server) => { - const methods = server.methods; - Object.keys(methods).forEach((methodId) => { - if (!unsubCalled) { - callback(server.instance, methods[methodId]); - } - }); - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - onMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodRemoved", callback); - return unsubscribeFunc; - } - onServerRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerRemoved", callback); - return unsubscribeFunc; - } - onServerMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodRemoved", callback); - return unsubscribeFunc; - } - getServerById(id) { - const server = this.servers[id]; - if (!server) { - return undefined; - } - return this.hideServerMethodSystemFlags(this.servers[id]); - } - reset() { - Object.keys(this.servers).forEach((key) => { - this.removeServerById(key, "reset"); - }); - this.servers = { - [this.myServer.id]: this.myServer - }; - this.methodsCount = {}; - } - createMethodIdentifier(methodInfo) { - const accepts = methodInfo.input_signature ?? ""; - const returns = methodInfo.result_signature ?? ""; - return (methodInfo.name + accepts + returns).toLowerCase(); - } - getServersByMethod(identifier) { - const allServers = []; - Object.values(this.servers).forEach((server) => { - Object.values(server.methods).forEach((method) => { - if (method.identifier === identifier) { - allServers.push(server.instance); - } - }); - }); - return allServers; - } - returnUnsubWithDelayedReplay(unsubscribeFunc, collectionToReplay, callback) { - let unsubCalled = false; - setTimeout(() => { - collectionToReplay.forEach((item) => { - if (!unsubCalled) { - callback(item); - } - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - hideServerMethodSystemFlags(server) { - const clientMethods = {}; - Object.entries(server.methods).forEach(([name, method]) => { - clientMethods[name] = hideMethodSystemFlags(method); - }); - return { - ...server, - methods: clientMethods - }; - } - extractMethodsFromServers(servers) { - const methods = Object.values(servers).reduce((clientMethods, server) => { - return [...clientMethods, ...Object.values(server.methods)]; - }, []); - return methods; - } - } - - class ServerRepository { - nextId = 0; - methods = []; - add(method) { - method.repoId = String(this.nextId); - this.nextId += 1; - this.methods.push(method); - return method; - } - remove(repoId) { - if (typeof repoId !== "string") { - return new TypeError("Expecting a string"); - } - this.methods = this.methods.filter((m) => { - return m.repoId !== repoId; - }); - } - getById(id) { - if (typeof id !== "string") { - return undefined; - } - return this.methods.find((m) => { - return m.repoId === id; - }); - } - getList() { - return this.methods.map((m) => m); - } - length() { - return this.methods.length; - } - reset() { - this.methods = []; - } - } - - const SUBSCRIPTION_REQUEST = "onSubscriptionRequest"; - const SUBSCRIPTION_ADDED = "onSubscriptionAdded"; - const SUBSCRIPTION_REMOVED = "onSubscriptionRemoved"; - class ServerStreaming { - session; - repository; - serverRepository; - logger; - ERR_URI_SUBSCRIPTION_FAILED = "com.tick42.agm.errors.subscription.failure"; - callbacks = CallbackRegistryFactory(); - nextStreamId = 0; - constructor(session, repository, serverRepository, logger) { - this.session = session; - this.repository = repository; - this.serverRepository = serverRepository; - this.logger = logger; - session.on("add-interest", (msg) => { - this.handleAddInterest(msg); - }); - session.on("remove-interest", (msg) => { - this.handleRemoveInterest(msg); - }); - } - acceptRequestOnBranch(requestContext, streamingMethod, branch) { - if (typeof branch !== "string") { - branch = ""; - } - if (typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - throw new TypeError("The streaming method is missing its subscriptions."); - } - if (!Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - throw new TypeError("The streaming method is missing its branches."); - } - const streamId = this.getStreamId(streamingMethod, branch); - const key = requestContext.msg.subscription_id; - const subscription = { - id: key, - arguments: requestContext.arguments, - instance: requestContext.instance, - branchKey: branch, - streamId, - subscribeMsg: requestContext.msg, - }; - streamingMethod.protocolState.subscriptionsMap[key] = subscription; - this.session.sendFireAndForget({ - type: "accepted", - subscription_id: key, - stream_id: streamId, - }).catch((err) => { - this.logger.warn(`Failed to send accepted message for subscription ${key}: ${JSON.stringify(err)}`); - }); - this.callbacks.execute(SUBSCRIPTION_ADDED, subscription, streamingMethod); - } - rejectRequest(requestContext, streamingMethod, reason) { - if (typeof reason !== "string") { - reason = ""; - } - this.sendSubscriptionFailed("Subscription rejected by user. " + reason, requestContext.msg.subscription_id); - } - pushData(streamingMethod, data, branches) { - if (typeof streamingMethod !== "object" || !Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - return; - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - if (typeof branches === "string") { - branches = [branches]; - } - else if (!Array.isArray(branches) || branches.length <= 0) { - branches = []; - } - const streamIdList = streamingMethod.protocolState.branchKeyToStreamIdMap - .filter((br) => { - if (!branches || branches.length === 0) { - return true; - } - return branches.indexOf(br.key) >= 0; - }).map((br) => { - return br.streamId; - }); - streamIdList.forEach((streamId) => { - const publishMessage = { - type: "publish", - stream_id: streamId, - data, - }; - this.session.sendFireAndForget(publishMessage) - .catch((err) => { - this.logger.warn(`Failed to send publish message for stream ${streamId}: ${JSON.stringify(err)}`); - }); - }); - } - pushDataToSingle(method, subscription, data) { - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - const postMessage = { - type: "post", - subscription_id: subscription.id, - data, - }; - this.session.sendFireAndForget(postMessage) - .catch((err) => { - this.logger.warn(`Failed to send post message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - } - closeSingleSubscription(streamingMethod, subscription) { - if (streamingMethod.protocolState.subscriptionsMap) { - delete streamingMethod.protocolState.subscriptionsMap[subscription.id]; - } - const dropSubscriptionMessage = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping a single subscription", - }; - this.session.sendFireAndForget(dropSubscriptionMessage) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - subscription.instance; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - closeMultipleSubscriptions(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object" || typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - let subscriptionsToClose = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey === "string") { - subscriptionsToClose = subscriptionsToClose.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - subscriptionsToClose.forEach((subscription) => { - delete subscriptionsMap[subscription.id]; - const drop = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping all subscriptions on stream_id: " + subscription.streamId, - }; - this.session.sendFireAndForget(drop) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - }); - } - getSubscriptionList(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object") { - return []; - } - let subscriptions = []; - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey !== "string") { - subscriptions = allSubscriptions; - } - else { - subscriptions = allSubscriptions.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - return subscriptions; - } - getBranchList(streamingMethod) { - if (typeof streamingMethod !== "object") { - return []; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - const result = []; - allSubscriptions.forEach((sub) => { - let branch = ""; - if (typeof sub === "object" && typeof sub.branchKey === "string") { - branch = sub.branchKey; - } - if (result.indexOf(branch) === -1) { - result.push(branch); - } - }); - return result; - } - onSubAdded(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED, callback); - } - onSubRequest(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST, callback); - } - onSubRemoved(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED, callback); - } - handleRemoveInterest(msg) { - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (typeof msg.subscription_id !== "string" || - typeof streamingMethod !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - if (typeof streamingMethod.protocolState.subscriptionsMap[msg.subscription_id] !== "object") { - return; - } - const subscription = streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - delete streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - onSubscriptionLifetimeEvent(eventName, handlerFunc) { - this.callbacks.add(eventName, handlerFunc); - } - getNextStreamId() { - return this.nextStreamId++ + ""; - } - handleAddInterest(msg) { - const caller = this.repository.getServerById(msg.caller_id); - const instance = caller?.instance ?? {}; - const requestContext = { - msg, - arguments: msg.arguments_kv || {}, - instance, - }; - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (streamingMethod === undefined) { - const errorMsg = "No method with id " + msg.method_id + " on this server."; - this.sendSubscriptionFailed(errorMsg, msg.subscription_id); - return; - } - if (streamingMethod.protocolState.subscriptionsMap && - streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]) { - this.sendSubscriptionFailed("A subscription with id " + msg.subscription_id + " already exists.", msg.subscription_id); - return; - } - this.callbacks.execute(SUBSCRIPTION_REQUEST, requestContext, streamingMethod); - } - sendSubscriptionFailed(reason, subscriptionId) { - const errorMessage = { - type: "error", - reason_uri: this.ERR_URI_SUBSCRIPTION_FAILED, - reason, - request_id: subscriptionId, - }; - this.session.sendFireAndForget(errorMessage) - .catch((err) => { - this.logger.warn(`Failed to send subscription failed message for subscription ${subscriptionId}: ${JSON.stringify(err)}`); - }); - } - getStreamId(streamingMethod, branchKey) { - if (typeof branchKey !== "string") { - branchKey = ""; - } - if (!streamingMethod.protocolState.branchKeyToStreamIdMap) { - throw new Error(`streaming ${streamingMethod.definition.name} method without protocol state`); - } - const needleBranch = streamingMethod.protocolState.branchKeyToStreamIdMap.filter((branch) => { - return branch.key === branchKey; - })[0]; - let streamId = (needleBranch ? needleBranch.streamId : undefined); - if (typeof streamId !== "string" || streamId === "") { - streamId = this.getNextStreamId(); - streamingMethod.protocolState.branchKeyToStreamIdMap.push({ key: branchKey, streamId }); - } - return streamId; - } - } - - class ServerProtocol { - session; - clientRepository; - serverRepository; - logger; - callbacks = CallbackRegistryFactory(); - streaming; - constructor(session, clientRepository, serverRepository, logger) { - this.session = session; - this.clientRepository = clientRepository; - this.serverRepository = serverRepository; - this.logger = logger; - this.streaming = new ServerStreaming(session, clientRepository, serverRepository, logger.subLogger("streaming")); - this.session.on("invoke", (msg) => this.handleInvokeMessage(msg)); - } - createStream(repoMethod) { - repoMethod.protocolState.subscriptionsMap = {}; - repoMethod.protocolState.branchKeyToStreamIdMap = []; - return this.register(repoMethod, true); - } - register(repoMethod, isStreaming) { - const methodDef = repoMethod.definition; - const flags = Object.assign({}, { metadata: methodDef.flags ?? {} }, { streaming: isStreaming || false }); - const registerMsg = { - type: "register", - methods: [{ - id: repoMethod.repoId, - name: methodDef.name, - display_name: methodDef.displayName, - description: methodDef.description, - version: methodDef.version, - flags, - object_types: methodDef.objectTypes || methodDef.object_types, - input_signature: methodDef.accepts, - result_signature: methodDef.returns, - restrictions: undefined, - }], - }; - return this.session.send(registerMsg, { methodId: repoMethod.repoId }) - .then(() => { - this.logger.debug("registered method " + repoMethod.definition.name + " with id " + repoMethod.repoId); - }) - .catch((msg) => { - this.logger.warn(`failed to register method ${repoMethod.definition.name} with id ${repoMethod.repoId} - ${JSON.stringify(msg)}`); - throw msg; - }); - } - onInvoked(callback) { - this.callbacks.add("onInvoked", callback); - } - methodInvocationResult(method, invocationId, err, result) { - let msg; - if (err || err === "") { - msg = { - type: "error", - request_id: invocationId, - reason_uri: "agm.errors.client_error", - reason: err, - context: result, - peer_id: undefined, - }; - } - else { - msg = { - type: "yield", - invocation_id: invocationId, - peer_id: this.session.peerId, - result, - request_id: undefined, - }; - } - this.session.sendFireAndForget(msg) - .catch((error => { - this.logger.warn(`Failed to send method invocation result for method ${method.definition.name} invocation ${invocationId} - ${JSON.stringify(error)}`); - })); - } - async unregister(method) { - const msg = { - type: "unregister", - methods: [method.repoId], - }; - await this.session.send(msg); - } - getBranchList(method) { - return this.streaming.getBranchList(method); - } - getSubscriptionList(method, branchKey) { - return this.streaming.getSubscriptionList(method, branchKey); - } - closeAllSubscriptions(method, branchKey) { - this.streaming.closeMultipleSubscriptions(method, branchKey); - } - pushData(method, data, branches) { - this.streaming.pushData(method, data, branches); - } - pushDataToSingle(method, subscription, data) { - this.streaming.pushDataToSingle(method, subscription, data); - } - closeSingleSubscription(method, subscription) { - this.streaming.closeSingleSubscription(method, subscription); - } - acceptRequestOnBranch(requestContext, method, branch) { - this.streaming.acceptRequestOnBranch(requestContext, method, branch); - } - rejectRequest(requestContext, method, reason) { - this.streaming.rejectRequest(requestContext, method, reason); - } - onSubRequest(callback) { - this.streaming.onSubRequest(callback); - } - onSubAdded(callback) { - this.streaming.onSubAdded(callback); - } - onSubRemoved(callback) { - this.streaming.onSubRemoved(callback); - } - handleInvokeMessage(msg) { - const invocationId = msg.invocation_id; - const callerId = msg.caller_id; - const methodId = msg.method_id; - const args = msg.arguments_kv; - const methodList = this.serverRepository.getList(); - const method = methodList.filter((m) => { - return m.repoId === methodId; - })[0]; - if (method === undefined) { - return; - } - const client = this.clientRepository.getServerById(callerId)?.instance; - const invocationArgs = { args, instance: client }; - this.callbacks.execute("onInvoked", method, invocationId, invocationArgs); - } - } - - class UserSubscription { - repository; - subscriptionData; - get requestArguments() { - return this.subscriptionData.params.arguments || {}; - } - get servers() { - return this.subscriptionData.trackedServers.reduce((servers, pair) => { - if (pair.subscriptionId) { - const server = this.repository.getServerById(pair.serverId)?.instance; - if (server) { - servers.push(server); - } - } - return servers; - }, []); - } - get serverInstance() { - return this.servers[0]; - } - get stream() { - return this.subscriptionData.method; - } - constructor(repository, subscriptionData) { - this.repository = repository; - this.subscriptionData = subscriptionData; - } - onData(dataCallback) { - if (typeof dataCallback !== "function") { - throw new TypeError("The data callback must be a function."); - } - this.subscriptionData.handlers.onData.push(dataCallback); - if (this.subscriptionData.handlers.onData.length === 1 && this.subscriptionData.queued.data.length > 0) { - this.subscriptionData.queued.data.forEach((dataItem) => { - dataCallback(dataItem); - }); - } - } - onClosed(closedCallback) { - if (typeof closedCallback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onClosed.push(closedCallback); - } - onFailed(callback) { - } - onConnected(callback) { - if (typeof callback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onConnected.push(callback); - } - close() { - this.subscriptionData.close(); - } - setNewSubscription(newSub) { - this.subscriptionData = newSub; - } - } - - class TimedCache { - config; - cache = []; - timeoutIds = []; - constructor(config) { - this.config = config; - } - add(element) { - const id = nanoid(10); - this.cache.push({ id, element }); - const timeoutId = setTimeout(() => { - const elementIdx = this.cache.findIndex((entry) => entry.id === id); - if (elementIdx < 0) { - return; - } - this.cache.splice(elementIdx, 1); - }, this.config.ELEMENT_TTL_MS); - this.timeoutIds.push(timeoutId); - } - flush() { - const elements = this.cache.map((entry) => entry.element); - this.timeoutIds.forEach((id) => clearInterval(id)); - this.cache = []; - this.timeoutIds = []; - return elements; - } - } - - const STATUS_AWAITING_ACCEPT = "awaitingAccept"; - const STATUS_SUBSCRIBED = "subscribed"; - const ERR_MSG_SUB_FAILED = "Subscription failed."; - const ERR_MSG_SUB_REJECTED = "Subscription rejected."; - const ON_CLOSE_MSG_SERVER_INIT = "ServerInitiated"; - const ON_CLOSE_MSG_CLIENT_INIT = "ClientInitiated"; - class ClientStreaming { - session; - repository; - logger; - subscriptionsList = {}; - timedCache = new TimedCache({ ELEMENT_TTL_MS: 10000 }); - subscriptionIdToLocalKeyMap = {}; - nextSubLocalKey = 0; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("subscribed", this.handleSubscribed); - session.on("event", this.handleEventData); - session.on("subscription-cancelled", this.handleSubscriptionCancelled); - } - subscribe(streamingMethod, params, targetServers, success, error, existingSub) { - if (targetServers.length === 0) { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " No available servers matched the target params.", - }); - return; - } - const subLocalKey = this.getNextSubscriptionLocalKey(); - const pendingSub = this.registerSubscription(subLocalKey, streamingMethod, params, success, error, params.methodResponseTimeout || 10000, existingSub); - if (typeof pendingSub !== "object") { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Unable to register the user callbacks.", - }); - return; - } - targetServers.forEach((target) => { - const serverId = target.server.id; - const method = target.methods.find((m) => m.name === streamingMethod.name); - if (!method) { - this.logger.error(`can not find method ${streamingMethod.name} for target ${target.server.id}`); - return; - } - pendingSub.trackedServers.push({ - serverId, - subscriptionId: undefined, - }); - const msg = { - type: "subscribe", - server_id: serverId, - method_id: method.gatewayId, - arguments_kv: params.arguments, - }; - this.session.send(msg, { serverId, subLocalKey }) - .then((m) => this.handleSubscribed(m)) - .catch((err) => this.handleErrorSubscribing(err)); - }); - } - drainSubscriptions() { - const existing = Object.values(this.subscriptionsList); - this.subscriptionsList = {}; - this.subscriptionIdToLocalKeyMap = {}; - return existing; - } - drainSubscriptionsCache() { - return this.timedCache.flush(); - } - getNextSubscriptionLocalKey() { - const current = this.nextSubLocalKey; - this.nextSubLocalKey += 1; - return current; - } - registerSubscription(subLocalKey, method, params, success, error, timeout, existingSub) { - const subsInfo = { - localKey: subLocalKey, - status: STATUS_AWAITING_ACCEPT, - method, - params, - success, - error, - trackedServers: [], - handlers: { - onData: existingSub?.handlers.onData || [], - onClosed: existingSub?.handlers.onClosed || [], - onConnected: existingSub?.handlers.onConnected || [], - }, - queued: { - data: [], - closers: [], - }, - timeoutId: undefined, - close: () => this.closeSubscription(subLocalKey), - subscription: existingSub?.subscription - }; - if (!existingSub) { - if (params.onData) { - subsInfo.handlers.onData.push(params.onData); - } - if (params.onClosed) { - subsInfo.handlers.onClosed.push(params.onClosed); - } - if (params.onConnected) { - subsInfo.handlers.onConnected.push(params.onConnected); - } - } - this.subscriptionsList[subLocalKey] = subsInfo; - subsInfo.timeoutId = setTimeout(() => { - if (this.subscriptionsList[subLocalKey] === undefined) { - return; - } - const pendingSub = this.subscriptionsList[subLocalKey]; - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - error({ - method, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Subscription attempt timed out after " + timeout + " ms.", - }); - delete this.subscriptionsList[subLocalKey]; - } - else if (pendingSub.status === STATUS_SUBSCRIBED && pendingSub.trackedServers.length > 0) { - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return (typeof server.subscriptionId !== "undefined"); - }); - delete pendingSub.timeoutId; - if (pendingSub.trackedServers.length <= 0) { - this.callOnClosedHandlers(pendingSub); - delete this.subscriptionsList[subLocalKey]; - } - } - }, timeout); - return subsInfo; - } - handleErrorSubscribing = (errorResponse) => { - const tag = errorResponse._tag; - const subLocalKey = tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return server.serverId !== tag.serverId; - }); - if (pendingSub.trackedServers.length <= 0) { - clearTimeout(pendingSub.timeoutId); - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - const reason = (typeof errorResponse.reason === "string" && errorResponse.reason !== "") ? - ' Publisher said "' + errorResponse.reason + '".' : - " No reason given."; - const callArgs = typeof pendingSub.params.arguments === "object" ? - JSON.stringify(pendingSub.params.arguments) : - "{}"; - pendingSub.error({ - message: ERR_MSG_SUB_REJECTED + reason + " Called with:" + callArgs, - called_with: pendingSub.params.arguments, - method: pendingSub.method, - }); - } - else if (pendingSub.status === STATUS_SUBSCRIBED) { - this.callOnClosedHandlers(pendingSub); - } - delete this.subscriptionsList[subLocalKey]; - } - }; - handleSubscribed = (msg) => { - const subLocalKey = msg._tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - const serverId = msg._tag.serverId; - const acceptingServer = pendingSub.trackedServers - .filter((server) => { - return server.serverId === serverId; - })[0]; - if (typeof acceptingServer !== "object") { - return; - } - acceptingServer.subscriptionId = msg.subscription_id; - this.subscriptionIdToLocalKeyMap[msg.subscription_id] = subLocalKey; - const isFirstResponse = (pendingSub.status === STATUS_AWAITING_ACCEPT); - pendingSub.status = STATUS_SUBSCRIBED; - if (isFirstResponse) { - let reconnect = false; - let sub = pendingSub.subscription; - if (sub) { - sub.setNewSubscription(pendingSub); - pendingSub.success(sub); - reconnect = true; - } - else { - sub = new UserSubscription(this.repository, pendingSub); - pendingSub.subscription = sub; - pendingSub.success(sub); - } - for (const handler of pendingSub.handlers.onConnected) { - try { - handler(sub.serverInstance, reconnect); - } - catch (e) { - } - } - } - }; - handleEventData = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const trackedServersFound = subscription.trackedServers.filter((s) => { - return s.subscriptionId === msg.subscription_id; - }); - if (trackedServersFound.length !== 1) { - return; - } - const isPrivateData = msg.oob; - const sendingServerId = trackedServersFound[0].serverId; - const server = this.repository.getServerById(sendingServerId); - const receivedStreamData = () => { - return { - data: msg.data, - server: server?.instance ?? {}, - requestArguments: subscription.params.arguments, - message: undefined, - private: isPrivateData, - }; - }; - const onDataHandlers = subscription.handlers.onData; - const queuedData = subscription.queued.data; - if (onDataHandlers.length > 0) { - onDataHandlers.forEach((callback) => { - if (typeof callback === "function") { - callback(receivedStreamData()); - } - }); - } - else { - queuedData.push(receivedStreamData()); - } - }; - handleSubscriptionCancelled = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const expectedNewLength = subscription.trackedServers.length - 1; - subscription.trackedServers = subscription.trackedServers.filter((server) => { - if (server.subscriptionId === msg.subscription_id) { - subscription.queued.closers.push(server.serverId); - return false; - } - else { - return true; - } - }); - if (subscription.trackedServers.length !== expectedNewLength) { - return; - } - if (subscription.trackedServers.length <= 0) { - this.timedCache.add(subscription); - clearTimeout(subscription.timeoutId); - this.callOnClosedHandlers(subscription); - delete this.subscriptionsList[subLocalKey]; - } - delete this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - }; - callOnClosedHandlers(subscription, reason) { - const closersCount = subscription.queued.closers.length; - const closingServerId = (closersCount > 0) ? subscription.queued.closers[closersCount - 1] : null; - let closingServer; - if (closingServerId !== undefined && typeof closingServerId === "string") { - closingServer = this.repository.getServerById(closingServerId)?.instance ?? {}; - } - subscription.handlers.onClosed.forEach((callback) => { - if (typeof callback !== "function") { - return; - } - callback({ - message: reason || ON_CLOSE_MSG_SERVER_INIT, - requestArguments: subscription.params.arguments || {}, - server: closingServer, - stream: subscription.method, - }); - }); - } - closeSubscription(subLocalKey) { - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - subscription.trackedServers.forEach((server) => { - if (typeof server.subscriptionId === "undefined") { - return; - } - subscription.queued.closers.push(server.serverId); - this.session.sendFireAndForget({ - type: "unsubscribe", - subscription_id: server.subscriptionId, - reason_uri: "", - reason: ON_CLOSE_MSG_CLIENT_INIT, - }).catch((err) => { - this.logger.warn(`Error sending unsubscribe for subscription id ${server.subscriptionId}: ${JSON.stringify(err)}`); - }); - delete this.subscriptionIdToLocalKeyMap[server.subscriptionId]; - }); - subscription.trackedServers = []; - this.callOnClosedHandlers(subscription, ON_CLOSE_MSG_CLIENT_INIT); - delete this.subscriptionsList[subLocalKey]; - } - } - - class ClientProtocol { - session; - repository; - logger; - streaming; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("peer-added", (msg) => this.handlePeerAdded(msg)); - session.on("peer-removed", (msg) => this.handlePeerRemoved(msg)); - session.on("methods-added", (msg) => this.handleMethodsAddedMessage(msg)); - session.on("methods-removed", (msg) => this.handleMethodsRemovedMessage(msg)); - this.streaming = new ClientStreaming(session, repository, logger); - } - subscribe(stream, options, targetServers, success, error, existingSub) { - this.streaming.subscribe(stream, options, targetServers, success, error, existingSub); - } - invoke(id, method, args, target) { - const serverId = target.id; - const methodId = method.gatewayId; - const msg = { - type: "call", - server_id: serverId, - method_id: methodId, - arguments_kv: args, - }; - return this.session.send(msg, { invocationId: id, serverId }) - .then((m) => this.handleResultMessage(m)) - .catch((err) => this.handleInvocationError(err)); - } - drainSubscriptions() { - return this.streaming.drainSubscriptions(); - } - drainSubscriptionsCache() { - return this.streaming.drainSubscriptionsCache(); - } - handlePeerAdded(msg) { - const newPeerId = msg.new_peer_id; - const remoteId = msg.identity; - const isLocal = msg.meta ? msg.meta.local : true; - const pid = Number(remoteId.process); - const serverInfo = { - machine: remoteId.machine, - pid: isNaN(pid) ? remoteId.process : pid, - instance: remoteId.instance, - application: remoteId.application, - applicationName: remoteId.applicationName, - environment: remoteId.environment, - region: remoteId.region, - user: remoteId.user, - windowId: remoteId.windowId, - peerId: newPeerId, - api: remoteId.api, - isLocal - }; - this.repository.addServer(serverInfo, newPeerId); - } - handlePeerRemoved(msg) { - const removedPeerId = msg.removed_id; - const reason = msg.reason; - this.repository.removeServerById(removedPeerId, reason); - } - handleMethodsAddedMessage(msg) { - const serverId = msg.server_id; - const methods = msg.methods; - methods.forEach((method) => { - this.repository.addServerMethod(serverId, method); - }); - } - handleMethodsRemovedMessage(msg) { - const serverId = msg.server_id; - const methodIdList = msg.methods; - const server = this.repository.getServerById(serverId); - if (server) { - const serverMethodKeys = Object.keys(server.methods); - serverMethodKeys.forEach((methodKey) => { - const method = server.methods[methodKey]; - if (methodIdList.indexOf(method.gatewayId) > -1) { - this.repository.removeServerMethod(serverId, methodKey); - } - }); - } - } - handleResultMessage(msg) { - const invocationId = msg._tag.invocationId; - const result = msg.result; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - return { - invocationId, - result, - instance: server?.instance, - status: InvokeStatus.Success, - message: "" - }; - } - handleInvocationError(msg) { - this.logger.debug(`handle invocation error ${JSON.stringify(msg)}`); - if ("_tag" in msg) { - const invocationId = msg._tag.invocationId; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - const message = msg.reason; - const context = msg.context; - return { - invocationId, - result: context, - instance: server?.instance, - status: InvokeStatus.Error, - message - }; - } - else { - return { - invocationId: "", - message: msg.message, - status: InvokeStatus.Error, - error: msg - }; - } - } - } - - function gW3ProtocolFactory (instance, connection, clientRepository, serverRepository, libConfig, interop) { - const logger = libConfig.logger.subLogger("gw3-protocol"); - let resolveReadyPromise; - const readyPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - const session = connection.domain("agm", ["subscribed"]); - const server = new ServerProtocol(session, clientRepository, serverRepository, logger.subLogger("server")); - const client = new ClientProtocol(session, clientRepository, logger.subLogger("client")); - async function handleReconnect() { - logger.info("reconnected - will replay registered methods and subscriptions"); - client.drainSubscriptionsCache().forEach((sub) => { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to soft-re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`soft-subscribing to method ${methodInfo.name} DONE`)).catch((error) => logger.warn(`subscribing to method ${methodInfo.name} failed: ${JSON.stringify(error)}}`)); - }); - const reconnectionPromises = []; - const existingSubscriptions = client.drainSubscriptions(); - for (const sub of existingSubscriptions) { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - reconnectionPromises.push(interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`subscribing to method ${methodInfo.name} DONE`))); - } - const registeredMethods = serverRepository.getList(); - serverRepository.reset(); - for (const method of registeredMethods) { - const def = method.definition; - if (method.stream) { - reconnectionPromises.push(interop.server.createStream(def, method.streamCallbacks, undefined, undefined, method.stream) - .then(() => logger.info(`subscribing to method ${def.name} DONE`)) - .catch(() => logger.warn(`subscribing to method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallback) { - reconnectionPromises.push(interop.register(def, method.theFunction.userCallback) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallbackAsync) { - reconnectionPromises.push(interop.registerAsync(def, method.theFunction.userCallbackAsync) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - } - await Promise.all(reconnectionPromises); - logger.info("Interop is re-announced"); - } - function handleInitialJoin() { - if (resolveReadyPromise) { - resolveReadyPromise({ - client, - server, - }); - resolveReadyPromise = undefined; - } - } - session.onJoined((reconnect) => { - clientRepository.addServer(instance, connection.peerId); - if (reconnect) { - handleReconnect().then(() => connection.setLibReAnnounced({ name: "interop" })).catch((error) => logger.warn(`Error while re-announcing interop: ${JSON.stringify(error)}`)); - } - else { - handleInitialJoin(); - } - }); - session.onLeft(() => { - clientRepository.reset(); - }); - session.join(); - return readyPromise; - } - - class Interop { - instance; - readyPromise; - client; - server; - unwrappedInstance; - protocol; - clientRepository; - serverRepository; - constructor(configuration) { - if (typeof configuration === "undefined") { - throw new Error("configuration is required"); - } - if (typeof configuration.connection === "undefined") { - throw new Error("configuration.connections is required"); - } - const connection = configuration.connection; - if (typeof configuration.methodResponseTimeout !== "number") { - configuration.methodResponseTimeout = 30 * 1000; - } - if (typeof configuration.waitTimeoutMs !== "number") { - configuration.waitTimeoutMs = 30 * 1000; - } - this.unwrappedInstance = new InstanceWrapper(this, undefined, connection); - this.instance = this.unwrappedInstance.unwrap(); - this.clientRepository = new ClientRepository(configuration.logger.subLogger("cRep"), this); - this.serverRepository = new ServerRepository(); - let protocolPromise; - if (connection.protocolVersion === 3) { - protocolPromise = gW3ProtocolFactory(this.instance, connection, this.clientRepository, this.serverRepository, configuration, this); - } - else { - throw new Error(`protocol ${connection.protocolVersion} not supported`); - } - this.readyPromise = protocolPromise.then((protocol) => { - this.protocol = protocol; - this.client = new Client(this.protocol, this.clientRepository, this.instance, configuration); - this.server = new Server(this.protocol, this.serverRepository); - return this; - }); - } - ready() { - return this.readyPromise; - } - serverRemoved(callback) { - return this.client.serverRemoved(callback); - } - serverAdded(callback) { - return this.client.serverAdded(callback); - } - serverMethodRemoved(callback) { - return this.client.serverMethodRemoved(callback); - } - serverMethodAdded(callback) { - return this.client.serverMethodAdded(callback); - } - methodRemoved(callback) { - return this.client.methodRemoved(callback); - } - methodAdded(callback) { - return this.client.methodAdded(callback); - } - methodsForInstance(instance) { - return this.client.methodsForInstance(instance); - } - methods(methodFilter) { - return this.client.methods(methodFilter); - } - servers(methodFilter) { - return this.client.servers(methodFilter); - } - subscribe(method, options, successCallback, errorCallback) { - return this.client.subscribe(method, options, successCallback, errorCallback); - } - createStream(streamDef, callbacks, successCallback, errorCallback) { - return this.server.createStream(streamDef, callbacks, successCallback, errorCallback); - } - unregister(methodFilter) { - return this.server.unregister(methodFilter); - } - registerAsync(methodDefinition, callback) { - return this.server.registerAsync(methodDefinition, callback); - } - register(methodDefinition, callback) { - return this.server.register(methodDefinition, callback); - } - invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - return this.client.invoke(methodFilter, argumentObj, target, additionalOptions, success, error); - } - waitForMethod(name) { - const pw = new PromiseWrapper(); - const unsubscribe = this.client.methodAdded((m) => { - if (m.name === name) { - unsubscribe(); - pw.resolve(m); - } - }); - return pw.promise; - } - } - - const successMessages = ["subscribed", "success"]; - class MessageBus { - connection; - logger; - peerId; - session; - subscriptions; - readyPromise; - constructor(connection, logger) { - this.connection = connection; - this.logger = logger; - this.peerId = connection.peerId; - this.subscriptions = []; - this.session = connection.domain("bus", successMessages); - this.readyPromise = this.session.join(); - this.readyPromise.then(() => { - this.watchOnEvent(); - }); - } - ready() { - return this.readyPromise; - } - publish = (topic, data, options) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "publish", - topic, - data, - peer_id: this.peerId, - routing_key: routingKey, - target_identity: target - }); - this.session.send(args) - .catch((err) => { - this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`); - }); - }; - subscribe = (topic, callback, options) => { - return new Promise((resolve, reject) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "subscribe", - topic, - peer_id: this.peerId, - routing_key: routingKey, - source: target - }); - this.session.send(args) - .then((response) => { - const { subscription_id } = response; - this.subscriptions.push({ subscription_id, topic, callback, source: target }); - resolve({ - unsubscribe: () => { - this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId }) - .then(() => { - this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id); - }).catch((err) => { - this.logger.warn(`Failed to send unsubscribe request for ${subscription_id}: ${JSON.stringify(err)}`); - }); - return Promise.resolve(); - } - }); - }) - .catch((error) => reject(error)); - }); - }; - watchOnEvent = () => { - this.session.on("event", (args) => { - const { data, subscription_id } = args; - const source = args["publisher-identity"]; - const subscription = this.subscriptions.find((s) => s.subscription_id === subscription_id); - if (subscription) { - if (!subscription.source) { - subscription.callback(data, subscription.topic, source); - } - else { - if (this.keysMatch(subscription.source, source)) { - subscription.callback(data, subscription.topic, source); - } - } - } - }); - }; - removeEmptyValues(obj) { - const cleaned = {}; - Object.keys(obj).forEach((key) => { - if (obj[key] !== undefined && obj[key] !== null) { - cleaned[key] = obj[key]; - } - }); - return cleaned; - } - keysMatch(obj1, obj2) { - const keysObj1 = Object.keys(obj1); - let allMatch = true; - keysObj1.forEach((key) => { - if (obj1[key] !== obj2[key]) { - allMatch = false; - } - }); - return allMatch; - } - } - - const IOConnectCoreFactory = (userConfig, ext) => { - const iodesktop = typeof window === "object" ? (window.iodesktop ?? window.glue42gd) : undefined; - const preloadPromise = typeof window === "object" ? (window.gdPreloadPromise ?? Promise.resolve()) : Promise.resolve(); - const glueInitTimer = timer("glue"); - userConfig = userConfig || {}; - ext = ext || {}; - const internalConfig = prepareConfig(userConfig, ext, iodesktop); - let _connection; - let _interop; - let _logger; - let _metrics; - let _contexts; - let _bus; - let _allowTrace; - const libs = {}; - function registerLib(name, inner, t) { - _allowTrace = _logger.canPublish("trace"); - if (_allowTrace) { - _logger.trace(`registering ${name} module`); - } - const done = (e) => { - inner.initTime = t.stop(); - inner.initEndTime = t.endTime; - inner.marks = t.marks; - if (!_allowTrace) { - return; - } - const traceMessage = e ? - `${name} failed - ${e.message}` : - `${name} is ready - ${t.endTime - t.startTime}`; - _logger.trace(traceMessage); - }; - inner.initStartTime = t.startTime; - if (inner.ready) { - inner.ready() - .then(() => { - done(); - }) - .catch((e) => { - const error = typeof e === "string" ? new Error(e) : e; - done(error); - }); - } - else { - done(); - } - if (!Array.isArray(name)) { - name = [name]; - } - name.forEach((n) => { - libs[n] = inner; - IOConnectCoreFactory[n] = inner; - }); - } - function setupConnection() { - const initTimer = timer("connection"); - _connection = new Connection(internalConfig.connection, _logger.subLogger("connection")); - let authPromise = Promise.resolve(internalConfig.auth); - if (internalConfig.connection && !internalConfig.auth) { - if (iodesktop) { - authPromise = iodesktop.getGWToken() - .then((token) => { - return { - gatewayToken: token - }; - }); - } - else if (typeof window !== "undefined" && window?.glue42electron) { - if (typeof window.glue42electron.gwToken === "string") { - authPromise = Promise.resolve({ - gatewayToken: window.glue42electron.gwToken - }); - } - } - else { - authPromise = Promise.reject("You need to provide auth information"); - } - } - return authPromise - .then((authConfig) => { - initTimer.mark("auth-promise-resolved"); - let authRequest; - if (Object.prototype.toString.call(authConfig) === "[object Object]") { - authRequest = authConfig; - } - else { - throw new Error("Invalid auth object - " + JSON.stringify(authConfig)); - } - return _connection.login(authRequest); - }) - .then(() => { - registerLib("connection", _connection, initTimer); - return internalConfig; - }) - .catch((e) => { - if (_connection) { - _connection.logout(); - } - throw e; - }); - } - function setupLogger() { - const initTimer = timer("logger"); - _logger = new Logger(`${internalConfig.connection.identity?.application}`, undefined, internalConfig.customLogger); - _logger.consoleLevel(internalConfig.logger.console); - _logger.publishLevel(internalConfig.logger.publish); - if (_logger.canPublish("debug")) { - _logger.debug("initializing glue..."); - } - registerLib("logger", _logger, initTimer); - return Promise.resolve(undefined); - } - function setupMetrics() { - const initTimer = timer("metrics"); - const config = internalConfig.metrics; - const metricsPublishingEnabledFunc = iodesktop?.getMetricsPublishingEnabled; - const identity = internalConfig.connection.identity; - const canUpdateMetric = metricsPublishingEnabledFunc ? metricsPublishingEnabledFunc : () => true; - const disableAutoAppSystem = (typeof config !== "boolean" && config.disableAutoAppSystem) ?? false; - _metrics = metrics({ - connection: config ? _connection : undefined, - logger: _logger.subLogger("metrics"), - canUpdateMetric, - system: "Glue42", - service: identity?.service ?? iodesktop?.applicationName ?? internalConfig.application, - instance: identity?.instance ?? identity?.windowId ?? nanoid(10), - disableAutoAppSystem, - pagePerformanceMetrics: typeof config !== "boolean" ? config?.pagePerformanceMetrics : undefined - }); - registerLib("metrics", _metrics, initTimer); - return Promise.resolve(); - } - function setupInterop() { - const initTimer = timer("interop"); - const agmConfig = { - connection: _connection, - logger: _logger.subLogger("interop"), - }; - _interop = new Interop(agmConfig); - Logger.Interop = _interop; - registerLib(["interop", "agm"], _interop, initTimer); - return Promise.resolve(); - } - function setupContexts() { - const hasActivities = (internalConfig.activities && _connection.protocolVersion === 3); - const needsContexts = internalConfig.contexts || hasActivities; - if (needsContexts) { - const initTimer = timer("contexts"); - _contexts = new ContextsModule({ - connection: _connection, - logger: _logger.subLogger("contexts"), - trackAllContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.trackAllContexts : false, - reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false, - subscribeOnGet: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnGet : true, - subscribeOnUpdate: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnUpdate : true, - onlyReAnnounceSubscribedContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.onlyReAnnounceSubscribedContexts : true - }); - registerLib("contexts", _contexts, initTimer); - } - else { - const replayer = _connection.replayer; - if (replayer) { - replayer.drain(ContextMessageReplaySpec.name); - } - } - return Promise.resolve(); - } - async function setupBus() { - if (!internalConfig.bus) { - return Promise.resolve(); - } - const initTimer = timer("bus"); - _bus = new MessageBus(_connection, _logger.subLogger("bus")); - registerLib("bus", _bus, initTimer); - return Promise.resolve(); - } - function setupExternalLibs(externalLibs) { - try { - externalLibs.forEach((lib) => { - setupExternalLib(lib.name, lib.create); - }); - return Promise.resolve(); - } - catch (e) { - return Promise.reject(e); - } - } - function setupExternalLib(name, createCallback) { - const initTimer = timer(name); - const lib = createCallback(libs); - if (lib) { - registerLib(name, lib, initTimer); - } - } - function waitForLibs() { - const libsReadyPromises = Object.keys(libs).map((key) => { - const lib = libs[key]; - return lib.ready ? - lib.ready() : Promise.resolve(); - }); - return Promise.all(libsReadyPromises); - } - function constructGlueObject() { - const feedbackFunc = (feedbackInfo) => { - if (!_interop) { - return; - } - _interop.invoke("T42.ACS.Feedback", feedbackInfo, "best"); - }; - const info = { - coreVersion: version, - version: internalConfig.version - }; - glueInitTimer.stop(); - const glue = { - feedback: feedbackFunc, - info, - logger: _logger, - interop: _interop, - agm: _interop, - connection: _connection, - metrics: _metrics, - contexts: _contexts, - bus: _bus, - version: internalConfig.version, - userConfig, - done: () => { - _logger?.info("done called by user..."); - return _connection.logout(); - } - }; - glue.performance = { - get glueVer() { - return internalConfig.version; - }, - get glueConfig() { - return JSON.stringify(userConfig); - }, - get browser() { - return window.performance.timing.toJSON(); - }, - get memory() { - return window.performance.memory; - }, - get initTimes() { - const all = getAllTimers(); - return Object.keys(all).map((key) => { - const t = all[key]; - return { - name: key, - duration: t.endTime - t.startTime, - marks: t.marks, - startTime: t.startTime, - endTime: t.endTime - }; - }); - } - }; - Object.keys(libs).forEach((key) => { - const lib = libs[key]; - glue[key] = lib; - }); - glue.config = {}; - Object.keys(internalConfig).forEach((k) => { - glue.config[k] = internalConfig[k]; - }); - if (ext && ext.extOptions) { - Object.keys(ext.extOptions).forEach((k) => { - glue.config[k] = ext?.extOptions[k]; - }); - } - if (ext?.enrichGlue) { - ext.enrichGlue(glue); - } - if (iodesktop && iodesktop.updatePerfData) { - iodesktop.updatePerfData(glue.performance); - } - if (glue.agm) { - const deprecatedDecorator = (fn, wrong, proper) => { - return function () { - glue.logger.warn(`glue.js - 'glue.agm.${wrong}' method is deprecated, use 'glue.interop.${proper}' instead.`); - return fn.apply(glue.agm, arguments); - }; - }; - const agmAny = glue.agm; - agmAny.method_added = deprecatedDecorator(glue.agm.methodAdded, "method_added", "methodAdded"); - agmAny.method_removed = deprecatedDecorator(glue.agm.methodRemoved, "method_removed", "methodRemoved"); - agmAny.server_added = deprecatedDecorator(glue.agm.serverAdded, "server_added", "serverAdded"); - agmAny.server_method_aded = deprecatedDecorator(glue.agm.serverMethodAdded, "server_method_aded", "serverMethodAdded"); - agmAny.server_method_removed = deprecatedDecorator(glue.agm.serverMethodRemoved, "server_method_removed", "serverMethodRemoved"); - } - return glue; - } - async function registerInstanceIfNeeded() { - const RegisterInstanceMethodName = "T42.ACS.RegisterInstance"; - if (Utils.isNode() && typeof process.env._GD_STARTING_CONTEXT_ === "undefined" && typeof userConfig?.application !== "undefined") { - const isMethodAvailable = _interop.methods({ name: RegisterInstanceMethodName }).length > 0; - if (isMethodAvailable) { - try { - await _interop.invoke(RegisterInstanceMethodName, { appName: userConfig?.application, pid: process.pid }); - } - catch (error) { - const typedError = error; - _logger.error(`Cannot register as an instance: ${JSON.stringify(typedError.message)}`); - } - } - } - } - return preloadPromise - .then(setupLogger) - .then(setupConnection) - .then(() => Promise.all([setupMetrics(), setupInterop(), setupContexts(), setupBus()])) - .then(() => _interop.readyPromise) - .then(() => registerInstanceIfNeeded()) - .then(() => { - return setupExternalLibs(internalConfig.libs || []); - }) - .then(waitForLibs) - .then(constructGlueObject) - .catch((err) => { - return Promise.reject({ - err, - libs - }); - }); - }; - if (typeof window !== "undefined") { - window.IOConnectCore = IOConnectCoreFactory; - } - IOConnectCoreFactory.version = version; - IOConnectCoreFactory.default = IOConnectCoreFactory; - - const iOConnectBrowserFactory = createFactoryFunction(IOConnectCoreFactory); - if (typeof window !== "undefined") { - const windowAny = window; - windowAny.IOBrowser = iOConnectBrowserFactory; - delete windowAny.GlueCore; - delete windowAny.IOConnectCore; - } - const legacyGlobal = window.glue42gd || window.glue42core; - const ioGlobal = window.iodesktop || window.iobrowser; - if (!legacyGlobal && !ioGlobal) { - window.iobrowser = { webStarted: false }; - } - if (!window.iodesktop && !window.iobrowser.system) { - window.iobrowser.system = setupGlobalSystem(); - } - iOConnectBrowserFactory.version = version$1; - - return iOConnectBrowserFactory; - -})); -//# sourceMappingURL=browser.umd.js.map diff --git a/javascript/solution/stocks/lib/workspaces.umd.js b/javascript/solution/stocks/lib/workspaces.umd.js deleted file mode 100644 index 8d833a0..0000000 --- a/javascript/solution/stocks/lib/workspaces.umd.js +++ /dev/null @@ -1,5618 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.workspaces = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder.oneOf; - /** See `Decoder.union` */ - Decoder.union; - /** See `Decoder.intersection` */ - var intersection = Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - Decoder.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder.lazy; - - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number"); - const positiveNumberDecoder = number().where((num) => num > 0, "Expected a positive number"); - const windowDragModeDecoder = oneOf(constant("keepInside"), constant("autoEject")); - const isWindowInSwimlaneResultDecoder = object({ - inWorkspace: boolean() - }); - const frameVisibilityResultDecoder = object({ - isVisible: boolean() - }); - const iconDecoder = object({ - base64Image: nonEmptyStringDecoder - }); - const setIconArgumentsDecoder = object({ - icon: iconDecoder, - frameId: nonEmptyStringDecoder - }); - const allParentDecoder = oneOf(constant("workspace"), constant("row"), constant("column"), constant("group")); - const subParentDecoder = oneOf(constant("row"), constant("column"), constant("group")); - const frameStateDecoder = oneOf(constant("maximized"), constant("minimized"), constant("normal")); - const loadingAnimationTypeDecoder = oneOf(constant("workspace")); - const checkThrowCallback = (callback, allowUndefined) => { - const argumentType = typeof callback; - if (allowUndefined && argumentType !== "function" && argumentType !== "undefined") { - throw new Error(`Provided argument must be either undefined or of type function, provided: ${argumentType}`); - } - if (!allowUndefined && argumentType !== "function") { - throw new Error(`Provided argument must be of type function, provided: ${argumentType}`); - } - }; - const workspaceBuilderCreateConfigDecoder = optional(object({ - saveLayout: optional(boolean()) - })); - const deleteLayoutConfigDecoder = object({ - name: nonEmptyStringDecoder - }); - const windowDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const groupDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropHeader: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()) - }); - const rowDefinitionConfigDecoder = object({ - minHeight: optional(number()), - maxHeight: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const columnDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const swimlaneWindowDefinitionDecoder = object({ - type: optional(constant("window")), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const strictSwimlaneWindowDefinitionDecoder = object({ - type: constant("window"), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const parentDefinitionDecoder = optional(object({ - type: optional(subParentDecoder), - children: optional(lazy(() => array(oneOf(swimlaneWindowDefinitionDecoder, parentDefinitionDecoder)))), - config: optional(anyJson()) - })); - const strictColumnDefinitionDecoder = object({ - type: constant("column"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(columnDefinitionConfigDecoder) - }); - const strictRowDefinitionDecoder = object({ - type: constant("row"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(rowDefinitionConfigDecoder) - }); - const strictGroupDefinitionDecoder = object({ - type: constant("group"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(groupDefinitionConfigDecoder) - }); - const strictParentDefinitionDecoder = oneOf(strictGroupDefinitionDecoder, strictColumnDefinitionDecoder, strictRowDefinitionDecoder); - oneOf(string().where((s) => s.toLowerCase() === "maximized", "Expected a case insensitive variation of 'maximized'"), string().where((s) => s.toLowerCase() === "normal", "Expected a case insensitive variation of 'normal'")); - const newFrameConfigDecoder = object({ - bounds: optional(object({ - left: optional(number()), - top: optional(number()), - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - })), - isVisible: optional(boolean()), - frameId: optional(nonEmptyStringDecoder) - }); - const loadingStrategyDecoder = oneOf(constant("direct"), constant("delayed"), constant("lazy")); - const restoreWorkspaceConfigDecoder = optional(object({ - app: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - loadingStrategy: optional(loadingStrategyDecoder), - title: optional(nonEmptyStringDecoder), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - frameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - lockdown: optional(boolean()), - activateFrame: optional(boolean()), - newFrame: optional(oneOf(newFrameConfigDecoder, boolean())), - noTabHeader: optional(boolean()), - inMemoryLayout: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - allowSystemHibernation: optional(boolean()) - })); - const openWorkspaceConfigDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const workspaceDefinitionDecoder = object({ - children: optional(array(oneOf(swimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder))), - context: optional(anyJson()), - config: optional(object({ - title: optional(nonEmptyStringDecoder), - position: optional(nonNegativeNumberDecoder), - isFocused: optional(boolean()), - noTabHeader: optional(boolean()), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - loadingStrategy: optional(loadingStrategyDecoder), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showCloseButton: optional(boolean()), - allowSplitters: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - windowDragMode: optional(windowDragModeDecoder) - })), - frame: optional(object({ - activate: optional(boolean()), - reuseFrameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - newFrame: optional(oneOf(boolean(), newFrameConfigDecoder)) - })) - }); - const workspaceSelectorDecoder = object({ - workspaceId: nonEmptyStringDecoder - }); - const restoreWorkspaceDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const emptyFrameDefinitionDecoder = optional(object({ - applicationName: optional(string()), - frameConfig: optional(newFrameConfigDecoder), - context: optional(object()), - layoutComponentId: optional(nonEmptyStringDecoder) - })); - const frameInitConfigDecoder = object({ - workspaces: array(oneOf(optional(workspaceDefinitionDecoder), optional(restoreWorkspaceDefinitionDecoder))) - }); - const frameInitProtocolConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaces: array(oneOf(workspaceDefinitionDecoder, restoreWorkspaceDefinitionDecoder)) - }); - const builderConfigDecoder = object({ - type: allParentDecoder, - definition: optional(oneOf(workspaceDefinitionDecoder, parentDefinitionDecoder)) - }); - const workspaceCreateConfigDecoder = intersection(workspaceDefinitionDecoder, object({ - saveConfig: optional(object({ - saveLayout: optional(boolean()) - })) - })); - const getFrameSummaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const frameInitializationContextDecoder = object({ - context: optional(object()) - }); - const frameSummaryDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - object({ - type: subParentDecoder, - id: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number() - }); - const eventTypeDecoder = oneOf(constant("frame"), constant("workspace"), constant("container"), constant("window")); - const streamRequestArgumentsDecoder = object({ - type: eventTypeDecoder, - branch: nonEmptyStringDecoder - }); - const workspaceEventActionDecoder = oneOf(constant("opened"), constant("closing"), constant("closed"), constant("focus"), constant("added"), constant("loaded"), constant("removed"), constant("childrenUpdate"), constant("containerChange"), constant("maximized"), constant("restored"), constant("minimized"), constant("normal"), constant("selected"), constant("lock-configuration-changed"), constant("hibernated"), constant("resumed")); - const workspaceConfigResultDecoder = object({ - frameId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder, - positionIndex: nonNegativeNumberDecoder, - name: nonEmptyStringDecoder, - layoutName: optional(nonEmptyStringDecoder), - isHibernated: optional(boolean()), - isSelected: optional(boolean()), - allowDrop: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - widthInPx: optional(number()), - heightInPx: optional(number()), - isPinned: optional(boolean()), - windowDragMode: optional(windowDragModeDecoder), - loadingStrategy: optional(loadingStrategyDecoder) - }); - const baseChildSnapshotConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number(), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()) - }); - const parentSnapshotConfigDecoder = anyJson(); - const swimlaneWindowSnapshotConfigDecoder = intersection(baseChildSnapshotConfigDecoder, object({ - windowId: optional(nonEmptyStringDecoder), - isMaximized: optional(boolean()), - isFocused: boolean(), - isSelected: optional(boolean()), - title: optional(string()), - appName: optional(nonEmptyStringDecoder), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - widthInPx: optional(number()), - heightInPx: optional(number()), - context: optional(anyJson()) - })); - const customWorkspaceSubParentSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: parentSnapshotConfigDecoder, - children: optional(lazy(() => array(customWorkspaceChildSnapshotDecoder))), - type: oneOf(constant("row"), constant("column"), constant("group")) - }); - const customWorkspaceWindowSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: swimlaneWindowSnapshotConfigDecoder, - type: constant("window") - }); - const customWorkspaceChildSnapshotDecoder = oneOf(customWorkspaceWindowSnapshotDecoder, customWorkspaceSubParentSnapshotDecoder); - const childSnapshotResultDecoder = customWorkspaceChildSnapshotDecoder; - const workspaceSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder, - children: array(childSnapshotResultDecoder), - frameSummary: frameSummaryDecoder, - context: optional(anyJson()) - }); - const windowLayoutItemDecoder = object({ - type: constant("window"), - config: object({ - appName: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - url: optional(nonEmptyStringDecoder), - title: optional(string()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - isMaximized: optional(boolean()) - }) - }); - const groupLayoutItemDecoder = object({ - type: constant("group"), - config: anyJson(), - children: array(oneOf(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object({ - type: constant("column"), - config: anyJson(), - children: array(oneOf(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object({ - type: constant("row"), - config: anyJson(), - children: array(oneOf(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutDecoder = object({ - name: nonEmptyStringDecoder, - type: constant("Workspace"), - metadata: optional(anyJson()), - components: array(object({ - type: constant("Workspace"), - application: optional(string()), - state: object({ - config: anyJson(), - context: anyJson(), - children: array(oneOf(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }) - })) - }); - const workspacesImportLayoutDecoder = object({ - layout: workspaceLayoutDecoder, - mode: oneOf(constant("replace"), constant("merge")) - }); - const workspacesImportLayoutsDecoder = object({ - layouts: array(workspaceLayoutDecoder), - mode: oneOf(constant("replace"), constant("merge")) - }); - const exportedLayoutsResultDecoder = object({ - layouts: array(workspaceLayoutDecoder) - }); - const frameSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - const frameSummariesResultDecoder = object({ - summaries: array(frameSummaryResultDecoder) - }); - const workspaceSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder - }); - const workspaceSummariesResultDecoder = object({ - summaries: array(workspaceSummaryResultDecoder) - }); - const frameSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: anyJson(), - workspaces: array(workspaceSnapshotResultDecoder) - }); - const layoutSummaryDecoder = object({ - name: nonEmptyStringDecoder, - applicationName: optional(string()) - }); - const layoutSummariesDecoder = object({ - summaries: array(layoutSummaryDecoder) - }); - const simpleWindowOperationSuccessResultDecoder = object({ - windowId: nonEmptyStringDecoder - }); - const voidResultDecoder = anyJson(); - const frameStateResultDecoder = object({ - state: frameStateDecoder - }); - const frameBoundsDecoder = object({ - top: number(), - left: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const frameBoundsResultDecoder = object({ - bounds: frameBoundsDecoder - }); - const getWorkspaceIconResultDecoder = object({ - icon: optional(nonEmptyStringDecoder) - }); - const getPlatformFrameIdResultDecoder = object({ - id: optional(nonEmptyStringDecoder) - }); - const operationCheckResultDecoder = object({ - isSupported: boolean() - }); - const resizeConfigDecoder = object({ - width: optional(positiveNumberDecoder), - height: optional(positiveNumberDecoder), - relative: optional(boolean()) - }); - const moveConfigDecoder = object({ - top: optional(number()), - left: optional(number()), - relative: optional(boolean()) - }); - const simpleItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const closeOptionsDecoder = object({ - allowPrevent: optional(boolean()), - showDialog: optional(boolean()), - }); - const closeItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - closeOptions: optional(closeOptionsDecoder) - }); - const frameSnapshotConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - excludeIds: optional(boolean()) - }); - const frameStateConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - requestedState: frameStateDecoder - }); - const setItemTitleConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder - }); - const moveWindowConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - containerId: nonEmptyStringDecoder - }); - const resizeItemConfigDecoder = intersection(simpleItemConfigDecoder, resizeConfigDecoder); - const setMaximizationBoundaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - enabled: boolean() - }); - const moveFrameConfigDecoder = intersection(simpleItemConfigDecoder, moveConfigDecoder); - object({ - id: nonEmptyStringDecoder, - type: subParentDecoder - }); - const addWindowConfigDecoder = object({ - definition: swimlaneWindowDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addContainerConfigDecoder = object({ - definition: strictParentDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addItemResultDecoder = object({ - itemId: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder) - }); - const pingResultDecoder = object({ - live: boolean() - }); - const bundleWorkspaceConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - workspaceId: nonEmptyStringDecoder - }); - const bundleItemConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - itemId: nonEmptyStringDecoder - }); - const containerSummaryResultDecoder = object({ - itemId: nonEmptyStringDecoder, - config: parentSnapshotConfigDecoder - }); - const frameStreamDataDecoder = object({ - frameSummary: frameSummaryDecoder, - frameBounds: optional(frameBoundsDecoder) - }); - const workspaceStreamDataDecoder = object({ - workspaceSummary: workspaceSummaryResultDecoder, - frameSummary: frameSummaryDecoder, - workspaceSnapshot: optional(workspaceSnapshotResultDecoder), - frameBounds: optional(frameBoundsDecoder) - }); - const containerStreamDataDecoder = object({ - containerSummary: containerSummaryResultDecoder - }); - const windowStreamDataDecoder = object({ - windowSummary: object({ - itemId: nonEmptyStringDecoder, - parentId: nonEmptyStringDecoder, - config: swimlaneWindowSnapshotConfigDecoder - }) - }); - const workspaceLayoutSaveConfigDecoder = object({ - name: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - saveContext: optional(boolean()), - allowMultiple: optional(boolean()), - metadata: optional(object()) - }); - const workspaceLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - }); - const lockWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - config: optional(workspaceLockConfigDecoder) - }); - const windowLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const elementResizeConfigDecoder = object({ - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - }); - const lockWindowDecoder = object({ - windowPlacementId: nonEmptyStringDecoder, - config: optional(windowLockConfigDecoder) - }); - const rowLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const columnLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const groupLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - allowDropHeader: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()), - }); - const lockRowDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("row"), - config: optional(rowLockConfigDecoder) - }); - const lockColumnDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("column"), - config: optional(columnLockConfigDecoder) - }); - const lockGroupDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("group"), - config: optional(groupLockConfigDecoder) - }); - const lockContainerDecoder = oneOf(lockRowDecoder, lockColumnDecoder, lockGroupDecoder); - const pinWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const setWorkspaceIconDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const workspacePinOptionsDecoder = optional(object({ - icon: optional(nonEmptyStringDecoder) - })); - const frameShowConfigDecoder = optional(object({ - activate: optional(boolean()) - })); - const shortcutConfigDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const shortcutClickedDataDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const frameClosingDataDecoder = object({ - frameId: nonEmptyStringDecoder, - }); - const setMaximizationBoundaryAPIConfigDecoder = object({ - enabled: boolean() - }); - const loadingAnimationConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - type: loadingAnimationTypeDecoder - }); - const operationCheckConfigDecoder = object({ - operation: nonEmptyStringDecoder - }); - const setWindowDragModeDecoder = object({ - itemId: nonEmptyStringDecoder, - dragMode: windowDragModeDecoder - }); - const setLoadingStrategyDecoder = object({ - itemId: nonEmptyStringDecoder, - strategy: loadingStrategyDecoder - }); - const frameClosingResultDecoder = object({ - prevent: boolean() - }); - const sizeDecoder = object({ - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const boundsDecoder = object({ - left: number(), - top: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const popupTargetLocationDecoder = oneOf(constant("none"), constant("left"), constant("right"), constant("top"), constant("bottom")); - const popupConfigDecoder = object({ - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const ShowPopupConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const changeFrameVisibilityConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - activate: optional(boolean()), - isVisible: boolean() - }); - const frameDialogOptionsDecoder = object({ - mode: optional(oneOf(constant("Global"), constant("WindowContainer"))), - type: string(), - size: optional(sizeDecoder), - message: nonEmptyStringDecoder, - messageTitle: optional(nonEmptyStringDecoder), - movable: optional(boolean()), - transparent: optional(boolean()), - title: nonEmptyStringDecoder, - context: optional(anyJson()), - affirmativeButtonName: optional(nonEmptyStringDecoder), - showAffirmativeButton: optional(boolean()), - cancelButtonName: optional(nonEmptyStringDecoder), - showCancelButton: optional(boolean()), - negativeButtonName: optional(nonEmptyStringDecoder), - showNegativeButton: optional(boolean()), - defaultAction: optional(oneOf(constant("affirmative"), constant("negative"), constant("cancel"))), - timerDuration: optional(positiveNumberDecoder), - showTimer: optional(boolean()), - inputMaxLength: optional(positiveNumberDecoder), - inputPattern: optional(nonEmptyStringDecoder), - inputPatternErrorMessage: optional(nonEmptyStringDecoder), - inputPlaceholder: optional(string()), - blur: optional(boolean()) - }); - const showFrameDialogConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - options: frameDialogOptionsDecoder - }); - - const webPlatformMethodName = "T42.Web.Platform.Control"; - const webPlatformWspStreamName = "T42.Web.Platform.WSP.Stream"; - const OUTGOING_METHODS = { - control: { name: "T42.Workspaces.Control", isStream: false }, - frameStream: { name: "T42.Workspaces.Stream.Frame", isStream: true }, - workspaceStream: { name: "T42.Workspaces.Stream.Workspace", isStream: true }, - containerStream: { name: "T42.Workspaces.Stream.Container", isStream: true }, - windowStream: { name: "T42.Workspaces.Stream.Window", isStream: true } - }; - const INCOMING_METHODS = { - control: { name: "T42.Workspaces.Client.Control", isStream: false }, - }; - const STREAMS = { - frame: { name: "T42.Workspaces.Stream.Frame", payloadDecoder: frameStreamDataDecoder }, - workspace: { name: "T42.Workspaces.Stream.Workspace", payloadDecoder: workspaceStreamDataDecoder }, - container: { name: "T42.Workspaces.Stream.Container", payloadDecoder: containerStreamDataDecoder }, - window: { name: "T42.Workspaces.Stream.Window", payloadDecoder: windowStreamDataDecoder } - }; - const CLIENT_OPERATIONS = { - shortcutClicked: { name: "shortcutClicked", argsDecoder: shortcutClickedDataDecoder, resultDecoder: voidResultDecoder }, - frameClosing: { name: "frameClosing", argsDecoder: frameClosingDataDecoder, resultDecoder: frameClosingResultDecoder }, - }; - const OPERATIONS = { - ping: { name: "ping", resultDecoder: pingResultDecoder }, - isWindowInWorkspace: { name: "isWindowInWorkspace", argsDecoder: simpleItemConfigDecoder, resultDecoder: isWindowInSwimlaneResultDecoder }, - createWorkspace: { name: "createWorkspace", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: workspaceCreateConfigDecoder }, - createFrame: { name: "createFrame", resultDecoder: frameSummaryResultDecoder, argsDecoder: emptyFrameDefinitionDecoder }, - initFrame: { name: "initFrame", resultDecoder: voidResultDecoder, argsDecoder: frameInitProtocolConfigDecoder }, - getAllFramesSummaries: { name: "getAllFramesSummaries", resultDecoder: frameSummariesResultDecoder }, - getFrameSummary: { name: "getFrameSummary", resultDecoder: frameSummaryDecoder, argsDecoder: getFrameSummaryConfigDecoder }, - getAllWorkspacesSummaries: { name: "getAllWorkspacesSummaries", resultDecoder: workspaceSummariesResultDecoder }, - getWorkspaceSnapshot: { name: "getWorkspaceSnapshot", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: simpleItemConfigDecoder }, - getAllLayoutsSummaries: { name: "getAllLayoutsSummaries", resultDecoder: layoutSummariesDecoder }, - openWorkspace: { name: "openWorkspace", argsDecoder: openWorkspaceConfigDecoder, resultDecoder: workspaceSnapshotResultDecoder }, - deleteLayout: { name: "deleteLayout", resultDecoder: voidResultDecoder, argsDecoder: deleteLayoutConfigDecoder }, - saveLayout: { name: "saveLayout", resultDecoder: workspaceLayoutDecoder, argsDecoder: workspaceLayoutSaveConfigDecoder }, - importLayout: { name: "importLayout", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutDecoder }, - importLayouts: { name: "importLayouts", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutsDecoder }, - exportAllLayouts: { name: "exportAllLayouts", resultDecoder: exportedLayoutsResultDecoder }, - restoreItem: { name: "restoreItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - maximizeItem: { name: "maximizeItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - focusItem: { name: "focusItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeItem: { name: "closeItem", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeWorkspace: { name: "closeWorkspace", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - resizeItem: { name: "resizeItem", argsDecoder: resizeItemConfigDecoder, resultDecoder: voidResultDecoder }, - setMaximizationBoundary: { name: "setMaximizationBoundary", argsDecoder: setMaximizationBoundaryConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameState: { name: "changeFrameState", argsDecoder: frameStateConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameState: { name: "getFrameState", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameStateResultDecoder }, - getFrameBounds: { name: "getFrameBounds", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameBoundsResultDecoder }, - moveFrame: { name: "moveFrame", argsDecoder: moveFrameConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameSnapshot: { name: "getFrameSnapshot", argsDecoder: frameSnapshotConfigDecoder, resultDecoder: frameSnapshotResultDecoder }, - forceLoadWindow: { name: "forceLoadWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - ejectWindow: { name: "ejectWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - setItemTitle: { name: "setItemTitle", argsDecoder: setItemTitleConfigDecoder, resultDecoder: voidResultDecoder }, - moveWindowTo: { name: "moveWindowTo", argsDecoder: moveWindowConfigDecoder, resultDecoder: voidResultDecoder }, - addWindow: { name: "addWindow", argsDecoder: addWindowConfigDecoder, resultDecoder: addItemResultDecoder }, - addContainer: { name: "addContainer", argsDecoder: addContainerConfigDecoder, resultDecoder: addItemResultDecoder }, - bundleWorkspace: { name: "bundleWorkspace", argsDecoder: bundleWorkspaceConfigDecoder, resultDecoder: voidResultDecoder }, - bundleItem: { name: "bundleItem", argsDecoder: bundleItemConfigDecoder, resultDecoder: voidResultDecoder }, - hibernateWorkspace: { name: "hibernateWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - resumeWorkspace: { name: "resumeWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - lockWorkspace: { name: "lockWorkspace", argsDecoder: lockWorkspaceDecoder, resultDecoder: voidResultDecoder }, - lockWindow: { name: "lockWindow", argsDecoder: lockWindowDecoder, resultDecoder: voidResultDecoder }, - lockContainer: { name: "lockContainer", argsDecoder: lockContainerDecoder, resultDecoder: voidResultDecoder }, - pinWorkspace: { name: "pinWorkspace", argsDecoder: pinWorkspaceDecoder, resultDecoder: voidResultDecoder }, - unpinWorkspace: { name: "unpinWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - getWorkspaceIcon: { name: "getWorkspaceIcon", argsDecoder: workspaceSelectorDecoder, resultDecoder: getWorkspaceIconResultDecoder }, - setWorkspaceIcon: { name: "setWorkspaceIcon", argsDecoder: setWorkspaceIconDecoder, resultDecoder: voidResultDecoder }, - registerShortcut: { name: "registerShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - unregisterShortcut: { name: "unregisterShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - showLoadingAnimation: { name: "showLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - hideLoadingAnimation: { name: "hideLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - getPlatformFrameId: { name: "getPlatformFrameId", resultDecoder: getPlatformFrameIdResultDecoder }, - operationCheck: { name: "operationCheck", argsDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - setWindowDragMode: { name: "setWindowDragMode", argsDecoder: setWindowDragModeDecoder, resultDecoder: voidResultDecoder }, - setLoadingStrategy: { name: "setLoadingStrategy", argsDecoder: setLoadingStrategyDecoder, resultDecoder: voidResultDecoder }, - getTaskbarIcon: { name: "getTaskbarIcon", resultDecoder: iconDecoder }, - setTaskbarIcon: { name: "setTaskbarIcon", argsDecoder: setIconArgumentsDecoder, resultDecoder: voidResultDecoder }, - subscribeToFrameClosing: { name: "subscribeToFrameClosing", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - showPopup: { name: "showPopup", argsDecoder: ShowPopupConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameVisibility: { name: "changeFrameVisibility", argsDecoder: changeFrameVisibilityConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameVisibility: { name: "getFrameVisibility", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameVisibilityResultDecoder }, - showFrameDialog: { name: "showFrameDialog", argsDecoder: showFrameDialogConfigDecoder, resultDecoder: anyJson() } - }; - - class PromiseWrapper { - resolve; - reject; - promise; - constructor() { - this.promise = new Promise((res, rej) => { - this.resolve = res; - this.reject = rej; - }); - } - } - - class Bridge { - transport; - registry; - activeSubscriptions = []; - pendingSubScriptions = []; - constructor(transport, registry) { - this.transport = transport; - this.registry = registry; - } - async createCoreEventSubscription() { - await this.transport.coreSubscriptionReady(this.handleCoreEvent.bind(this)); - } - handleCoreSubscription(config) { - const registryKey = `${config.eventType}-${config.action}`; - const scope = config.scope; - const scopeId = config.scopeId; - return this.registry.add(registryKey, (args) => { - const scopeConfig = { - type: scope, - id: scopeId - }; - const receivedIds = { - frame: args.frameSummary?.id || args.windowSummary?.config.frameId, - workspace: args.workspaceSummary?.id || args.windowSummary?.config.workspaceId, - container: args.containerSummary?.itemId, - window: args.windowSummary?.itemId - }; - const shouldInvokeCallback = this.checkScopeMatch(scopeConfig, receivedIds); - if (!shouldInvokeCallback) { - return; - } - config.callback(args); - }); - } - async send(operationName, operationArgs, invocationOptions) { - const operationDefinition = Object.values(OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - try { - const operationResult = await this.transport.transmitControl(operationDefinition.name, operationArgs, invocationOptions); - operationDefinition.resultDecoder.runWithException(operationResult); - return operationResult; - } - catch (error) { - if (error.kind) { - throw new Error(`Unexpected internal incoming validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - throw new Error(error.message); - } - } - async subscribe(config) { - const pendingSub = this.getPendingSubscription(config); - if (pendingSub) { - await pendingSub.promise; - } - let activeSub = this.getActiveSubscription(config); - const registryKey = this.getRegistryKey(config); - if (!activeSub) { - const pendingPromise = new PromiseWrapper(); - const pendingSubscription = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - promise: pendingPromise.promise - }; - this.pendingSubScriptions.push(pendingSubscription); - try { - const stream = STREAMS[config.eventType]; - const gdSub = await this.transport.subscribe(stream.name, this.getBranchKey(config), config.eventType); - gdSub.onData((streamData) => { - const data = streamData.data; - const requestedArgumentsResult = streamRequestArgumentsDecoder.run(streamData.requestArguments); - const actionResult = workspaceEventActionDecoder.run(data.action); - if (!requestedArgumentsResult.ok || !actionResult.ok) { - return; - } - const streamType = requestedArgumentsResult.result.type; - const branch = requestedArgumentsResult.result.branch; - const keyToExecute = `${streamType}-${branch}-${actionResult.result}`; - const validatedPayload = STREAMS[streamType].payloadDecoder.run(data.payload); - if (!validatedPayload.ok) { - return; - } - this.registry.execute(keyToExecute, validatedPayload.result); - }); - activeSub = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - callbacksCount: 0, - gdSub - }; - this.activeSubscriptions.push(activeSub); - pendingPromise.resolve(); - } - catch (error) { - pendingPromise.reject(error); - throw error; - } - finally { - this.removePendingSubscription(pendingSubscription); - } - } - const unsubscribe = this.registry.add(registryKey, config.callback); - ++activeSub.callbacksCount; - return () => { - unsubscribe(); - --activeSub.callbacksCount; - if (activeSub.callbacksCount === 0) { - activeSub.gdSub.close(); - this.activeSubscriptions.splice(this.activeSubscriptions.indexOf(activeSub), 1); - } - }; - } - onOperation(callback) { - const wrappedCallback = (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - callback(payload, caller); - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - onOperationWithResponse(callback) { - const wrappedCallback = async (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - const result = await callback(payload, caller); - if (operationDefinition.resultDecoder) { - try { - operationDefinition.resultDecoder.runWithException(result); - } - catch (error) { - throw new Error(`Unexpected internal outgoing result validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - return result; - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - checkScopeMatch(scope, receivedIds) { - if (scope.type === "global") { - return true; - } - if (scope.type === "frame" && scope.id === receivedIds.frame) { - return true; - } - if (scope.type === "workspace" && scope.id === receivedIds.workspace) { - return true; - } - if (scope.type === "container" && scope.id === receivedIds.container) { - return true; - } - if (scope.type === "window" && scope.id === receivedIds.window) { - return true; - } - return false; - } - handleCoreEvent(args) { - const data = args.data; - try { - const verifiedAction = workspaceEventActionDecoder.runWithException(data.action); - const verifiedType = eventTypeDecoder.runWithException(data.type); - const verifiedPayload = STREAMS[verifiedType].payloadDecoder.runWithException(data.payload); - const registryKey = `${verifiedType}-${verifiedAction}`; - this.registry.execute(registryKey, verifiedPayload); - } - catch (error) { - console.warn(`Cannot handle event with data ${JSON.stringify(data)}, because of validation error: ${error.message}`); - } - } - getBranchKey(config) { - return config.scope === "global" ? config.scope : `${config.scope}_${config.scopeId}`; - } - getRegistryKey(config) { - return `${config.eventType}-${this.getBranchKey(config)}-${config.action}`; - } - getActiveSubscription(config) { - return this.activeSubscriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - getPendingSubscription(config) { - return this.pendingSubScriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - removePendingSubscription(pendingSubscription) { - const index = this.pendingSubScriptions.indexOf(pendingSubscription); - if (index >= 0) { - this.pendingSubScriptions.splice(index, 1); - } - } - } - - const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage; - reject(message); - }, timeoutMilliseconds); - promise() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - - const isDesktop = () => { - return typeof window === "undefined" ? - true : - window.glue42gd || window.iodesktop; - }; - const browserGlobal = () => { - return typeof window === "undefined" ? null : - window.glue42core || window.iobrowser; - }; - - class InteropTransport { - agm; - registry; - defaultTransportTimeout = 120000; - coreEventMethodInitiated = false; - corePlatformSubPromise; - constructor(agm, registry) { - this.agm = agm; - this.registry = registry; - } - async initiate(actualWindowId) { - if (isDesktop()) { - await Promise.all(Object.values(OUTGOING_METHODS).map((method) => { - return this.verifyMethodLive(method.name); - })); - await Promise.all(Object.keys(INCOMING_METHODS).map((method) => { - return this.registerMethod(method); - })); - return; - } - const systemId = browserGlobal().communicationId; - await Promise.all([ - this.verifyMethodLive(webPlatformMethodName, systemId), - this.verifyMethodLive(webPlatformWspStreamName, systemId) - ]); - await this.transmitControl("frameHello", { windowId: actualWindowId }); - } - coreSubscriptionReady(eventCallback) { - if (!this.coreEventMethodInitiated) { - this.subscribePlatform(eventCallback); - } - return this.corePlatformSubPromise; - } - subscribePlatform(eventCallback) { - this.coreEventMethodInitiated = true; - const systemId = browserGlobal().communicationId; - this.corePlatformSubPromise = this.agm.subscribe(webPlatformWspStreamName, systemId ? { target: { instance: systemId } } : undefined); - this.corePlatformSubPromise - .then((sub) => { - sub.onData((data) => eventCallback(data.data)); - }); - } - async subscribe(streamName, streamBranch, streamType) { - const subscriptionArgs = { - branch: streamBranch, - type: streamType - }; - let subscription; - try { - subscription = await this.agm.subscribe(streamName, { arguments: subscriptionArgs }); - } - catch (error) { - const message = `Internal subscription error! Error details: stream - ${streamName}, branch: ${streamBranch}. Internal message: ${error.message}`; - throw new Error(message); - } - return subscription; - } - async transmitControl(operation, operationArguments, invocationOptions) { - const invocationArguments = isDesktop() ? { operation, operationArguments } : { operation, domain: "workspaces", data: operationArguments }; - const methodName = isDesktop() ? OUTGOING_METHODS.control.name : webPlatformMethodName; - const platformTarget = isDesktop() ? undefined : browserGlobal().communicationId; - let invocationResult; - const baseErrorMessage = `Internal Workspaces Communication Error. Attempted operation: ${JSON.stringify(invocationArguments)}. `; - try { - invocationResult = await this.agm.invoke(methodName, invocationArguments, platformTarget ? { instance: platformTarget } : "best", { methodResponseTimeoutMs: invocationOptions?.timeout ?? this.defaultTransportTimeout }); - if (!invocationResult) { - throw new Error("Received unsupported result from GD - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from GD - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - onInternalMethodInvoked(key, callback) { - return this.registry.add(key, callback); - } - verifyMethodLive(name, systemId) { - return promisePlus(() => { - return new Promise((resolve) => { - const hasMethod = this.agm.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = systemId ? - method.getServers().some((server) => server.instance === systemId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - resolve(); - return; - } - const unSub = this.agm.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = systemId ? - server.instance === systemId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }); - }, 15000, "Timeout waiting for the Workspaces communication channels"); - } - registerMethod(key) { - const method = INCOMING_METHODS[key]; - return this.agm.register(method.name, (args, caller) => { - return Promise.all(this.registry.execute(key, args, caller)); - }); - } - } - - const privateData$4 = new WeakMap(); - class ParentBuilder { - constructor(definition, base) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$4.set(this, { base, children, definition }); - } - get type() { - return privateData$4.get(this).definition.type; - } - addColumn(definition) { - const base = privateData$4.get(this).base; - return base.add("column", privateData$4.get(this).children, definition); - } - addRow(definition) { - const base = privateData$4.get(this).base; - return base.add("row", privateData$4.get(this).children, definition); - } - addGroup(definition) { - const base = privateData$4.get(this).base; - return base.add("group", privateData$4.get(this).children, definition); - } - addWindow(definition) { - const base = privateData$4.get(this).base; - base.addWindow(privateData$4.get(this).children, definition); - return this; - } - serialize() { - const definition = privateData$4.get(this).definition; - definition.children = privateData$4.get(this).base.serializeChildren(privateData$4.get(this).children); - return definition; - } - } - - class BaseBuilder { - getBuilder; - constructor(getBuilder) { - this.getBuilder = getBuilder; - } - wrapChildren(children) { - return children.map((child) => { - if (child.type === "window") { - return child; - } - return this.getBuilder({ type: child.type, definition: child }); - }); - } - add(type, children, definition) { - const validatedDefinition = parentDefinitionDecoder.runWithException(definition); - const childBuilder = this.getBuilder({ type, definition: validatedDefinition }); - children.push(childBuilder); - return childBuilder; - } - addWindow(children, definition) { - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - validatedDefinition.type = "window"; - children.push(validatedDefinition); - } - serializeChildren(children) { - return children.map((child) => { - if (child instanceof ParentBuilder) { - return child.serialize(); - } - else { - return child; - } - }); - } - } - - const privateData$3 = new WeakMap(); - class WorkspaceBuilder { - constructor(definition, base, controller) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$3.set(this, { base, children, definition, controller }); - } - addColumn(definition) { - const children = privateData$3.get(this).children; - const areAllColumns = children.every((child) => child instanceof ParentBuilder && child.type === "column"); - if (!areAllColumns) { - throw new Error("Cannot add a column to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("column", children, definition); - } - addRow(definition) { - const children = privateData$3.get(this).children; - const areAllRows = children.every((child) => child instanceof ParentBuilder && child.type === "row"); - if (!areAllRows) { - throw new Error("Cannot add a row to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("row", children, definition); - } - addGroup(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a group to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - return base.add("group", children, definition); - } - addWindow(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a window to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - base.addWindow(children, definition); - return this; - } - getChildAt(index) { - nonNegativeNumberDecoder.runWithException(index); - const data = privateData$3.get(this).children; - return data[index]; - } - async create(config) { - const saveConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - const definition = privateData$3.get(this).definition; - definition.children = privateData$3.get(this).base.serializeChildren(privateData$3.get(this).children); - const controller = privateData$3.get(this).controller; - return controller.createWorkspace(definition, saveConfig); - } - } - - const privateData$2 = new WeakMap(); - const getBase$2 = (model) => { - return privateData$2.get(model).base; - }; - class Row { - constructor(base) { - privateData$2.set(this, { base }); - } - get type() { - return "row"; - } - get id() { - return getBase$2(this).getId(this); - } - get frameId() { - return getBase$2(this).getFrameId(this); - } - get workspaceId() { - return getBase$2(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$2(this).getPositionIndex(this); - } - get children() { - return getBase$2(this).getAllChildren(this); - } - get parent() { - return getBase$2(this).getMyParent(this); - } - get frame() { - return getBase$2(this).getMyFrame(this); - } - get workspace() { - return getBase$2(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$2(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$2(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$2(this).getMinWidth(this); - } - get minHeight() { - return getBase$2(this).getMinHeight(this); - } - get maxWidth() { - return getBase$2(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$2(this).getMaxHeight(this); - } - get width() { - return getBase$2(this).getWidthInPx(this); - } - get height() { - return getBase$2(this).getHeightInPx(this); - } - get isPinned() { - return getBase$2(this).getIsPinned(this); - } - get isMaximized() { - return getBase$2(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$2(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$2(this).addWindow(this, definition, "row"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "group", "row", definition); - } - async addColumn(definition) { - if (definition?.type && definition.type !== "column") { - throw new Error(`Expected a column definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "column", "row", definition); - } - async addRow() { - throw new Error("Adding rows as row children is not supported"); - } - removeChild(predicate) { - return getBase$2(this).removeChild(this, predicate); - } - maximize() { - return getBase$2(this).maximize(this); - } - restore() { - return getBase$2(this).restore(this); - } - close() { - return getBase$2(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : rowLockConfigDecoder.runWithException(lockConfigResult); - return getBase$2(this).lockContainer(this, verifiedConfig); - } - async setHeight(height) { - nonNegativeNumberDecoder.runWithException(height); - return getBase$2(this).setHeight(this, height); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$2(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$2(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData$1 = new WeakMap(); - const getBase$1 = (model) => { - return privateData$1.get(model).base; - }; - class Column { - constructor(base) { - privateData$1.set(this, { base }); - } - get type() { - return "column"; - } - get id() { - return getBase$1(this).getId(this); - } - get frameId() { - return getBase$1(this).getFrameId(this); - } - get workspaceId() { - return getBase$1(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$1(this).getPositionIndex(this); - } - get children() { - return getBase$1(this).getAllChildren(this); - } - get parent() { - return getBase$1(this).getMyParent(this); - } - get frame() { - return getBase$1(this).getMyFrame(this); - } - get workspace() { - return getBase$1(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$1(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$1(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$1(this).getMinWidth(this); - } - get minHeight() { - return getBase$1(this).getMinHeight(this); - } - get maxWidth() { - return getBase$1(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$1(this).getMaxHeight(this); - } - get width() { - return getBase$1(this).getWidthInPx(this); - } - get height() { - return getBase$1(this).getHeightInPx(this); - } - get isPinned() { - return getBase$1(this).getIsPinned(this); - } - get isMaximized() { - return getBase$1(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$1(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$1(this).addWindow(this, definition, "column"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "group", "column", definition); - } - async addColumn() { - throw new Error("Adding columns as column children is not supported"); - } - async addRow(definition) { - if (definition?.type && definition.type !== "row") { - throw new Error(`Expected a row definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "row", "column", definition); - } - removeChild(predicate) { - return getBase$1(this).removeChild(this, predicate); - } - maximize() { - return getBase$1(this).maximize(this); - } - restore() { - return getBase$1(this).restore(this); - } - close() { - return getBase$1(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : columnLockConfigDecoder.runWithException(lockConfigResult); - return getBase$1(this).lockContainer(this, verifiedConfig); - } - async setWidth(width) { - nonNegativeNumberDecoder.runWithException(width); - return getBase$1(this).setWidth(this, width); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$1(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$1(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData = new WeakMap(); - const getBase = (model) => { - return privateData.get(model).base; - }; - class Group { - constructor(base) { - privateData.set(this, { base }); - } - get type() { - return "group"; - } - get id() { - return getBase(this).getId(this); - } - get frameId() { - return getBase(this).getFrameId(this); - } - get workspaceId() { - return getBase(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase(this).getPositionIndex(this); - } - get children() { - return getBase(this).getAllChildren(this); - } - get parent() { - return getBase(this).getMyParent(this); - } - get frame() { - return getBase(this).getMyFrame(this); - } - get workspace() { - return getBase(this).getMyWorkspace(this); - } - get allowExtract() { - return getBase(this).getAllowExtract(this); - } - get allowReorder() { - return getBase(this).getAllowReorder(this); - } - get allowDropLeft() { - return getBase(this).getAllowDropLeft(this); - } - get allowDropRight() { - return getBase(this).getAllowDropRight(this); - } - get allowDropTop() { - return getBase(this).getAllowDropTop(this); - } - get allowDropBottom() { - return getBase(this).getAllowDropBottom(this); - } - get allowDropHeader() { - return getBase(this).getAllowDropHeader(this); - } - get allowDrop() { - return getBase(this).getAllowDrop(this); - } - get showMaximizeButton() { - return getBase(this).getShowMaximizeButton(this); - } - get showEjectButton() { - return getBase(this).getShowEjectButton(this); - } - get showAddWindowButton() { - return getBase(this).getShowAddWindowButton(this); - } - get minWidth() { - return getBase(this).getMinWidth(this); - } - get minHeight() { - return getBase(this).getMinHeight(this); - } - get maxWidth() { - return getBase(this).getMaxWidth(this); - } - get maxHeight() { - return getBase(this).getMaxHeight(this); - } - get width() { - return getBase(this).getWidthInPx(this); - } - get height() { - return getBase(this).getHeightInPx(this); - } - get isMaximized() { - return getBase(this).getIsMaximized(this); - } - addWindow(definition) { - return getBase(this).addWindow(this, definition, "group"); - } - async addGroup() { - throw new Error("Adding groups as group child is not supported"); - } - async addColumn() { - throw new Error("Adding columns as group child is not supported"); - } - async addRow() { - throw new Error("Adding rows as group child is not supported"); - } - removeChild(predicate) { - return getBase(this).removeChild(this, predicate); - } - maximize() { - return getBase(this).maximize(this); - } - restore() { - return getBase(this).restore(this); - } - close() { - return getBase(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropRight: this.allowDropRight, - allowDropTop: this.allowDropTop, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : groupLockConfigDecoder.runWithException(lockConfigResult); - return getBase(this).lockContainer(this, verifiedConfig); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - return getBase(this).setSize(this, config.width, config.height); - } - async bundleToRow() { - await getBase(this).bundleTo(this, "row"); - await this.workspace.refreshReference(); - } - async bundleToColumn() { - await getBase(this).bundleTo(this, "column"); - await this.workspace.refreshReference(); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase(this).processLocalSubscription(this, config); - return unsubscribe; - } - } - - const DEFAULT_WINDOW_DRAG_MODE = "keepInside"; - const ONE_DAY_MS = 86_400_000; - - const data$3 = new WeakMap(); - const getData$3 = (model) => { - return data$3.get(model).manager.getWorkspaceData(model); - }; - const getDataManager = (model) => { - return data$3.get(model).manager; - }; - class Workspace { - constructor(dataManager) { - data$3.set(this, { manager: dataManager }); - } - get id() { - return getData$3(this).id; - } - get frameId() { - return getData$3(this).config.frameId; - } - get positionIndex() { - return getData$3(this).config.positionIndex; - } - get title() { - return getData$3(this).config.title; - } - get layoutName() { - return getData$3(this).config.layoutName; - } - get isHibernated() { - return getData$3(this).config.isHibernated; - } - get isSelected() { - return getData$3(this).config.isSelected; - } - get children() { - return getData$3(this).children; - } - get frame() { - return getData$3(this).frame; - } - get allowSplitters() { - return getData$3(this).config.allowSplitters; - } - get allowSystemHibernation() { - return getData$3(this).config.allowSystemHibernation; - } - get allowDrop() { - return getData$3(this).config.allowDrop; - } - get allowDropLeft() { - return getData$3(this).config.allowDropLeft; - } - get allowDropTop() { - return getData$3(this).config.allowDropTop; - } - get allowDropRight() { - return getData$3(this).config.allowDropRight; - } - get allowDropBottom() { - return getData$3(this).config.allowDropBottom; - } - get allowExtract() { - return getData$3(this).config.allowExtract; - } - get allowWindowReorder() { - return getData$3(this).config.allowWindowReorder; - } - get showCloseButton() { - return getData$3(this).config.showCloseButton; - } - get showSaveButton() { - return getData$3(this).config.showSaveButton; - } - get allowWorkspaceTabReorder() { - return getData$3(this).config.allowWorkspaceTabReorder; - } - get allowWorkspaceTabExtract() { - return getData$3(this).config.allowWorkspaceTabExtract; - } - get minWidth() { - return getData$3(this).config.minWidth; - } - get minHeight() { - return getData$3(this).config.minHeight; - } - get maxWidth() { - return getData$3(this).config.maxWidth; - } - get maxHeight() { - return getData$3(this).config.maxHeight; - } - get width() { - return getData$3(this).config.widthInPx; - } - get height() { - return getData$3(this).config.heightInPx; - } - get showWindowCloseButtons() { - return getData$3(this).config.showWindowCloseButtons; - } - get showEjectButtons() { - return getData$3(this).config.showEjectButtons; - } - get showAddWindowButtons() { - return getData$3(this).config.showAddWindowButtons; - } - get isPinned() { - return getData$3(this).config.isPinned; - } - get windowDragMode() { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - return DEFAULT_WINDOW_DRAG_MODE; - } - return getData$3(this).config.windowDragMode; - } - get loadingStrategy() { - if (!isDesktop()) { - console.warn("The workspace.loadingStrategy property is not supported in IO Connect Browser"); - } - return getData$3(this).config.loadingStrategy; - } - async setLoadingStrategy(strategy) { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - const controller = getData$3(this).controller; - await controller.setLoadingStrategy(this.id, strategy); - await this.refreshReference(); - } - async removeChild(predicate) { - checkThrowCallback(predicate); - const child = this.children.find(predicate); - if (!child) { - return; - } - await child.close(); - await this.refreshReference(); - } - async remove(predicate) { - checkThrowCallback(predicate); - const controller = getData$3(this).controller; - const child = controller.iterateFindChild(this.children, predicate); - await child.close(); - await this.refreshReference(); - } - async focus() { - await getData$3(this).controller.focusItem(this.id); - await this.refreshReference(); - } - async close() { - const controller = getData$3(this).controller; - await controller.closeWorkspace(this.id, this.frameId); - } - snapshot() { - return getData$3(this).controller.getSnapshot(this.id, "workspace"); - } - async saveLayout(name, config) { - nonEmptyStringDecoder.runWithException(name); - await getData$3(this).controller.saveLayout({ name, workspaceId: this.id, saveContext: config?.saveContext, metadata: config?.metadata, allowMultiple: config?.allowMultiple }); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const controller = getData$3(this).controller; - await controller.setItemTitle(this.id, title); - await this.refreshReference(); - } - getContext() { - const controller = getData$3(this).controller; - return controller.getWorkspaceContext(this.id); - } - setContext(data) { - const controller = getData$3(this).controller; - return controller.setWorkspaceContext(this.id, data); - } - updateContext(data) { - const controller = getData$3(this).controller; - return controller.updateWorkspaceContext(this.id, data); - } - onContextUpdated(callback) { - const controller = getData$3(this).controller; - return controller.subscribeWorkspaceContextUpdated(this.id, callback); - } - async refreshReference() { - const newSnapshot = (await getData$3(this).controller.getSnapshot(this.id, "workspace")); - const currentChildrenFlat = getData$3(this).controller.flatChildren(getData$3(this).children); - const newChildren = getData$3(this).controller.refreshChildren({ - existingChildren: currentChildrenFlat, - workspace: this, - parent: this, - children: newSnapshot.children - }); - const currentFrame = this.frame; - let actualFrame; - if (currentFrame.id === newSnapshot.config.frameId) { - getDataManager(this).remapFrame(currentFrame, newSnapshot.frameSummary); - actualFrame = currentFrame; - } - else { - const frameCreateConfig = { - summary: newSnapshot.frameSummary - }; - const newFrame = getData$3(this).ioc.getModel("frame", frameCreateConfig); - actualFrame = newFrame; - } - getDataManager(this).remapWorkspace(this, { - config: newSnapshot.config, - children: newChildren, - frame: actualFrame - }); - } - async getIcon() { - const controller = getData$3(this).controller; - return controller.getWorkspaceIcon(this.id); - } - async setIcon(icon) { - const controller = getData$3(this).controller; - return controller.setWorkspaceIcon(this.id, icon); - } - getBox(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type !== "window" && predicate(child)); - } - getAllBoxes(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allParents = controller.iterateFilterChildren(children, (child) => child.type !== "window"); - if (!predicate) { - return allParents; - } - return allParents.filter(predicate); - } - getRow(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "row" && predicate(parent)); - } - getAllRows(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "row" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "row"); - } - getColumn(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "column" && predicate(parent)); - } - getAllColumns(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "column" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "column"); - } - getGroup(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "group" && predicate(parent)); - } - getAllGroups(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "group" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "group"); - } - getWindow(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type === "window" && predicate(child)); - } - getAllWindows(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allWindows = controller.iterateFilterChildren(children, (child) => child.type === "window"); - if (!predicate) { - return allWindows; - } - return allWindows.filter(predicate); - } - addRow(definition) { - return getData$3(this).base.addParent(this, "row", "workspace", definition); - } - addColumn(definition) { - return getData$3(this).base.addParent(this, "column", "workspace", definition); - } - addGroup(definition) { - return getData$3(this).base.addParent(this, "group", "workspace", definition); - } - addWindow(definition) { - return getData$3(this).base.addWindow(this, definition, "workspace"); - } - async bundleToRow() { - await getData$3(this).controller.bundleWorkspaceTo("row", this.id); - await this.refreshReference(); - } - async bundleToColumn() { - await getData$3(this).controller.bundleWorkspaceTo("column", this.id); - await this.refreshReference(); - } - async hibernate() { - await getData$3(this).controller.hibernateWorkspace(this.id); - await this.refreshReference(); - } - async resume() { - await getData$3(this).controller.resumeWorkspace(this.id); - await this.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowWindowReorder: this.allowWindowReorder, - allowSplitters: this.allowSplitters, - showCloseButton: this.showCloseButton, - showSaveButton: this.showSaveButton, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - showAddWindowButtons: this.showAddWindowButtons, - showEjectButtons: this.showEjectButtons, - showWindowCloseButtons: this.showWindowCloseButtons - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : workspaceLockConfigDecoder.runWithException(lockConfigResult); - await getData$3(this).controller.lockWorkspace(this.id, verifiedConfig); - await this.refreshReference(); - } - async pin(options) { - workspacePinOptionsDecoder.runWithException(options); - await getData$3(this).controller.pinWorkspace(this.id, options?.icon); - await this.refreshReference(); - } - async unpin() { - await getData$3(this).controller.unpinWorkspace(this.id); - await this.refreshReference(); - } - async showLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.showWorkspaceLoadingAnimation(this.id); - } - async hideLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.hideWorkspaceLoadingAnimation(this.id); - } - async setWindowDragMode(mode) { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - throw new Error("Not supported in IO Connect Browser"); - } - windowDragModeDecoder.runWithException(mode); - await getData$3(this).controller.setWindowDragMode(this.id, mode); - await this.refreshReference(); - } - async onClosed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - action: "closed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onHibernated(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "hibernated", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onResumed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "resumed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "added", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - action: "removed", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const foundWindow = this.getWindow((win) => { - return win.id && win.id === payload.windowSummary.config.windowId; - }); - callback(foundWindow); - }; - const config = { - action: "loaded", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowMaximized(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "maximized", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRestored(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "restored", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowSelected(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "selected", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowSplitters: this.allowSplitters, - allowWindowReorder: this.allowWindowReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - showAddWindowButtons: this.showAddWindowButtons, - showCloseButton: this.showCloseButton, - showEjectButtons: this.showEjectButtons, - showSaveButton: this.showSaveButton, - showWindowCloseButtons: this.showWindowCloseButtons - }); - }; - const config = { - action: "lock-configuration-changed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$2 = new WeakMap(); - const getData$2 = (model) => { - return data$2.get(model).manager.getWindowData(model); - }; - class Window { - constructor(dataManager) { - data$2.set(this, { manager: dataManager }); - } - get id() { - return getData$2(this).config.windowId; - } - get elementId() { - return getData$2(this).id; - } - get type() { - return "window"; - } - get frameId() { - return getData$2(this).frame.id; - } - get workspaceId() { - return getData$2(this).workspace.id; - } - get positionIndex() { - return getData$2(this).config.positionIndex; - } - get isMaximized() { - return getData$2(this).config.isMaximized; - } - get isLoaded() { - return getData$2(this).controller.checkIsWindowLoaded(this.id); - } - get isSelected() { - return getData$2(this).config.isSelected; - } - get focused() { - return this.getGdWindow().isFocused; - } - get title() { - return getData$2(this).config.title; - } - get allowExtract() { - return getData$2(this).config.allowExtract; - } - get allowReorder() { - return getData$2(this).config.allowReorder; - } - get showCloseButton() { - return getData$2(this).config.showCloseButton; - } - get width() { - return getData$2(this).config.widthInPx; - } - get height() { - return getData$2(this).config.heightInPx; - } - get minWidth() { - return getData$2(this).config.minWidth; - } - get minHeight() { - return getData$2(this).config.minHeight; - } - get maxWidth() { - return getData$2(this).config.maxWidth; - } - get maxHeight() { - return getData$2(this).config.maxHeight; - } - get workspace() { - return getData$2(this).workspace; - } - get frame() { - return getData$2(this).frame; - } - get parent() { - return getData$2(this).parent; - } - get appName() { - return getData$2(this).config.appName; - } - async forceLoad() { - if (this.isLoaded) { - return; - } - const controller = getData$2(this).controller; - const itemId = getData$2(this).id; - const windowId = await controller.forceLoadWindow(itemId); - getData$2(this).config.windowId = windowId; - await this.workspace.refreshReference(); - } - async focus() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.focusItem(id); - await this.workspace.refreshReference(); - } - async close() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.closeItem(id); - await getData$2(this) - .parent - .removeChild((child) => child.id === id); - await this.workspace.refreshReference(); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const itemId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.setItemTitle(itemId, title); - await this.workspace.refreshReference(); - } - async maximize() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.maximizeItem(id); - await this.workspace.refreshReference(); - } - async restore() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.restoreItem(id); - await this.workspace.refreshReference(); - } - async eject() { - if (!this.isLoaded) { - throw new Error("Cannot eject this window, because it is not loaded yet"); - } - const itemId = getData$2(this).id; - const windowId = getData$2(this).config.windowId; - const newWindowId = await getData$2(this).controller.ejectWindow(itemId, windowId); - getData$2(this).config.windowId = newWindowId; - await this.workspace.refreshReference(); - return this.getGdWindow(); - } - getGdWindow() { - if (!this.isLoaded) { - throw new Error("Cannot fetch this GD window, because the window is not yet loaded"); - } - const myId = getData$2(this).config.windowId; - const controller = getData$2(this).controller; - return controller.getGDWindow(myId); - } - async moveTo(parent) { - if (!(parent instanceof Row || parent instanceof Column || parent instanceof Group)) { - throw new Error("Cannot add to the provided parent, because the provided parent is not an instance of Row, Column or Group"); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - const foundParent = await controller.getParent((p) => p.id === parent.id); - if (!foundParent) { - throw new Error("Cannot move the window to the selected parent, because this parent does not exist."); - } - await controller.moveWindowTo(myId, parent.id); - await this.workspace.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : windowLockConfigDecoder.runWithException(lockConfigResult); - const windowPlacementId = getData$2(this).id; - await getData$2(this).controller.lockWindow(windowPlacementId, verifiedConfig); - await this.workspace.refreshReference(); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.resizeItem(myId, { - height: verifiedConfig.height, - width: verifiedConfig.width, - relative: false - }); - await this.workspace.refreshReference(); - } - async onRemoved(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback(); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$1 = new WeakMap(); - const getData$1 = (model) => { - return data$1.get(model).manager.getFrameData(model); - }; - class Frame { - constructor(dataManager) { - data$1.set(this, { manager: dataManager }); - } - async registerShortcut(shortcut, callback) { - nonEmptyStringDecoder.runWithException(shortcut); - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const unsubscribe = await getData$1(this).controller.registerShortcut(shortcut, myId, callback); - return unsubscribe; - } - get id() { - return getData$1(this).summary.id; - } - get isInitialized() { - return getData$1(this).summary.isInitialized; - } - getBounds() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameBounds(myId); - } - async resize(config) { - const validatedConfig = resizeConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.resizeItem(myId, validatedConfig); - } - async move(config) { - const validatedConfig = moveConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.moveFrame(myId, validatedConfig); - } - focus() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.focusItem(myId); - } - async state() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameState(myId); - } - setIcon(icon) { - if (!isDesktop()) { - throw new Error("frame.setIcon() is not supported in IO Connect Browser"); - } - iconDecoder.runWithException(icon); - const frameId = this.id; - return getData$1(this).controller.setTaskbarIcon(icon, frameId); - } - getIcon() { - if (!isDesktop()) { - throw new Error("frame.getIcon() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getTaskbarIcon(frameId); - } - isVisible() { - if (!isDesktop()) { - throw new Error("frame.isVisible() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getFrameVisibility(frameId); - } - async minimize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "minimized"); - } - async maximize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "maximized"); - } - async restore() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "normal"); - } - close(options) { - const validatedOptions = optional(closeOptionsDecoder).runWithException(options); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.closeFrame(myId, validatedOptions); - } - snapshot() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getSnapshot(myId, "frame"); - } - async workspaces() { - const controller = getData$1(this).controller; - return controller.getWorkspacesByFrameId(this.id); - } - async getConstraints() { - const controller = getData$1(this).controller; - const myId = getData$1(this).summary.id; - return controller.getFrameConstraints(myId); - } - async restoreWorkspace(name, options) { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return getData$1(this).controller.restoreWorkspace(name, validatedOptions); - } - createWorkspace(definition, config) { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - return getData$1(this).controller.createWorkspace(validatedDefinition, validatedConfig); - } - async init(config) { - frameInitConfigDecoder.runWithException(config); - if (getData$1(this).summary.isInitialized) { - throw new Error("The frame has already been initialized"); - } - return getData$1(this).controller.initFrame(this.id, config); - } - async showPopup(config) { - if (!isDesktop()) { - throw new Error("Popup operations are not supported in IO Connect Browser"); - } - const validatedConfig = popupConfigDecoder.runWithException(config); - const controller = getData$1(this).controller; - await controller.showPopup(validatedConfig, this.id); - return controller.getGDWindow(validatedConfig.windowId); - } - async show(config) { - if (!isDesktop()) { - throw new Error("The show operation is not supported in IO Connect Browser"); - } - const validatedConfig = frameShowConfigDecoder.runWithException(config); - return getData$1(this).controller.showFrame(this.id, validatedConfig); - } - async hide() { - if (!isDesktop()) { - throw new Error("The hide operation is not supported in IO Connect Browser"); - } - return getData$1(this).controller.hideFrame(this.id); - } - async showDialog(options) { - if (!isDesktop()) { - throw new Error("The showModal operation is not supported in IO Connect Browser"); - } - frameDialogOptionsDecoder.runWithException(options); - return getData$1(this).controller.showFrameDialog(this.id, options); - } - async onClosing(callback) { - if (!isDesktop()) { - throw new Error("Frame closing operations are not supported in io.Connect Browser"); - } - checkThrowCallback(callback); - const wrappedCallback = async () => { - let shouldPrevent = false; - const preventClose = () => shouldPrevent = true; - await callback({ prevent: preventClose }); - return { prevent: shouldPrevent }; - }; - const unsubscribe = await getData$1(this).controller.registerFrameOnClosing(this.id, wrappedCallback); - return unsubscribe; - } - async onClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMaximized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "maximized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMinimized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "minimized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onNormal(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "normal", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceOpened(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "opened", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceSelected(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.getWorkspaceById(payload.workspaceSummary.id); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "selected", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "added", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => { - return parent.id === payload.windowSummary.parentId; - }); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "loaded", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onInitializationRequested(callback) { - checkThrowCallback(callback); - if (!this.isInitialized) { - callback(getData$1(this).summary.initializationContext); - } - return () => { }; - } - async onFocusChanged(callback) { - checkThrowCallback(callback); - const myData = getData$1(this); - const { id } = myData.summary; - const wrappedCallback = (args) => { - callback({ isFocused: args.frameSummary.isFocused }); - }; - const config = { - callback: wrappedCallback, - action: "focus", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await myData.controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - class PrivateDataManager { - parentsData = new WeakMap(); - workspacesData = new WeakMap(); - windowsData = new WeakMap(); - framesData = new WeakMap(); - deleteData(model) { - if (model instanceof Window) { - this.windowsData.delete(model); - } - if (model instanceof Workspace) { - this.workspacesData.delete(model); - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - this.parentsData.delete(model); - } - if (model instanceof Frame) { - this.framesData.delete(model); - } - } - setWindowData(model, data) { - this.windowsData.set(model, data); - } - setWorkspaceData(model, data) { - this.workspacesData.set(model, data); - } - setParentData(model, data) { - this.parentsData.set(model, data); - } - setFrameData(model, data) { - this.framesData.set(model, data); - } - getWindowData(model) { - return this.windowsData.get(model); - } - getWorkspaceData(model) { - return this.workspacesData.get(model); - } - getParentData(model) { - return this.parentsData.get(model); - } - getFrameData(model) { - return this.framesData.get(model); - } - remapChild(model, newData) { - if (model instanceof Window) { - const data = this.windowsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - const data = this.parentsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - remapFrame(model, newData) { - const data = this.framesData.get(model); - data.summary = newData; - } - remapWorkspace(model, newData) { - const data = this.workspacesData.get(model); - data.frame = newData.frame || data.frame; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - - const data = new WeakMap(); - const getData = (base, model) => { - const manager = data.get(base).manager; - if (model instanceof Workspace) { - return manager.getWorkspaceData(model); - } - return data.get(base).manager.getParentData(model); - }; - class Base { - frameId; - workspaceId; - positionIndex; - constructor(dataManager) { - data.set(this, { manager: dataManager }); - } - getId(model) { - return getData(this, model).id; - } - getPositionIndex(model) { - return getData(this, model).config.positionIndex; - } - getWorkspaceId(model) { - const privateData = getData(this, model); - return privateData.config.workspaceId || privateData.workspace.id; - } - getFrameId(model) { - return getData(this, model).frame.id; - } - getAllChildren(model, predicate) { - checkThrowCallback(predicate, true); - const children = getData(this, model).children; - if (typeof predicate === "undefined") { - return children; - } - return children.filter(predicate); - } - getMyParent(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).parent; - } - getMyFrame(model) { - return getData(this, model).frame; - } - getMyWorkspace(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).workspace; - } - async addWindow(model, definition, parentType) { - if (!definition.appName && !definition.windowId) { - throw new Error("The window definition should contain either an appName or a windowId"); - } - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - const controller = getData(this, model).controller; - const operationResult = await controller.add("window", getData(this, model).id, parentType, validatedDefinition); - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getWindow(w => w.elementId === operationResult.itemId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getWindow(w => w.elementId === operationResult.itemId); - } - async addParent(model, typeToAdd, parentType, definition) { - const parentDefinition = this.transformDefinition(typeToAdd, definition); - const controller = getData(this, model).controller; - const newParentId = (await controller.add("container", getData(this, model).id, parentType, parentDefinition)).itemId; - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getBox((parent) => parent.id === newParentId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getBox((parent) => parent.id === newParentId); - } - async removeChild(model, predicate) { - checkThrowCallback(predicate); - const child = this.getAllChildren(model).find(predicate); - if (!child) { - return; - } - await child.close(); - if (model instanceof Workspace) { - await model.refreshReference(); - return; - } - await this.getMyWorkspace(model).refreshReference(); - } - async maximize(model) { - const { controller, id } = getData(this, model); - await controller.maximizeItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async restore(model) { - const { controller, id } = getData(this, model); - await controller.restoreItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async close(model) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.closeItem(modelData.id); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async lockContainer(model, config) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.lockContainer(modelData.id, model.type, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - getAllowDrop(model) { - return getData(this, model).config.allowDrop; - } - getAllowDropLeft(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropLeft is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropLeft; - } - getAllowDropRight(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropRight is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropRight; - } - getAllowDropTop(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropTop is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropTop; - } - getAllowDropBottom(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropBottom is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropBottom; - } - getAllowDropHeader(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropHeader is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropHeader; - } - getAllowSplitters(model) { - const privateData = getData(this, model); - if (privateData.type === "group") { - throw new Error(`Cannot get allow splitters from private data ${privateData.type}`); - } - return privateData.config.allowSplitters; - } - getAllowExtract(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowExtract; - } - getAllowReorder(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowReorder; - } - getShowMaximizeButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show maximize button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showMaximizeButton; - } - getShowEjectButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show eject button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showEjectButton; - } - getShowAddWindowButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get add window button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showAddWindowButton; - } - getMinWidth(model) { - const privateData = getData(this, model); - return privateData.config.minWidth; - } - getMaxWidth(model) { - const privateData = getData(this, model); - return privateData.config.maxWidth; - } - getMinHeight(model) { - const privateData = getData(this, model); - return privateData.config.minHeight; - } - getMaxHeight(model) { - const privateData = getData(this, model); - return privateData.config.maxHeight; - } - getWidthInPx(model) { - const privateData = getData(this, model); - return privateData.config.widthInPx; - } - getHeightInPx(model) { - const privateData = getData(this, model); - return privateData.config.heightInPx; - } - getIsPinned(model) { - const privateData = getData(this, model); - return privateData.config.isPinned; - } - getIsMaximized(model) { - const privateData = getData(this, model); - return privateData.config.isMaximized; - } - getMaximizationBoundary(model) { - const privateData = getData(this, model); - return privateData.config.maximizationBoundary; - } - async setHeight(model, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setWidth(model, width) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setSize(model, width, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width, - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setMaximizationBoundary(model, config) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.setMaximizationBoundary(id, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async bundleTo(model, type) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.bundleItemTo(type, id); - } - async processLocalSubscription(model, subscriptionConfig) { - return getData(this, model).controller.processLocalSubscription(subscriptionConfig, this.getId(model)); - } - transformDefinition(type, definition) { - let parentDefinition; - if (typeof definition === "undefined") { - parentDefinition = { type, children: [] }; - } - else if (definition instanceof ParentBuilder) { - parentDefinition = definition.serialize(); - } - else { - if (typeof definition.type === "undefined") { - definition.type = type; - } - parentDefinition = strictParentDefinitionDecoder.runWithException(definition); - parentDefinition.children = parentDefinition.children || []; - } - return parentDefinition; - } - } - - class BaseController { - ioc; - windows; - contexts; - layouts; - constructor(ioc, windows, contexts, layouts) { - this.ioc = ioc; - this.windows = windows; - this.contexts = contexts; - this.layouts = layouts; - } - get bridge() { - return this.ioc.bridge; - } - get privateDataManager() { - return this.ioc.privateDataManager; - } - checkIsWindowLoaded(windowId) { - return (!!windowId) && this.windows.list().some((win) => win.id === windowId); - } - async createWorkspace(createConfig) { - const snapshot = await this.bridge.send(OPERATIONS.createWorkspace.name, createConfig); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async createEmptyFrame(definition) { - const frameSummary = await this.bridge.send(OPERATIONS.createFrame.name, definition); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - async initFrame(frameId, config) { - await this.bridge.send(OPERATIONS.initFrame.name, { frameId, ...config }); - } - async restoreWorkspace(name, options) { - const snapshot = await this.bridge.send(OPERATIONS.openWorkspace.name, { name, restoreOptions: options }); - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: snapshot.config.frameId }); - const frameConfig = { - summary: frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async add(type, parentId, parentType, definition) { - let operationName; - const operationArgs = { definition, parentId, parentType }; - if (type === "window") { - operationName = OPERATIONS.addWindow.name; - } - else if (type === "container") { - operationName = OPERATIONS.addContainer.name; - } - else { - throw new Error(`Unrecognized add type: ${type}`); - } - return await this.bridge.send(operationName, operationArgs); - } - async getFrame(windowId) { - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: windowId }); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - getFrames(allFrameSummaries, predicate) { - return allFrameSummaries.reduce((frames, frameSummary) => { - const frameConfig = { - summary: frameSummary - }; - const frameToCheck = this.ioc.getModel("frame", frameConfig); - if (!predicate || predicate(frameToCheck)) { - frames.push(frameToCheck); - } - return frames; - }, []); - } - getAllWorkspaceSummaries(...bridgeResults) { - const allSummaries = bridgeResults.reduce((summaries, summaryResult) => { - summaries.push(...summaryResult.summaries); - return summaries; - }, []); - return allSummaries.map((summary) => { - return Object.assign({}, { id: summary.id, width: summary.config.widthInPx, height: summary.config.heightInPx }, summary.config); - }); - } - handleOnSaved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - const addedUnSub = this.layouts.onAdded(wrappedCallback); - const changedUnSub = this.layouts.onChanged(wrappedCallback); - return () => { - addedUnSub(); - changedUnSub(); - }; - } - handleOnRemoved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - return this.layouts.onRemoved(wrappedCallback); - } - async importLayouts(layouts, mode) { - await this.layouts.import(layouts, mode); - } - async transformStreamPayloadToWorkspace(payload) { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const snapshot = payload.workspaceSnapshot || (await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId: payload.workspaceSummary.id })); - const workspaceConfig = { frame, snapshot }; - const workspace = this.ioc.getModel("workspace", workspaceConfig); - return workspace; - } - async fetchWorkspace(itemId) { - const snapshot = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async bundleWorkspaceTo(type, workspaceId) { - await this.bridge.send(OPERATIONS.bundleWorkspace.name, { type, workspaceId }); - } - async bundleItemTo(type, itemId) { - const isSupported = await this.isOperationSupported(OPERATIONS.bundleItem.name); - if (!isSupported) { - throw new Error(`Operation ${OPERATIONS.bundleItem.name} is not supported. Ensure that you are running the latest version of all packages`); - } - await this.bridge.send(OPERATIONS.bundleItem.name, { type, itemId }); - } - async getTaskbarIcon(frameId) { - return await this.bridge.send(OPERATIONS.getTaskbarIcon.name, { frameId }); - } - async setTaskbarIcon(icon, frameId) { - await this.bridge.send(OPERATIONS.setTaskbarIcon.name, { icon, frameId }); - } - getWorkspaceContext(workspaceId) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.get(contextName); - } - setWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.set(contextName, data); - } - updateWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.update(contextName, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.subscribe(contextName, callback); - } - async restoreItem(itemId) { - await this.bridge.send(OPERATIONS.restoreItem.name, { itemId }); - } - async maximizeItem(itemId) { - await this.bridge.send(OPERATIONS.maximizeItem.name, { itemId }); - } - async focusItem(itemId) { - await this.bridge.send(OPERATIONS.focusItem.name, { itemId }); - } - async closeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.closeWorkspace.name, { itemId: workspaceId }); - } - async closeItem(itemId) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId }); - } - async closeFrame(itemId, closeOptions) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId, closeOptions }); - } - async resizeItem(itemId, config) { - await this.bridge.send(OPERATIONS.resizeItem.name, Object.assign({}, { itemId }, config)); - } - async setMaximizationBoundary(itemId, config) { - await this.bridge.send(OPERATIONS.setMaximizationBoundary.name, Object.assign({}, { itemId }, config)); - } - async showWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.showLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.hideLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async setWindowDragMode(workspaceId, dragMode) { - await this.bridge.send(OPERATIONS.setWindowDragMode.name, { itemId: workspaceId, dragMode }); - } - async moveFrame(itemId, config) { - await this.bridge.send(OPERATIONS.moveFrame.name, Object.assign({}, { itemId }, config)); - } - getGDWindow(itemId) { - return this.windows.list().find((gdWindow) => gdWindow.id === itemId); - } - async forceLoadWindow(itemId) { - const controlResult = await this.bridge.send(OPERATIONS.forceLoadWindow.name, { itemId }); - return controlResult.windowId; - } - async ejectWindow(itemId, windowId) { - return await this.bridge.send(OPERATIONS.ejectWindow.name, { itemId, windowId }); - } - async moveWindowTo(itemId, newParentId) { - await this.bridge.send(OPERATIONS.moveWindowTo.name, { itemId, containerId: newParentId }); - } - async getSnapshot(itemId, type) { - let result; - if (type === "workspace") { - result = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - } - else if (type === "frame") { - result = await this.bridge.send(OPERATIONS.getFrameSnapshot.name, { itemId }); - } - return result; - } - async setItemTitle(itemId, title) { - await this.bridge.send(OPERATIONS.setItemTitle.name, { itemId, title }); - } - refreshChildren(config) { - const { parent, children, existingChildren, workspace } = config; - if (parent instanceof Window || parent.type === "window") { - return; - } - const newChildren = children.map((newChildSnapshot) => { - let childToAdd = existingChildren.find((child) => { - return child.type === "window" ? child.elementId === newChildSnapshot.id : child.id === newChildSnapshot.id; - }); - if (childToAdd) { - this.privateDataManager.remapChild(childToAdd, { - parent: parent, - children: [], - config: newChildSnapshot.config - }); - } - else { - let createConfig; - if (newChildSnapshot.type === "window") { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - }; - } - else { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - children: [] - }; - } - childToAdd = this.ioc.getModel(newChildSnapshot.type, createConfig); - } - if (newChildSnapshot.type !== "window") { - this.refreshChildren({ - workspace, existingChildren, - children: newChildSnapshot.children, - parent: childToAdd - }); - } - return childToAdd; - }); - if (parent instanceof Workspace) { - return newChildren; - } - else { - this.privateDataManager.remapChild(parent, { children: newChildren }); - return newChildren; - } - } - iterateFindChild(children, predicate) { - let foundChild = children.find((child) => predicate(child)); - if (foundChild) { - return foundChild; - } - children.some((child) => { - if (child instanceof Window) { - return false; - } - foundChild = this.iterateFindChild(child.children, predicate); - if (foundChild) { - return true; - } - }); - return foundChild; - } - iterateFilterChildren(children, predicate) { - const foundChildren = children.filter((child) => predicate(child)); - const grandChildren = children.reduce((innerFound, child) => { - if (child instanceof Window) { - return innerFound; - } - innerFound.push(...this.iterateFilterChildren(child.children, predicate)); - return innerFound; - }, []); - foundChildren.push(...grandChildren); - return foundChildren; - } - notifyWindowAdded(windowId) { - return new Promise((resolve) => { - const alreadyPresent = this.windows.list().some((win) => win.id === windowId); - if (alreadyPresent) { - return resolve(); - } - const unsubscribe = this.windows.onWindowAdded((win) => { - if (win.id !== windowId) { - return; - } - if (unsubscribe) { - unsubscribe(); - } - resolve(); - }); - }); - } - async hibernateWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.hibernateWorkspace.name, { workspaceId }); - } - async resumeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.resumeWorkspace.name, { workspaceId }); - } - async lockWorkspace(workspaceId, config) { - await this.bridge.send(OPERATIONS.lockWorkspace.name, { workspaceId, config }); - } - async lockWindow(windowPlacementId, config) { - await this.bridge.send(OPERATIONS.lockWindow.name, { windowPlacementId, config }); - } - async lockContainer(itemId, type, config) { - await this.bridge.send(OPERATIONS.lockContainer.name, { itemId, type, config }); - } - async pinWorkspace(workspaceId, icon) { - await this.bridge.send(OPERATIONS.pinWorkspace.name, { workspaceId, icon }); - } - async unpinWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.unpinWorkspace.name, { workspaceId }); - } - async getWorkspaceIcon(workspaceId) { - const result = await this.bridge.send(OPERATIONS.getWorkspaceIcon.name, { workspaceId }); - return result.icon; - } - setWorkspaceIcon(workspaceId, icon) { - return this.bridge.send(OPERATIONS.setWorkspaceIcon.name, { workspaceId, icon }); - } - async getPlatformFrameId() { - try { - const result = await this.bridge.send(OPERATIONS.getPlatformFrameId.name, {}); - return result; - } - catch (error) { - return {}; - } - } - async setLoadingStrategy(workspaceId, strategy) { - await this.isOperationSupported(OPERATIONS.setLoadingStrategy.name); - return this.bridge.send(OPERATIONS.setLoadingStrategy.name, { itemId: workspaceId, strategy }); - } - async showFrame(frameId, config) { - const payload = { frameId, isVisible: true, ...config }; - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, payload); - } - async hideFrame(frameId) { - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, { frameId, isVisible: false }); - } - async getFrameVisibility(frameId) { - const result = await this.bridge.send(OPERATIONS.getFrameVisibility.name, { itemId: frameId }); - return result.isVisible; - } - async showFrameDialog(frameId, options) { - const result = await this.bridge.send(OPERATIONS.showFrameDialog.name, { frameId, options }, { timeout: ONE_DAY_MS }); - return result; - } - async isOperationSupported(operation) { - if (isDesktop()) { - return { isSupported: true }; - } - return await this.bridge.send(OPERATIONS.operationCheck.name, { operation }); - } - async showPopup(config, frameId) { - return this.bridge.send(OPERATIONS.showPopup.name, { ...config, frameId }); - } - } - - class MainController { - bridge; - base; - shortcutsController; - closingController; - constructor(bridge, base, shortcutsController, closingController) { - this.bridge = bridge; - this.base = base; - this.shortcutsController = shortcutsController; - this.closingController = closingController; - } - setTaskbarIcon(icon, frameId) { - return this.base.setTaskbarIcon(icon, frameId); - } - getTaskbarIcon(frameId) { - return this.base.getTaskbarIcon(frameId); - } - checkIsWindowLoaded(windowId) { - return this.base.checkIsWindowLoaded(windowId); - } - async checkIsInSwimlane(windowId) { - const controlResult = await this.bridge.send(OPERATIONS.isWindowInWorkspace.name, { itemId: windowId }); - return controlResult.inWorkspace; - } - async createWorkspace(definition, saveConfig) { - const createConfig = Object.assign({}, definition, { saveConfig }); - return await this.base.createWorkspace(createConfig); - } - async createEmptyFrame(definition) { - return await this.base.createEmptyFrame(definition); - } - async initFrame(frameId, config) { - return this.base.initFrame(frameId, config); - } - async restoreWorkspace(name, options) { - const allLayouts = await this.getLayoutSummaries(); - const layoutExists = allLayouts.some((summary) => summary.name === name); - if (!layoutExists) { - throw new Error(`This layout: ${name} cannot be restored, because it doesn't exist.`); - } - if (options?.frameId) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - const foundMatchingFrame = allFrameSummaries.summaries.some((summary) => summary.id === options.frameId); - if (!foundMatchingFrame) { - throw new Error(`Cannot reuse the frame with id: ${options.frameId}, because there is no frame with that ID found`); - } - } - return await this.base.restoreWorkspace(name, options); - } - async add(type, parentId, parentType, definition) { - return await this.base.add(type, parentId, parentType, definition); - } - processLocalSubscription(config, levelId) { - return isDesktop() ? - this.handleEnterpriseLocalSubscription(config, levelId) : - this.handleCoreLocalSubscription(config, levelId); - } - processGlobalSubscription(callback, eventType, action) { - return isDesktop() ? - this.handleEnterpriseGlobalSubscription(callback, eventType, action) : - this.handleCoreGlobalSubscription(callback, eventType, action); - } - async getFrame(selector) { - if (selector.windowId) { - return await this.base.getFrame(selector.windowId); - } - if (selector.predicate) { - return (await this.getFrames(selector.predicate))[0]; - } - throw new Error(`The provided selector is not valid: ${JSON.stringify(selector)}`); - } - async getFrames(predicate) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - return this.base.getFrames(allFrameSummaries.summaries, predicate); - } - getWorkspaceById(workspaceId) { - return this.base.fetchWorkspace(workspaceId); - } - async getWorkspaceByWindowId(itemId) { - if (!isDesktop()) { - return (await this.getWorkspaces((wsp) => !!wsp.getWindow((w) => w.id === itemId)))[0]; - } - return this.base.fetchWorkspace(itemId); - } - transformStreamPayloadToWorkspace(payload) { - return this.base.transformStreamPayloadToWorkspace(payload); - } - async getWorkspace(predicate) { - let foundWorkspace; - await this.iterateWorkspaces((wsp, end) => { - if (predicate(wsp)) { - foundWorkspace = wsp; - end(); - } - }); - return foundWorkspace; - } - async getWorkspaces(predicate) { - const matchingWorkspaces = []; - await this.iterateWorkspaces((wsp) => { - if (!predicate || predicate(wsp)) { - matchingWorkspaces.push(wsp); - } - }); - return matchingWorkspaces; - } - async getWorkspacesByFrameId(frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - const workspacesForFrame = await Promise.all(summariesForFrame.map((summary) => { - return this.base.fetchWorkspace(summary.id); - })); - return workspacesForFrame; - } - async isLastWorkspaceInFrame(workspaceId, frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - return summariesForFrame.length === 1 && summariesForFrame[0].id === workspaceId; - } - async getAllWorkspaceSummaries() { - const allSummariesResult = await this.bridge.send(OPERATIONS.getAllWorkspacesSummaries.name, {}); - return this.base.getAllWorkspaceSummaries(allSummariesResult); - } - async getWindow(predicate) { - let resultWindow; - await this.iterateWorkspaces((wsp, end) => { - const foundWindow = wsp.getWindow(predicate); - if (foundWindow) { - resultWindow = foundWindow; - end(); - } - }); - return resultWindow; - } - async getParent(predicate) { - let resultParent; - await this.iterateWorkspaces((wsp, end) => { - const foundParent = wsp.getBox(predicate); - if (foundParent) { - resultParent = foundParent; - end(); - } - }); - return resultParent; - } - async getLayoutSummaries() { - const allLayouts = await this.bridge.send(OPERATIONS.getAllLayoutsSummaries.name); - return allLayouts.summaries; - } - async deleteLayout(name) { - await this.bridge.send(OPERATIONS.deleteLayout.name, { name }); - } - async exportLayout(predicate) { - const allLayoutsResult = await this.bridge.send(OPERATIONS.exportAllLayouts.name); - return allLayoutsResult.layouts.reduce((matchingLayouts, layout) => { - if (!predicate || predicate(layout)) { - matchingLayouts.push(layout); - } - return matchingLayouts; - }, []); - } - async saveLayout(config) { - return await this.bridge.send(OPERATIONS.saveLayout.name, config); - } - async importLayouts(layouts, mode) { - if (isDesktop()) { - try { - await this.bridge.send(OPERATIONS.importLayouts.name, { layouts, mode }); - } - catch (error) { - await Promise.all(layouts.map((layout) => this.bridge.send(OPERATIONS.importLayout.name, { layout, mode }))); - } - return; - } - await this.base.importLayouts(layouts, mode); - } - handleOnSaved(callback) { - return this.base.handleOnSaved(callback); - } - handleOnRemoved(callback) { - return this.base.handleOnRemoved(callback); - } - async bundleWorkspaceTo(type, workspaceId) { - return await this.base.bundleWorkspaceTo(type, workspaceId); - } - async bundleItemTo(type, id) { - return await this.base.bundleItemTo(type, id); - } - getWorkspaceContext(workspaceId) { - return this.base.getWorkspaceContext(workspaceId); - } - setWorkspaceContext(workspaceId, data) { - return this.base.setWorkspaceContext(workspaceId, data); - } - updateWorkspaceContext(workspaceId, data) { - return this.base.updateWorkspaceContext(workspaceId, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - return this.base.subscribeWorkspaceContextUpdated(workspaceId, callback); - } - async restoreItem(itemId) { - return await this.base.restoreItem(itemId); - } - async maximizeItem(itemId) { - return await this.base.maximizeItem(itemId); - } - async focusItem(itemId) { - return await this.base.focusItem(itemId); - } - async changeFrameState(frameId, state) { - await this.bridge.send(OPERATIONS.changeFrameState.name, { frameId, requestedState: state }); - } - async getFrameBounds(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameBounds.name, { itemId: frameId }); - return frameResult.bounds; - } - async getFrameState(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameState.name, { itemId: frameId }); - return frameResult.state; - } - async closeWorkspace(workspaceId, frameId) { - if (isDesktop()) { - return await this.closeItem(workspaceId); - } - let closeWorkspaceCommandExists = false; - try { - const { isSupported } = await this.base.isOperationSupported(OPERATIONS.closeWorkspace.name); - closeWorkspaceCommandExists = isSupported; - } - catch (error) { - closeWorkspaceCommandExists = false; - } - if (closeWorkspaceCommandExists) { - return await this.base.closeWorkspace(workspaceId); - } - return await this.legacyCloseWorkspace(workspaceId, frameId); - } - async closeItem(itemId) { - return await this.base.closeItem(itemId); - } - async closeFrame(itemId, closeOptions) { - return await this.base.closeFrame(itemId, closeOptions); - } - async resizeItem(itemId, config) { - return await this.base.resizeItem(itemId, config); - } - async setMaximizationBoundary(itemId, config) { - return await this.base.setMaximizationBoundary(itemId, config); - } - async showWorkspaceLoadingAnimation(workspaceId) { - return await this.base.showWorkspaceLoadingAnimation(workspaceId); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - return await this.base.hideWorkspaceLoadingAnimation(workspaceId); - } - async setWindowDragMode(workspaceId, dragMode) { - return await this.base.setWindowDragMode(workspaceId, dragMode); - } - async moveFrame(itemId, config) { - return await this.base.moveFrame(itemId, config); - } - getGDWindow(itemId) { - return this.base.getGDWindow(itemId); - } - async forceLoadWindow(itemId) { - const windowId = await this.base.forceLoadWindow(itemId); - await this.base.notifyWindowAdded(windowId); - return windowId; - } - async ejectWindow(itemId, windowId) { - const id = (await this.base.ejectWindow(itemId, windowId)).windowId; - await this.base.notifyWindowAdded(id); - return id; - } - async moveWindowTo(itemId, newParentId) { - return await this.base.moveWindowTo(itemId, newParentId); - } - async getSnapshot(itemId, type) { - return await this.base.getSnapshot(itemId, type); - } - async setItemTitle(itemId, title) { - return await this.base.setItemTitle(itemId, title); - } - flatChildren(children) { - return children.reduce((soFar, child) => { - soFar.push(child); - if (child.type !== "window") { - soFar.push(...this.flatChildren(child.children)); - } - return soFar; - }, []); - } - refreshChildren(config) { - return this.base.refreshChildren(config); - } - iterateFindChild(children, predicate) { - return this.base.iterateFindChild(children, predicate); - } - iterateFilterChildren(children, predicate) { - return this.base.iterateFilterChildren(children, predicate); - } - hibernateWorkspace(workspaceId) { - return this.base.hibernateWorkspace(workspaceId); - } - resumeWorkspace(workspaceId) { - return this.base.resumeWorkspace(workspaceId); - } - lockWorkspace(workspaceId, config) { - return this.base.lockWorkspace(workspaceId, config); - } - lockWindow(windowPlacementId, config) { - return this.base.lockWindow(windowPlacementId, config); - } - lockContainer(itemId, type, config) { - return this.base.lockContainer(itemId, type, config); - } - pinWorkspace(workspaceId, icon) { - return this.base.pinWorkspace(workspaceId, icon); - } - unpinWorkspace(workspaceId) { - return this.base.unpinWorkspace(workspaceId); - } - getWorkspaceIcon(workspaceId) { - return this.base.getWorkspaceIcon(workspaceId); - } - setWorkspaceIcon(workspaceId, icon) { - return this.base.setWorkspaceIcon(workspaceId, icon); - } - async getFrameConstraints(frameId) { - const frameSnapshot = await this.getSnapshot(frameId, "frame"); - return { - minWidth: frameSnapshot.config.minWidth, - maxWidth: frameSnapshot.config.maxWidth, - minHeight: frameSnapshot.config.minHeight, - maxHeight: frameSnapshot.config.maxHeight, - }; - } - registerShortcut(shortcut, frameId, callback) { - return this.shortcutsController.registerShortcut(shortcut, frameId, callback); - } - getPlatformFrameId() { - return this.base.getPlatformFrameId(); - } - setLoadingStrategy(workspaceId, strategy) { - return this.base.setLoadingStrategy(workspaceId, strategy); - } - registerFrameOnClosing(frameId, callback) { - return this.closingController.registerFrameOnClosing(frameId, callback); - } - showPopup(config, frameId) { - return this.base.showPopup(config, frameId); - } - async showFrame(frameId, config) { - return this.base.showFrame(frameId, config); - } - async hideFrame(frameId) { - return this.base.hideFrame(frameId); - } - async getFrameVisibility(frameId) { - return this.base.getFrameVisibility(frameId); - } - async showFrameDialog(frameId, options) { - return this.base.showFrameDialog(frameId, options); - } - async handleCoreLocalSubscription(config, levelId) { - await this.bridge.createCoreEventSubscription(); - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseLocalSubscription(config, levelId) { - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async handleCoreGlobalSubscription(callback, eventType, action) { - await this.bridge.createCoreEventSubscription(); - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseGlobalSubscription(callback, eventType, action) { - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async iterateWorkspaces(callback) { - let ended = false; - const end = () => { ended = true; }; - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - for (const summary of workspaceSummaries) { - if (ended) { - return; - } - const wsp = await this.base.fetchWorkspace(summary.id); - callback(wsp, end); - } - } - async legacyCloseWorkspace(workspaceId, frameId) { - const isLastWorkspaceInFrame = await this.isLastWorkspaceInFrame(workspaceId, frameId); - const platformFrameId = (await this.getPlatformFrameId()).id; - const shouldCloseFrame = isLastWorkspaceInFrame && - platformFrameId !== frameId; - if (shouldCloseFrame) { - return await this.closeFrame(frameId, {}); - } - await this.closeItem(workspaceId); - } - } - - class ShortcutsController { - bridge; - _shortcuts = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.bridge.onOperation((payload) => { - if (payload.operation === CLIENT_OPERATIONS.shortcutClicked.name) { - const data = payload.data; - this._shortcuts.execute(`${data.frameId}-${data.shortcut}`); - } - }); - } - async registerShortcut(shortcut, frameId, callback) { - await this.bridge.send(OPERATIONS.registerShortcut.name, { shortcut, frameId }); - const un = this._shortcuts.add(`${frameId}-${shortcut}`, callback); - return () => { - un(); - this.bridge.send(OPERATIONS.unregisterShortcut.name, { shortcut, frameId }); - }; - } - } - - class ClosingController { - bridge; - registry = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.subscribeToFrameClosing(); - } - async registerFrameOnClosing(frameId, callback) { - await this.bridge.send(OPERATIONS.subscribeToFrameClosing.name, { itemId: frameId }); - return this.registry.add(frameId, callback); - } - subscribeToFrameClosing() { - this.bridge.onOperationWithResponse(async (payload) => { - if (payload.operation !== CLIENT_OPERATIONS.frameClosing.name) { - return; - } - const data = payload.data; - const frameClosingResult = await Promise.all(this.registry.execute(data.frameId)); - return this.aggregateFrameClosingResult(frameClosingResult); - }); - } - aggregateFrameClosingResult(results) { - return { - prevent: results.some((result) => result?.prevent) - }; - } - } - - class IoC { - agm; - windows; - layouts; - contexts; - _controllerInstance; - _bridgeInstance; - _transportInstance; - _privateDataManagerInstance; - _parentBaseInstance; - _baseController; - _shortcutsController; - _closingController; - constructor(agm, windows, layouts, contexts) { - this.agm = agm; - this.windows = windows; - this.layouts = layouts; - this.contexts = contexts; - } - get baseController() { - if (!this._baseController) { - this._baseController = new BaseController(this, this.windows, this.contexts, this.layouts); - } - return this._baseController; - } - get controller() { - if (!this._controllerInstance) { - this._controllerInstance = new MainController(this.bridge, this.baseController, this.shortcutsController, this.closingController); - } - return this._controllerInstance; - } - get shortcutsController() { - if (!this._shortcutsController) { - this._shortcutsController = new ShortcutsController(this.bridge); - } - return this._shortcutsController; - } - get closingController() { - if (!this._closingController) { - this._closingController = new ClosingController(this.bridge); - } - return this._closingController; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new Bridge(this.transport, CallbackFactory()); - } - return this._bridgeInstance; - } - get transport() { - if (!this._transportInstance) { - this._transportInstance = new InteropTransport(this.agm, CallbackFactory()); - } - return this._transportInstance; - } - get privateDataManager() { - if (!this._privateDataManagerInstance) { - this._privateDataManagerInstance = new PrivateDataManager(); - } - return this._privateDataManagerInstance; - } - get parentBase() { - if (!this._parentBaseInstance) { - this._parentBaseInstance = new Base(this.privateDataManager); - } - return this._parentBaseInstance; - } - async initiate(actualWindowId) { - await this.transport.initiate(actualWindowId); - } - getModel(type, createConfig) { - switch (type) { - case "frame": { - const newFrame = new Frame(this.privateDataManager); - const { summary } = createConfig; - const frameData = { summary, controller: this.controller }; - this.privateDataManager.setFrameData(newFrame, frameData); - return newFrame; - } - case "window": { - const { id, parent, frame, workspace, config } = createConfig; - const windowPrivateData = { - type: "window", - controller: this.controller, - config, id, parent, frame, workspace - }; - const newWindow = new Window(this.privateDataManager); - this.privateDataManager.setWindowData(newWindow, windowPrivateData); - return newWindow; - } - case "row": - case "column": - case "group": { - const { id, children, parent, frame, workspace, config } = createConfig; - const newParent = type === "column" ? new Column(this.parentBase) : - type === "row" ? new Row(this.parentBase) : new Group(this.parentBase); - const builtChildren = this.buildChildren(children, frame, workspace, newParent); - const parentPrivateData = { - id, parent, frame, workspace, - config, - type, - controller: this.controller, - children: builtChildren, - }; - this.privateDataManager.setParentData(newParent, parentPrivateData); - return newParent; - } - case "workspace": { - const { snapshot, frame } = createConfig; - const newWorkspace = new Workspace(this.privateDataManager); - const children = this.buildChildren(snapshot.children, frame, newWorkspace, newWorkspace); - const workspacePrivateData = { - id: snapshot.id, - type: "workspace", - config: snapshot.config, - base: this.parentBase, - controller: this.controller, - children, frame, ioc: this - }; - this.privateDataManager.setWorkspaceData(newWorkspace, workspacePrivateData); - return newWorkspace; - } - default: throw new Error(`Unrecognized type: ${type}`); - } - } - getBuilder(config) { - config.definition = config.definition || {}; - if (!Array.isArray(config.definition.children)) { - config.definition.children = []; - } - const baseBuilder = new BaseBuilder(this.getBuilder.bind(this)); - switch (config.type) { - case "workspace": { - return new WorkspaceBuilder(config.definition, baseBuilder, this.controller); - } - case "row": - case "column": - case "group": { - config.definition.type = config.type; - return new ParentBuilder(config.definition, baseBuilder); - } - default: throw new Error(`Unexpected Builder creation error, provided config: ${JSON.stringify(config)}`); - } - } - buildChildren(children, frame, workspace, parent) { - return children.map((child) => { - switch (child.type) { - case "window": return this.getModel("window", { - id: child.id, - config: child.config, - frame, workspace, parent - }); - case "column": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "row": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "group": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - default: throw new Error(`Unsupported child type: ${child.type}`); - } - }); - } - } - - var version = "4.2.3"; - - const composeAPI = (glue, ioc) => { - const controller = ioc.controller; - const inWorkspace = () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - return controller.checkIsInSwimlane(myId); - }; - const getBuilder = (config) => { - const validatedConfig = builderConfigDecoder.runWithException(config); - return ioc.getBuilder(validatedConfig); - }; - const getMyFrame = async () => { - const windowId = glue.windows.my().id; - if (!windowId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(windowId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your frame, because this window is not in a workspace"); - } - return controller.getFrame({ windowId }); - }; - const getFrame = async (predicate) => { - checkThrowCallback(predicate); - return controller.getFrame({ predicate }); - }; - const getAllFrames = async (predicate) => { - checkThrowCallback(predicate, true); - return controller.getFrames(predicate); - }; - const getAllWorkspacesSummaries = () => { - return controller.getAllWorkspaceSummaries(); - }; - const getMyWorkspace = async () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my workspace, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(myId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your workspace, because this window is not in a workspace"); - } - return await controller.getWorkspaceByWindowId(myId); - }; - const getWorkspace = async (predicate) => { - checkThrowCallback(predicate); - return (await controller.getWorkspaces(predicate))[0]; - }; - const getWorkspaceById = async (workspaceId) => { - nonEmptyStringDecoder.runWithException(workspaceId); - return controller.getWorkspaceById(workspaceId); - }; - const getAllWorkspaces = (predicate) => { - checkThrowCallback(predicate, true); - return controller.getWorkspaces(predicate); - }; - const getWindow = async (predicate) => { - checkThrowCallback(predicate); - return controller.getWindow(predicate); - }; - const getParent = async (predicate) => { - checkThrowCallback(predicate); - return controller.getParent(predicate); - }; - const restoreWorkspace = async (name, options) => { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return controller.restoreWorkspace(name, validatedOptions); - }; - const createWorkspace = async (definition, saveConfig) => { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(saveConfig); - return controller.createWorkspace(validatedDefinition, validatedConfig); - }; - const createEmptyFrame = async (definition) => { - const validatedDefinition = emptyFrameDefinitionDecoder.runWithException(definition); - return controller.createEmptyFrame(validatedDefinition ?? {}); - }; - const layouts = { - getSummaries: () => { - return controller.getLayoutSummaries(); - }, - delete: async (name) => { - nonEmptyStringDecoder.runWithException(name); - return controller.deleteLayout(name); - }, - export: async (predicate) => { - checkThrowCallback(predicate, true); - return controller.exportLayout(predicate); - }, - import: async (layouts, mode = "replace") => { - if (!Array.isArray(layouts)) { - throw new Error(`The provided layouts argument is not an array: ${JSON.stringify(layouts)}`); - } - layouts.forEach((layout) => workspaceLayoutDecoder.runWithException(layout)); - return controller.importLayouts(layouts, mode); - }, - save: async (config) => { - const verifiedConfig = workspaceLayoutSaveConfigDecoder.runWithException(config); - return controller.saveLayout(verifiedConfig); - }, - onSaved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnSaved(callback); - }, - onRemoved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnRemoved(callback); - } - }; - const onFrameOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - callback(frame); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "opened"); - return unsubscribe; - }; - const onFrameClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "closed"); - return unsubscribe; - }; - const onWorkspaceOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "opened"); - return unsubscribe; - }; - const onWorkspaceClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "closed"); - return unsubscribe; - }; - const onWorkspaceHibernated = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "hibernated"); - return unsubscribe; - }; - const onWorkspaceResumed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "resumed"); - return unsubscribe; - }; - const onWindowAdded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "added"); - return unsubscribe; - }; - const onWindowLoaded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const foundWindow = workspace.getWindow((win) => win.id && win.id === payload.windowSummary.config.windowId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "loaded"); - return unsubscribe; - }; - const onWindowRemoved = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "removed"); - return unsubscribe; - }; - const onWindowMaximized = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "maximized"); - return unsubscribe; - }; - const onWindowRestored = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "restored"); - return unsubscribe; - }; - const onWindowSelected = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "selected"); - return unsubscribe; - }; - const waitForFrame = async (id) => { - nonEmptyStringDecoder.runWithException(id); - return new Promise((res, rej) => { - let unsub = () => { - }; - onFrameOpened((f) => { - if (f.id === id) { - res(f); - unsub(); - } - }).then((u) => { - unsub = u; - return getAllFrames(); - }).then((frames) => { - const myFrame = frames.find((f) => f.id === id); - if (myFrame) { - res(myFrame); - unsub(); - } - }).catch(rej); - }); - }; - return { - inWorkspace, - getBuilder, - getMyFrame, - getFrame, - getAllFrames, - getAllWorkspacesSummaries, - getMyWorkspace, - getWorkspace, - getWorkspaceById, - getAllWorkspaces, - getWindow, - getBox: getParent, - restoreWorkspace, - createWorkspace, - createEmptyFrame, - waitForFrame, - layouts, - onFrameOpened, - onFrameClosed, - onWorkspaceOpened, - onWorkspaceClosed, - onWorkspaceHibernated, - onWorkspaceResumed, - onWindowAdded, - onWindowLoaded, - onWindowRemoved, - onWindowMaximized, - onWindowRestored, - onWindowSelected, - version - }; - }; - - const factoryFunction = async (io) => { - const ioc = new IoC(io.agm, io.windows, io.layouts, io.contexts); - const actualWindowId = io.interop.instance.windowId; - await ioc.initiate(actualWindowId); - io.workspaces = composeAPI(io, ioc); - }; - if (typeof window !== "undefined") { - window.IOWorkspaces = factoryFunction; - } - - return factoryFunction; - -})); -//# sourceMappingURL=workspaces.umd.js.map diff --git a/javascript/solution/stocks/package-lock.json b/javascript/solution/stocks/package-lock.json new file mode 100644 index 0000000..525a164 --- /dev/null +++ b/javascript/solution/stocks/package-lock.json @@ -0,0 +1,1280 @@ +{ + "name": "stocks", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "stocks", + "version": "1.0.0", + "dependencies": { + "@interopio/browser": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@interopio/browser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser/-/browser-4.2.4.tgz", + "integrity": "sha512-BPgkwH6N8HyGf7st99ZJwQ7arijz9j1bGu7pUAXBrtbv6cu4zH5GR7JKPGANZmFl0uefNPQyAQ4hc7C/i1i++A==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0", + "@interopio/search-api": "^3.2.1", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.2" + } + }, + "node_modules/@interopio/core": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@interopio/core/-/core-6.8.1.tgz", + "integrity": "sha512-WFWIV8JilNuAcxXaB+81IjL9j82sU73ABMUUEOWpvWoyqxhPlneOS+rSYViFX5gdk5pLH3fM6T/MmRGn3UFLwQ==", + "license": "MIT", + "dependencies": { + "callback-registry": "^2.7.2", + "ws": "^8.18.0" + } + }, + "node_modules/@interopio/desktop": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/@interopio/desktop/-/desktop-6.18.0.tgz", + "integrity": "sha512-YqRHRiCymbY2fOCT2HHJnLY4780JSRI1fUtaWEoIa5Z3djZk/3xRgVxIjOVw9Y/TAFGCwyIeW142a7HYnSGD5Q==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/schemas": "^10.1.0", + "@interopio/utils": "^1.4.2", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.1" + } + }, + "node_modules/@interopio/schemas": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@interopio/schemas/-/schemas-10.1.0.tgz", + "integrity": "sha512-8uDEoOAZenTr4a3O8vLq6JyS/LutkT/gh9EjuOrS9fOmHEUfJaS2u+qPo5em9/8MtjKgblZEJStSsW1gr34CtQ==", + "license": "ISC", + "dependencies": { + "ajv": "^6.12.6", + "ajv-keywords": "^3.4.1" + }, + "peerDependencies": { + "log4js": "^6.4.2" + }, + "peerDependenciesMeta": { + "log4js": { + "optional": true + } + } + }, + "node_modules/@interopio/search-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@interopio/search-api/-/search-api-3.2.1.tgz", + "integrity": "sha512-raUZzqBQoidm/6Mvgao2wFWlTDu9D4jghiX1dqor1LdsIfUpelJkkuFGeDl0z/3DWneaxDF8Vc/uoBtLz7qJLw==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1" + } + }, + "node_modules/@interopio/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@interopio/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-14Bb2WI9Cwf9zjhTurP4qP9AVY4cxR1AOrwrOtHrTGAeeHp88mALFWfMEv1QnRhlQ06To2vQcRgebNrPlHDZ8Q==", + "license": "ISC", + "dependencies": { + "decoder-validate": "^0.0.2" + } + }, + "node_modules/@interopio/workspaces-api": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@interopio/workspaces-api/-/workspaces-api-4.2.3.tgz", + "integrity": "sha512-5wrR1yhETKuX4txVrmS5q3G+8KI6GW4yOxsrVdf5qErO2HxN938XUdiAHIesarwlQoncrgnVx7uTn6IeOWUoXg==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/callback-registry": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/callback-registry/-/callback-registry-2.7.2.tgz", + "integrity": "sha512-VVrtF21DaH0VHeNMkLDd4VGuxsYM3V3l3lwYneKVMU/6X3TRtcQszUwlAcqj2HrLcbP1NyS12LsanUwCykaz/Q==", + "license": "ISC" + }, + "node_modules/decoder-validate": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/decoder-validate/-/decoder-validate-0.0.2.tgz", + "integrity": "sha512-9BsqAH9Zq6CvlxKHkSrZrH2iYlhuhHcrh6uTnDvcsa9P5YEweEzt1ci+X/9STgSCE7b9BA7/QIiwhfUDDWmjxw==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/javascript/solution/stocks/package.json b/javascript/solution/stocks/package.json new file mode 100644 index 0000000..1ccc6d9 --- /dev/null +++ b/javascript/solution/stocks/package.json @@ -0,0 +1,14 @@ +{ + "name": "stocks", + "version": "1.0.0", + "scripts": { + "start": "vite --port 9100" + }, + "dependencies": { + "@interopio/browser": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } +} diff --git a/javascript/solution/workspace/package-lock.json b/javascript/solution/workspace/package-lock.json new file mode 100644 index 0000000..5e7b5c3 --- /dev/null +++ b/javascript/solution/workspace/package-lock.json @@ -0,0 +1,496 @@ +{ + "name": "workspace", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "workspace", + "version": "1.0.0", + "dependencies": { + "http-server": "^0.12.3" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, + "node_modules/basic-auth": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-1.1.0.tgz", + "integrity": "sha512-CtGuTyWf3ig+sgRyC7uP6DM3N+5ur/p8L+FPfsd+BbIfIs74TFfCajZTHnCw6K5dqM0bZEbRIqRy1fAdiUJhTA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "license": "MIT", + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/corser": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", + "integrity": "sha512-utCYNzRSQIZNPIcGZdQc92UVJYAhtGAteCFg0yRaFm8f0P+CPtyGyHXJcGXnffjCybUCEx3FQ2G7U3/o9eIkVQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecstatic": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/ecstatic/-/ecstatic-3.3.2.tgz", + "integrity": "sha512-fLf9l1hnwrHI2xn9mEDT7KIi22UDqA2jaCwyCbSUJh9a1V+LEUSL/JO/6TIz/QyuBURWUHrFL5Kg2TtO1bkkog==", + "deprecated": "This package is unmaintained and deprecated. See the GH Issue 259.", + "license": "MIT", + "dependencies": { + "he": "^1.1.1", + "mime": "^1.6.0", + "minimist": "^1.1.0", + "url-join": "^2.0.5" + }, + "bin": { + "ecstatic": "lib/ecstatic.js" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "license": "MIT" + }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-server": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-0.12.3.tgz", + "integrity": "sha512-be0dKG6pni92bRjq0kvExtj/NrrAd28/8fCXkaI/4piTwQMSDSLMhWyW0NI1V+DBI3aa1HMlQu46/HjVLfmugA==", + "license": "MIT", + "dependencies": { + "basic-auth": "^1.0.3", + "colors": "^1.4.0", + "corser": "^2.0.1", + "ecstatic": "^3.3.2", + "http-proxy": "^1.18.0", + "minimist": "^1.2.5", + "opener": "^1.5.1", + "portfinder": "^1.0.25", + "secure-compare": "3.0.1", + "union": "~0.5.0" + }, + "bin": { + "hs": "bin/http-server", + "http-server": "bin/http-server" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/opener": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", + "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", + "license": "(WTFPL OR MIT)", + "bin": { + "opener": "bin/opener-bin.js" + } + }, + "node_modules/portfinder": { + "version": "1.0.38", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.38.tgz", + "integrity": "sha512-rEwq/ZHlJIKw++XtLAO8PPuOQA/zaPJOZJ37BVuN97nLpMJeuDVLVGRwbFoBgLudgdTMP2hdRJP++H+8QOA3vg==", + "license": "MIT", + "dependencies": { + "async": "^3.2.6", + "debug": "^4.3.6" + }, + "engines": { + "node": ">= 10.12" + } + }, + "node_modules/qs": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz", + "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "license": "MIT" + }, + "node_modules/secure-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/secure-compare/-/secure-compare-3.0.1.tgz", + "integrity": "sha512-AckIIV90rPDcBcglUwXPF3kg0P0qmPsPXAj6BBEENQE1p5yA1xfmDJzfi1Tappj37Pv2mVbKpL3Z1T+Nn7k1Qw==", + "license": "MIT" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/union": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/union/-/union-0.5.0.tgz", + "integrity": "sha512-N6uOhuW6zO95P3Mel2I2zMsbsanvvtgn6jVqJv4vbVcz/JN0OkL9suomjQGmWtxJQXOCqUJvquc1sMeNz/IwlA==", + "dependencies": { + "qs": "^6.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/url-join": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-2.0.5.tgz", + "integrity": "sha512-c2H1fIgpUdwFRIru9HFno5DT73Ok8hg5oOb5AT3ayIgvCRfxgs2jyt5Slw8kEB7j3QUr6yJmMPDT/odjk7jXow==", + "license": "MIT" + } + } +} diff --git a/javascript/solution/workspace/package.json b/javascript/solution/workspace/package.json new file mode 100644 index 0000000..aab41ea --- /dev/null +++ b/javascript/solution/workspace/package.json @@ -0,0 +1,10 @@ +{ + "name": "workspace", + "version": "1.0.0", + "scripts": { + "start": "http-server . -p 9300 -c-1" + }, + "dependencies": { + "http-server": "^0.12.3" + } +} diff --git a/javascript/start/client-details/index.html b/javascript/start/client-details/index.html index 18fd426..9f50a20 100644 --- a/javascript/start/client-details/index.html +++ b/javascript/start/client-details/index.html @@ -9,9 +9,7 @@ - - - + diff --git a/javascript/start/client-details/index.js b/javascript/start/client-details/index.js index 5c9380e..b76c24a 100644 --- a/javascript/start/client-details/index.js +++ b/javascript/start/client-details/index.js @@ -1,3 +1,8 @@ +// TODO: Chapter 2 +// import IOBrowser from '@interopio/browser'; +// TODO: Chapter 9.3 +// import IOWorkspaces from '@interopio/workspaces-api'; + const setFields = (client) => { const elementName = document.querySelectorAll("[data-name]")[0]; elementName.innerText = client.name; diff --git a/javascript/start/client-details/lib/browser.umd.js b/javascript/start/client-details/lib/browser.umd.js deleted file mode 100644 index a5e6fcb..0000000 --- a/javascript/start/client-details/lib/browser.umd.js +++ /dev/null @@ -1,17399 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.browser = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs$1 (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) - }; - - function isNonNullObject(value) { - return !!value && typeof value === 'object' - } - - function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); - - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) - } - - // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 - var canUseSymbol = typeof Symbol === 'function' && Symbol.for; - var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; - - function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE - } - - function emptyTarget(val) { - return Array.isArray(val) ? [] : {} - } - - function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value - } - - function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) - } - - function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge - } - - function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return Object.propertyIsEnumerable.call(target, symbol) - }) - : [] - } - - function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) - } - - function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } - } - - // Protects from prototype poisoning and unexpected merging up the prototype chain. - function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. - } - - function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } - - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination - } - - function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; - - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } - } - - deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } - - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) - }; - - var deepmerge_1 = deepmerge; - - var cjs = deepmerge_1; - - var deepmerge$1 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$2 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$2 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$2 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$2 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$2 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$2 = function (f, r) { - return r.ok === true ? ok$2(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$2(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$2 = function (f, r) { - return r.ok === true ? r : err$2(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$2 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$2 = function() { - __assign$2 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - - function __rest$2(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$2(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$2(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$2(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$2 = function (json) { return Array.isArray(json); }; - var isJsonObject$2 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$2(json); - }; - var typeString$2 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$2 = function (expected, got) { - return "expected " + expected + ", got " + typeString$2(got); - }; - var printPath$2 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$2 = function (newAt, _a) { - var at = _a.at, rest = __rest$2(_a, ["at"]); - return (__assign$2({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$2 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$2(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$2(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$2(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$2(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$2(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$2(json) - : err$2({ message: expectedGot$2('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$2(json) - : err$2({ message: expectedGot$2('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$2(json) - : err$2({ message: expectedGot$2('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$2(json, value) - ? ok$2(value) - : err$2({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$2(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$2({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else if (isJsonObject$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$2(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$2(function (err$$1) { return prependAt$2("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$2([])); - } - else if (isJsonArray$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$2(json)) { - if (json.length !== decoders.length) { - return err$2({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$2(prependAt$2("[" + i + "]", nth.error)); - } - } - return ok$2(result); - } - else { - return err$2({ message: expectedGot$2("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$2(Object.assign, acc, decoder.decode(json)); }, ok$2({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$2(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$2(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$2(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$2(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$2({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$2(withDefault$2(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$2(function (error) { - return jsonAtPath === undefined - ? { at: printPath$2(paths), message: 'path does not exist' } - : prependAt$2(printPath$2(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$2(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$2({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$2 = Decoder$2.string; - /** See `Decoder.number` */ - var number$2 = Decoder$2.number; - /** See `Decoder.boolean` */ - var boolean$2 = Decoder$2.boolean; - /** See `Decoder.anyJson` */ - var anyJson$2 = Decoder$2.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$2.unknownJson; - /** See `Decoder.constant` */ - var constant$2 = Decoder$2.constant; - /** See `Decoder.object` */ - var object$2 = Decoder$2.object; - /** See `Decoder.array` */ - var array$2 = Decoder$2.array; - /** See `Decoder.tuple` */ - Decoder$2.tuple; - /** See `Decoder.dict` */ - Decoder$2.dict; - /** See `Decoder.optional` */ - var optional$2 = Decoder$2.optional; - /** See `Decoder.oneOf` */ - var oneOf$1 = Decoder$2.oneOf; - /** See `Decoder.union` */ - var union$1 = Decoder$2.union; - /** See `Decoder.intersection` */ - var intersection = Decoder$2.intersection; - /** See `Decoder.withDefault` */ - Decoder$2.withDefault; - /** See `Decoder.valueAt` */ - Decoder$2.valueAt; - /** See `Decoder.succeed` */ - Decoder$2.succeed; - /** See `Decoder.fail` */ - Decoder$2.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder$2.lazy; - - const defaultConfig = { - gateway: { webPlatform: {} }, - libraries: [], - exposeAPI: true, - }; - const defaultWidgetConfig = { - awaitFactory: true, - enable: false, - timeout: 5 * 1000, - restoreLastKnownPosition: true, - }; - const defaultModalsConfig = { - alerts: { - enabled: false - }, - dialogs: { - enabled: false - }, - awaitFactory: true, - timeout: 5 * 1000, - }; - const defaultIntentResolverConfig = { - enable: false, - timeout: 5 * 1000, - awaitFactory: true, - }; - - const Glue42CoreMessageTypes = { - platformUnload: { name: "platformUnload" }, - transportSwitchRequest: { name: "transportSwitchRequest" }, - transportSwitchResponse: { name: "transportSwitchResponse" }, - getCurrentTransport: { name: "getCurrentTransport" }, - getCurrentTransportResponse: { name: "getCurrentTransportResponse" }, - checkPreferredLogic: { name: "checkPreferredLogic" }, - checkPreferredConnection: { name: "checkPreferredConnection" }, - checkPreferredLogicResponse: { name: "checkPreferredLogicResponse" }, - checkPreferredConnectionResponse: { name: "checkPreferredConnectionResponse" } - }; - const webPlatformTransportName = "web-platform"; - const latestFDC3Type = "latest_fdc3_type"; - const errorChannel = new MessageChannel(); - const REQUEST_WIDGET_READY = "requestWidgetFactoryReady"; - const REQUEST_MODALS_UI_FACTORY_READY = "requestModalsUIFactoryReady"; - const MAX_SET_TIMEOUT_DELAY = 2147483647; - const REQUEST_INTENT_RESOLVER_UI_FACTORY_READY = "requestIntentResolverUIFactoryReady"; - const READONLY_PROPERTY_DESCRIPTOR = { - configurable: false, - enumerable: true, - writable: false, - }; - - const extractErrorMsg = (error) => { - if (typeof error === "string") { - return error; - } - if (error?.message) { - return typeof error.message === "string" ? error.message : JSON.stringify(error.message); - } - return JSON.stringify(error); - }; - const runDecoderWithIOError = (decoder, json) => { - try { - const result = decoder.runWithException(json); - return result; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const getSupportedOperationsNames = (operations) => { - return Object.keys(operations).filter((operation) => (operations)[operation].execute); - }; - const handleOperationCheck = (supportedOperations, operationName) => { - const isSupported = supportedOperations.some((operation) => operation.toLowerCase() === operationName.toLowerCase()); - return { isSupported }; - }; - const getSafeTimeoutDelay = (delay) => { - return Math.min(delay, MAX_SET_TIMEOUT_DELAY); - }; - const wrapPromise = () => { - let wrapperResolve; - let wrapperReject; - const promise = new Promise((resolve, reject) => { - wrapperResolve = resolve; - wrapperReject = reject; - }); - return { promise, resolve: wrapperResolve, reject: wrapperReject }; - }; - - class IOError { - raiseError(error, shouldThrowOriginalError) { - const errorMessage = extractErrorMsg(error); - errorChannel.port1.postMessage(errorMessage); - if (shouldThrowOriginalError) { - throw error; - } - throw new Error(errorMessage); - } - } - const ioError = new IOError(); - - const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"]; - const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"]; - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$1 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$1 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$1 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$1 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$1 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$1 = function (f, r) { - return r.ok === true ? ok$1(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$1 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$1(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$1 = function (f, r) { - return r.ok === true ? r : err$1(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$1 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$1 = function() { - __assign$1 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - - function __rest$1(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$1(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$1(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$1(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$1 = function (json) { return Array.isArray(json); }; - var isJsonObject$1 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$1(json); - }; - var typeString$1 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$1 = function (expected, got) { - return "expected " + expected + ", got " + typeString$1(got); - }; - var printPath$1 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$1 = function (newAt, _a) { - var at = _a.at, rest = __rest$1(_a, ["at"]); - return (__assign$1({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$1 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$1(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$1(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$1(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$1(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$1(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$1(json) - : err$1({ message: expectedGot$1('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$1(json) - : err$1({ message: expectedGot$1('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$1(json) - : err$1({ message: expectedGot$1('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$1(json, value) - ? ok$1(value) - : err$1({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$1(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$1({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else if (isJsonObject$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$1(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$1(function (err$$1) { return prependAt$1("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$1(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$1([])); - } - else if (isJsonArray$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$1(json)) { - if (json.length !== decoders.length) { - return err$1({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$1(prependAt$1("[" + i + "]", nth.error)); - } - } - return ok$1(result); - } - else { - return err$1({ message: expectedGot$1("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$1(Object.assign, acc, decoder.decode(json)); }, ok$1({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$1(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$1(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$1(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$1(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$1({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$1(withDefault$1(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$1(function (error) { - return jsonAtPath === undefined - ? { at: printPath$1(paths), message: 'path does not exist' } - : prependAt$1(printPath$1(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$1(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$1({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$1 = Decoder$1.string; - /** See `Decoder.number` */ - var number$1 = Decoder$1.number; - /** See `Decoder.boolean` */ - var boolean$1 = Decoder$1.boolean; - /** See `Decoder.anyJson` */ - var anyJson$1 = Decoder$1.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$1.unknownJson; - /** See `Decoder.constant` */ - var constant$1 = Decoder$1.constant; - /** See `Decoder.object` */ - var object$1 = Decoder$1.object; - /** See `Decoder.array` */ - var array$1 = Decoder$1.array; - /** See `Decoder.tuple` */ - Decoder$1.tuple; - /** See `Decoder.dict` */ - var dict = Decoder$1.dict; - /** See `Decoder.optional` */ - var optional$1 = Decoder$1.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder$1.oneOf; - /** See `Decoder.union` */ - Decoder$1.union; - /** See `Decoder.intersection` */ - Decoder$1.intersection; - /** See `Decoder.withDefault` */ - Decoder$1.withDefault; - /** See `Decoder.valueAt` */ - Decoder$1.valueAt; - /** See `Decoder.succeed` */ - Decoder$1.succeed; - /** See `Decoder.fail` */ - Decoder$1.fail; - /** See `Decoder.lazy` */ - Decoder$1.lazy; - - const nonEmptyStringDecoder$3 = string$1().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$3 = number$1().where((num) => num >= 0, "Expected a non-negative number"); - const regexDecoder = anyJson$1().andThen((value) => { - return value instanceof RegExp ? anyJson$1() : fail(`expected a regex, got a ${typeof value}`); - }); - - const intentDefinitionDecoder$1 = object$1({ - name: nonEmptyStringDecoder$3, - displayName: optional$1(string$1()), - contexts: optional$1(array$1(string$1())), - customConfig: optional$1(object$1()) - }); - const v2TypeDecoder = oneOf(constant$1("web"), constant$1("native"), constant$1("citrix"), constant$1("onlineNative"), constant$1("other")); - const v2DetailsDecoder = object$1({ - url: nonEmptyStringDecoder$3 - }); - const v2IconDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3) - }); - const v2ScreenshotDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3), - label: optional$1(nonEmptyStringDecoder$3) - }); - const v2ListensForIntentDecoder = object$1({ - contexts: array$1(nonEmptyStringDecoder$3), - displayName: optional$1(nonEmptyStringDecoder$3), - resultType: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(anyJson$1()) - }); - const v2IntentsDecoder = object$1({ - listensFor: optional$1(dict(v2ListensForIntentDecoder)), - raises: optional$1(dict(array$1(nonEmptyStringDecoder$3))) - }); - const v2UserChannelDecoder = object$1({ - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2AppChannelDecoder = object$1({ - name: nonEmptyStringDecoder$3, - description: optional$1(nonEmptyStringDecoder$3), - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2InteropDecoder = object$1({ - intents: optional$1(v2IntentsDecoder), - userChannels: optional$1(v2UserChannelDecoder), - appChannels: optional$1(array$1(v2AppChannelDecoder)) - }); - const glue42ApplicationDetailsDecoder = object$1({ - url: optional$1(nonEmptyStringDecoder$3), - top: optional$1(number$1()), - left: optional$1(number$1()), - width: optional$1(nonNegativeNumberDecoder$3), - height: optional$1(nonNegativeNumberDecoder$3) - }); - const glue42HostManifestsBrowserDecoder = object$1({ - name: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3.where((s) => s === "window", "Expected a value of window")), - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - customProperties: optional$1(anyJson$1()), - icon: optional$1(string$1()), - caption: optional$1(string$1()), - details: optional$1(glue42ApplicationDetailsDecoder), - intents: optional$1(array$1(intentDefinitionDecoder$1)), - hidden: optional$1(boolean$1()) - }); - const v1DefinitionDecoder = object$1({ - name: nonEmptyStringDecoder$3, - appId: nonEmptyStringDecoder$3, - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - manifest: nonEmptyStringDecoder$3, - manifestType: nonEmptyStringDecoder$3, - tooltip: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - images: optional$1(array$1(object$1({ url: optional$1(nonEmptyStringDecoder$3) }))), - icons: optional$1(array$1(object$1({ icon: optional$1(nonEmptyStringDecoder$3) }))), - customConfig: anyJson$1(), - intents: optional$1(array$1(intentDefinitionDecoder$1)) - }); - const v2LocalizedDefinitionDecoder = object$1({ - appId: optional$1(nonEmptyStringDecoder$3), - name: optional$1(nonEmptyStringDecoder$3), - details: optional$1(v2DetailsDecoder), - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder) - }); - const v2DefinitionDecoder = object$1({ - appId: nonEmptyStringDecoder$3, - name: optional$1(nonEmptyStringDecoder$3), - type: v2TypeDecoder, - details: v2DetailsDecoder, - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder), - localizedVersions: optional$1(dict(v2LocalizedDefinitionDecoder)) - }); - const allDefinitionsDecoder = oneOf(v1DefinitionDecoder, v2DefinitionDecoder); - - const parseDecoderErrorToStringMessage = (error) => { - return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`; - }; - - class FDC3Service { - fdc3ToDesktopDefinitionType = { - web: "window", - native: "exe", - citrix: "citrix", - onlineNative: "clickonce", - other: "window" - }; - toApi() { - return { - isFdc3Definition: this.isFdc3Definition.bind(this), - parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this), - parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this) - }; - } - isFdc3Definition(definition) { - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - return { isFdc3: false, reason: parseDecoderErrorToStringMessage(decodeRes.error) }; - } - if (definition.appId && definition.details) { - return { isFdc3: true, version: "2.0" }; - } - if (definition.manifest) { - return { isFdc3: true, version: "1.2" }; - } - return { isFdc3: false, reason: "The passed definition is not FDC3" }; - } - parseToBrowserBaseAppData(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - const userProperties = this.getUserPropertiesFromDefinition(definition, version); - const createOptions = { url: this.getUrl(definition, version) }; - const baseApplicationData = { - name: definition.appId, - type: "window", - createOptions, - userProperties: { - ...userProperties, - intents: version === "1.2" - ? userProperties.intents - : this.getIntentsFromV2AppDefinition(definition), - details: createOptions - }, - title: definition.title, - version: definition.version, - icon: this.getIconFromDefinition(definition, version), - caption: definition.description, - fdc3: version === "2.0" ? { ...definition, definitionVersion: "2.0" } : undefined, - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return baseApplicationData; - } - const ioDefinitionDecodeRes = glue42HostManifestsBrowserDecoder.run(ioConnectDefinition); - if (!ioDefinitionDecodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(ioDefinitionDecodeRes.error)}`); - } - if (!Object.keys(ioDefinitionDecodeRes.result).length) { - return baseApplicationData; - } - return this.mergeBaseAppDataWithGlueManifest(baseApplicationData, ioDefinitionDecodeRes.result); - } - parseToDesktopAppConfig(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - if (version === "1.2") { - const fdc3v1Definition = definition; - return { - name: fdc3v1Definition.appId, - type: "window", - details: { - url: this.getUrl(definition, version) - }, - version: fdc3v1Definition.version, - title: fdc3v1Definition.title, - tooltip: fdc3v1Definition.tooltip, - caption: fdc3v1Definition.description, - icon: fdc3v1Definition.icons?.[0].icon, - intents: fdc3v1Definition.intents, - customProperties: { - manifestType: fdc3v1Definition.manifestType, - images: fdc3v1Definition.images, - contactEmail: fdc3v1Definition.contactEmail, - supportEmail: fdc3v1Definition.supportEmail, - publisher: fdc3v1Definition.publisher, - icons: fdc3v1Definition.icons, - customConfig: fdc3v1Definition.customConfig - } - }; - } - const fdc3v2Definition = definition; - const desktopDefinition = { - name: fdc3v2Definition.appId, - type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type], - details: fdc3v2Definition.details, - version: fdc3v2Definition.version, - title: fdc3v2Definition.title, - tooltip: fdc3v2Definition.tooltip, - caption: fdc3v2Definition.description, - icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"), - intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition), - fdc3: { ...fdc3v2Definition, definitionVersion: "2.0" } - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return desktopDefinition; - } - if (typeof ioConnectDefinition !== "object" || Array.isArray(ioConnectDefinition)) { - throw new Error(`Invalid '${definition.hostManifests.ioConnect ? "hostManifests.ioConnect" : "hostManifests['Glue42']"}' key`); - } - return this.mergeDesktopConfigWithGlueManifest(desktopDefinition, ioConnectDefinition); - } - getUserPropertiesFromDefinition(definition, version) { - if (version === "1.2") { - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key))); - } - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key))); - } - getUrl(definition, version) { - let url; - if (version === "1.2") { - const parsedManifest = JSON.parse(definition.manifest); - url = parsedManifest.details?.url || parsedManifest.url; - } - else { - url = definition.details?.url; - } - if (!url || typeof url !== "string") { - throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`); - } - return url; - } - getIntentsFromV2AppDefinition(definition) { - const fdc3Intents = definition.interop?.intents?.listensFor; - if (!fdc3Intents) { - return; - } - const intents = Object.entries(fdc3Intents).map((fdc3Intent) => { - const [intentName, intentData] = fdc3Intent; - return { - name: intentName, - ...intentData - }; - }); - return intents; - } - getIconFromDefinition(definition, version) { - if (version === "1.2") { - return definition.icons?.find((iconDef) => iconDef.icon)?.icon || undefined; - } - return definition.icons?.find((iconDef) => iconDef.src)?.src || undefined; - } - mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) { - let baseApplicationDefinition = baseAppData; - if (hostManifestDefinition.customProperties) { - baseApplicationDefinition.userProperties = { ...baseAppData.userProperties, ...hostManifestDefinition.customProperties }; - } - if (hostManifestDefinition.details) { - const details = { ...baseAppData.createOptions, ...hostManifestDefinition.details }; - baseApplicationDefinition.createOptions = details; - baseApplicationDefinition.userProperties.details = details; - } - if (Array.isArray(hostManifestDefinition.intents)) { - baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents); - } - baseApplicationDefinition = { ...baseApplicationDefinition, ...hostManifestDefinition }; - delete baseApplicationDefinition.details; - delete baseApplicationDefinition.intents; - return baseApplicationDefinition; - } - mergeDesktopConfigWithGlueManifest(config, desktopDefinition) { - const appConfig = Object.assign({}, config, desktopDefinition, { details: { ...config.details, ...desktopDefinition.details } }); - if (Array.isArray(desktopDefinition.intents)) { - appConfig.intents = (config.intents || []).concat(desktopDefinition.intents); - } - return appConfig; - } - } - - const decoders$1 = { - common: { - nonEmptyStringDecoder: nonEmptyStringDecoder$3, - nonNegativeNumberDecoder: nonNegativeNumberDecoder$3, - regexDecoder - }, - fdc3: { - allDefinitionsDecoder, - v1DefinitionDecoder, - v2DefinitionDecoder - } - }; - - var INTENTS_ERRORS; - (function (INTENTS_ERRORS) { - INTENTS_ERRORS["USER_CANCELLED"] = "User Closed Intents Resolver UI without choosing a handler"; - INTENTS_ERRORS["CALLER_NOT_DEFINED"] = "Caller Id is not defined"; - INTENTS_ERRORS["TIMEOUT_HIT"] = "Timeout hit"; - INTENTS_ERRORS["INTENT_NOT_FOUND"] = "Cannot find Intent"; - INTENTS_ERRORS["HANDLER_NOT_FOUND"] = "Cannot find Intent Handler"; - INTENTS_ERRORS["TARGET_INSTANCE_UNAVAILABLE"] = "Cannot start Target Instance"; - INTENTS_ERRORS["INTENT_DELIVERY_FAILED"] = "Target Instance did not add a listener"; - INTENTS_ERRORS["RESOLVER_UNAVAILABLE"] = "Intents Resolver UI unavailable"; - INTENTS_ERRORS["RESOLVER_TIMEOUT"] = "User did not choose a handler"; - INTENTS_ERRORS["INVALID_RESOLVER_RESPONSE"] = "Intents Resolver UI returned invalid response"; - INTENTS_ERRORS["INTENT_HANDLER_REJECTION"] = "Intent Handler function processing the raised intent threw an error or rejected the promise it returned"; - })(INTENTS_ERRORS || (INTENTS_ERRORS = {})); - - let IoC$1 = class IoC { - _fdc3; - _decoders = decoders$1; - _errors = { - intents: INTENTS_ERRORS - }; - get fdc3() { - if (!this._fdc3) { - this._fdc3 = new FDC3Service().toApi(); - } - return this._fdc3; - } - get decoders() { - return this._decoders; - } - get errors() { - return this._errors; - } - }; - - const ioc = new IoC$1(); - ioc.fdc3; - const decoders = ioc.decoders; - ioc.errors; - - const nonEmptyStringDecoder$2 = string$2().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$2 = number$2().where((num) => num >= 0, "Expected a non-negative number"); - const optionalNonEmptyStringDecoder = optional$2(nonEmptyStringDecoder$2); - const libDomainDecoder = oneOf$1(constant$2("system"), constant$2("windows"), constant$2("appManager"), constant$2("layouts"), constant$2("intents"), constant$2("notifications"), constant$2("channels"), constant$2("extension"), constant$2("themes"), constant$2("prefs"), constant$2("ui")); - const windowOperationTypesDecoder = oneOf$1(constant$2("openWindow"), constant$2("windowHello"), constant$2("windowAdded"), constant$2("windowRemoved"), constant$2("getBounds"), constant$2("getFrameBounds"), constant$2("getUrl"), constant$2("moveResize"), constant$2("focus"), constant$2("close"), constant$2("getTitle"), constant$2("setTitle"), constant$2("focusChange"), constant$2("getChannel"), constant$2("notifyChannelsChanged"), constant$2("setZoomFactor"), constant$2("zoomFactorChange"), constant$2("refresh"), constant$2("operationCheck")); - const appManagerOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("appDirectoryStateChange"), constant$2("instanceStarted"), constant$2("instanceStopped"), constant$2("applicationStart"), constant$2("instanceStop"), constant$2("clear"), constant$2("operationCheck")); - const layoutsOperationTypesDecoder = oneOf$1(constant$2("layoutAdded"), constant$2("layoutChanged"), constant$2("layoutRemoved"), constant$2("layoutRenamed"), constant$2("get"), constant$2("getAll"), constant$2("export"), constant$2("import"), constant$2("remove"), constant$2("rename"), constant$2("clientSaveRequest"), constant$2("getGlobalPermissionState"), constant$2("checkGlobalActivated"), constant$2("requestGlobalPermission"), constant$2("getDefaultGlobal"), constant$2("setDefaultGlobal"), constant$2("clearDefaultGlobal"), constant$2("updateMetadata"), constant$2("operationCheck"), constant$2("getCurrent"), constant$2("defaultLayoutChanged"), constant$2("layoutRestored")); - const notificationsOperationTypesDecoder = oneOf$1(constant$2("raiseNotification"), constant$2("requestPermission"), constant$2("notificationShow"), constant$2("notificationClick"), constant$2("getPermission"), constant$2("list"), constant$2("notificationRaised"), constant$2("notificationClosed"), constant$2("click"), constant$2("clear"), constant$2("clearAll"), constant$2("configure"), constant$2("getConfiguration"), constant$2("configurationChanged"), constant$2("setState"), constant$2("clearOld"), constant$2("activeCountChange"), constant$2("stateChange"), constant$2("operationCheck"), constant$2("getActiveCount")); - const systemOperationTypesDecoder = oneOf$1(constant$2("getEnvironment"), constant$2("getBase"), constant$2("platformShutdown"), constant$2("isFdc3DataWrappingSupported"), constant$2("clientError"), constant$2("systemHello"), constant$2("operationCheck")); - const windowRelativeDirectionDecoder = oneOf$1(constant$2("top"), constant$2("left"), constant$2("right"), constant$2("bottom")); - const windowBoundsDecoder = object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }); - const windowOpenSettingsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - context: optional$2(anyJson$2()), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - windowId: optional$2(nonEmptyStringDecoder$2), - layoutComponentId: optional$2(nonEmptyStringDecoder$2) - })); - const openWindowConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2, - options: windowOpenSettingsDecoder - }); - const windowHelloDecoder = object$2({ - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const coreWindowDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleWindowDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const helloSuccessDecoder = object$2({ - windows: array$2(coreWindowDataDecoder), - isWorkspaceFrame: boolean$2() - }); - const windowTitleConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - title: string$2() - }); - const focusEventDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - hasFocus: boolean$2() - }); - const windowMoveResizeConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relative: optional$2(boolean$2()) - }); - const windowBoundsResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const frameWindowBoundsResultDecoder = object$2({ - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const windowUrlResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2 - }); - const windowZoomFactorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - factorIndex: nonNegativeNumberDecoder$2 - }); - const anyDecoder = anyJson$2(); - const boundsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2) - }); - const instanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - applicationName: nonEmptyStringDecoder$2 - }); - const iframePermissionsPolicyConfigDecoder = object$2({ - flags: string$2() - }); - const workspacesSandboxDecoder = object$2({ - flags: string$2() - }); - const requestChannelSelectorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelsNames: array$2(nonEmptyStringDecoder$2) - }); - const channelSelectorDecoder$1 = object$2({ - enabled: boolean$2(), - }); - const applicationDetailsDecoder = object$2({ - url: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - workspacesSandbox: optional$2(workspacesSandboxDecoder), - channelSelector: optional$2(channelSelectorDecoder$1), - iframePermissionsPolicy: optional$2(iframePermissionsPolicyConfigDecoder) - }); - const intentDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - displayName: optional$2(string$2()), - contexts: optional$2(array$2(string$2())), - customConfig: optional$2(object$2()), - resultType: optional$2(string$2()) - }); - const applicationDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - customProperties: optional$2(anyJson$2()), - icon: optional$2(string$2()), - caption: optional$2(string$2()), - details: applicationDetailsDecoder, - intents: optional$2(array$2(intentDefinitionDecoder)), - hidden: optional$2(boolean$2()), - fdc3: optional$2(decoders.fdc3.v2DefinitionDecoder) - }); - const appRemoveConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const appsExportOperationDecoder = object$2({ - definitions: array$2(applicationDefinitionDecoder) - }); - const applicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - instances: array$2(instanceDataDecoder), - userProperties: optional$2(anyJson$2()), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const baseApplicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - userProperties: anyJson$2(), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const appDirectoryStateChangeDecoder = object$2({ - appsAdded: array$2(baseApplicationDataDecoder), - appsChanged: array$2(baseApplicationDataDecoder), - appsRemoved: array$2(baseApplicationDataDecoder) - }); - const appHelloSuccessDecoder = object$2({ - apps: array$2(applicationDataDecoder), - initialChannelId: optional$2(nonEmptyStringDecoder$2) - }); - const basicInstanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const layoutTypeDecoder = oneOf$1(constant$2("Global"), constant$2("Activity"), constant$2("ApplicationDefault"), constant$2("Swimlane"), constant$2("Workspace")); - const componentTypeDecoder = oneOf$1(constant$2("application"), constant$2("activity")); - const windowComponentStateDecoder = object$2({ - context: optional$2(anyJson$2()), - bounds: windowBoundsDecoder, - createArgs: object$2({ - name: optional$2(nonEmptyStringDecoder$2), - url: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - instanceId: nonEmptyStringDecoder$2, - isCollapsed: optional$2(boolean$2()), - isSticky: optional$2(boolean$2()), - restoreSettings: object$2({ - groupId: optional$2(nonEmptyStringDecoder$2), - groupZOrder: optional$2(number$2()) - }), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const windowLayoutComponentDecoder = object$2({ - type: constant$2("window"), - componentType: optional$2(componentTypeDecoder), - application: nonEmptyStringDecoder$2, - state: windowComponentStateDecoder - }); - const windowLayoutItemDecoder = object$2({ - type: constant$2("window"), - config: object$2({ - appName: nonEmptyStringDecoder$2, - url: optional$2(nonEmptyStringDecoder$2), - title: optional$2(string$2()), - allowExtract: optional$2(boolean$2()), - allowReorder: optional$2(boolean$2()), - showCloseButton: optional$2(boolean$2()), - isMaximized: optional$2(boolean$2()) - }) - }); - const groupLayoutItemDecoder = object$2({ - type: constant$2("group"), - config: anyJson$2(), - children: array$2(oneOf$1(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object$2({ - type: constant$2("column"), - config: anyJson$2(), - children: array$2(oneOf$1(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object$2({ - type: constant$2("row"), - config: anyJson$2(), - children: array$2(oneOf$1(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutComponentStateDecoder = object$2({ - config: anyJson$2(), - context: anyJson$2(), - children: array$2(oneOf$1(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }); - const workspaceLayoutComponentDecoder = object$2({ - type: constant$2("Workspace"), - application: optional$2(nonEmptyStringDecoder$2), - state: workspaceLayoutComponentStateDecoder - }); - const workspaceFrameComponentStateDecoder = object$2({ - bounds: windowBoundsDecoder, - instanceId: nonEmptyStringDecoder$2, - selectedWorkspace: nonNegativeNumberDecoder$2, - workspaces: array$2(workspaceLayoutComponentStateDecoder), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }); - const workspaceFrameComponentDecoder = object$2({ - type: constant$2("workspaceFrame"), - application: nonEmptyStringDecoder$2, - componentType: optional$2(componentTypeDecoder), - state: workspaceFrameComponentStateDecoder - }); - const glueLayoutDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()) - }); - const renamedLayoutNotificationDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()), - prevName: nonEmptyStringDecoder$2 - }); - const newLayoutOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - instances: optional$2(array$2(nonEmptyStringDecoder$2)), - ignoreInstances: optional$2(array$2(nonEmptyStringDecoder$2)), - setAsCurrent: optional$2(boolean$2()), - ignoreContexts: optional$2(boolean$2()) - }); - const restoreOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - closeRunningInstance: optional$2(boolean$2()), - closeMe: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2) - }); - const layoutSummaryDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()) - }); - const simpleLayoutConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder - }); - const saveLayoutConfigDecoder = object$2({ - layout: newLayoutOptionsDecoder - }); - const renameLayoutConfigDecoder = object$2({ - layout: glueLayoutDecoder, - newName: nonEmptyStringDecoder$2 - }); - const layoutResultDecoder = object$2({ - status: nonEmptyStringDecoder$2 - }); - const updateLayoutMetadataConfigDecoder = object$2({ - layout: glueLayoutDecoder, - }); - const restoreLayoutConfigDecoder = object$2({ - layout: restoreOptionsDecoder - }); - const getAllLayoutsConfigDecoder = object$2({ - type: layoutTypeDecoder - }); - const allLayoutsFullConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder) - }); - const defaultGlobalChangedDecoder = optional$2(object$2({ - name: nonEmptyStringDecoder$2 - })); - const importModeDecoder = oneOf$1(constant$2("replace"), constant$2("merge")); - const layoutsImportConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder), - mode: importModeDecoder, - skipManagerRequest: optional$2(boolean$2()) - }); - const allLayoutsSummariesResultDecoder = object$2({ - summaries: array$2(layoutSummaryDecoder) - }); - const simpleLayoutResultDecoder = object$2({ - layout: glueLayoutDecoder - }); - const optionalSimpleLayoutResult = object$2({ - layout: optional$2(glueLayoutDecoder) - }); - const setDefaultGlobalConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const intentsOperationTypesDecoder = oneOf$1(constant$2("findIntent"), constant$2("getIntents"), constant$2("getIntentsByHandler"), constant$2("raise"), constant$2("filterHandlers")); - const intentHandlerDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2, - applicationTitle: optional$2(string$2()), - applicationDescription: optional$2(string$2()), - applicationIcon: optional$2(string$2()), - type: oneOf$1(constant$2("app"), constant$2("instance")), - displayName: optional$2(string$2()), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - instanceId: optional$2(string$2()), - instanceTitle: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - object$2({ - applicationName: string$2(), - applicationIcon: optional$2(string$2()), - instanceId: optional$2(string$2()), - }); - object$2({ - intent: nonEmptyStringDecoder$2, - handler: intentHandlerDecoder - }); - const intentDecoder = object$2({ - name: nonEmptyStringDecoder$2, - handlers: array$2(intentHandlerDecoder) - }); - const intentTargetDecoder = oneOf$1(constant$2("startNew"), constant$2("reuse"), object$2({ - app: optional$2(nonEmptyStringDecoder$2), - instance: optional$2(nonEmptyStringDecoder$2) - })); - const intentContextDecoder = object$2({ - type: optional$2(nonEmptyStringDecoder$2), - data: optional$2(anyJson$2()) - }); - const intentsDecoder = array$2(intentDecoder); - const wrappedIntentsDecoder = object$2({ - intents: intentsDecoder - }); - const intentFilterDecoder = object$2({ - name: optional$2(nonEmptyStringDecoder$2), - contextType: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const findFilterDecoder = oneOf$1(nonEmptyStringDecoder$2, intentFilterDecoder); - const wrappedIntentFilterDecoder = object$2({ - filter: optional$2(intentFilterDecoder) - }); - const applicationStartOptionsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const intentRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - target: optional$2(intentTargetDecoder), - context: optional$2(intentContextDecoder), - options: optional$2(applicationStartOptionsDecoder), - handlers: optional$2(array$2(intentHandlerDecoder)), - timeout: optional$2(nonNegativeNumberDecoder$2), - waitUserResponseIndefinitely: optional$2(boolean$2()), - clearSavedHandler: optional$2(boolean$2()) - }); - const originAppDecoder = object$2({ - interopInstance: nonEmptyStringDecoder$2, - name: optional$2(nonEmptyStringDecoder$2) - }); - const startReasonDecoder = object$2({ - originApp: originAppDecoder, - intentRequest: optional$2(intentRequestDecoder) - }); - const applicationStartConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - waitForAGMReady: boolean$2(), - id: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()), - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - forceChromeTab: optional$2(boolean$2()), - layoutComponentId: optional$2(nonEmptyStringDecoder$2), - channelId: optional$2(nonEmptyStringDecoder$2), - startReason: startReasonDecoder - }); - const raiseRequestDecoder = oneOf$1(nonEmptyStringDecoder$2, intentRequestDecoder); - const resolverConfigDecoder = object$2({ - enabled: boolean$2(), - appName: nonEmptyStringDecoder$2, - waitResponseTimeout: number$2() - }); - const handlerExclusionCriteriaApplicationNameDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaInstanceIdDecoder = object$2({ - instanceId: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaDecoder = oneOf$1(handlerExclusionCriteriaApplicationNameDecoder, handlerExclusionCriteriaInstanceIdDecoder); - const handlerFilterDecoder = object$2({ - title: optional$2(nonEmptyStringDecoder$2), - openResolver: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2), - intent: optional$2(nonEmptyStringDecoder$2), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - resultType: optional$2(nonEmptyStringDecoder$2), - applicationNames: optional$2(array$2(nonEmptyStringDecoder$2)), - excludeList: optional$2(array$2(handlerExclusionCriteriaDecoder)) - }); - const embeddedResolverConfigDecoder = object$2({ - enabled: boolean$2(), - initialCaller: object$2({ instanceId: nonEmptyStringDecoder$2 }), - }); - const raiseIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const intentResultDecoder = object$2({ - request: intentRequestDecoder, - handler: intentHandlerDecoder, - result: anyJson$2() - }); - const filterHandlersResultDecoder = object$2({ - handlers: array$2(intentHandlerDecoder) - }); - const filterHandlersWithResolverConfigDecoder = object$2({ - filterHandlersRequest: handlerFilterDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const AddIntentListenerRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - displayName: optional$2(string$2()), - icon: optional$2(string$2()), - description: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - const AddIntentListenerDecoder = oneOf$1(nonEmptyStringDecoder$2, AddIntentListenerRequestDecoder); - const intentInfoDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - description: optional$2(nonEmptyStringDecoder$2), - displayName: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const getIntentsResultDecoder = object$2({ - intents: array$2(intentInfoDecoder) - }); - const channelNameDecoder = (channelNames) => { - return nonEmptyStringDecoder$2.where(s => channelNames.includes(s), "Expected a valid channel name"); - }; - const fdc3OptionsDecoder = object$2({ - contextType: optional$2(nonEmptyStringDecoder$2) - }); - const publishOptionsDecoder = optional$2(oneOf$1(nonEmptyStringDecoder$2, object$2({ - name: optional$2(nonEmptyStringDecoder$2), - fdc3: optional$2(boolean$2()) - }))); - const leaveChannelsConfig = object$2({ - windowId: optionalNonEmptyStringDecoder, - channel: optionalNonEmptyStringDecoder - }); - const fdc3ContextDecoder = anyJson$2().where((value) => typeof value.type === "string", "Expected a valid FDC3 Context with compulsory 'type' field"); - const interopActionSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$2, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("all"), constant$2("best"))) - }); - const glue42NotificationActionDecoder = object$2({ - action: string$2(), - title: nonEmptyStringDecoder$2, - icon: optional$2(string$2()), - interop: optional$2(interopActionSettingsDecoder) - }); - const notificationStateDecoder = oneOf$1(constant$2("Active"), constant$2("Acknowledged"), constant$2("Seen"), constant$2("Closed"), constant$2("Stale"), constant$2("Snoozed"), constant$2("Processing")); - const activeNotificationsCountChangeDecoder = object$2({ - count: number$2() - }); - const notificationDefinitionDecoder = object$2({ - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())) - }); - const glue42NotificationOptionsDecoder = object$2({ - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const notificationSetStateRequestDecoder = object$2({ - id: nonEmptyStringDecoder$2, - state: notificationStateDecoder - }); - object$2().where((value) => value.fdc3 ? typeof value.fdc3.type === "string" : true, "Expected a valid FDC3 Context with compulsory 'type' field"); - const channelFDC3DisplayMetadataDecoder = object$2({ - color: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - name: optional$2(nonEmptyStringDecoder$2), - glyph: optional$2(nonEmptyStringDecoder$2) - }); - const channelFdc3MetaDecoder = object$2({ - id: nonEmptyStringDecoder$2, - displayMetadata: optional$2(channelFDC3DisplayMetadataDecoder) - }); - const channelMetaDecoder = object$2({ - color: nonEmptyStringDecoder$2, - fdc3: optional$2(channelFdc3MetaDecoder) - }); - const channelDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - meta: channelMetaDecoder, - data: optional$2(object$2()), - }); - const pathValueDecoder = object$2({ - path: nonEmptyStringDecoder$2, - value: anyJson$2() - }); - const pathsValueDecoder = array$2(pathValueDecoder); - const removeChannelDataDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const channelRestrictionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const channelRestrictionConfigWithWindowIdDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: nonEmptyStringDecoder$2 - }); - const restrictionConfigDataDecoder = object$2({ - config: channelRestrictionConfigWithWindowIdDecoder - }); - const restrictionsDecoder = object$2({ - channels: array$2(channelRestrictionsDecoder) - }); - const getRestrictionsDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const restrictionsConfigDecoder = object$2({ - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const restrictAllDataDecoder = object$2({ - restrictions: restrictionsConfigDecoder - }); - const raiseNotificationDecoder = object$2({ - settings: glue42NotificationOptionsDecoder, - id: nonEmptyStringDecoder$2 - }); - const raiseNotificationResultDecoder = object$2({ - settings: glue42NotificationOptionsDecoder - }); - const permissionRequestResultDecoder = object$2({ - permissionGranted: boolean$2() - }); - const permissionQueryResultDecoder = object$2({ - permission: oneOf$1(constant$2("default"), constant$2("granted"), constant$2("denied")) - }); - const notificationEventPayloadDecoder = object$2({ - definition: notificationDefinitionDecoder, - action: optional$2(string$2()), - id: optional$2(nonEmptyStringDecoder$2) - }); - const notificationFilterDecoder = object$2({ - allowed: optional$2(array$2(nonEmptyStringDecoder$2)), - blocked: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const notificationsConfigurationDecoder = object$2({ - enable: optional$2(boolean$2()), - enableToasts: optional$2(boolean$2()), - sourceFilter: optional$2(notificationFilterDecoder), - showNotificationBadge: optional$2(boolean$2()) - }); - const notificationsConfigurationProtocolDecoder = object$2({ - configuration: notificationsConfigurationDecoder - }); - const strictNotificationsConfigurationProtocolDecoder = object$2({ - configuration: object$2({ - enable: boolean$2(), - enableToasts: boolean$2(), - sourceFilter: object$2({ - allowed: array$2(nonEmptyStringDecoder$2), - blocked: array$2(nonEmptyStringDecoder$2) - }) - }) - }); - const platformSaveRequestConfigDecoder = object$2({ - layoutType: oneOf$1(constant$2("Global"), constant$2("Workspace")), - layoutName: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()) - }); - const saveRequestClientResponseDecoder = object$2({ - windowContext: optional$2(anyJson$2()), - }); - const permissionStateResultDecoder = object$2({ - state: oneOf$1(constant$2("prompt"), constant$2("denied"), constant$2("granted")) - }); - const simpleAvailabilityResultDecoder = object$2({ - isAvailable: boolean$2() - }); - const simpleItemIdDecoder = object$2({ - itemId: nonEmptyStringDecoder$2 - }); - const operationCheckResultDecoder = object$2({ - isSupported: boolean$2() - }); - const operationCheckConfigDecoder = object$2({ - operation: nonEmptyStringDecoder$2 - }); - const workspaceFrameBoundsResultDecoder = object$2({ - bounds: windowBoundsDecoder - }); - const themeDecoder = object$2({ - displayName: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleThemeResponseDecoder = object$2({ - theme: themeDecoder - }); - const allThemesResponseDecoder = object$2({ - themes: array$2(themeDecoder) - }); - const selectThemeConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const notificationsDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const simpleNotificationDataDecoder = object$2({ - notification: notificationsDataDecoder - }); - const allNotificationsDataDecoder = object$2({ - notifications: array$2(notificationsDataDecoder) - }); - const simpleNotificationSelectDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelResultDecoder = object$2({ - windowIds: array$2(nonEmptyStringDecoder$2) - }); - const channelsOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("addChannel"), constant$2("getMyChannel"), constant$2("getWindowIdsOnChannel"), constant$2("getWindowIdsWithChannels"), constant$2("joinChannel"), constant$2("restrict"), constant$2("getRestrictions"), constant$2("restrictAll"), constant$2("notifyChannelsChanged"), constant$2("leaveChannel"), constant$2("getMode"), constant$2("operationCheck")); - const modeDecoder = oneOf$1(constant$2("single"), constant$2("multi")); - const getChannelsModeDecoder = object$2({ - mode: modeDecoder - }); - const channelsAppHelloDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const channelsAppHelloSuccessDecoder = object$2({ - mode: modeDecoder, - channels: array$2(nonEmptyStringDecoder$2), - restrictions: array$2(channelRestrictionsDecoder) - }); - const getMyChanelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2) - }); - const windowWithChannelFilterDecoder = object$2({ - application: optional$2(nonEmptyStringDecoder$2), - channels: optional$2(array$2(nonEmptyStringDecoder$2)), - windowIds: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const wrappedWindowWithChannelFilterDecoder = object$2({ - filter: optional$2(windowWithChannelFilterDecoder) - }); - const getWindowIdsWithChannelsResultDecoder = object$2({ - windowIdsWithChannels: array$2(object$2({ - application: nonEmptyStringDecoder$2, - channel: optional$2(nonEmptyStringDecoder$2), - windowId: nonEmptyStringDecoder$2 - })) - }); - const startApplicationContextDecoder = optional$2(anyJson$2()); - const startApplicationOptionsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - reuseId: optional$2(nonEmptyStringDecoder$2), - originIntentRequest: optional$2(intentRequestDecoder) - })); - const joinChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2, - windowId: nonEmptyStringDecoder$2 - }); - const leaveChannelDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelName: optional$2(nonEmptyStringDecoder$2) - }); - const channelsChangedDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelNames: array$2(nonEmptyStringDecoder$2) - }); - const windowChannelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2), - }); - const prefsOperationTypesDecoder = oneOf$1(constant$2("clear"), constant$2("clearAll"), constant$2("get"), constant$2("getAll"), constant$2("set"), constant$2("update"), constant$2("prefsChanged"), constant$2("prefsHello"), constant$2("operationCheck"), constant$2("registerSubscriber")); - const appPreferencesDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - lastUpdate: optional$2(nonEmptyStringDecoder$2), - }); - const basePrefsConfigDecoder = object$2({ - app: nonEmptyStringDecoder$2, - }); - const getPrefsResultDecoder = object$2({ - prefs: appPreferencesDecoder, - }); - const getAllPrefsResultDecoder = object$2({ - all: array$2(appPreferencesDecoder), - }); - const subscriberRegisterConfigDecoder = object$2({ - interopId: nonEmptyStringDecoder$2, - appName: optional$2(nonEmptyStringDecoder$2) - }); - const changePrefsDataDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - }); - const prefsHelloSuccessDecoder = object$2({ - platform: object$2({ - app: nonEmptyStringDecoder$2, - }), - validNonExistentApps: optional$2(array$2(nonEmptyStringDecoder$2)), - }); - const clientErrorDataDecoder = object$2({ - message: nonEmptyStringDecoder$2 - }); - const systemHelloSuccessDecoder = object$2({ - isClientErrorOperationSupported: boolean$2() - }); - - const nonEmptyStringDecoder$1 = decoders.common.nonEmptyStringDecoder; - const nonNegativeNumberDecoder$1 = decoders.common.nonNegativeNumberDecoder; - const widgetSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const modalsSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const intentResolverSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const channelSelectorTypeDecoder = oneOf$1(constant$2("directional"), constant$2("default")); - const channelSelectorDecoder = object$2({ - type: optional$2(channelSelectorTypeDecoder), - enable: optional$2(boolean$2()) - }); - const positionDecoder = oneOf$1(constant$2("top-left"), constant$2("top-center"), constant$2("top-right"), constant$2("center-left"), constant$2("center-right"), constant$2("bottom-left"), constant$2("bottom-center"), constant$2("bottom-right")); - const displayModeDecoder = oneOf$1(constant$2("all"), constant$2("fdc3")); - const widgetChannelsDecoder = object$2({ - selector: optional$2(channelSelectorDecoder), - displayMode: optional$2(displayModeDecoder) - }); - const platformWidgetDefaultConfigDecoder = object$2({ - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const widgetConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const modalsConfigDecoder = object$2({ - alerts: optional$2(object$2({ - enabled: boolean$2() - })), - dialogs: optional$2(object$2({ - enabled: boolean$2() - })), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - }); - const uiOperationTypesDecoder = oneOf$1(constant$2("getResources"), constant$2("operationCheck"), constant$2("showAlert"), constant$2("showDialog"), constant$2("alertInteropAction"), constant$2("showResolver")); - const getResourcesDataDecoder = object$2({ - origin: nonEmptyStringDecoder$1 - }); - const blockedResourcesDecoder = object$2({ - blockedOrigin: constant$2(true) - }); - const availableWidgetResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - config: platformWidgetDefaultConfigDecoder, - sources: widgetSourcesDecoder - }); - const widgetResourcesDecoder = union$1(blockedResourcesDecoder, availableWidgetResourcesDecoder); - const availableModalsResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: modalsSourcesDecoder - }); - const modalsResourcesDecoder = union$1(blockedResourcesDecoder, availableModalsResourcesDecoder); - const availableIntentResolverResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: intentResolverSourcesDecoder - }); - const intentResolverResourcesDecoder = union$1(blockedResourcesDecoder, availableIntentResolverResourcesDecoder); - const resourcesDecoder = object$2({ - widget: optional$2(widgetResourcesDecoder), - modals: optional$2(modalsResourcesDecoder), - intentResolver: optional$2(intentResolverResourcesDecoder) - }); - const getResourcesResultDecoder = object$2({ - resources: resourcesDecoder, - }); - const alertsInteropSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$1, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("best"), constant$2("all"), nonEmptyStringDecoder$1)) - }); - const modalRequestTargetDecoder = oneOf$1(constant$2("Global"), constant$2("WindowContainer"), nonEmptyStringDecoder$1); - const modalRequestMessageTargetDecoder = object$2({ - instance: nonEmptyStringDecoder$1, - container: optional$2(oneOf$1(constant$2("Global"), constant$2("WindowContainer"))) - }); - const alertRequestConfigDecoder = object$2({ - variant: oneOf$1(constant$2("default"), constant$2("success"), constant$2("critical"), constant$2("info"), constant$2("warning")), - text: nonEmptyStringDecoder$1, - showCloseButton: optional$2(boolean$2()), - clickInterop: optional$2(alertsInteropSettingsDecoder), - onCloseInterop: optional$2(alertsInteropSettingsDecoder), - actions: optional$2(array$2(object$2({ - id: nonEmptyStringDecoder$1, - title: nonEmptyStringDecoder$1, - clickInterop: alertsInteropSettingsDecoder - }))), - data: optional$2(anyJson$2()), - ttl: optional$2(nonNegativeNumberDecoder$1), - target: optional$2(modalRequestTargetDecoder) - }); - const uiAlertRequestMessageDecoder = object$2({ - config: alertRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const dialogRequestConfigDecoder = object$2({ - templateName: nonEmptyStringDecoder$1, - variables: anyJson$2(), - target: optional$2(modalRequestTargetDecoder), - timer: optional$2(object$2({ - duration: nonNegativeNumberDecoder$1 - })), - size: optional$2(object$2({ - width: nonNegativeNumberDecoder$1, - height: nonNegativeNumberDecoder$1 - })), - movable: optional$2(boolean$2()), - transparent: optional$2(boolean$2()) - }); - const dialogResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - isEnterPressed: optional$2(boolean$2()), - responseButtonClicked: optional$2(object$2({ - id: nonEmptyStringDecoder$1, - text: nonEmptyStringDecoder$1 - })), - inputs: optional$2(array$2(object$2({ - type: oneOf$1(constant$2("checkbox"), constant$2("email"), constant$2("number"), constant$2("password"), constant$2("text")), - id: nonEmptyStringDecoder$1, - checked: optional$2(boolean$2()), - value: optional$2(string$2()) - }))) - }); - object$2({ - result: dialogResponseDecoder - }); - const uiDialogRequestMessageDecoder = object$2({ - config: dialogRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const openAlertResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const openDialogResultDecoder = object$2({ - id: nonEmptyStringDecoder$1, - responsePromise: anyJson$2() - }); - const dialogOnCompletionConfigDecoder = object$2({ - response: dialogResponseDecoder - }); - const alertInteropActionDecoder = object$2({ - name: nonEmptyStringDecoder$1, - settings: alertsInteropSettingsDecoder - }); - const alertOnClickConfigDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const alertInteropActionDataDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const intentResolverConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1) - }); - const openResolverResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const userSettingsDecoder = object$2({ - preserveChoice: boolean$2() - }); - const userChoiceResponseDecoder = object$2({ - intent: nonEmptyStringDecoder$1, - handler: intentHandlerDecoder, - userSettings: userSettingsDecoder - }); - const intentResolverResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - userChoice: optional$2(userChoiceResponseDecoder) - }); - const onUserResponseResponseDecoder = object$2({ - response: intentResolverResponseDecoder - }); - const openConfigWithIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder - }); - const openConfigWithHandlerFilterDecoder = object$2({ - handlerFilter: handlerFilterDecoder - }); - const intentResolverOpenConfigDecoder = union$1(openConfigWithIntentRequestDecoder, openConfigWithHandlerFilterDecoder); - const uiResolverRequestMessageConfigDecoder = intersection(intentResolverOpenConfigDecoder, object$2({ timeout: nonNegativeNumberDecoder$1 })); - const uiResolverRequestMessageDecoder = object$2({ - config: uiResolverRequestMessageConfigDecoder - }); - const uiResolverResponseMessageDecoder = object$2({ - result: intentResolverResponseDecoder - }); - - const parseConfig = (config = {}) => { - const isPlatformInternal = !!config?.gateway?.webPlatform?.port; - const decodedWidgetConfigResult = optional$2(widgetConfigDecoder).run(config.widget); - if (!decodedWidgetConfigResult.ok) { - throw ioError.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(decodedWidgetConfigResult.error)}`); - } - const decodedModalsConfigResult = optional$2(modalsConfigDecoder).run(config.modals); - if (!decodedModalsConfigResult.ok) { - throw ioError.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(decodedModalsConfigResult.error)}`); - } - const decodedIntentResolverConfigResult = optional$2(intentResolverConfigDecoder).run(config.intentResolver); - if (!decodedIntentResolverConfigResult.ok) { - throw ioError.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(decodedIntentResolverConfigResult.error)}`); - } - const combined = { - ...defaultConfig, - ...config, - isPlatformInternal, - logger: config.systemLogger?.level ?? "info", - customLogger: config.systemLogger?.customLogger, - widget: deepmerge$1(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}), - modals: deepmerge$1(defaultModalsConfig, decodedModalsConfigResult.result ?? {}), - intentResolver: deepmerge$1(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}), - }; - return combined; - }; - - const checkSingleton = () => { - const ioConnectBrowserNamespace = window.glue42core || window.iobrowser; - if (ioConnectBrowserNamespace && ioConnectBrowserNamespace.webStarted) { - return ioError.raiseError("IoConnect Browser has already been started for this application."); - } - if (!ioConnectBrowserNamespace) { - window.iobrowser = { webStarted: true }; - return; - } - ioConnectBrowserNamespace.webStarted = true; - }; - - const enterprise = (config) => { - const enterpriseConfig = { - windows: true, - layouts: "full", - appManager: "full", - channels: true, - libraries: config?.libraries ?? [], - logger: config?.systemLogger?.level ?? "warn" - }; - const injectedFactory = window.IODesktop || window.Glue; - return injectedFactory(enterpriseConfig); - }; - - const operations$a = { - openWindow: { name: "openWindow", dataDecoder: openWindowConfigDecoder, resultDecoder: coreWindowDataDecoder }, - windowHello: { name: "windowHello", dataDecoder: windowHelloDecoder, resultDecoder: helloSuccessDecoder }, - windowAdded: { name: "windowAdded", dataDecoder: coreWindowDataDecoder }, - windowRemoved: { name: "windowRemoved", dataDecoder: simpleWindowDecoder }, - getBounds: { name: "getBounds", dataDecoder: simpleWindowDecoder, resultDecoder: windowBoundsResultDecoder }, - getFrameBounds: { name: "getFrameBounds", dataDecoder: simpleWindowDecoder, resultDecoder: frameWindowBoundsResultDecoder }, - getUrl: { name: "getUrl", dataDecoder: simpleWindowDecoder, resultDecoder: windowUrlResultDecoder }, - moveResize: { name: "moveResize", dataDecoder: windowMoveResizeConfigDecoder }, - focus: { name: "focus", dataDecoder: simpleWindowDecoder }, - close: { name: "close", dataDecoder: simpleWindowDecoder }, - getTitle: { name: "getTitle", dataDecoder: simpleWindowDecoder, resultDecoder: windowTitleConfigDecoder }, - setTitle: { name: "setTitle", dataDecoder: windowTitleConfigDecoder }, - focusChange: { name: "focusChange", dataDecoder: focusEventDataDecoder }, - getChannel: { name: "getChannel", dataDecoder: simpleWindowDecoder, resultDecoder: windowChannelResultDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - setZoomFactor: { name: "setZoomFactor", dataDecoder: windowZoomFactorConfigDecoder }, - zoomFactorChange: { name: "zoomFactorChange", dataDecoder: windowZoomFactorConfigDecoder }, - refresh: { name: "refresh", dataDecoder: simpleWindowDecoder }, - operationCheck: { name: "operationCheck" } - }; - - function createRegistry$1(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry$1.default = createRegistry$1; - var lib$1 = createRegistry$1; - - - var CallbackRegistryFactory$1 = /*@__PURE__*/getDefaultExportFromCjs$1(lib$1); - - const ZOOM_FACTORS = Object.freeze({ - 0: 24, - 1: 33, - 2: 50, - 3: 67, - 4: 75, - 5: 80, - 6: 90, - 7: 100, - 8: 110, - 9: 125, - 10: 150, - 11: 175, - 12: 200, - 13: 250, - 14: 300, - 15: 400, - 16: 500 - }); - - class WebWindowModel { - _id; - _name; - _bridge; - _logger; - registry = CallbackRegistryFactory$1(); - myCtxKey; - ctxUnsubscribe; - zoomFactorIndex = 7; - me; - constructor(_id, _name, _bridge, _logger) { - this._id = _id; - this._name = _name; - this._bridge = _bridge; - this._logger = _logger; - this.myCtxKey = `___window___${this.id}`; - } - get id() { - return this._id.slice(); - } - get name() { - return this._name.slice(); - } - get zoomFactor() { - return ZOOM_FACTORS[this.zoomFactorIndex]; - } - clean() { - if (this.ctxUnsubscribe) { - this.ctxUnsubscribe(); - } - } - processSelfFocusEvent(hasFocus) { - this.me.isFocused = hasFocus; - this.registry.execute("focus-change", this.me); - } - processChannelsChangedEvent(channelNames) { - this.registry.execute("channels-changed", channelNames); - } - processSelfZoomFactorChangedEvent(factorIndex) { - this.zoomFactorIndex = factorIndex; - this.registry.execute("zoom-factor-changed", this.me); - } - async toApi() { - this.ctxUnsubscribe = await this._bridge.contextLib.subscribe(this.myCtxKey, (data) => this.registry.execute("context-updated", data)); - this.me = { - id: this.id, - name: this.name, - isFocused: false, - zoomFactor: this.zoomFactor, - getURL: this.getURL.bind(this), - moveResize: this.moveResize.bind(this), - resizeTo: this.resizeTo.bind(this), - moveTo: this.moveTo.bind(this), - focus: this.focus.bind(this), - close: this.close.bind(this), - getTitle: this.getTitle.bind(this), - setTitle: this.setTitle.bind(this), - getBounds: this.getBounds.bind(this), - getContext: this.getContext.bind(this), - updateContext: this.updateContext.bind(this), - setContext: this.setContext.bind(this), - refresh: this.refresh.bind(this), - onContextUpdated: this.onContextUpdated.bind(this), - onFocusChanged: this.onFocusChanged.bind(this), - getChannel: this.getChannel.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - zoomIn: this.zoomIn.bind(this), - zoomOut: this.zoomOut.bind(this), - setZoomFactor: this.setZoomFactor.bind(this), - onZoomFactorChanged: this.onZoomFactorChanged.bind(this), - }; - Object.defineProperties(this.me, { - id: READONLY_PROPERTY_DESCRIPTOR, - name: READONLY_PROPERTY_DESCRIPTOR, - zoomFactor: { - get: () => { - return this.zoomFactor; - }, - enumerable: true, - }, - }); - return this.me; - } - async getURL() { - const result = await this._bridge.send("windows", operations$a.getUrl, { windowId: this.id }); - return result.url; - } - onFocusChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - return this.registry.add("focus-change", callback); - } - async moveResize(dimension) { - const targetBounds = runDecoderWithIOError(boundsDecoder, dimension); - const commandArgs = Object.assign({}, targetBounds, { windowId: this.id, relative: false }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async resizeTo(width, height) { - if (typeof width === "undefined" && typeof height === "undefined") { - return this.me; - } - if (typeof width !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, width); - } - if (typeof height !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, height); - } - const commandArgs = Object.assign({}, { width, height }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async moveTo(top, left) { - if (typeof top === "undefined" && typeof left === "undefined") { - return this.me; - } - if (typeof top !== "undefined") { - runDecoderWithIOError(number$2(), top); - } - if (typeof left !== "undefined") { - runDecoderWithIOError(number$2(), left); - } - const commandArgs = Object.assign({}, { top, left }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async focus() { - if (this.name === "Platform") { - window.open(undefined, this.id); - } - else { - await this._bridge.send("windows", operations$a.focus, { windowId: this.id }); - } - return this.me; - } - async close() { - await this._bridge.send("windows", operations$a.close, { windowId: this.id }); - return this.me; - } - async getTitle() { - const result = await this._bridge.send("windows", operations$a.getTitle, { windowId: this.id }); - return result.title; - } - async setTitle(title) { - const ttl = runDecoderWithIOError(nonEmptyStringDecoder$2, title); - await this._bridge.send("windows", operations$a.setTitle, { windowId: this.id, title: ttl }); - return this.me; - } - async getBounds() { - const result = await this._bridge.send("windows", operations$a.getBounds, { windowId: this.id }); - return result.bounds; - } - async getContext() { - const ctx = await this._bridge.contextLib.get(this.myCtxKey); - const { ___io___, ...rest } = ctx; - return rest; - } - async updateContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - await this._bridge.contextLib.update(this.myCtxKey, ctx); - return this.me; - } - async setContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - const current = await this._bridge.contextLib.get(this.myCtxKey); - const newCtx = current.___io___ ? { ...ctx, ___io___: current.___io___ } : ctx; - await this._bridge.contextLib.set(this.myCtxKey, newCtx); - return this.me; - } - onContextUpdated(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - const wrappedCallback = (data) => { - const { ___io___, ...rest } = data; - callback(rest, this.me); - }; - return this.registry.add("context-updated", wrappedCallback); - } - async getChannel() { - const result = await this._bridge.send("windows", operations$a.getChannel, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return result.channel; - } - onChannelsChanged(callback) { - return this.registry.add("channels-changed", callback); - } - getClosestZoomFactorIndex(factor) { - const closestIndex = Object.entries(ZOOM_FACTORS).reduce((closestIndex, [currentIndex, currentValue]) => { - return (Math.abs(currentValue - factor) <= Math.abs(ZOOM_FACTORS[closestIndex] - factor) ? parseInt(currentIndex) : closestIndex); - }, 0); - const closestFactor = ZOOM_FACTORS[closestIndex]; - if (closestFactor !== factor) { - this._logger.warn(`Zoom factor ${factor} is not available, using closest value ${closestFactor} instead.`); - } - return closestIndex; - } - async zoom(factorIndex) { - if (factorIndex === this.zoomFactorIndex || !(factorIndex in ZOOM_FACTORS)) { - return; - } - await this._bridge.send("windows", operations$a.setZoomFactor, { windowId: this.id, factorIndex }, undefined, { includeOperationCheck: true }); - this.zoomFactorIndex = factorIndex; - } - async zoomIn() { - await this.zoom(this.zoomFactorIndex + 1); - return this.me; - } - async zoomOut() { - await this.zoom(this.zoomFactorIndex - 1); - return this.me; - } - async setZoomFactor(factor) { - const targetZoomFactor = runDecoderWithIOError(number$2(), factor); - const closestZoomFactorIndex = this.getClosestZoomFactorIndex(targetZoomFactor); - await this.zoom(closestZoomFactorIndex); - return this.me; - } - onZoomFactorChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"); - } - return this.registry.add("zoom-factor-changed", callback); - } - async refresh() { - await this._bridge.send("windows", operations$a.refresh, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return this.me; - } - } - - const commonOperations = { - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - getWorkspaceWindowFrameBounds: { name: "getWorkspaceWindowFrameBounds", resultDecoder: workspaceFrameBoundsResultDecoder, dataDecoder: simpleItemIdDecoder } - }; - - const PromiseWrap = (callback, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - callback() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - const PromisePlus$1 = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WindowsController { - supportedOperationsNames = []; - focusEventHandler; - registry = CallbackRegistryFactory$1(); - platformRegistration; - ioc; - bridge; - publicWindowId; - allWindowProjections = []; - me; - logger; - isWorkspaceFrame; - instanceId; - channelsController; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("windows.controller.web"); - this.logger.trace("starting the web windows controller"); - this.publicWindowId = ioc.publicWindowId; - this.addWindowOperationExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.instanceId = coreGlue.interop.instance.instance; - this.channelsController = ioc.channelsController; - this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`); - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - await this.initializeFocusTracking(); - this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning"); - const api = this.toApi(); - coreGlue.windows = api; - } - handlePlatformShutdown() { - this.registry.clear(); - this.allWindowProjections = []; - if (!this.focusEventHandler) { - return; - } - document.removeEventListener("visibilityChange", this.focusEventHandler); - window.removeEventListener("focus", this.focusEventHandler); - window.removeEventListener("blur", this.focusEventHandler); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(windowOperationTypesDecoder, args.operation); - const operation = operations$a[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async open(name, url, options) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(nonEmptyStringDecoder$2, url); - const settings = runDecoderWithIOError(windowOpenSettingsDecoder, options); - const windowSuccess = await this.bridge.send("windows", operations$a.openWindow, { name, url, options: settings }); - return this.waitForWindowAdded(windowSuccess.windowId); - } - list() { - return this.allWindowProjections.map((projection) => projection.api); - } - findById(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - return this.allWindowProjections.find((projection) => projection.id === id)?.api; - } - toApi() { - return { - open: this.open.bind(this), - my: this.my.bind(this), - list: this.list.bind(this), - findById: this.findById.bind(this), - onWindowAdded: this.onWindowAdded.bind(this), - onWindowRemoved: this.onWindowRemoved.bind(this), - onWindowGotFocus: this.onWindowGotFocus.bind(this), - onWindowLostFocus: this.onWindowLostFocus.bind(this) - }; - } - addWindowOperationExecutors() { - operations$a.focusChange.execute = this.handleFocusChangeEvent.bind(this); - operations$a.windowAdded.execute = this.handleWindowAdded.bind(this); - operations$a.windowRemoved.execute = this.handleWindowRemoved.bind(this); - operations$a.getBounds.execute = this.handleGetBounds.bind(this); - operations$a.getFrameBounds.execute = this.handleGetBounds.bind(this); - operations$a.getTitle.execute = this.handleGetTitle.bind(this); - operations$a.getUrl.execute = this.handleGetUrl.bind(this); - operations$a.moveResize.execute = this.handleMoveResize.bind(this); - operations$a.setTitle.execute = this.handleSetTitle.bind(this); - operations$a.getChannel.execute = this.handleGetChannel.bind(this); - operations$a.notifyChannelsChanged.execute = this.handleChannelsChanged.bind(this); - operations$a.setZoomFactor.execute = this.handleSetZoomFactor.bind(this); - operations$a.zoomFactorChange.execute = this.handleZoomFactorChanged.bind(this); - operations$a.refresh.execute = this.handleRefresh.bind(this); - operations$a.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$a); - } - my() { - return Object.assign({}, this.me); - } - onWindowAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"); - } - return this.registry.add("window-added", callback); - } - onWindowRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"); - } - return this.registry.add("window-removed", callback); - } - onWindowGotFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-got-focus", callback); - } - onWindowLostFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-lost-focus", callback); - } - async sayHello() { - const helloSuccess = await this.bridge.send("windows", operations$a.windowHello, { windowId: this.publicWindowId }); - return helloSuccess; - } - async registerWithPlatform() { - const { windows, isWorkspaceFrame } = await this.sayHello(); - this.isWorkspaceFrame = isWorkspaceFrame; - this.logger.trace("the platform responded to the hello message"); - if (!this.isWorkspaceFrame && this.publicWindowId) { - this.logger.trace("i am not treated as a workspace frame, setting my window"); - const myWindow = windows.find((w) => w.windowId === this.publicWindowId); - if (!myWindow) { - const windowsInfo = windows.map(w => `${w.windowId}:${w.name}`).join(", "); - return ioError.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${windowsInfo}`); - } - const myProjection = await this.ioc.buildWebWindow(this.publicWindowId, myWindow.name, this.logger); - this.me = myProjection.api; - this.allWindowProjections.push(myProjection); - } - const currentWindows = await Promise.all(windows - .filter((w) => w.windowId !== this.publicWindowId) - .map((w) => this.ioc.buildWebWindow(w.windowId, w.name, this.logger))); - this.logger.trace("all windows projections are completed, building the list collection"); - this.allWindowProjections.push(...currentWindows); - } - async handleFocusChangeEvent(focusData) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === focusData.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfFocusEvent(focusData.hasFocus); - const keyToExecute = focusData.hasFocus ? "window-got-focus" : "window-lost-focus"; - this.registry.execute(keyToExecute, foundProjection.api); - } - async handleWindowAdded(data) { - if (this.allWindowProjections.some((projection) => projection.id === data.windowId)) { - return; - } - const webWindowProjection = await this.ioc.buildWebWindow(data.windowId, data.name, this.logger); - this.allWindowProjections.push(webWindowProjection); - this.registry.execute("window-added", webWindowProjection.api); - } - async handleWindowRemoved(data) { - const removed = this.allWindowProjections.find((w) => w.id === data.windowId); - if (!removed) { - return; - } - this.allWindowProjections = this.allWindowProjections.filter((w) => w.id !== data.windowId); - removed.model.clean(); - this.registry.execute("window-removed", removed.api); - } - async handleGetBounds() { - if (!this.me && !this.isWorkspaceFrame) { - return ioError.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.isWorkspaceFrame ? "noop" : this.me.id, - bounds: { - top: window.screenTop, - left: window.screenLeft, - width: window.innerWidth, - height: window.innerHeight - } - }; - } - async handleGetTitle() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - title: document.title - }; - } - async handleGetUrl() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - url: window.location.href - }; - } - async handleMoveResize(config) { - const targetTop = typeof config.top === "number" ? config.top : - config.relative ? 0 : window.screenTop; - const targetLeft = typeof config.left === "number" ? config.left : - config.relative ? 0 : window.screenLeft; - const targetHeight = typeof config.height === "number" ? config.height : - config.relative ? 0 : window.innerHeight; - const targetWidth = typeof config.width === "number" ? config.width : - config.relative ? 0 : window.innerWidth; - const moveMethod = config.relative ? window.moveBy : window.moveTo; - const resizeMethod = config.relative ? window.resizeBy : window.resizeTo; - moveMethod(targetLeft, targetTop); - resizeMethod(targetWidth, targetHeight); - } - async handleSetTitle(config) { - document.title = config.title; - } - async initializeFocusTracking() { - if (this.isWorkspaceFrame) { - this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame"); - return; - } - try { - await this.bridge.send("windows", commonOperations.operationCheck, { operation: "focusChange" }); - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client."); - return; - } - const hasFocus = document.hasFocus(); - await this.transmitFocusChange(true); - if (!hasFocus) { - await this.transmitFocusChange(false); - } - this.defineEventListeners(); - } - processFocusEvent() { - const hasFocus = document.hasFocus(); - this.transmitFocusChange(hasFocus); - } - waitForWindowAdded(windowId) { - const foundWindow = this.allWindowProjections.find((projection) => projection.id === windowId); - if (foundWindow) { - return Promise.resolve(foundWindow.api); - } - return PromisePlus$1((resolve) => { - const unsubscribe = this.onWindowAdded((addedWindow) => { - if (addedWindow.id === windowId) { - unsubscribe(); - resolve(addedWindow); - } - }); - }, 30000, `Timed out waiting for ${windowId} to be announced`); - } - async transmitFocusChange(hasFocus) { - const eventData = { - windowId: this.me?.id || `iframe-${this.instanceId}`, - hasFocus - }; - if (this.me) { - this.me.isFocused = hasFocus; - } - await this.bridge.send("windows", operations$a.focusChange, eventData); - } - defineEventListeners() { - this.focusEventHandler = this.processFocusEvent.bind(this); - document.addEventListener("visibilityChange", this.focusEventHandler); - window.addEventListener("focus", this.focusEventHandler); - window.addEventListener("blur", this.focusEventHandler); - } - async handleGetChannel() { - if (!this.me) { - return ioError.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe"); - } - const channel = this.channelsController.my(); - return { - ...(channel ? { channel } : {}), - }; - } - async handleRefresh() { - if (!this.me) { - return ioError.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe"); - } - setTimeout(() => { - window.location.reload(); - }, 0); - } - async handleChannelsChanged(data) { - const windowProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - windowProjection?.model.processChannelsChangedEvent(data.channelNames); - } - async handleSetZoomFactor(config) { - if (!this.me) { - return ioError.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe"); - } - document.body.style.zoom = `${ZOOM_FACTORS[config.factorIndex]}%`; - } - async handleZoomFactorChanged(data) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfZoomFactorChangedEvent(data.factorIndex); - } - } - - const GlueWebPlatformControlName = "T42.Web.Platform.Control"; - const GlueWebPlatformStreamName = "T42.Web.Platform.Stream"; - const GlueClientControlName = "T42.Web.Client.Control"; - const GlueCorePlusThemesStream = "T42.Core.Plus.Themes.Stream"; - - class GlueBridge { - coreGlue; - communicationId; - platformMethodTimeoutMs = 10000; - controllers; - sub; - running; - constructor(coreGlue, communicationId) { - this.coreGlue = coreGlue; - this.communicationId = communicationId; - } - get contextLib() { - return this.coreGlue.contexts; - } - get interopInstance() { - return this.coreGlue.interop.instance.instance; - } - async stop() { - this.running = false; - this.sub.close(); - await this.coreGlue.interop.unregister(GlueClientControlName); - } - async start(controllers) { - this.running = true; - this.controllers = controllers; - await Promise.all([ - this.checkWaitMethod(GlueWebPlatformControlName), - this.checkWaitMethod(GlueWebPlatformStreamName) - ]); - const systemId = this.communicationId; - const [sub] = await Promise.all([ - this.coreGlue.interop.subscribe(GlueWebPlatformStreamName, systemId ? { target: { instance: this.communicationId } } : undefined), - this.coreGlue.interop.registerAsync(GlueClientControlName, (args, _, success, error) => this.passMessageController(args, success, error)) - ]); - this.sub = sub; - this.sub.onData((pkg) => this.passMessageController(pkg.data)); - } - getInteropInstance(windowId) { - const result = this.coreGlue.interop.servers().find((s) => s.windowId && s.windowId === windowId); - return { - application: result?.application, - applicationName: result?.applicationName, - peerId: result?.peerId, - instance: result?.instance, - windowId: result?.windowId - }; - } - async send(domain, operation, operationData, options, webOptions) { - if (operation.dataDecoder) { - try { - operation.dataDecoder.runWithException(operationData); - } - catch (error) { - return ioError.raiseError(`Unexpected Web->Platform outgoing validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - } - const operationSupported = webOptions?.includeOperationCheck ? - (await this.checkOperationSupported(domain, operation)).isSupported : - true; - if (!operationSupported) { - return ioError.raiseError(`Cannot complete operation: ${operation.name} for domain: ${domain} because this client is connected to a platform which does not support it`); - } - try { - const operationResult = await this.transmitMessage(domain, operation, operationData, options); - if (operation.resultDecoder) { - operation.resultDecoder.runWithException(operationResult); - } - return operationResult; - } - catch (error) { - if (error?.kind) { - return ioError.raiseError(`Unexpected Web<-Platform incoming validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - return ioError.raiseError(error); - } - } - async createNotificationsSteam() { - const streamExists = this.coreGlue.interop.methods().some((method) => method.name === GlueCorePlusThemesStream); - if (!streamExists) { - return ioError.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus."); - } - return this.coreGlue.interop.subscribe(GlueCorePlusThemesStream, this.communicationId ? { target: { instance: this.communicationId } } : undefined); - } - async checkOperationSupported(domain, operation) { - try { - const result = await this.send(domain, commonOperations.operationCheck, { operation: operation.name }); - return result; - } - catch (error) { - return { isSupported: false }; - } - } - checkWaitMethod(name) { - return PromisePlus$1((resolve) => { - const hasMethod = this.coreGlue.interop.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = this.communicationId ? - method.getServers().some((server) => server.instance === this.communicationId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - return resolve(); - } - const unSub = this.coreGlue.interop.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = this.communicationId ? - server.instance === this.communicationId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }, this.platformMethodTimeoutMs, `Cannot initiate Glue Web, because a system method's discovery timed out: ${name}`); - } - passMessageController(args, success, error) { - const decodeResult = libDomainDecoder.run(args.domain); - if (!decodeResult.ok) { - if (error) { - error(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(decodeResult.error)}`); - } - return; - } - const domain = decodeResult.result; - this.controllers[domain] - .handleBridgeMessage(args) - .then((resolutionData) => { - if (success) { - success(resolutionData); - } - }) - .catch((err) => { - if (error) { - error(err); - } - console.warn(err); - }); - } - async transmitMessage(domain, operation, data, options) { - const messageData = { domain, data, operation: operation.name }; - let invocationResult; - const baseErrorMessage = `Internal Platform Communication Error. Attempted operation: ${JSON.stringify(operation.name)} with data: ${JSON.stringify(data)}. `; - const systemId = this.communicationId; - try { - if (!this.running) { - throw new Error("Cannot send a control message, because the platform shut down"); - } - invocationResult = await this.coreGlue.interop.invoke(GlueWebPlatformControlName, messageData, systemId ? { instance: this.communicationId } : undefined, options); - if (!invocationResult) { - throw new Error("Received unsupported result from the platform - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from the platform - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - } - - const operations$9 = { - appHello: { name: "appHello", dataDecoder: windowHelloDecoder, resultDecoder: appHelloSuccessDecoder }, - appDirectoryStateChange: { name: "appDirectoryStateChange", dataDecoder: appDirectoryStateChangeDecoder }, - instanceStarted: { name: "instanceStarted", dataDecoder: instanceDataDecoder }, - instanceStopped: { name: "instanceStopped", dataDecoder: instanceDataDecoder }, - applicationStart: { name: "applicationStart", dataDecoder: applicationStartConfigDecoder, resultDecoder: instanceDataDecoder }, - instanceStop: { name: "instanceStop", dataDecoder: basicInstanceDataDecoder }, - import: { name: "import" }, - remove: { name: "remove", dataDecoder: appRemoveConfigDecoder }, - export: { name: "export", resultDecoder: appsExportOperationDecoder }, - clear: { name: "clear" }, - operationCheck: { name: "operationCheck" } - }; - - class AppManagerController { - me; - supportedOperationsNames = []; - baseApplicationsTimeoutMS = 60000; - appImportTimeoutMS = 20; - registry = CallbackRegistryFactory$1(); - ioc; - bridge; - publicWindowId; - applications = []; - instances = []; - platformRegistration; - logger; - channelsController; - interop; - initialChannelId; - handlePlatformShutdown() { - this.registry.clear(); - this.applications = []; - this.instances = []; - delete this.me; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("appManger.controller.web"); - this.logger.trace("starting the web appManager controller"); - this.publicWindowId = ioc.publicWindowId; - this.addOperationsExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.interop = coreGlue.interop; - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning"); - const api = this.toApi(); - coreGlue.appManager = api; - } - async postStart() { - if (!this.initialChannelId) { - return; - } - await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(appManagerOperationTypesDecoder, args.operation); - const operation = operations$9[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStarted requires a single argument of type function"); - } - return this.registry.add("instance-started", callback, this.instances); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStopped requires a single argument of type function"); - } - return this.registry.add("instance-stopped", callback); - } - async startApplication(appName, context, options) { - const channels = await this.channelsController.all(); - if (options?.channelId && !channels.includes(options.channelId)) { - return ioError.raiseError(`The channel with name "${options.channelId}" doesn't exist!`); - } - const startOptions = { - name: appName, - waitForAGMReady: options?.waitForAGMReady ?? true, - context, - top: options?.top, - left: options?.left, - width: options?.width, - height: options?.height, - relativeTo: options?.relativeTo, - relativeDirection: options?.relativeDirection, - id: options?.reuseId, - forceChromeTab: options?.forceTab, - layoutComponentId: options?.layoutComponentId, - channelId: options?.channelId, - startReason: { - originApp: { - name: this.me?.application.name, - interopInstance: this.interop.instance.instance - } - } - }; - if (options?.originIntentRequest) { - startOptions.startReason.intentRequest = options.originIntentRequest; - } - const openResult = await this.bridge.send("appManager", operations$9.applicationStart, startOptions); - const app = this.applications.find((a) => a.name === openResult.applicationName); - return this.ioc.buildInstance(openResult, app); - } - getApplication(name) { - const verifiedName = runDecoderWithIOError(nonEmptyStringDecoder$2, name); - return this.applications.find((app) => app.name === verifiedName); - } - getInstances() { - return this.instances.slice(); - } - onAppAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppAdded requires a single argument of type function"); - } - return this.registry.add("application-added", callback, this.applications); - } - onAppRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppRemoved requires a single argument of type function"); - } - return this.registry.add("application-removed", callback); - } - toApi() { - const api = { - myInstance: this.me, - inMemory: { - import: this.importApps.bind(this), - remove: this.remove.bind(this), - export: this.exportApps.bind(this), - clear: this.clear.bind(this) - }, - application: this.getApplication.bind(this), - applications: this.getApplications.bind(this), - instances: this.getInstances.bind(this), - onAppAdded: this.onAppAdded.bind(this), - onAppChanged: this.onAppChanged.bind(this), - onAppRemoved: this.onAppRemoved.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - return api; - } - addOperationsExecutors() { - operations$9.appDirectoryStateChange.execute = this.handleAppDirectoryStateChange.bind(this); - operations$9.instanceStarted.execute = this.handleInstanceStartedMessage.bind(this); - operations$9.instanceStopped.execute = this.handleInstanceStoppedMessage.bind(this); - operations$9.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$9); - } - async handleAppDirectoryStateChange(data) { - data.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)); - data.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)); - data.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this)); - } - onAppChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppChanged requires a single argument of type function"); - } - return this.registry.add("application-changed", callback); - } - async handleApplicationAddedMessage(appData) { - if (this.applications.some((app) => app.name === appData.name)) { - return; - } - const app = await this.ioc.buildApplication(appData, []); - const instances = this.instances.filter((instance) => instance.application.name === app.name); - app.instances.push(...instances); - this.applications.push(app); - this.registry.execute("application-added", app); - } - async handleApplicationRemovedMessage(appData) { - const appIndex = this.applications.findIndex((app) => app.name === appData.name); - if (appIndex < 0) { - return; - } - const app = this.applications[appIndex]; - this.applications.splice(appIndex, 1); - this.registry.execute("application-removed", app); - } - async handleApplicationChangedMessage(appData) { - const app = this.applications.find((app) => app.name === appData.name); - if (!app) { - return this.handleApplicationAddedMessage(appData); - } - app.title = appData.title; - app.version = appData.version; - app.icon = appData.icon; - app.caption = appData.caption; - app.userProperties = appData.userProperties; - this.registry.execute("application-changed", app); - } - async handleInstanceStartedMessage(instanceData) { - if (this.instances.some((instance) => instance.id === instanceData.id)) { - return; - } - const application = this.applications.find((app) => app.name === instanceData.applicationName); - if (!application) { - return ioError.raiseError(`Cannot add instance: ${instanceData.id}, because there is no application definition associated with it`); - } - const instance = this.ioc.buildInstance(instanceData, application); - this.instances.push(instance); - application.instances.push(instance); - this.registry.execute("instance-started", instance); - } - async handleInstanceStoppedMessage(instanceData) { - const instance = this.instances.find((i) => i.id === instanceData.id); - if (instance) { - const instIdx = this.instances.findIndex((inst) => inst.id === instanceData.id); - this.instances.splice(instIdx, 1); - } - const application = this.applications.find((app) => app.instances.some((inst) => inst.id === instanceData.id)); - if (application) { - const instIdxApps = application.instances.findIndex((inst) => inst.id === instanceData.id); - application.instances.splice(instIdxApps, 1); - } - if (!instance) { - return; - } - this.registry.execute("instance-stopped", instance); - } - async importApps(definitions, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(definitions)) { - return ioError.raiseError("Import must be called with an array of definitions"); - } - if (definitions.length > 10000) { - return ioError.raiseError("Cannot import more than 10000 app definitions in Glue42 Core."); - } - const parseResult = definitions.reduce((soFar, definition) => { - const { isValid, error } = this.isValidDefinition(definition); - if (!isValid) { - soFar.invalid.push({ app: definition?.name, error: error ?? `Provided definition is invalid ${JSON.stringify(definition)}` }); - } - else { - soFar.valid.push(definition); - } - return soFar; - }, { valid: [], invalid: [] }); - const responseTimeout = this.baseApplicationsTimeoutMS + this.appImportTimeoutMS * parseResult.valid.length; - await this.bridge.send("appManager", operations$9.import, { definitions: parseResult.valid, mode }, { methodResponseTimeoutMs: responseTimeout }); - return { - imported: parseResult.valid.map((valid) => valid.name), - errors: parseResult.invalid - }; - } - isValidDefinition(definition) { - const isFdc3V2Definition = definition?.appId && definition?.details; - if (isFdc3V2Definition) { - const decodeResult = decoders.fdc3.v2DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v2 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const isFdc3V1Definition = definition?.appId && definition?.manifest; - if (isFdc3V1Definition) { - const decodeResult = decoders.fdc3.v1DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v1 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const decodeResult = applicationDefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("appManager", operations$9.remove, { name }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async clear() { - await this.bridge.send("appManager", operations$9.clear, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async exportApps() { - const response = await this.bridge.send("appManager", operations$9.export, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - return response.definitions; - } - getApplications() { - return this.applications.slice(); - } - async registerWithPlatform() { - const result = await this.bridge.send("appManager", operations$9.appHello, { windowId: this.publicWindowId }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - this.logger.trace("the platform responded to the hello message with a full list of apps"); - this.applications = await Promise.all(result.apps.map((app) => this.ioc.buildApplication(app, app.instances))); - this.instances = this.applications.reduce((instancesSoFar, app) => { - instancesSoFar.push(...app.instances); - return instancesSoFar; - }, []); - this.me = this.findMyInstance(); - this.logger.trace(`all applications were parsed and saved. I am ${this.me ? "NOT a" : "a"} valid instance`); - this.initialChannelId = result.initialChannelId; - } - findMyInstance() { - for (const app of this.applications) { - const foundInstance = app.instances.find((instance) => instance.id === this.publicWindowId); - if (foundInstance) { - return foundInstance; - } - } - return undefined; - } - } - - class InstanceModel { - data; - bridge; - application; - me; - myCtxKey; - constructor(data, bridge, application) { - this.data = data; - this.bridge = bridge; - this.application = application; - this.myCtxKey = `___instance___${this.data.id}`; - } - toApi() { - const agm = this.bridge.getInteropInstance(this.data.id); - const api = { - id: this.data.id, - agm, - application: this.application, - stop: this.stop.bind(this), - getContext: this.getContext.bind(this) - }; - this.me = Object.freeze(api); - return this.me; - } - async getContext() { - return this.bridge.contextLib.get(this.myCtxKey); - } - async stop() { - await this.bridge.send("appManager", operations$9.instanceStop, { id: this.data.id }); - } - } - - class ApplicationModel { - data; - instances; - controller; - me; - constructor(data, instances, controller) { - this.data = data; - this.instances = instances; - this.controller = controller; - } - toApi() { - const api = { - name: this.data.name, - title: this.data.title, - version: this.data.version, - icon: this.data.icon, - caption: this.data.caption, - userProperties: this.data.userProperties, - instances: this.instances, - start: this.start.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - this.me = api; - return this.me; - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStarted((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStopped((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - async start(context, options) { - const verifiedContext = runDecoderWithIOError(startApplicationContextDecoder, context); - const verifiedOptions = runDecoderWithIOError(startApplicationOptionsDecoder, options); - return this.controller.startApplication(this.data.name, verifiedContext, verifiedOptions); - } - } - - const operations$8 = { - layoutAdded: { name: "layoutAdded", dataDecoder: glueLayoutDecoder }, - layoutChanged: { name: "layoutChanged", dataDecoder: glueLayoutDecoder }, - layoutRemoved: { name: "layoutRemoved", dataDecoder: glueLayoutDecoder }, - layoutRestored: { name: "layoutRestored", dataDecoder: glueLayoutDecoder }, - defaultLayoutChanged: { name: "defaultLayoutChanged", dataDecoder: defaultGlobalChangedDecoder }, - layoutRenamed: { name: "layoutRenamed", dataDecoder: renamedLayoutNotificationDecoder }, - get: { name: "get", dataDecoder: simpleLayoutConfigDecoder, resultDecoder: optionalSimpleLayoutResult }, - getAll: { name: "getAll", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsSummariesResultDecoder }, - export: { name: "export", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsFullConfigDecoder }, - import: { name: "import", dataDecoder: layoutsImportConfigDecoder }, - remove: { name: "remove", dataDecoder: simpleLayoutConfigDecoder }, - rename: { name: "rename", dataDecoder: renameLayoutConfigDecoder, resultDecoder: layoutResultDecoder }, - save: { name: "save", dataDecoder: saveLayoutConfigDecoder, resultDecoder: simpleLayoutResultDecoder }, - restore: { name: "restore", dataDecoder: restoreLayoutConfigDecoder }, - clientSaveRequest: { name: "clientSaveRequest", dataDecoder: platformSaveRequestConfigDecoder, resultDecoder: saveRequestClientResponseDecoder }, - getGlobalPermissionState: { name: "getGlobalPermissionState", resultDecoder: permissionStateResultDecoder }, - requestGlobalPermission: { name: "requestGlobalPermission", resultDecoder: simpleAvailabilityResultDecoder }, - checkGlobalActivated: { name: "checkGlobalActivated", resultDecoder: simpleAvailabilityResultDecoder }, - getDefaultGlobal: { name: "getDefaultGlobal", resultDecoder: optionalSimpleLayoutResult }, - setDefaultGlobal: { name: "setDefaultGlobal", dataDecoder: setDefaultGlobalConfigDecoder }, - clearDefaultGlobal: { name: "clearDefaultGlobal" }, - getCurrent: { name: "getCurrent", resultDecoder: optionalSimpleLayoutResult }, - updateMetadata: { name: "updateMetadata", dataDecoder: updateLayoutMetadataConfigDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class LayoutsController { - supportedOperationsNames = []; - defaultLayoutRestoreTimeoutMS = 120000; - registry = CallbackRegistryFactory$1(); - bridge; - logger; - windowsController; - saveRequestSubscription; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("layouts.controller.web"); - this.logger.trace("starting the web layouts controller"); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.addOperationsExecutors(); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"); - coreGlue.layouts = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(layoutsOperationTypesDecoder, args.operation); - const operation = operations$8[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - get: this.get.bind(this), - getAll: this.getAll.bind(this), - getCurrentLayout: this.getCurrentLayout.bind(this), - export: this.exportLayouts.bind(this), - import: this.importLayouts.bind(this), - save: this.save.bind(this), - restore: this.restore.bind(this), - remove: this.remove.bind(this), - onAdded: this.onAdded.bind(this), - onChanged: this.onChanged.bind(this), - onRemoved: this.onRemoved.bind(this), - onDefaultGlobalChanged: this.onDefaultGlobalChanged.bind(this), - onSaveRequested: this.subscribeOnSaveRequested.bind(this), - getMultiScreenPermissionState: this.getGlobalPermissionState.bind(this), - requestMultiScreenPermission: this.requestGlobalPermission.bind(this), - getGlobalTypeState: this.checkGlobalActivated.bind(this), - getDefaultGlobal: this.getDefaultGlobal.bind(this), - setDefaultGlobal: this.setDefaultGlobal.bind(this), - clearDefaultGlobal: this.clearDefaultGlobal.bind(this), - rename: this.rename.bind(this), - onRenamed: this.onRenamed.bind(this), - onRestored: this.onRestored.bind(this), - updateMetadata: this.updateMetadata.bind(this) - }; - return Object.freeze(api); - } - addOperationsExecutors() { - operations$8.layoutAdded.execute = this.handleOnAdded.bind(this); - operations$8.layoutChanged.execute = this.handleOnChanged.bind(this); - operations$8.layoutRemoved.execute = this.handleOnRemoved.bind(this); - operations$8.layoutRenamed.execute = this.handleOnRenamed.bind(this); - operations$8.layoutRestored.execute = this.handleOnRestored.bind(this); - operations$8.defaultLayoutChanged.execute = this.handleOnDefaultChanged.bind(this); - operations$8.clientSaveRequest.execute = this.handleSaveRequest.bind(this); - operations$8.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$8); - } - async get(name, type) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.get, { name, type }); - return result.layout; - } - async getCurrentLayout() { - const result = await this.bridge.send("layouts", operations$8.getCurrent, undefined); - return result.layout; - } - async getAll(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.getAll, { type }); - return result.summaries; - } - async exportLayouts(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.export, { type }); - return result.layouts; - } - async importLayouts(layouts, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(layouts)) { - return ioError.raiseError("Import must be called with an array of layouts"); - } - if (layouts.length > 1000) { - return ioError.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core."); - } - const parseResult = layouts.reduce((soFar, layout) => { - const decodeResult = glueLayoutDecoder.run(layout); - if (decodeResult.ok) { - soFar.valid.push(layout); - } - else { - this.logger.warn(`A layout with name: ${layout.name} was not imported, because of error: ${JSON.stringify(decodeResult.error)}`); - } - return soFar; - }, { valid: [] }); - const layoutsToImport = layouts.filter((layout) => parseResult.valid.some((validLayout) => validLayout.name === layout.name)); - await this.bridge.send("layouts", operations$8.import, { layouts: layoutsToImport, mode }); - } - async save(layout) { - runDecoderWithIOError(newLayoutOptionsDecoder, layout); - const saveResult = await this.bridge.send("layouts", operations$8.save, { layout }); - return saveResult.layout; - } - async restore(options) { - runDecoderWithIOError(restoreOptionsDecoder, options); - const invocationTimeout = options.timeout ? options.timeout * 2 : this.defaultLayoutRestoreTimeoutMS; - await this.bridge.send("layouts", operations$8.restore, { layout: options }, { methodResponseTimeoutMs: invocationTimeout }); - } - async remove(type, name) { - runDecoderWithIOError(layoutTypeDecoder, type); - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.remove, { type, name }); - } - async handleSaveRequest(config) { - const response = {}; - if (this.saveRequestSubscription) { - try { - const onSaveRequestResponse = this.saveRequestSubscription(config); - response.windowContext = onSaveRequestResponse?.windowContext; - } - catch (error) { - this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(error)}`); - } - } - return response; - } - async getGlobalPermissionState() { - const requestResult = await this.bridge.send("layouts", operations$8.getGlobalPermissionState, undefined); - return requestResult; - } - async requestGlobalPermission() { - const currentState = (await this.getGlobalPermissionState()).state; - if (currentState === "denied") { - return { permissionGranted: false }; - } - if (currentState === "granted") { - return { permissionGranted: true }; - } - const myWindow = this.windowsController.my(); - const globalNamespace = window.glue42core || window.iobrowser; - const amIWorkspaceFrame = globalNamespace.isPlatformFrame; - if (myWindow.name !== "Platform" && !amIWorkspaceFrame) { - return ioError.raiseError("Cannot request permission for multi-window placement from any app other than the Platform."); - } - const requestResult = await this.bridge.send("layouts", operations$8.requestGlobalPermission, undefined, { methodResponseTimeoutMs: 180000 }); - return { permissionGranted: requestResult.isAvailable }; - } - async checkGlobalActivated() { - const requestResult = await this.bridge.send("layouts", operations$8.checkGlobalActivated, undefined); - return { activated: requestResult.isAvailable }; - } - async getDefaultGlobal() { - const requestResult = await this.bridge.send("layouts", operations$8.getDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - return requestResult.layout; - } - async setDefaultGlobal(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.setDefaultGlobal, { name }, undefined, { includeOperationCheck: true }); - } - async clearDefaultGlobal() { - await this.bridge.send("layouts", operations$8.clearDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - } - async rename(layout, newName) { - runDecoderWithIOError(glueLayoutDecoder, layout); - runDecoderWithIOError(nonEmptyStringDecoder$2, newName); - const result = await this.bridge.send("layouts", operations$8.rename, { layout, newName }, undefined, { includeOperationCheck: true }); - return result; - } - async updateMetadata(layout) { - runDecoderWithIOError(glueLayoutDecoder, layout); - await this.bridge.send("layouts", operations$8.updateMetadata, { layout }, undefined, { includeOperationCheck: true }); - } - onAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"); - } - this.exportLayouts("Global").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - this.exportLayouts("Workspace").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - return this.registry.add(operations$8.layoutAdded.name, callback); - } - onChanged(callback) { - return this.registry.add(operations$8.layoutChanged.name, callback); - } - onDefaultGlobalChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"); - } - this.getDefaultGlobal().then((layout) => callback(layout ? { name: layout.name } : undefined)).catch(() => { }); - return this.registry.add(operations$8.defaultLayoutChanged.name, callback); - } - onRemoved(callback) { - return this.registry.add(operations$8.layoutRemoved.name, callback); - } - onRenamed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRenamed.name, callback); - } - onRestored(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRestored.name, callback); - } - subscribeOnSaveRequested(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."); - } - if (this.saveRequestSubscription) { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."); - } - this.saveRequestSubscription = callback; - return () => { - delete this.saveRequestSubscription; - }; - } - async handleOnAdded(layout) { - this.registry.execute(operations$8.layoutAdded.name, layout); - } - async handleOnChanged(layout) { - this.registry.execute(operations$8.layoutChanged.name, layout); - } - async handleOnDefaultChanged(layout) { - this.registry.execute(operations$8.defaultLayoutChanged.name, layout); - } - async handleOnRemoved(layout) { - this.registry.execute(operations$8.layoutRemoved.name, layout); - } - async handleOnRestored(layout) { - this.registry.execute(operations$8.layoutRestored.name, layout); - } - async handleOnRenamed(renamedData) { - const { prevName, ...layout } = renamedData; - this.registry.execute(operations$8.layoutRenamed.name, layout, { name: prevName }); - } - } - - const operations$7 = { - raiseNotification: { name: "raiseNotification", dataDecoder: raiseNotificationDecoder, resultDecoder: raiseNotificationResultDecoder }, - requestPermission: { name: "requestPermission", resultDecoder: permissionRequestResultDecoder }, - notificationShow: { name: "notificationShow", dataDecoder: notificationEventPayloadDecoder }, - notificationClick: { name: "notificationClick", dataDecoder: notificationEventPayloadDecoder }, - getPermission: { name: "getPermission", resultDecoder: permissionQueryResultDecoder }, - list: { name: "list", resultDecoder: allNotificationsDataDecoder }, - notificationRaised: { name: "notificationRaised", dataDecoder: simpleNotificationDataDecoder }, - notificationClosed: { name: "notificationClosed", dataDecoder: simpleNotificationSelectDecoder }, - click: { name: "click" }, - clear: { name: "clear" }, - clearAll: { name: "clearAll" }, - clearOld: { name: "clearOld" }, - configure: { name: "configure", dataDecoder: notificationsConfigurationProtocolDecoder }, - getConfiguration: { name: "getConfiguration", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - getActiveCount: { name: "getActiveCount", resultDecoder: activeNotificationsCountChangeDecoder }, - configurationChanged: { name: "configurationChanged", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - setState: { name: "setState", dataDecoder: notificationSetStateRequestDecoder }, - activeCountChange: { name: "activeCountChange", resultDecoder: activeNotificationsCountChangeDecoder }, - stateChange: { name: "stateChange", resultDecoder: notificationSetStateRequestDecoder }, - operationCheck: { name: "operationCheck" } - }; - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet$1 = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid$1 = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet$1[(Math.random() * 64) | 0]; - } - return id - }; - - class NotificationsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - bridge; - notificationsSettings; - notifications = {}; - coreGlue; - buildNotificationFunc; - notificationsConfiguration; - notificationsActiveCount = 0; - handlePlatformShutdown() { - this.notifications = {}; - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("notifications.controller.web"); - this.logger.trace("starting the web notifications controller"); - this.bridge = ioc.bridge; - this.coreGlue = coreGlue; - this.notificationsSettings = ioc.config.notifications; - this.buildNotificationFunc = ioc.buildNotification; - this.notificationsConfiguration = await this.getConfiguration(); - this.notificationsActiveCount = await this.getActiveCount(); - const api = this.toApi(); - this.addOperationExecutors(); - coreGlue.notifications = api; - this.logger.trace("notifications are ready"); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(notificationsOperationTypesDecoder, args.operation); - const operation = operations$7[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - requestPermission: this.requestPermission.bind(this), - getPermission: this.getPermission.bind(this), - list: this.list.bind(this), - onRaised: this.onRaised.bind(this), - onClosed: this.onClosed.bind(this), - click: this.click.bind(this), - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearOld: this.clearOld.bind(this), - configure: this.configure.bind(this), - getConfiguration: this.getConfiguration.bind(this), - getFilter: this.getFilter.bind(this), - setFilter: this.setFilter.bind(this), - setState: this.setState.bind(this), - onConfigurationChanged: this.onConfigurationChanged.bind(this), - onActiveCountChanged: this.onActiveCountChanged.bind(this), - onCounterChanged: this.onActiveCountChanged.bind(this), - onStateChanged: this.onStateChanged.bind(this) - }; - return Object.freeze(api); - } - async getPermission() { - const queryResult = await this.bridge.send("notifications", operations$7.getPermission, undefined); - return queryResult.permission; - } - async requestPermission() { - const permissionResult = await this.bridge.send("notifications", operations$7.requestPermission, undefined); - return permissionResult.permissionGranted; - } - async raise(options) { - const settings = runDecoderWithIOError(glue42NotificationOptionsDecoder, options); - settings.showToast = typeof settings.showToast === "boolean" ? settings.showToast : true; - settings.showInPanel = typeof settings.showInPanel === "boolean" ? settings.showInPanel : true; - const permissionGranted = await this.requestPermission(); - if (!permissionGranted) { - return ioError.raiseError("Cannot raise the notification, because the user has declined the permission request"); - } - const id = nanoid$1(10); - const raiseResult = await this.bridge.send("notifications", operations$7.raiseNotification, { settings, id }); - const notification = this.buildNotificationFunc(raiseResult.settings, id); - this.notifications[id] = notification; - return notification; - } - async list() { - const bridgeResponse = await this.bridge.send("notifications", operations$7.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.notifications; - } - onRaised(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onRaised expects a callback of type function"); - } - return this.registry.add("notification-raised", callback); - } - onClosed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onClosed expects a callback of type function"); - } - return this.registry.add("notification-closed", callback); - } - async click(id, action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - if (action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, action); - } - await this.bridge.send("notifications", operations$7.click, { id, action }, undefined, { includeOperationCheck: true }); - } - async clear(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - await this.bridge.send("notifications", operations$7.clear, { id }, undefined, { includeOperationCheck: true }); - } - async clearAll() { - await this.bridge.send("notifications", operations$7.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearOld() { - await this.bridge.send("notifications", operations$7.clearOld, undefined, undefined, { includeOperationCheck: true }); - } - async configure(config) { - const verifiedConfig = runDecoderWithIOError(notificationsConfigurationDecoder, config); - await this.bridge.send("notifications", operations$7.configure, { configuration: verifiedConfig }, undefined, { includeOperationCheck: true }); - } - async getConfiguration() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration; - } - async getActiveCount() { - try { - const response = await this.bridge.send("notifications", operations$7.getActiveCount, undefined, undefined, { includeOperationCheck: true }); - return response.count; - } - catch (error) { - console.warn("Failed to get accurate active notifications count", error); - return 0; - } - } - async getFilter() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration.sourceFilter; - } - async setFilter(filter) { - const verifiedFilter = runDecoderWithIOError(notificationFilterDecoder, filter); - await this.bridge.send("notifications", operations$7.configure, { configuration: { sourceFilter: verifiedFilter } }, undefined, { includeOperationCheck: true }); - return verifiedFilter; - } - async setState(id, state) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - runDecoderWithIOError(notificationStateDecoder, state); - await this.bridge.send("notifications", operations$7.setState, { id, state }, undefined, { includeOperationCheck: true }); - } - onConfigurationChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"); - } - setTimeout(() => callback(this.notificationsConfiguration), 0); - return this.registry.add("notifications-config-changed", callback); - } - onActiveCountChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"); - } - setTimeout(() => callback({ count: this.notificationsActiveCount }), 0); - return this.registry.add("notifications-active-count-changed", callback); - } - onStateChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"); - } - return this.registry.add("notification-state-changed", callback); - } - addOperationExecutors() { - operations$7.notificationShow.execute = this.handleNotificationShow.bind(this); - operations$7.notificationClick.execute = this.handleNotificationClick.bind(this); - operations$7.notificationRaised.execute = this.handleNotificationRaised.bind(this); - operations$7.notificationClosed.execute = this.handleNotificationClosed.bind(this); - operations$7.configurationChanged.execute = this.handleConfigurationChanged.bind(this); - operations$7.activeCountChange.execute = this.handleActiveCountChanged.bind(this); - operations$7.stateChange.execute = this.handleNotificationStateChanged.bind(this); - operations$7.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$7); - } - async handleConfigurationChanged(data) { - this.notificationsConfiguration = data.configuration; - this.registry.execute("notifications-config-changed", data.configuration); - } - async handleActiveCountChanged(data) { - this.notificationsActiveCount = data.count; - this.registry.execute("notifications-active-count-changed", data); - } - async handleNotificationStateChanged(data) { - this.registry.execute("notification-state-changed", { id: data.id }, data.state); - } - async handleNotificationShow(data) { - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onshow) { - notification.onshow(); - } - } - async handleNotificationClick(data) { - if (!data.action && this.notificationsSettings?.defaultClick) { - this.notificationsSettings.defaultClick(this.coreGlue, data.definition); - } - if (data.action && this.notificationsSettings?.actionClicks?.some((actionDef) => actionDef.action === data.action)) { - const foundHandler = this.notificationsSettings?.actionClicks?.find((actionDef) => actionDef.action === data.action); - foundHandler.handler(this.coreGlue, data.definition); - } - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onclick) { - notification.onclick(); - delete this.notifications[data.id]; - } - } - async handleNotificationRaised(data) { - this.registry.execute("notification-raised", data.notification); - } - async handleNotificationClosed(data) { - this.registry.execute("notification-closed", data); - } - } - - const operations$6 = { - getIntents: { name: "getIntents", resultDecoder: wrappedIntentsDecoder }, - findIntent: { name: "findIntent", dataDecoder: wrappedIntentFilterDecoder, resultDecoder: wrappedIntentsDecoder }, - raise: { name: "raise", dataDecoder: raiseIntentRequestDecoder, resultDecoder: intentResultDecoder }, - filterHandlers: { name: "filterHandlers", dataDecoder: filterHandlersWithResolverConfigDecoder, resultDecoder: filterHandlersResultDecoder }, - getIntentsByHandler: { name: "getIntentsByHandler", dataDecoder: intentHandlerDecoder, resultDecoder: getIntentsResultDecoder } - }; - - const GLUE42_FDC3_INTENTS_METHOD_PREFIX = "Tick42.FDC3.Intents."; - const INTENTS_RESOLVER_APP_NAME = "intentsResolver"; - const DEFAULT_RESOLVER_RESPONSE_TIMEOUT = 60 * 1000; - const ADDITIONAL_BRIDGE_OPERATION_TIMEOUT = 30 * 1000; - const DEFAULT_PICK_HANDLER_BY_TIMEOUT = 90 * 1000; - - class IntentsController { - bridge; - logger; - interop; - appManagerController; - windowsController; - myIntents = new Set(); - prefsController; - uiController; - useIntentsResolverUI = true; - intentsResolverAppName; - intentResolverResponseTimeout = DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - unregisterIntentPromises = []; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("intents.controller.web"); - this.logger.trace("starting the web intents controller"); - this.bridge = ioc.bridge; - this.interop = coreGlue.interop; - this.appManagerController = ioc.appManagerController; - this.windowsController = ioc.windowsController; - this.prefsController = ioc.prefsController; - this.uiController = ioc.uiController; - this.checkIfIntentsResolverIsEnabled(ioc.config); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"); - coreGlue.intents = api; - } - handlePlatformShutdown() { - this.myIntents = new Set(); - this.unregisterIntentPromises = []; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(intentsOperationTypesDecoder, args.operation); - const operation = operations$6[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - all: this.all.bind(this), - addIntentListener: this.addIntentListener.bind(this), - register: this.register.bind(this), - find: this.find.bind(this), - filterHandlers: this.filterHandlers.bind(this), - getIntents: this.getIntentsByHandler.bind(this), - clearSavedHandlers: this.clearSavedHandlers.bind(this), - onHandlerAdded: this.onHandlerAdded.bind(this), - onHandlerRemoved: this.onHandlerRemoved.bind(this) - }; - return api; - } - async raise(request) { - const validatedIntentRequest = runDecoderWithIOError(raiseRequestDecoder, request); - const intentRequest = typeof validatedIntentRequest === "string" - ? { intent: validatedIntentRequest } - : validatedIntentRequest; - await Promise.all(this.unregisterIntentPromises); - if (intentRequest.clearSavedHandler) { - this.logger.trace(`User removes saved handler for intent ${intentRequest.intent}`); - await this.removeRememberedHandler(intentRequest.intent); - } - const resultFromRememberedHandler = await this.checkHandleRaiseWithRememberedHandler(intentRequest); - if (resultFromRememberedHandler) { - return resultFromRememberedHandler; - } - const requestWithResolverInfo = { - intentRequest, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - const methodResponseTimeoutMs = intentRequest.waitUserResponseIndefinitely - ? MAX_SET_TIMEOUT_DELAY - : (intentRequest.timeout || this.intentResolverResponseTimeout) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(request)} and method response timeout of ${methodResponseTimeoutMs}ms`); - const response = await this.bridge.send("intents", operations$6.raise, requestWithResolverInfo, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }); - this.logger.trace(`Raise operation completed with response: ${JSON.stringify(response)}`); - return response; - } - getLegacyResolverConfigByRequest(filter) { - if (filter.handlerFilter) { - return { - enabled: typeof filter.handlerFilter?.openResolver === "boolean" ? filter.handlerFilter?.openResolver : this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout: filter.handlerFilter?.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT - }; - } - const waitResponseTimeout = filter.intentRequest?.waitUserResponseIndefinitely ? MAX_SET_TIMEOUT_DELAY : this.intentResolverResponseTimeout; - return { - enabled: this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout - }; - } - getEmbeddedResolverConfig() { - return { - enabled: this.uiController.isIntentResolverEnabled(), - initialCaller: { instanceId: this.interop.instance.instance } - }; - } - async all() { - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.getIntents, undefined); - return result.intents; - } - addIntentListener(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - let registerPromise; - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - const result = { - unsubscribe: () => { - this.myIntents.delete(intentName); - registerPromise - .then(() => this.interop.unregister(methodName)) - .catch((err) => this.logger.trace(`Unregistration of a method with name ${methodName} failed with reason: ${err}`)); - } - }; - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - registerPromise = this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - return handler(rest); - } - }); - registerPromise.catch(err => { - this.myIntents.delete(intentName); - this.logger.warn(`Registration of a method with name ${methodName} failed with reason: ${err}`); - }); - return result; - } - async register(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - await Promise.all(this.unregisterIntentPromises); - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - try { - await this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - const caller = this.interop.servers().find((server) => server.instance === _initialCallerId); - return handler(rest, caller); - } - }); - } - catch (err) { - this.myIntents.delete(intentName); - return ioError.raiseError(`Registration of a method with name ${methodName} failed with reason: ${JSON.stringify(err)}`); - } - return { - unsubscribe: () => this.unsubscribeIntent(intentName) - }; - } - async find(intentFilter) { - let data = undefined; - if (typeof intentFilter !== "undefined") { - const intentFilterObj = runDecoderWithIOError(findFilterDecoder, intentFilter); - if (typeof intentFilterObj === "string") { - data = { - filter: { - name: intentFilterObj - } - }; - } - else if (typeof intentFilterObj === "object") { - data = { - filter: intentFilterObj - }; - } - } - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.findIntent, data); - return result.intents; - } - onHandlerAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!"); - } - const unOnAppAdded = this.subscribeForAppEvent("onAppAdded", callback); - const unOnServerMethodAdded = this.subscribeForServerMethodEvent("serverMethodAdded", callback); - return () => { - unOnAppAdded(); - unOnServerMethodAdded(); - }; - } - onHandlerRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!"); - } - const unOnAppRemoved = this.subscribeForAppEvent("onAppRemoved", callback); - const unOnServerMethodRemoved = this.subscribeForServerMethodEvent("serverMethodRemoved", callback); - return () => { - unOnAppRemoved(); - unOnServerMethodRemoved(); - }; - } - subscribeForAppEvent(method, callback) { - return this.appManagerController[method]((app) => { - const appIntents = app.userProperties.intents; - if (!appIntents?.length) { - return; - } - appIntents.forEach((intent) => { - const handler = this.buildIntentHandlerFromApp(app, intent); - callback(handler, intent.name); - }); - }); - } - subscribeForServerMethodEvent(eventMethod, callback) { - return this.interop[eventMethod](async ({ server, method }) => { - if (!method.name.startsWith(GLUE42_FDC3_INTENTS_METHOD_PREFIX)) { - return; - } - const intentName = method.name.replace(GLUE42_FDC3_INTENTS_METHOD_PREFIX, ""); - const handler = await this.buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName); - callback(handler, intentName); - }); - } - buildIntentHandlerFromApp(app, intent) { - const handler = { - applicationName: app.name, - type: "app", - applicationDescription: app.caption, - applicationIcon: app.icon, - applicationTitle: app.title, - contextTypes: intent.contexts, - displayName: intent.displayName, - resultType: intent.resultType, - customConfig: intent.customConfig - }; - return handler; - } - async buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName) { - const info = method.flags.intent; - const app = this.appManagerController.getApplication(server.application || server.applicationName); - let title; - if (eventMethod === "serverMethodAdded" && server.windowId) { - title = await (this.windowsController.findById(server.windowId))?.getTitle(); - } - const appIntent = app?.userProperties?.intents?.find((intent) => intent.name === intentName); - const handler = { - applicationName: server.application || server.applicationName || "", - instanceId: server.windowId || server.instance, - type: "instance", - applicationIcon: info?.icon || app?.icon, - applicationTitle: app?.title, - applicationDescription: info?.description || app?.caption, - contextTypes: info?.contextTypes || appIntent?.contexts, - instanceTitle: title, - displayName: info?.displayName || appIntent?.displayName, - resultType: info?.resultType || appIntent?.resultType, - customConfig: info?.customConfig - }; - return handler; - } - async clearSavedHandlers() { - this.logger.trace("Removing all saved handlers from prefs storage for current app"); - await this.prefsController.update({ intents: undefined }); - } - checkIfIntentsResolverIsEnabled(options) { - this.useIntentsResolverUI = typeof options.intents?.enableIntentsResolverUI === "boolean" - ? options.intents.enableIntentsResolverUI - : true; - this.intentsResolverAppName = options.intents?.intentsResolverAppName ?? INTENTS_RESOLVER_APP_NAME; - this.intentResolverResponseTimeout = options.intents?.methodResponseTimeoutMs ?? DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - } - clearUnregistrationPromise(promiseToRemove) { - this.unregisterIntentPromises = this.unregisterIntentPromises.filter(promise => promise !== promiseToRemove); - } - buildInteropMethodName(intentName) { - return `${GLUE42_FDC3_INTENTS_METHOD_PREFIX}${intentName}`; - } - unsubscribeIntent(intentName) { - this.myIntents.delete(intentName); - const methodName = this.buildInteropMethodName(intentName); - const unregisterPromise = this.interop.unregister(methodName); - this.unregisterIntentPromises.push(unregisterPromise); - unregisterPromise - .then(() => { - this.clearUnregistrationPromise(unregisterPromise); - }) - .catch((err) => { - this.logger.error(`Unregistration of a method with name ${methodName} failed with reason: ${err}`); - this.clearUnregistrationPromise(unregisterPromise); - }); - } - async filterHandlers(handlerFilter) { - runDecoderWithIOError(handlerFilterDecoder, handlerFilter); - this.checkIfAtLeastOneFilterIsPresent(handlerFilter); - const embeddedResolverConfig = this.getEmbeddedResolverConfig(); - if (handlerFilter.openResolver && !this.useIntentsResolverUI && !embeddedResolverConfig.enabled) { - return ioError.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled"); - } - const methodResponseTimeoutMs = (handlerFilter.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - const filterHandlersRequestWithResolverConfig = { - filterHandlersRequest: handlerFilter, - resolverConfig: this.getLegacyResolverConfigByRequest({ handlerFilter }), - embeddedResolverConfig - }; - const result = await this.bridge.send("intents", operations$6.filterHandlers, filterHandlersRequestWithResolverConfig, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }, { includeOperationCheck: true }); - return result; - } - checkIfAtLeastOneFilterIsPresent(filter) { - const errorMsg = "Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'"; - if (!Object.keys(filter).length) { - return ioError.raiseError(errorMsg); - } - const { intent, resultType, contextTypes, applicationNames } = filter; - const existingValidContextTypes = contextTypes?.length; - const existingValidApplicationNames = applicationNames?.length; - if (!intent && !resultType && !existingValidContextTypes && !existingValidApplicationNames) { - return ioError.raiseError(errorMsg); - } - } - async getIntentsByHandler(handler) { - runDecoderWithIOError(intentHandlerDecoder, handler); - const result = await this.bridge.send("intents", operations$6.getIntentsByHandler, handler, undefined, { includeOperationCheck: true }); - return result; - } - async removeRememberedHandler(intentName) { - this.logger.trace(`Removing saved handler from prefs storage for intent ${intentName}`); - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const intentPrefs = prefs.data?.intents; - if (!intentPrefs) { - this.logger.trace("No app prefs found for current app"); - return; - } - delete intentPrefs[intentName]; - const updatedPrefs = { - ...prefs.data, - intents: intentPrefs - }; - try { - await this.prefsController.update(updatedPrefs); - } - catch (error) { - this.logger.warn(`prefs.update() threw the following error: ${error}`); - return; - } - this.logger.trace(`Handler saved choice for intent ${intentName} removed successfully`); - } - async checkForRememberedHandler(intentRequest) { - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const prefsForIntent = prefs.data?.intents?.[intentRequest.intent]; - return prefsForIntent?.handler; - } - async checkHandleRaiseWithRememberedHandler(intentRequest) { - if (intentRequest.target) { - return; - } - const rememberedHandler = await this.checkForRememberedHandler(intentRequest); - if (!rememberedHandler) { - return; - } - const operationData = { - intentRequest: { - ...intentRequest, - target: { - app: rememberedHandler.applicationName, - instance: rememberedHandler.instanceId - } - }, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - try { - const response = await this.bridge.send("intents", operations$6.raise, operationData); - return response; - } - catch (error) { - this.logger.trace(`Could not raise intent to remembered handler. Reason: ${error}. Removing it from Prefs store`); - await this.removeRememberedHandler(intentRequest.intent); - } - } - } - - const operations$5 = { - appHello: { name: "appHello", dataDecoder: channelsAppHelloDataDecoder, resultDecoder: channelsAppHelloSuccessDecoder }, - addChannel: { name: "addChannel", dataDecoder: channelDefinitionDecoder }, - removeChannel: { name: "removeChannel", dataDecoder: removeChannelDataDecoder }, - getMyChannel: { name: "getMyChannel", resultDecoder: getMyChanelResultDecoder }, - getWindowIdsOnChannel: { name: "getWindowIdsOnChannel", dataDecoder: getWindowIdsOnChannelDataDecoder, resultDecoder: getWindowIdsOnChannelResultDecoder }, - getWindowIdsWithChannels: { name: "getWindowIdsWithChannels", dataDecoder: wrappedWindowWithChannelFilterDecoder, resultDecoder: getWindowIdsWithChannelsResultDecoder }, - joinChannel: { name: "joinChannel", dataDecoder: joinChannelDataDecoder }, - restrict: { name: "restrict", dataDecoder: restrictionConfigDataDecoder }, - getRestrictions: { name: "getRestrictions", dataDecoder: getRestrictionsDataDecoder, resultDecoder: restrictionsDecoder }, - restrictAll: { name: "restrictAll", dataDecoder: restrictAllDataDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - leaveChannel: { name: "leaveChannel", dataDecoder: leaveChannelDataDecoder }, - requestChannelSelector: { name: "requestChannelSelector", dataDecoder: requestChannelSelectorConfigDecoder }, - getMode: { name: "getMode", resultDecoder: getChannelsModeDecoder }, - operationCheck: { name: "operationCheck" }, - }; - - const DEFAULT_MODE = "single"; - const CHANNELS_PREFIX = "___channel___"; - const SUBS_KEY = "subs"; - const CHANGED_KEY = "changed"; - const CHANNELS_CHANGED = "channels_changed"; - const STORAGE_NAMESPACE = "io_connect_channels"; - const DEFAULT_STORAGE_MODE = "inMemory"; - - class ChannelsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - contexts; - interop; - bridge; - windowsController; - _mode; - myWindowId; - storage; - handlePlatformShutdown() { - this.registry.clear(); - this.storage.clear(); - } - addOperationsExecutors() { - operations$5.getMyChannel.execute = this.handleGetMyChannel.bind(this); - operations$5.joinChannel.execute = this.handleJoinChannel.bind(this); - operations$5.leaveChannel.execute = this.handleLeaveChannel.bind(this); - operations$5.restrict.execute = this.handleRestrict.bind(this); - operations$5.getRestrictions.execute = ({ windowId }) => this.getRestrictions(windowId); - operations$5.restrictAll.execute = this.handleRestrictAll.bind(this); - operations$5.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$5); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("channels.controller.web"); - this.logger.trace("starting the web channels controller"); - this.contexts = coreGlue.contexts; - this.interop = coreGlue.interop; - this.addOperationsExecutors(); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.storage = ioc.channelsStorage; - this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"); - this.myWindowId = this.windowsController.my().id ?? this.interop.instance.instance; - await this.initialize(); - const api = this.toApi(); - coreGlue.channels = api; - } - async postStart(io, ioc) { - try { - await this.requestChannelSelector(io.appManager.myInstance); - } - catch (error) { - this.logger.warn(`Failed to display channel selector: ${extractErrorMsg(error)}`); - } - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(channelsOperationTypesDecoder, args.operation); - const operation = operations$5[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async list() { - const channelNames = this.getAllChannelNames(); - const channelContexts = await Promise.all(channelNames.map((channelName) => this.get(channelName))); - return channelContexts; - } - my() { - return this.current(); - } - async handleGetMyChannel() { - const channel = this.my(); - return channel ? { channel } : {}; - } - async join(name, windowId) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const joinData = { channel: name, windowId: windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.joinChannel, joinData, undefined, { includeOperationCheck: true }); - } - handleJoinChannel({ channel }) { - if (this._mode === "single") { - return this.switchToChannel(channel); - } - return this.joinAdditionalChannel(channel); - } - onChanged(callback) { - return this.changed(callback); - } - async leave(config = {}) { - runDecoderWithIOError(leaveChannelsConfig, config); - if (config.channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.channel); - } - const leaveData = { channelName: config.channel, windowId: config.windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.leaveChannel, leaveData, undefined, { includeOperationCheck: true }); - } - async handleAppManagerInitialChannelId(channel) { - if (this.storage.mode === "inMemory") { - return; - } - if (this.storage.getSessionStorageData()) { - return; - } - return this.handleJoinChannel({ channel, windowId: this.myWindowId }); - } - async handleLeaveChannel({ channelName }) { - const channelNamesToLeave = channelName ? [channelName] : this.storage.channels; - channelNamesToLeave.forEach((name) => this.storage.invokeUnsubscribes(name)); - this.storage.channels = this.storage.channels.filter((channelName) => !channelNamesToLeave.includes(channelName)); - this.executeChangedEvents(); - await this.notifyChannelsChanged(); - } - toApi() { - const api = { - mode: this._mode, - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - publish: this.publish.bind(this), - all: this.all.bind(this), - list: this.list.bind(this), - get: this.get.bind(this), - getMyChannels: this.getMyChannels.bind(this), - myChannels: this.myChannels.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - join: this.join.bind(this), - leave: this.leave.bind(this), - current: this.current.bind(this), - my: this.my.bind(this), - changed: this.changed.bind(this), - onChanged: this.onChanged.bind(this), - add: this.add.bind(this), - remove: this.remove.bind(this), - getMy: this.getMy.bind(this), - getWindowsOnChannel: this.getWindowsOnChannel.bind(this), - getWindowsWithChannels: this.getWindowsWithChannels.bind(this), - restrict: this.restrict.bind(this), - getRestrictions: this.getRestrictions.bind(this), - restrictAll: this.restrictAll.bind(this), - clearChannelData: this.clearChannelData.bind(this), - setPath: this.setPath.bind(this), - setPaths: this.setPaths.bind(this) - }; - return Object.freeze(api); - } - createContextName(channelName) { - return `${CHANNELS_PREFIX}${channelName}`; - } - getAllChannelNames() { - const contextNames = this.contexts.all(); - const channelContextNames = contextNames.filter((contextName) => contextName.startsWith(CHANNELS_PREFIX)); - const channelNames = channelContextNames.map((channelContextName) => channelContextName.replace(CHANNELS_PREFIX, "")); - return channelNames; - } - async joinAdditionalChannel(name) { - if (this.storage.channels.includes(name)) { - return; - } - this.storage.channels = [...this.storage.channels, name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - async switchToChannel(name) { - const currentChannel = this.storage.channels[0]; - if (name === currentChannel) { - return; - } - this.storage.invokeUnsubscribes(currentChannel); - this.storage.channels = [name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - executeChangedEvents(name) { - this.registry.execute(CHANGED_KEY, name); - this.registry.execute(CHANNELS_CHANGED, this.storage.channels); - } - async notifyChannelsChanged() { - const windowId = this.windowsController.my().id; - if (!windowId) { - return; - } - try { - await this.bridge.send("channels", operations$5.notifyChannelsChanged, { channelNames: this.storage.channels, windowId }, undefined, { includeOperationCheck: true }); - } - catch (error) { - this.logger.warn(`Failed to notify channel changed: ${extractErrorMsg(error)}`); - } - } - async updateData(name, data) { - const contextName = this.createContextName(name); - const fdc3Type = this.getFDC3Type(data); - if (this.contexts.setPathSupported) { - const pathValues = Object.keys(data).map((key) => { - return { - path: `data.${key}`, - value: data[key] - }; - }); - if (fdc3Type) { - pathValues.push({ path: latestFDC3Type, value: fdc3Type }); - } - await this.contexts.setPaths(contextName, pathValues); - } - else { - if (fdc3Type) { - data[latestFDC3Type] = fdc3Type; - } - await this.contexts.update(contextName, { data }); - } - } - getFDC3Type(data) { - const fdc3PropsArr = Object.keys(data).filter((key) => key.indexOf("fdc3_") === 0); - if (fdc3PropsArr.length === 0) { - return; - } - if (fdc3PropsArr.length > 1) { - return ioError.raiseError("FDC3 does not support updating of multiple context keys"); - } - return fdc3PropsArr[0].split("_").slice(1).join("_"); - } - subscribe(callback, options) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels, because the provided callback is not a function!"); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const currentChannel = this.current(); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - if (currentChannel) { - this.replaySubscribe(wrappedCallback, currentChannel); - } - return this.registry.add(SUBS_KEY, wrappedCallback); - } - async subscribeFor(name, callback, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (typeof callback !== "function") { - return ioError.raiseError(`Cannot subscribe to channel ${name}, because the provided callback is not a function!`); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - wrappedCallback(context.data, context, delta, extraData?.updaterId); - }); - } - async publish(data, options) { - if (typeof data !== "object") { - return ioError.raiseError("Cannot publish to channel, because the provided data is not an object!"); - } - runDecoderWithIOError(publishOptionsDecoder, options); - if (typeof options === "object") { - return this.publishWithOptions(data, options); - } - if (typeof options === "string") { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options); - } - if (!options && this.storage.channels.length > 1) { - return this.publishOnMultipleChannels(data); - } - const channelName = typeof options === "string" ? options : this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - return this.updateData(channelName, data); - } - async all() { - const channelNames = this.getAllChannelNames(); - return channelNames; - } - async get(name, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const channelContext = await this.contexts.get(contextName); - if (options?.contextType) { - return this.getContextForFdc3Type(channelContext, options.contextType); - } - if (channelContext.latest_fdc3_type) { - return this.getContextWithFdc3Data(channelContext); - } - return channelContext; - } - async getMyChannels() { - return Promise.all(this.storage.channels.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.get(contextName); - })); - } - myChannels() { - return this.storage.channels; - } - getContextForFdc3Type(channelContext, searchedType) { - const encodedType = `fdc3_${searchedType.split(".").join("&")}`; - if (!channelContext.data[encodedType]) { - return { - name: channelContext.name, - meta: channelContext.meta, - data: {} - }; - } - const fdc3Context = { type: searchedType, ...channelContext.data[encodedType] }; - return { - name: channelContext.name, - meta: channelContext.meta, - data: { fdc3: fdc3Context } - }; - } - getContextWithFdc3Data(channelContext) { - const { latest_fdc3_type, ...rest } = channelContext; - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Context = { type: parsedType, ...rest.data[`fdc3_${latest_fdc3_type}`] }; - delete rest.data[`fdc3_${latest_fdc3_type}`]; - const context = { - name: channelContext.name, - meta: channelContext.meta, - data: { - ...rest.data, - fdc3: fdc3Context - } - }; - return context; - } - current() { - return this.storage.channels[0]; - } - changed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"); - } - return this.registry.add(CHANGED_KEY, callback); - } - async add(info) { - const channelContext = runDecoderWithIOError(channelDefinitionDecoder, info); - const channelWithSuchNameExists = this.getAllChannelNames().includes(channelContext.name); - if (channelWithSuchNameExists) { - return ioError.raiseError("There's an already existing channel with such name"); - } - await this.bridge.send("channels", operations$5.addChannel, channelContext); - return { - name: channelContext.name, - meta: channelContext.meta, - data: channelContext.data || {} - }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - const channelWithSuchNameExists = this.getAllChannelNames().includes(name); - if (!channelWithSuchNameExists) { - return ioError.raiseError("There's no channel with such name"); - } - await this.bridge.send("channels", operations$5.removeChannel, { name }, undefined, { includeOperationCheck: true }); - } - replaySubscribe = (callback, channelId) => { - this.get(channelId) - .then((channelContext) => { - if (!channelContext) { - return undefined; - } - const contextName = this.createContextName(channelContext.name); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - callback(context.data, context, delta, extraData?.updaterId); - }); - }) - .then((un) => un?.()) - .catch(err => this.logger.trace(err)); - }; - async getMy(options) { - if (!this.storage.channels.length) { - return; - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - return this.get(this.storage.channels[this.storage.channels.length - 1], options); - } - async getWindowsOnChannel(channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), channel); - const { windowIds } = await this.bridge.send("channels", operations$5.getWindowIdsOnChannel, { channel }, undefined, { includeOperationCheck: true }); - const result = windowIds.reduce((windows, windowId) => { - const window = this.windowsController.findById(windowId); - return window ? [...windows, window] : windows; - }, []); - return result; - } - async getWindowsWithChannels(filter) { - const operationData = filter !== undefined - ? { filter: runDecoderWithIOError(windowWithChannelFilterDecoder, filter) } - : {}; - const { windowIdsWithChannels } = await this.bridge.send("channels", operations$5.getWindowIdsWithChannels, operationData, undefined, { includeOperationCheck: true }); - const result = windowIdsWithChannels.reduce((windowsWithChannels, { application, channel, windowId }) => { - const window = this.windowsController.findById(windowId); - return window ? [...windowsWithChannels, { application, channel, window }] : windowsWithChannels; - }, []); - return result; - } - async clearChannelData(name) { - const paths = [ - { path: "data", value: {} }, - { path: "latest_fdc3_type", value: null }, - ]; - await this.handleSetPaths("clearChannelData", paths, name); - } - async restrict(config) { - runDecoderWithIOError(channelRestrictionsDecoder, config); - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.name); - const configData = { - config: { - ...config, - windowId: config.windowId ?? this.myWindowId - } - }; - await this.bridge.send("channels", operations$5.restrict, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrict({ config }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateRestriction(config); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateRestriction(config); - const isForCurrentChannel = config.name === currentChannel.name; - if (!isForCurrentChannel || prevReadAllowed || !config.read) { - return; - } - this.replaySubscribeCallback(config.name); - } - updateRestriction(config) { - const exists = this.storage.restrictions.some((r) => r.name === config.name); - this.storage.restrictions = exists - ? this.storage.restrictions.map((restriction) => restriction.name === config.name ? config : restriction) - : this.storage.restrictions.concat(config); - } - updateAllRestrictions(config) { - const allChannelNames = this.getAllChannelNames(); - this.storage.restrictions = allChannelNames.map((name) => ({ name, ...config })); - } - async getRestrictions(windowId) { - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const forAnotherClient = windowId && windowId !== this.interop.instance.instance; - if (windowId && forAnotherClient) { - return this.bridge.send("channels", operations$5.getRestrictions, { windowId }, undefined, { includeOperationCheck: true }); - } - return { channels: this.storage.restrictions }; - } - async restrictAll(restrictions) { - runDecoderWithIOError(restrictionsConfigDecoder, restrictions); - const configData = { - restrictions: { - ...restrictions, - windowId: restrictions.windowId ?? this.myWindowId - } - }; - return this.bridge.send("channels", operations$5.restrictAll, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrictAll({ restrictions }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateAllRestrictions(restrictions); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateAllRestrictions(restrictions); - if (prevReadAllowed || !restrictions.read) { - return; - } - this.replaySubscribeCallback(currentChannel.name); - } - async setPath(path, name) { - const validatedPath = runDecoderWithIOError(pathValueDecoder, path); - const paths = [{ path: `data.${validatedPath.path}`, value: validatedPath.value }]; - await this.handleSetPaths("setPath", paths, name); - } - async setPaths(paths, name) { - const validatedPaths = runDecoderWithIOError(pathsValueDecoder, paths); - const dataPaths = validatedPaths.map(({ path, value }) => ({ path: `data.${path}`, value })); - await this.handleSetPaths("setPaths", dataPaths, name); - } - async handleSetPaths(operation, paths, name) { - const channelNamesToUpdate = name ? [name] : this.storage.channels; - if (!channelNamesToUpdate.length) { - return ioError.raiseError(`Cannot complete ${operation} operation, because channel is not specified. Either join one or pass a channel name as second argument!`); - } - this.validateChannelNames(channelNamesToUpdate); - const { allowed, forbidden } = this.groupChannelsByPermission("write", channelNamesToUpdate); - if (channelNamesToUpdate.length === forbidden.length) { - return ioError.raiseError(`Cannot complete ${operation} operation due to write restrictions to the following channels: ${channelNamesToUpdate.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Cannot set paths on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} due to write restrictions`); - } - await Promise.all(allowed.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.setPaths(contextName, paths); - })); - } - validateChannelNames(names) { - const allChannelNames = this.getAllChannelNames(); - names.forEach((name) => runDecoderWithIOError(channelNameDecoder(allChannelNames), name)); - } - groupChannelsByPermission(action, channelNames) { - return channelNames.reduce((byFar, channelName) => { - const isAllowed = this.isAllowedByRestrictions(channelName, action); - if (isAllowed) { - byFar.allowed.push(channelName); - } - else { - byFar.forbidden.push(channelName); - } - return byFar; - }, { allowed: [], forbidden: [] }); - } - isAllowedByRestrictions(channelName, action) { - const restriction = this.storage.restrictions.find((restriction) => restriction.name === channelName); - return restriction ? restriction[action] : true; - } - replaySubscribeCallback(channelName) { - const contextName = this.createContextName(channelName); - this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }).then((unsub) => { - if (unsub && typeof unsub === "function") { - unsub(); - } - }).catch(err => this.logger.error(err)); - } - async publishWithOptions(data, options) { - if (options.name) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options.name); - } - const publishOnMultipleChannels = options.name ? false : this.storage.channels.length > 1; - if (publishOnMultipleChannels) { - return this.publishOnMultipleChannels(data, options.fdc3); - } - const channelName = options.name || this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - if (!options.fdc3) { - return this.updateData(channelName, data); - } - return this.publishFdc3Data(channelName, data); - } - async publishOnMultipleChannels(data, isFdc3) { - const { allowed, forbidden } = this.groupChannelsByPermission("write", this.storage.channels); - if (this.storage.channels.length === forbidden.length) { - return ioError.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Data on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} won't be published due to write restrictions`); - } - const publishMethod = isFdc3 ? this.publishFdc3Data.bind(this) : this.updateData.bind(this); - await Promise.all(allowed.map((channelName) => publishMethod(channelName, data))); - } - async publishFdc3Data(channelName, data) { - runDecoderWithIOError(fdc3ContextDecoder, data); - const { type, ...rest } = data; - const parsedType = type.split(".").join("&"); - const fdc3DataToPublish = { [`fdc3_${parsedType}`]: rest }; - return this.updateData(channelName, fdc3DataToPublish); - } - getWrappedSubscribeCallback(callback) { - const wrappedCallback = (channelData, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const latestTypePropName = `fdc3_${latest_fdc3_type}`; - if (!latest_fdc3_type || (delta.data && !delta.data[latestTypePropName])) { - callback(channelData, context, updaterId); - return; - } - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Data = { type: parsedType, ...data[latestTypePropName] }; - const { [latestTypePropName]: latestFDC3Type, ...rest } = channelData; - callback({ ...rest, fdc3: fdc3Data }, context, updaterId); - }; - return wrappedCallback; - } - getWrappedSubscribeCallbackWithFdc3Type(callback, fdc3Type) { - const didReplay = { replayed: false }; - const wrappedCallback = (_, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const searchedType = `fdc3_${fdc3Type.split(".").join("&")}`; - if (!data[searchedType] || (delta.data && !delta.data[searchedType])) { - return; - } - if (didReplay.replayed) { - return this.parseDataAndInvokeSubscribeCallback({ latestFdc3TypeEncoded: latest_fdc3_type, searchedType: fdc3Type, callback, context, updaterId }); - } - const fdc3Data = { type: fdc3Type, ...data[searchedType] }; - callback({ fdc3: fdc3Data }, context, updaterId); - didReplay.replayed = true; - }; - return wrappedCallback; - } - parseDataAndInvokeSubscribeCallback(args) { - const { latestFdc3TypeEncoded, searchedType, callback, context, updaterId } = args; - const latestPublishedType = latestFdc3TypeEncoded.split("&").join("."); - if (latestPublishedType !== searchedType) { - return; - } - const fdc3Data = { type: searchedType, ...context.data[`fdc3_${latestFdc3TypeEncoded}`] }; - callback({ fdc3: fdc3Data }, context, updaterId); - } - async requestChannelSelector(myInstance) { - if (!myInstance) { - return; - } - const myApplicationData = myInstance.application; - const myAppDetails = myApplicationData.userProperties?.details; - if (!myAppDetails) { - return; - } - if (!myAppDetails?.channelSelector?.enabled) { - return; - } - const windowId = myInstance.id; - const requestChannelSelectorConfig = { windowId, channelsNames: this.storage.channels }; - await this.bridge.send("channels", operations$5.requestChannelSelector, requestChannelSelectorConfig, undefined, { includeOperationCheck: true }); - } - async getPlatformChannelsMode() { - try { - const result = await this.bridge.send("channels", operations$5.getMode, {}, undefined, { includeOperationCheck: true }); - return result.mode; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - return DEFAULT_MODE; - } - } - onChannelsChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"); - } - return this.registry.add(CHANNELS_CHANGED, callback); - } - async initialize() { - const isAppHelloSupported = await this.checkIfAppHelloSupported(); - if (!isAppHelloSupported) { - return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions"); - } - const { success, error } = await this.sendAppHello(); - if (error) { - return this.handleAppHelloFailure(error); - } - this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(success)}`); - const { mode, channels, restrictions } = success; - this.storage.mode = "inMemory"; - this._mode = mode; - this.storage.channels = channels; - this.storage.restrictions = restrictions; - } - async handleAppHelloFailure(errorMsg) { - this.logger.trace(errorMsg); - this.storage.mode = "sessionStorage"; - this._mode = await this.getPlatformChannelsMode(); - } - async sendAppHello() { - try { - const result = await this.bridge.send("channels", operations$5.appHello, { windowId: this.myWindowId }, undefined, { includeOperationCheck: true }); - return { success: result, error: undefined }; - } - catch (error) { - return { error: `Failed to get initial state from platform. Error: ${extractErrorMsg(error)}`, success: undefined }; - } - } - async checkIfAppHelloSupported() { - try { - const { isSupported } = await this.bridge.send("channels", operations$5.operationCheck, { operation: operations$5.appHello.name }, undefined, { includeOperationCheck: true }); - return isSupported; - } - catch (error) { - this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${extractErrorMsg(error)}`); - return false; - } - } - } - - const operations$4 = { - getEnvironment: { name: "getEnvironment", resultDecoder: anyDecoder }, - getBase: { name: "getBase", resultDecoder: anyDecoder }, - platformShutdown: { name: "platformShutdown" }, - isFdc3DataWrappingSupported: { name: "isFdc3DataWrappingSupported" }, - clientError: { name: "clientError", dataDecoder: clientErrorDataDecoder }, - systemHello: { name: "systemHello", resultDecoder: systemHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class SystemController { - supportedOperationsNames = []; - bridge; - ioc; - logger; - errorPort = errorChannel.port2; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("system.controller.web"); - this.logger.trace("starting the web system controller"); - this.bridge = ioc.bridge; - this.ioc = ioc; - this.addOperationsExecutors(); - let isClientErrorOperationSupported = false; - try { - const systemHelloSuccess = await this.bridge.send("system", operations$4.systemHello, undefined, undefined, { includeOperationCheck: true }); - isClientErrorOperationSupported = systemHelloSuccess.isClientErrorOperationSupported; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support some system operations."); - } - this.errorPort.onmessage = async (event) => { - if (!isClientErrorOperationSupported) { - return; - } - await this.bridge.send("system", operations$4.clientError, { message: event.data }, undefined, { includeOperationCheck: true }); - }; - await this.setEnvironment(); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(systemOperationTypesDecoder, args.operation); - const operation = operations$4[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async processPlatformShutdown() { - Object.values(this.ioc.controllers).forEach((controller) => controller.handlePlatformShutdown ? controller.handlePlatformShutdown() : null); - this.ioc.preferredConnectionController.stop(); - this.ioc.eventsDispatcher.stop(); - await this.bridge.stop(); - } - async setEnvironment() { - const environment = await this.bridge.send("system", operations$4.getEnvironment, undefined); - const base = await this.bridge.send("system", operations$4.getBase, undefined); - const globalNamespace = window.glue42core || window.iobrowser; - const globalNamespaceName = window.glue42core ? "glue42core" : "iobrowser"; - const globalObj = Object.assign({}, globalNamespace, base, { environment }); - window[globalNamespaceName] = globalObj; - } - addOperationsExecutors() { - operations$4.platformShutdown.execute = this.processPlatformShutdown.bind(this); - operations$4.isFdc3DataWrappingSupported.execute = this.handleIsFdc3DataWrappingSupported.bind(this); - operations$4.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$4); - } - async handleIsFdc3DataWrappingSupported() { - return { isSupported: true }; - } - } - - class Notification { - onclick = () => { }; - onshow = () => { }; - id; - title; - badge; - body; - data; - dir; - icon; - image; - lang; - renotify; - requireInteraction; - silent; - tag; - timestamp; - vibrate; - clickInterop; - actions; - focusPlatformOnDefaultClick; - severity; - showToast; - showInPanel; - state; - constructor(config, id) { - this.id = id; - this.badge = config.badge; - this.body = config.body; - this.data = config.data; - this.dir = config.dir; - this.icon = config.icon; - this.image = config.image; - this.lang = config.lang; - this.renotify = config.renotify; - this.requireInteraction = config.requireInteraction; - this.silent = config.silent; - this.tag = config.tag; - this.timestamp = config.timestamp; - this.vibrate = config.vibrate; - this.title = config.title; - this.clickInterop = config.clickInterop; - this.actions = config.actions; - this.focusPlatformOnDefaultClick = config.focusPlatformOnDefaultClick; - this.severity = config.severity; - this.showToast = config.showToast; - this.showInPanel = config.showInPanel; - this.state = config.state; - } - } - - oneOf$1(constant$2("clientHello")); - const extensionConfigDecoder = object$2({ - widget: object$2({ - inject: boolean$2() - }) - }); - - const operations$3 = { - clientHello: { name: "clientHello", resultDecoder: extensionConfigDecoder } - }; - - class ExtController { - windowId; - logger; - bridge; - eventsDispatcher; - channelsController; - config; - channels = []; - unsubFuncs = []; - contentCommands = { - widgetVisualizationPermission: { name: "widgetVisualizationPermission", handle: this.handleWidgetVisualizationPermission.bind(this) }, - changeChannel: { name: "changeChannel", handle: this.handleChangeChannel.bind(this) } - }; - handlePlatformShutdown() { - this.unsubFuncs.forEach((unsub) => unsub()); - this.channels = []; - this.unsubFuncs = []; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("extension.controller.web"); - this.windowId = ioc.publicWindowId; - this.logger.trace("starting the extension web controller"); - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.eventsDispatcher = ioc.eventsDispatcher; - try { - await this.registerWithPlatform(); - } - catch (error) { - return; - } - this.channels = await this.channelsController.list(); - const unsubDispatcher = this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)); - const unsubChannels = this.channelsController.onChanged((channel) => { - this.eventsDispatcher.sendContentMessage({ command: "channelChange", newChannel: channel }); - }); - this.unsubFuncs.push(unsubDispatcher); - this.unsubFuncs.push(unsubChannels); - } - async handleBridgeMessage(_) { - } - handleContentMessage(message) { - if (!message || typeof message.command !== "string") { - return; - } - const foundHandler = this.contentCommands[message.command]; - if (!foundHandler) { - return; - } - foundHandler.handle(message); - } - async registerWithPlatform() { - this.logger.trace("registering with the platform"); - this.config = await this.bridge.send("extension", operations$3.clientHello, { windowId: this.windowId }); - this.logger.trace("the platform responded to the hello message with a valid extension config"); - } - async handleWidgetVisualizationPermission() { - if (!this.config?.widget.inject) { - return this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: false }); - } - const currentChannel = this.channels.find((channel) => channel.name === this.channelsController.my()); - this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: true, channels: this.channels, currentChannel }); - } - async handleChangeChannel(message) { - if (message.name === "no-channel") { - await this.channelsController.leave(); - return; - } - await this.channelsController.join(message.name); - } - } - - class EventsDispatcher { - config; - glue; - registry = CallbackRegistryFactory$1(); - glue42EventName = "Glue42"; - _handleMessage; - _resolveWidgetReadyPromise; - _resolveModalsUIFactoryReadyPromise; - _resolveIntentResolverUIFactoryReadyPromise; - constructor(config) { - this.config = config; - } - events = { - notifyStarted: { name: "notifyStarted", handle: this.handleNotifyStarted.bind(this) }, - contentInc: { name: "contentInc", handle: this.handleContentInc.bind(this) }, - requestGlue: { name: "requestGlue", handle: this.handleRequestGlue.bind(this) }, - widgetFactoryReady: { name: "widgetFactoryReady", handle: this.handleWidgetReady.bind(this) }, - modalsUIFactoryReady: { name: "modalsUIFactoryReady", handle: this.handleModalsUIFactoryReady.bind(this) }, - intentResolverUIFactoryReady: { name: "intentResolverUIFactoryReady", handle: this.handleIntentResolverUIFactoryReady.bind(this) }, - }; - stop() { - window.removeEventListener(this.glue42EventName, this._handleMessage); - } - start(glue) { - this.glue = glue; - this.wireCustomEventListener(); - this.announceStarted(); - } - sendContentMessage(message) { - this.send("contentOut", "glue42core", message); - } - onContentMessage(callback) { - return this.registry.add("content-inc", callback); - } - async widgetReady() { - const widgetReadyPromise = new Promise((resolve) => { - this._resolveWidgetReadyPromise = resolve; - }); - this.requestWidgetReady(); - return widgetReadyPromise; - } - async modalsUIFactoryReady() { - const modalsUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveModalsUIFactoryReadyPromise = resolve; - }); - this.requestModalsUIFactoryReady(); - return modalsUIFactoryReadyPromise; - } - async intentResolverUIFactoryReady() { - const intentResolverUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveIntentResolverUIFactoryReadyPromise = resolve; - }); - this.requestIntentResolverUIFactoryReady(); - return intentResolverUIFactoryReadyPromise; - } - wireCustomEventListener() { - this._handleMessage = this.handleMessage.bind(this); - window.addEventListener(this.glue42EventName, this._handleMessage); - } - handleMessage(event) { - const data = event.detail; - const namespace = data?.glue42 ?? data?.glue42core; - if (!namespace) { - return; - } - const glue42Event = namespace.event; - const foundHandler = this.events[glue42Event]; - if (!foundHandler) { - return; - } - foundHandler.handle(namespace.message); - } - announceStarted() { - this.send("start", "glue42"); - } - handleRequestGlue() { - if (!this.config.exposeAPI) { - this.send("requestGlueResponse", "glue42", { error: "Will not give access to the underlying Glue API, because it was explicitly denied upon initialization." }); - return; - } - this.send("requestGlueResponse", "glue42", { glue: this.glue }); - } - handleNotifyStarted() { - this.announceStarted(); - } - handleContentInc(message) { - this.registry.execute("content-inc", message); - } - requestWidgetReady() { - this.send(REQUEST_WIDGET_READY, "glue42"); - } - handleWidgetReady() { - this._resolveWidgetReadyPromise?.(); - } - requestModalsUIFactoryReady() { - this.send(REQUEST_MODALS_UI_FACTORY_READY, "glue42"); - } - handleModalsUIFactoryReady() { - this._resolveModalsUIFactoryReadyPromise?.(); - } - requestIntentResolverUIFactoryReady() { - this.send(REQUEST_INTENT_RESOLVER_UI_FACTORY_READY, "glue42"); - } - handleIntentResolverUIFactoryReady() { - this._resolveIntentResolverUIFactoryReadyPromise?.(); - } - send(eventName, namespace, message) { - const payload = {}; - payload[namespace] = { event: eventName, message }; - const event = new CustomEvent(this.glue42EventName, { detail: payload }); - window.dispatchEvent(event); - } - } - - class PreferredConnectionController { - coreGlue; - transactionTimeout = 15000; - transactionLocks = {}; - webPlatformTransport; - webPlatformMessagesUnsubscribe; - reconnectCounter = 0; - logger; - constructor(coreGlue) { - this.coreGlue = coreGlue; - this.logger = this.coreGlue.logger.subLogger("web.preferred.connection.controller"); - } - stop() { - if (!this.webPlatformMessagesUnsubscribe) { - return; - } - this.webPlatformMessagesUnsubscribe(); - } - async start(coreConfig) { - if (coreConfig.isPlatformInternal) { - this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic."); - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - if (!isConnectedToPlatform) { - return ioError.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport."); - } - if (!this.coreGlue.connection.transport.isPreferredActivated) { - this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization."); - return; - } - this.webPlatformTransport = this.coreGlue.connection.transport; - this.webPlatformMessagesUnsubscribe = this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this)); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - handleWebPlatformMessage(msg) { - if (typeof msg === "string") { - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - const type = msg.type; - const args = msg.args; - const transactionId = msg.transactionId; - if (type === Glue42CoreMessageTypes.transportSwitchRequest.name) { - return this.handleTransportSwitchRequest(args, transactionId); - } - if (type === Glue42CoreMessageTypes.platformUnload.name && !isConnectedToPlatform) { - return this.handlePlatformUnload(); - } - if (type === Glue42CoreMessageTypes.getCurrentTransportResponse.name) { - return this.handleGetCurrentTransportResponse(args, transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredLogic.name) { - return this.handleCheckPreferredLogic(transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredConnection.name) { - return this.handleCheckPreferredConnection(args, transactionId); - } - } - async reEstablishPlatformPort() { - try { - await this.webPlatformTransport.connect(); - } - catch (error) { - this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(error)}`); - --this.reconnectCounter; - if (this.reconnectCounter > 0) { - return this.reEstablishPlatformPort(); - } - this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform."); - } - this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."); - this.reconnectCounter = 0; - this.webPlatformTransport.close(); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - async checkSwitchTransport(config) { - const myCurrentTransportName = this.coreGlue.connection.transport.name(); - if (myCurrentTransportName === config.transportName) { - this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary"); - return; - } - this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${myCurrentTransportName}, but it should reconnect to ${JSON.stringify(config)}`); - const result = await this.coreGlue.connection.switchTransport(config); - this.setConnected(); - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - } - async getCurrentPlatformTransportState() { - this.logger.trace("Requesting the current transport state of the platform."); - const transaction = this.setTransaction(Glue42CoreMessageTypes.getCurrentTransport.name); - this.sendPlatformMessage(Glue42CoreMessageTypes.getCurrentTransport.name, transaction.id); - const transportState = await transaction.lock; - this.logger.trace(`The platform responded with transport state: ${JSON.stringify(transportState)}`); - return transportState; - } - setTransaction(operation) { - const transaction = {}; - const transactionId = nanoid$1(10); - const transactionLock = new Promise((resolve, reject) => { - let transactionLive = true; - transaction.lift = (args) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - resolve(args); - }; - transaction.fail = (reason) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - reject(reason); - }; - setTimeout(() => { - if (!transactionLive) { - return; - } - transactionLive = false; - this.logger.warn(`Transaction for operation: ${operation} timed out.`); - delete this.transactionLocks[transactionId]; - reject(`Transaction for operation: ${operation} timed out.`); - }, this.transactionTimeout); - }); - transaction.lock = transactionLock; - transaction.id = transactionId; - this.transactionLocks[transactionId] = transaction; - return transaction; - } - sendPlatformMessage(type, transactionId, args) { - this.logger.trace(`Sending a platform message of type: ${type}, id: ${transactionId} and args: ${JSON.stringify(args)}`); - this.webPlatformTransport.sendObject({ - glue42core: { type, args, transactionId } - }); - } - handleTransportSwitchRequest(args, transactionId) { - this.logger.trace(`Received a transport switch request with id: ${transactionId} and data: ${JSON.stringify(args)}`); - this.coreGlue.connection.switchTransport(args.switchSettings) - .then((result) => { - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - this.setConnected(); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: result.success }); - }) - .catch((error) => { - this.logger.error(error); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: false }); - }); - } - handlePlatformUnload() { - this.reconnectCounter = 5; - this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."); - this.reEstablishPlatformPort(); - } - handleGetCurrentTransportResponse(args, transactionId) { - this.logger.trace(`Got a current transport response from the platform with id: ${transactionId} and data: ${JSON.stringify(args)}`); - const transportState = args.transportState; - const transaction = this.transactionLocks[transactionId]; - transaction?.lift(transportState); - } - handleCheckPreferredLogic(transactionId) { - setTimeout(() => this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredLogicResponse.name, transactionId), 0); - } - handleCheckPreferredConnection(args, transactionId) { - const url = args.url; - this.logger.trace(`Testing the possible connection to: ${url}`); - this.checkPreferredConnection(url) - .then((result) => { - this.logger.trace(`The connection to ${url} is possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, result); - }) - .catch((error) => { - this.logger.trace(`The connection to ${url} is not possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, { error }); - }); - } - checkPreferredConnection(url) { - return new Promise((resolve) => { - const ws = new WebSocket(url); - ws.onerror = () => resolve({ live: false }); - ws.onopen = () => { - ws.close(); - resolve({ live: true }); - }; - }); - } - setConnected() { - this.webPlatformTransport.manualSetReadyState(); - } - } - - const operations$2 = { - getCurrent: { name: "getCurrent", resultDecoder: simpleThemeResponseDecoder }, - list: { name: "list", resultDecoder: allThemesResponseDecoder }, - select: { name: "select", dataDecoder: selectThemeConfigDecoder } - }; - - class ThemesController { - logger; - bridge; - registry = CallbackRegistryFactory$1(); - themesSubscription; - activeThemeSubs = 0; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("themes.controller.web"); - this.logger.trace("starting the web themes controller"); - this.bridge = ioc.bridge; - const api = this.toApi(); - coreGlue.themes = api; - this.logger.trace("themes are ready"); - } - handlePlatformShutdown() { - this.registry.clear(); - this.activeThemeSubs = 0; - this.themesSubscription?.close(); - delete this.themesSubscription; - } - async handleBridgeMessage() { - } - toApi() { - const api = { - getCurrent: this.getCurrent.bind(this), - list: this.list.bind(this), - select: this.select.bind(this), - onChanged: this.onChanged.bind(this) - }; - return Object.freeze(api); - } - async getCurrent() { - const bridgeResponse = await this.bridge.send("themes", operations$2.getCurrent, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.theme; - } - async list() { - const bridgeResponse = await this.bridge.send("themes", operations$2.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.themes; - } - async select(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("themes", operations$2.select, { name }, undefined, { includeOperationCheck: true }); - } - async onChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onChanged requires a callback of type function"); - } - const subReady = this.themesSubscription ? - Promise.resolve() : - this.configureThemeSubscription(); - await subReady; - ++this.activeThemeSubs; - const unsubFunc = this.registry.add("on-theme-change", callback); - return () => this.themeUnsub(unsubFunc); - } - async configureThemeSubscription() { - if (this.themesSubscription) { - return; - } - this.themesSubscription = await this.bridge.createNotificationsSteam(); - this.themesSubscription.onData((data) => { - const eventData = data.data; - const validation = simpleThemeResponseDecoder.run(eventData); - if (!validation.ok) { - this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`); - return; - } - const themeChanged = validation.result; - this.registry.execute("on-theme-change", themeChanged.theme); - }); - this.themesSubscription.onClosed(() => { - this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"); - this.registry.clear(); - this.activeThemeSubs = 0; - delete this.themesSubscription; - }); - } - themeUnsub(registryUnsub) { - registryUnsub(); - --this.activeThemeSubs; - if (this.activeThemeSubs) { - return; - } - this.themesSubscription?.close(); - delete this.themesSubscription; - } - } - - class ChannelsStorage { - sessionStorage = window.sessionStorage; - _mode = DEFAULT_STORAGE_MODE; - inMemoryChannels = []; - inMemoryRestrictions = []; - _unsubscribeDict = {}; - clear() { - this._mode = DEFAULT_STORAGE_MODE; - this.inMemoryChannels = []; - this.inMemoryRestrictions = []; - this._unsubscribeDict = {}; - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify([])); - } - get mode() { - return this._mode; - } - set mode(mode) { - this._mode = mode; - } - get channels() { - if (this.mode === "inMemory") { - return this.inMemoryChannels.slice(); - } - return this.getSessionStorageData()?.channels ?? []; - } - set channels(channels) { - if (this.mode === "inMemory") { - this.inMemoryChannels = channels; - } - this.setSessionStorageChannels(channels); - } - get restrictions() { - if (this.mode === "inMemory") { - return this.inMemoryRestrictions.slice(); - } - return this.getSessionStorageData()?.restrictions ?? []; - } - set restrictions(restrictions) { - if (this.mode === "inMemory") { - this.inMemoryRestrictions = restrictions; - } - this.setSessionStorageRestrictions(restrictions); - } - getSessionStorageData() { - return JSON.parse(this.sessionStorage.getItem(STORAGE_NAMESPACE) || "null"); - } - addUnsubscribe(channel, unsubscribe) { - this._unsubscribeDict[channel] = unsubscribe; - } - invokeUnsubscribes(channel) { - if (channel) { - this._unsubscribeDict[channel]?.(); - delete this._unsubscribeDict[channel]; - return; - } - Object.values(this._unsubscribeDict).forEach((unsub) => unsub()); - this._unsubscribeDict = {}; - } - setSessionStorageChannels(channels) { - const data = this.getSessionStorageData(); - if (data?.channels) { - data.channels = channels; - return this.setSessionStorageData(data); - } - const newData = { channels, restrictions: data?.restrictions ?? [] }; - return this.setSessionStorageData(newData); - } - setSessionStorageRestrictions(restrictions) { - const data = this.getSessionStorageData(); - if (data?.restrictions) { - data.restrictions = restrictions; - return this.setSessionStorageData(data); - } - const newData = { channels: data?.channels ?? [], restrictions }; - return this.setSessionStorageData(newData); - } - setSessionStorageData(data) { - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify(data)); - } - } - - const operations$1 = { - clear: { name: "clear", dataDecoder: basePrefsConfigDecoder }, - clearAll: { name: "clearAll" }, - get: { name: "get", dataDecoder: basePrefsConfigDecoder, resultDecoder: getPrefsResultDecoder }, - getAll: { name: "getAll", resultDecoder: getAllPrefsResultDecoder }, - set: { name: "set", dataDecoder: changePrefsDataDecoder }, - update: { name: "update", dataDecoder: changePrefsDataDecoder }, - prefsChanged: { name: "prefsChanged", dataDecoder: getPrefsResultDecoder }, - prefsHello: { name: "prefsHello", resultDecoder: prefsHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" }, - registerSubscriber: { name: "registerSubscriber", dataDecoder: subscriberRegisterConfigDecoder }, - }; - - class PrefsController { - supportedOperationsNames = []; - bridge; - config; - logger; - appManagerController; - platformAppName; - registry = CallbackRegistryFactory$1(); - validNonExistentApps; - signaledSubscription = false; - interopId; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("prefs.controller.web"); - this.logger.trace("starting the web prefs controller"); - this.addOperationsExecutors(); - this.interopId = coreGlue.interop.instance.instance; - this.bridge = ioc.bridge; - this.config = ioc.config; - this.appManagerController = ioc.appManagerController; - try { - const prefsHelloSuccess = await this.bridge.send("prefs", operations$1.prefsHello, undefined, undefined, { includeOperationCheck: true }); - this.platformAppName = prefsHelloSuccess.platform.app; - this.validNonExistentApps = prefsHelloSuccess.validNonExistentApps ?? []; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support Prefs API."); - return; - } - this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning"); - const api = this.toApi(); - coreGlue.prefs = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(prefsOperationTypesDecoder, args.operation); - const operation = operations$1[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async get(app) { - const verifiedApp = app === undefined || app === null ? this.getMyAppName() : runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const { prefs } = await this.bridge.send("prefs", operations$1.get, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - return prefs; - } - async update(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.updateFor(app, data); - } - addOperationsExecutors() { - operations$1.prefsChanged.execute = this.handleOnChanged.bind(this); - operations$1.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$1); - } - toApi() { - const api = { - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearFor: this.clearFor.bind(this), - get: this.get.bind(this), - getAll: this.getAll.bind(this), - set: this.set.bind(this), - setFor: this.setFor.bind(this), - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - update: this.update.bind(this), - updateFor: this.updateFor.bind(this), - }; - return api; - } - async clear() { - const app = this.getMyAppName(); - await this.clearFor(app); - } - async clearAll() { - await this.bridge.send("prefs", operations$1.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearFor(app) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - await this.bridge.send("prefs", operations$1.clear, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - } - async getAll() { - const result = await this.bridge.send("prefs", operations$1.getAll, undefined, undefined, { includeOperationCheck: true }); - return result; - } - async set(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.setFor(app, data); - } - async setFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.set, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - subscribe(callback) { - const app = this.getMyAppName(); - return this.subscribeFor(app, callback); - } - subscribeFor(app, callback) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const applications = this.appManagerController.getApplications(); - const isValidApp = verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp); - if (!isValidApp) { - return ioError.raiseError(`The provided app name "${app}" is not valid.`); - } - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!"); - } - if (!this.signaledSubscription) { - this.bridge.send("prefs", operations$1.registerSubscriber, { interopId: this.interopId, appName: verifiedApp }, undefined, { includeOperationCheck: true }) - .catch((error) => { - this.logger.warn("Failed to register subscriber for prefs"); - this.logger.error(error); - }); - this.signaledSubscription = true; - } - const subscriptionKey = this.getSubscriptionKey(verifiedApp); - this.get(verifiedApp).then(callback); - return this.registry.add(subscriptionKey, callback); - } - async updateFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.update, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - getMyAppName() { - const myAppName = this.config.isPlatformInternal ? this.platformAppName : this.appManagerController.me?.application.name; - if (!myAppName) { - return ioError.raiseError("App Preferences operations can not be executed for windows that do not have app!"); - } - return myAppName; - } - getSubscriptionKey(app) { - return `prefs-changed-${app}`; - } - async handleOnChanged({ prefs }) { - const subscriptionKey = this.getSubscriptionKey(prefs.app); - this.registry.execute(subscriptionKey, prefs); - } - } - - const operations = { - getResources: { name: "getResources", dataDecoder: getResourcesDataDecoder, resultDecoder: getResourcesResultDecoder }, - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - showAlert: { name: "showAlert", dataDecoder: uiAlertRequestMessageDecoder }, - showDialog: { name: "showDialog", dataDecoder: uiDialogRequestMessageDecoder }, - alertInteropAction: { name: "alertInteropAction", dataDecoder: alertInteropActionDataDecoder }, - showResolver: { name: "showResolver", dataDecoder: uiResolverRequestMessageDecoder, resultDecoder: uiResolverResponseMessageDecoder }, - }; - - const DEFAULT_ALERT_TTL = 5 * 1000; - const MODALS_SHADOW_HOST_ID = "io-modals-shadow-host"; - const MODALS_ROOT_ELEMENT_ID = "io-modals-root"; - const WIDGET_SHADOW_HOST_ID = "io-widget-shadow-host"; - const WIDGET_ROOT_ELEMENT_ID = "io-widget-root"; - const INTENT_RESOLVER_SHADOW_HOST_ID = "io-intent-resolver-shadow-host"; - const INTENT_RESOLVER_ROOT_ELEMENT_ID = "io-intent-resolver-root"; - const SHADOW_ROOT_ELEMENT_CLASSNAME = "io-body io-variables"; - - class UIController { - ioc; - supportedOperationsNames = []; - logger; - bridge; - config; - zIndexDictionary = { - [WIDGET_SHADOW_HOST_ID]: "100", - [MODALS_SHADOW_HOST_ID]: "101", - [INTENT_RESOLVER_SHADOW_HOST_ID]: "100" - }; - widgetResources; - modalsResources; - intentResolverResources; - modalsUiApi; - isDialogOpen = false; - intentResolverUiApi; - isIntentResolverOpen = false; - constructor(ioc) { - this.ioc = ioc; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("ui.controller.web"); - this.logger.trace("starting the ui controller"); - this.bridge = ioc.bridge; - this.config = ioc.config; - this.addOperationsExecutors(); - const resources = await this.getResources(); - if (!resources) { - this.logger.trace("No UI elements to display - platform is not initialized with any UI resources"); - return; - } - this.logger.trace(`Received UI resources from platform: ${JSON.stringify(resources)}`); - this.setResources(resources); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(uiOperationTypesDecoder, args.operation); - const operation = operations[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async showComponents(io) { - const initializeWidgetPromise = this.widgetResources ? this.initializeWidget(io, this.widgetResources) : Promise.resolve(); - const initializeModalsPromise = this.modalsResources ? this.initializeModalsUi(io, this.modalsResources) : Promise.resolve(); - const initializeIntentResolverPromise = this.intentResolverResources ? this.initializeIntentResolverUI(io, this.intentResolverResources) : Promise.resolve(); - await Promise.all([ - this.config.widget.awaitFactory ? initializeWidgetPromise : Promise.resolve(), - this.config.modals.awaitFactory ? initializeModalsPromise : Promise.resolve(), - this.config.intentResolver.awaitFactory ? initializeIntentResolverPromise : Promise.resolve(), - ]); - } - isIntentResolverEnabled() { - return !!this.intentResolverResources && this.config.intentResolver.enable; - } - addOperationsExecutors() { - operations.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - operations.showAlert.execute = this.handleShowAlert.bind(this); - operations.showDialog.execute = this.handleShowDialog.bind(this); - operations.showResolver.execute = this.handleShowResolver.bind(this); - this.supportedOperationsNames = getSupportedOperationsNames(operations); - } - async handleShowAlert({ config }) { - if (!this.config.modals.alerts.enabled) { - return ioError.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showAlert operation because modalsUiApi is missing."); - } - const { promise: closePromise, resolve: resolveClosePromise } = wrapPromise(); - const onClick = (config) => { - const decodedConfig = alertOnClickConfigDecoder.run(config); - if (!decodedConfig.ok) { - this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(decodedConfig.error)}.`); - return; - } - const { interopAction } = decodedConfig.result; - this.bridge.send("ui", operations.alertInteropAction, { interopAction }, undefined, { includeOperationCheck: true }) - .catch((error) => this.logger.warn(extractErrorMsg(error))); - }; - let result; - try { - this.logger.trace(`Open alert with config: ${JSON.stringify(config)}`); - result = modalsUiApi.alerts.open({ ...config, onClick, onClose: resolveClosePromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openAlertResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - const timeoutId = setTimeout(() => { - resolveClosePromise(); - }, getSafeTimeoutDelay(config.ttl ?? DEFAULT_ALERT_TTL)); - closePromise.then(() => { - clearTimeout(timeoutId); - try { - modalsUiApi.alerts.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close alert with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - }); - } - async handleShowDialog({ config }) { - if (!this.config.modals.dialogs.enabled) { - return ioError.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showDialog operation because modalsUiApi is missing."); - } - if (this.isDialogOpen) { - return ioError.raiseError("Cannot open a dialog because another one is already open."); - } - const { promise: completionPromise, resolve: resolveCompletionPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open dialog with config: ${JSON.stringify(config)}`); - result = modalsUiApi.dialogs.open({ ...config, onCompletion: resolveCompletionPromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openDialogResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - this.isDialogOpen = true; - let timeoutId; - if (config.timer) { - timeoutId = setTimeout(() => { - resolveCompletionPromise({ response: { isExpired: true } }); - }, getSafeTimeoutDelay(config.timer.duration)); - } - const response = await completionPromise; - clearTimeout(timeoutId); - this.isDialogOpen = false; - try { - modalsUiApi.dialogs.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close dialog with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodeResponse = dialogOnCompletionConfigDecoder.run(response); - if (!decodeResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodeResponse.error)}.`); - } - return { result: decodeResponse.result.response }; - } - async handleShowResolver({ config }) { - this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(config)}`); - if (!this.config.intentResolver.enable) { - return ioError.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config."); - } - const intentResolverApi = this.intentResolverUiApi; - if (!intentResolverApi) { - return ioError.raiseError("Unable to perform showResolver operation because intentResolverApi is missing."); - } - if (this.isIntentResolverOpen) { - return ioError.raiseError("Cannot open the intent resolver because another one is already open."); - } - const { promise: completionPromise, resolve: resolveIntentResolverPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open intent resolver with config: ${JSON.stringify(config)}`); - result = intentResolverApi.open({ ...config, onUserResponse: resolveIntentResolverPromise }); - } - catch (error) { - return ioError.raiseError(`intentResolverUI.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodedOpenResult = openResolverResultDecoder.run(result); - if (!decodedOpenResult.ok) { - return ioError.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(decodedOpenResult.error)}.`); - } - const timer = setTimeout(() => resolveIntentResolverPromise({ response: { isExpired: true } }), getSafeTimeoutDelay(config.timeout)); - const response = await completionPromise; - clearTimeout(timer); - this.isIntentResolverOpen = false; - try { - intentResolverApi.close({ id: decodedOpenResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close intent resolver with id ${decodedOpenResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodedResponse = onUserResponseResponseDecoder.run(response); - if (!decodedResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodedResponse.error)}.`); - } - return { result: decodedResponse.result.response }; - } - async getResources() { - const data = { - origin: window.origin - }; - try { - const result = await this.bridge.send("ui", operations.getResources, data, undefined, { includeOperationCheck: true }); - return result.resources; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - } - } - appendModalsResources(resources) { - this.logger.trace("Appending modals resources"); - return this.appendResources(MODALS_SHADOW_HOST_ID, MODALS_ROOT_ELEMENT_ID, resources.sources); - } - appendWidgetResources(resources) { - this.logger.trace("Appending widget resources"); - return this.appendResources(WIDGET_SHADOW_HOST_ID, WIDGET_ROOT_ELEMENT_ID, resources.sources); - } - appendIntentResolverResources(resources) { - this.logger.trace("Appending intent resolver resources"); - return this.appendResources(INTENT_RESOLVER_SHADOW_HOST_ID, INTENT_RESOLVER_ROOT_ELEMENT_ID, resources.sources); - } - appendResources(shadowHostId, rootElementId, sources) { - const { bundle, fonts = [], styles } = sources; - const shadowHost = document.createElement("div"); - shadowHost.id = shadowHostId; - shadowHost.style.position = "fixed"; - shadowHost.style.zIndex = this.zIndexDictionary[shadowHostId]; - const shadowRoot = shadowHost.attachShadow({ mode: "open" }); - const script = document.createElement("script"); - script.src = bundle; - script.type = "module"; - shadowRoot.appendChild(script); - const rootElement = document.createElement("div"); - rootElement.id = rootElementId; - rootElement.className = SHADOW_ROOT_ELEMENT_CLASSNAME; - shadowRoot.appendChild(rootElement); - styles.forEach((style) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = style; - shadowRoot.appendChild(link); - }); - fonts.forEach((font) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = font; - document.head.insertBefore(link, document.head.firstChild); - }); - document.body.appendChild(shadowHost); - return { rootElement }; - } - async initializeWidget(io, resources) { - this.logger.trace("Initializing IOBrowserWidget."); - const { rootElement } = this.appendWidgetResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...deepmerge$1(resources.config, this.config.widget), - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.widgetReady(); - this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(config)}`); - await window.IOBrowserWidget(io, config); - this.logger.trace("IOBrowserWidget was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserWidget to initialize.`); - } - async initializeModalsUi(io, resources) { - this.logger.trace("Initializing IOBrowserModalsUI."); - const { rootElement } = this.appendModalsResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.modals, - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.modalsUIFactoryReady(); - this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.modalsUiApi = await window.IOBrowserModalsUI(io, config); - this.logger.trace("IOBrowserModalsUI was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`); - } - async initializeIntentResolverUI(io, resources) { - this.logger.trace("Initializing IOBrowserIntentResolverUI."); - const { rootElement } = this.appendIntentResolverResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.intentResolver, - rootElement - }; - const timeout = config.timeout; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(); - this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.intentResolverUiApi = await window.IOBrowserIntentResolverUI(io, config); - this.logger.trace("IOBrowserIntentResolverUI initialized successfully."); - }, timeout, `Timeout of ${timeout}ms hit waiting for IOBrowserIntentResolverUI to initialize.`); - } - setResources(resources) { - this.setWidgetResources(resources.widget); - this.setModalsUiResources(resources.modals); - this.setIntentResolverResources(resources.intentResolver); - } - setWidgetResources(resources) { - const baseMsg = "Widget won't be displayed. Reason: "; - const decodedConfig = widgetConfigDecoder.run(this.config.widget); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid widget config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.widget.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'widget: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`); - return; - } - this.widgetResources = resources; - } - setModalsUiResources(resources) { - const baseMsg = "Modals won't be displayed. Reason: "; - const decodedConfig = modalsConfigDecoder.run(this.config.modals); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid modals config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.modals.alerts.enabled && !this.config.modals.dialogs.enabled) { - this.logger.trace(`${baseMsg} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`); - return; - } - this.modalsResources = resources; - } - setIntentResolverResources(resources) { - const baseMsg = "Intent Resolver UI won't be displayed. Reason: "; - const decodedConfig = intentResolverConfigDecoder.run(this.config.intentResolver); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid intent resolver config. Error: ${JSON.stringify(decodedConfig.error)}`); - return; - } - if (!this.config.intentResolver.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'intentResolver: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`); - return; - } - this.intentResolverResources = resources; - } - subscribeForThemeChanges(io, element) { - const themesApi = io.themes; - if (!themesApi) { - return; - } - const changeTheme = async (theme) => { - if (element.classList.contains(theme.name)) { - return; - } - const allThemes = await themesApi.list(); - element.classList.remove(...allThemes.map(({ name }) => name)); - element.classList.add(theme.name); - }; - themesApi.onChanged(changeTheme); - themesApi.getCurrent().then(changeTheme); - } - } - - class IoC { - _coreGlue; - _communicationId; - _publicWindowId; - _webConfig; - _windowsControllerInstance; - _appManagerControllerInstance; - _layoutsControllerInstance; - _notificationsControllerInstance; - _intentsControllerInstance; - _channelsControllerInstance; - _themesControllerInstance; - _extensionController; - _systemControllerInstance; - _bridgeInstance; - _eventsDispatcher; - _preferredConnectionController; - _channelsStorage; - _prefsControllerInstance; - _uiController; - controllers = { - windows: this.windowsController, - appManager: this.appManagerController, - layouts: this.layoutsController, - notifications: this.notificationsController, - intents: this.intentsController, - channels: this.channelsController, - system: this.systemController, - extension: this.extensionController, - themes: this.themesController, - prefs: this.prefsController, - ui: this.uiController - }; - get communicationId() { - return this._communicationId; - } - get publicWindowId() { - return this._publicWindowId; - } - get windowsController() { - if (!this._windowsControllerInstance) { - this._windowsControllerInstance = new WindowsController(); - } - return this._windowsControllerInstance; - } - get uiController() { - if (!this._uiController) { - this._uiController = new UIController(this); - } - return this._uiController; - } - get appManagerController() { - if (!this._appManagerControllerInstance) { - this._appManagerControllerInstance = new AppManagerController(); - } - return this._appManagerControllerInstance; - } - get layoutsController() { - if (!this._layoutsControllerInstance) { - this._layoutsControllerInstance = new LayoutsController(); - } - return this._layoutsControllerInstance; - } - get themesController() { - if (!this._themesControllerInstance) { - this._themesControllerInstance = new ThemesController(); - } - return this._themesControllerInstance; - } - get notificationsController() { - if (!this._notificationsControllerInstance) { - this._notificationsControllerInstance = new NotificationsController(); - } - return this._notificationsControllerInstance; - } - get intentsController() { - if (!this._intentsControllerInstance) { - this._intentsControllerInstance = new IntentsController(); - } - return this._intentsControllerInstance; - } - get systemController() { - if (!this._systemControllerInstance) { - this._systemControllerInstance = new SystemController(); - } - return this._systemControllerInstance; - } - get channelsController() { - if (!this._channelsControllerInstance) { - this._channelsControllerInstance = new ChannelsController(); - } - return this._channelsControllerInstance; - } - get prefsController() { - if (!this._prefsControllerInstance) { - this._prefsControllerInstance = new PrefsController(); - } - return this._prefsControllerInstance; - } - get extensionController() { - if (!this._extensionController) { - this._extensionController = new ExtController(); - } - return this._extensionController; - } - get eventsDispatcher() { - if (!this._eventsDispatcher) { - this._eventsDispatcher = new EventsDispatcher(this.config); - } - return this._eventsDispatcher; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new GlueBridge(this._coreGlue, this.communicationId); - } - return this._bridgeInstance; - } - get preferredConnectionController() { - if (!this._preferredConnectionController) { - this._preferredConnectionController = new PreferredConnectionController(this._coreGlue); - } - return this._preferredConnectionController; - } - get channelsStorage() { - if (!this._channelsStorage) { - this._channelsStorage = new ChannelsStorage(); - } - return this._channelsStorage; - } - get config() { - return this._webConfig; - } - defineGlue(coreGlue) { - this._coreGlue = coreGlue; - this._publicWindowId = coreGlue.connection.transport.publicWindowId; - const globalNamespace = window.glue42core || window.iobrowser; - this._communicationId = coreGlue.connection.transport.communicationId || globalNamespace.communicationId; - } - defineConfig(config) { - this._webConfig = config; - } - async buildWebWindow(id, name, logger) { - const model = new WebWindowModel(id, name, this.bridge, logger); - const api = await model.toApi(); - return { id, model, api }; - } - buildNotification(config, id) { - return new Notification(config, id); - } - async buildApplication(app, applicationInstances) { - const application = (new ApplicationModel(app, [], this.appManagerController)).toApi(); - const instances = applicationInstances.map((instanceData) => this.buildInstance(instanceData, application)); - application.instances.push(...instances); - return application; - } - buildInstance(instanceData, app) { - return (new InstanceModel(instanceData, this.bridge, app)).toApi(); - } - } - - var version$1 = "4.2.4"; - - const setupGlobalSystem = (io, bridge) => { - return { - getContainerInfo: async () => { - if (window === window.parent) { - return; - } - if (window.name.includes("#wsp")) { - return { - workspaceFrame: { - id: "N/A" - } - }; - } - return window.parent === window.top ? - { top: {} } : - { parent: {} }; - }, - getProfileData: async () => { - if (!bridge) { - throw new Error("Bridge is not available and cannot fetch the profile data"); - } - const data = await bridge.send("system", { name: "getProfileData" }, undefined); - return data; - } - }; - }; - - const createFactoryFunction = (coreFactoryFunction) => { - let cachedApiPromise; - const initAPI = async (config) => { - const ioc = new IoC(); - const glue = await PromiseWrap(() => coreFactoryFunction(config, { version: version$1 }), 30000, "Glue Web initialization timed out, because core didn't resolve"); - const logger = glue.logger.subLogger("web.main.controller"); - ioc.defineGlue(glue); - await ioc.preferredConnectionController.start(config); - await ioc.bridge.start(ioc.controllers); - ioc.defineConfig(config); - logger.trace("the bridge has been started, initializing all controllers"); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.start(glue, ioc))); - logger.trace("all controllers reported started, starting all additional libraries"); - try { - await Promise.all(config.libraries.map((lib) => lib(glue, config))); - logger.trace("all libraries were started"); - ioc.eventsDispatcher.start(glue); - logger.trace("start event dispatched, glue is ready, returning it"); - await ioc.uiController.showComponents(glue).catch((err) => logger.warn(err?.message ? err.message : JSON.stringify(err))); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.postStart ? controller.postStart(glue, ioc) : Promise.resolve())); - window.iobrowser.system = setupGlobalSystem(glue, ioc.bridge); - window.iobrowser = Object.freeze({ ...window.iobrowser }); - return glue; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const factory = (userConfig) => { - if (window.glue42gd || window.iodesktop) { - return enterprise(userConfig); - } - const config = parseConfig(userConfig); - try { - checkSingleton(); - } - catch (error) { - return typeof cachedApiPromise === "undefined" ? Promise.reject(new Error(error)) : cachedApiPromise; - } - const apiPromise = initAPI(config); - cachedApiPromise = userConfig?.memoizeAPI ? apiPromise : undefined; - return apiPromise; - }; - return factory; - }; - - var MetricTypes = { - STRING: 1, - NUMBER: 2, - TIMESTAMP: 3, - OBJECT: 4 - }; - - function getMetricTypeByValue(metric) { - if (metric.type === MetricTypes.TIMESTAMP) { - return "timestamp"; - } - else if (metric.type === MetricTypes.NUMBER) { - return "number"; - } - else if (metric.type === MetricTypes.STRING) { - return "string"; - } - else if (metric.type === MetricTypes.OBJECT) { - return "object"; - } - return "unknown"; - } - function getTypeByValue(value) { - if (value.constructor === Date) { - return "timestamp"; - } - else if (typeof value === "number") { - return "number"; - } - else if (typeof value === "string") { - return "string"; - } - else if (typeof value === "object") { - return "object"; - } - else { - return "string"; - } - } - function serializeMetric(metric) { - const serializedMetrics = {}; - const type = getMetricTypeByValue(metric); - if (type === "object") { - const values = Object.keys(metric.value).reduce((memo, key) => { - const innerType = getTypeByValue(metric.value[key]); - if (innerType === "object") { - const composite = defineNestedComposite(metric.value[key]); - memo[key] = { - type: "object", - description: "", - context: {}, - composite, - }; - } - else { - memo[key] = { - type: innerType, - description: "", - context: {}, - }; - } - return memo; - }, {}); - serializedMetrics.composite = values; - } - serializedMetrics.name = normalizeMetricName(metric.path.join("/") + "/" + metric.name); - serializedMetrics.type = type; - serializedMetrics.description = metric.description; - serializedMetrics.context = {}; - return serializedMetrics; - } - function defineNestedComposite(values) { - return Object.keys(values).reduce((memo, key) => { - const type = getTypeByValue(values[key]); - if (type === "object") { - memo[key] = { - type: "object", - description: "", - context: {}, - composite: defineNestedComposite(values[key]), - }; - } - else { - memo[key] = { - type, - description: "", - context: {}, - }; - } - return memo; - }, {}); - } - function normalizeMetricName(name) { - if (typeof name !== "undefined" && name.length > 0 && name[0] !== "/") { - return "/" + name; - } - else { - return name; - } - } - function getMetricValueByType(metric) { - const type = getMetricTypeByValue(metric); - if (type === "timestamp") { - return Date.now(); - } - else { - return publishNestedComposite(metric.value); - } - } - function publishNestedComposite(values) { - if (typeof values !== "object") { - return values; - } - return Object.keys(values).reduce((memo, key) => { - const value = values[key]; - if (typeof value === "object" && value.constructor !== Date) { - memo[key] = publishNestedComposite(value); - } - else if (value.constructor === Date) { - memo[key] = new Date(value).getTime(); - } - else if (value.constructor === Boolean) { - memo[key] = value.toString(); - } - else { - memo[key] = value; - } - return memo; - }, {}); - } - function flatten(arr) { - return arr.reduce((flat, toFlatten) => { - return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); - }, []); - } - function getHighestState(arr) { - return arr.sort((a, b) => { - if (!a.state) { - return 1; - } - if (!b.state) { - return -1; - } - return b.state - a.state; - })[0]; - } - function aggregateDescription(arr) { - let msg = ""; - arr.forEach((m, idx, a) => { - const path = m.path.join("."); - if (idx === a.length - 1) { - msg += path + "." + m.name + ": " + m.description; - } - else { - msg += path + "." + m.name + ": " + m.description + ","; - } - }); - if (msg.length > 100) { - return msg.slice(0, 100) + "..."; - } - else { - return msg; - } - } - function composeMsgForRootStateMetric(system) { - const aggregatedState = system.root.getAggregateState(); - const merged = flatten(aggregatedState); - const highestState = getHighestState(merged); - const aggregateDesc = aggregateDescription(merged); - return { - description: aggregateDesc, - value: highestState.state, - }; - } - - function gw3 (connection, config) { - if (!connection || typeof connection !== "object") { - throw new Error("Connection is required parameter"); - } - let joinPromise; - let session; - const init = (repo) => { - let resolveReadyPromise; - joinPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - session = connection.domain("metrics"); - session.onJoined((reconnect) => { - if (!reconnect && resolveReadyPromise) { - resolveReadyPromise(); - resolveReadyPromise = undefined; - } - const rootStateMetric = { - name: "/State", - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const defineRootMetricsMsg = { - type: "define", - metrics: [rootStateMetric], - }; - session.sendFireAndForget(defineRootMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(err)}`); - }); - if (reconnect) { - replayRepo(repo); - } - }); - session.join({ - system: config.system, - service: config.service, - instance: config.instance - }); - }; - const replayRepo = (repo) => { - replaySystem(repo.root); - }; - const replaySystem = (system) => { - createSystem(system); - system.metrics.forEach((m) => { - createMetric(m); - }); - system.subSystems.forEach((ss) => { - replaySystem(ss); - }); - }; - const createSystem = async (system) => { - if (system.parent === undefined) { - return; - } - await joinPromise; - const metric = { - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const createMetricsMsg = { - type: "define", - metrics: [metric], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const updateSystem = async (system, state) => { - await joinPromise; - const shadowedUpdateMetric = { - type: "publish", - values: [{ - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - value: { - Description: state.description, - Value: state.state, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(shadowedUpdateMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - const stateObj = composeMsgForRootStateMetric(system); - const rootMetric = { - type: "publish", - peer_id: connection.peerId, - values: [{ - name: "/State", - value: { - Description: stateObj.description, - Value: stateObj.value, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(rootMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for root state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const createMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - const m = serializeMetric(metricClone); - const createMetricsMsg = { - type: "define", - metrics: [m], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for metric ${metric.name}: ${JSON.stringify(err)}`); - }); - if (typeof metricClone.value !== "undefined") { - updateMetricCore(metricClone); - } - }; - const updateMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - updateMetricCore(metricClone); - }; - const updateMetricCore = (metric) => { - if (canUpdate()) { - const value = getMetricValueByType(metric); - const publishMetricsMsg = { - type: "publish", - values: [{ - name: normalizeMetricName(metric.path.join("/") + "/" + metric.name), - value, - timestamp: Date.now(), - }], - }; - return session.sendFireAndForget(publishMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to publish metric ${metric.name}: ${JSON.stringify(err)}`); - }); - } - return Promise.resolve(); - }; - const cloneMetric = (metric) => { - const metricClone = { ...metric }; - if (typeof metric.value === "object" && metric.value !== null) { - metricClone.value = { ...metric.value }; - } - return metricClone; - }; - const canUpdate = () => { - try { - const func = config.canUpdateMetric ?? (() => true); - return func(); - } - catch { - return true; - } - }; - return { - init, - createSystem, - updateSystem, - createMetric, - updateMetric, - }; - } - - var Helpers = { - validate: (definition, parent, transport) => { - if (definition === null || typeof definition !== "object") { - throw new Error("Missing definition"); - } - if (parent === null || typeof parent !== "object") { - throw new Error("Missing parent"); - } - if (transport === null || typeof transport !== "object") { - throw new Error("Missing transport"); - } - }, - }; - - class BaseMetric { - definition; - system; - transport; - value; - type; - path = []; - name; - description; - get repo() { - return this.system?.repo; - } - get id() { return `${this.system.path}/${name}`; } - constructor(definition, system, transport, value, type) { - this.definition = definition; - this.system = system; - this.transport = transport; - this.value = value; - this.type = type; - Helpers.validate(definition, system, transport); - this.path = system.path.slice(0); - this.path.push(system.name); - this.name = definition.name; - this.description = definition.description; - transport.createMetric(this); - } - update(newValue) { - this.value = newValue; - return this.transport.updateMetric(this); - } - } - - class NumberMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.NUMBER); - } - incrementBy(num) { - this.update(this.value + num); - } - increment() { - this.incrementBy(1); - } - decrement() { - this.incrementBy(-1); - } - decrementBy(num) { - this.incrementBy(num * -1); - } - } - - class ObjectMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.OBJECT); - } - update(newValue) { - this.mergeValues(newValue); - return this.transport.updateMetric(this); - } - mergeValues(values) { - return Object.keys(this.value).forEach((k) => { - if (typeof values[k] !== "undefined") { - this.value[k] = values[k]; - } - }); - } - } - - class StringMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.STRING); - } - } - - class TimestampMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.TIMESTAMP); - } - now() { - this.update(new Date()); - } - } - - function system(name, repo, protocol, parent, description) { - if (!repo) { - throw new Error("Repository is required"); - } - if (!protocol) { - throw new Error("Transport is required"); - } - const _transport = protocol; - const _name = name; - const _description = description || ""; - const _repo = repo; - const _parent = parent; - const _path = _buildPath(parent); - let _state = {}; - const id = _arrayToString(_path, "/") + name; - const root = repo.root; - const _subSystems = []; - const _metrics = []; - function subSystem(nameSystem, descriptionSystem) { - if (!nameSystem || nameSystem.length === 0) { - throw new Error("name is required"); - } - const match = _subSystems.filter((s) => s.name === nameSystem); - if (match.length > 0) { - return match[0]; - } - const _system = system(nameSystem, _repo, _transport, me, descriptionSystem); - _subSystems.push(_system); - return _system; - } - function setState(state, stateDescription) { - _state = { state, description: stateDescription }; - _transport.updateSystem(me, _state); - } - function stringMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.STRING, value, (metricDef) => new StringMetric(metricDef, me, _transport, value)); - } - function numberMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.NUMBER, value, (metricDef) => new NumberMetric(metricDef, me, _transport, value)); - } - function objectMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.OBJECT, value, (metricDef) => new ObjectMetric(metricDef, me, _transport, value)); - } - function timestampMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.TIMESTAMP, value, (metricDef) => new TimestampMetric(metricDef, me, _transport, value)); - } - function _getOrCreateMetric(metricObject, expectedType, value, createMetric) { - let metricDef = { name: "" }; - if (typeof metricObject === "string") { - metricDef = { name: metricObject }; - } - else { - metricDef = metricObject; - } - const matching = _metrics.filter((shadowedMetric) => shadowedMetric.name === metricDef.name); - if (matching.length > 0) { - const existing = matching[0]; - if (existing.type !== expectedType) { - throw new Error(`A metric named ${metricDef.name} is already defined with different type.`); - } - if (typeof value !== "undefined") { - existing - .update(value) - .catch(() => { }); - } - return existing; - } - const metric = createMetric(metricDef); - _metrics.push(metric); - return metric; - } - function _buildPath(shadowedSystem) { - if (!shadowedSystem || !shadowedSystem.parent) { - return []; - } - const path = _buildPath(shadowedSystem.parent); - path.push(shadowedSystem.name); - return path; - } - function _arrayToString(path, separator) { - return ((path && path.length > 0) ? path.join(separator) : ""); - } - function getAggregateState() { - const aggState = []; - if (Object.keys(_state).length > 0) { - aggState.push({ - name: _name, - path: _path, - state: _state.state, - description: _state.description, - }); - } - _subSystems.forEach((shadowedSubSystem) => { - const result = shadowedSubSystem.getAggregateState(); - if (result.length > 0) { - aggState.push(...result); - } - }); - return aggState; - } - const me = { - get name() { - return _name; - }, - get description() { - return _description; - }, - get repo() { - return _repo; - }, - get parent() { - return _parent; - }, - path: _path, - id, - root, - get subSystems() { - return _subSystems; - }, - get metrics() { - return _metrics; - }, - subSystem, - getState: () => { - return _state; - }, - setState, - stringMetric, - timestampMetric, - objectMetric, - numberMetric, - getAggregateState, - }; - _transport.createSystem(me); - return me; - } - - class Repository { - root; - constructor(options, protocol) { - protocol.init(this); - this.root = system("", this, protocol); - this.addSystemMetrics(this.root, options.clickStream || options.clickStream === undefined); - } - addSystemMetrics(rootSystem, useClickStream) { - if (typeof navigator !== "undefined") { - rootSystem.stringMetric("UserAgent", navigator.userAgent); - } - if (useClickStream && typeof document !== "undefined") { - const clickStream = rootSystem.subSystem("ClickStream"); - const documentClickHandler = (e) => { - if (!e.target) { - return; - } - const target = e.target; - const className = target ? target.getAttribute("class") ?? "" : ""; - clickStream.objectMetric("LastBrowserEvent", { - type: "click", - timestamp: new Date(), - target: { - className, - id: target.id, - type: "<" + target.tagName.toLowerCase() + ">", - href: target.href || "", - }, - }); - }; - clickStream.objectMetric("Page", { - title: document.title, - page: window.location.href, - }); - if (document.addEventListener) { - document.addEventListener("click", documentClickHandler); - } - else { - document.attachEvent("onclick", documentClickHandler); - } - } - rootSystem.stringMetric("StartTime", (new Date()).toString()); - const urlMetric = rootSystem.stringMetric("StartURL", ""); - const appNameMetric = rootSystem.stringMetric("AppName", ""); - if (typeof window !== "undefined") { - if (typeof window.location !== "undefined") { - const startUrl = window.location.href; - urlMetric.update(startUrl); - } - if (typeof window.glue42gd !== "undefined") { - appNameMetric.update(window.glue42gd.appName); - } - } - } - } - - class NullProtocol { - init(repo) { - } - createSystem(system) { - return Promise.resolve(); - } - updateSystem(metric, state) { - return Promise.resolve(); - } - createMetric(metric) { - return Promise.resolve(); - } - updateMetric(metric) { - return Promise.resolve(); - } - } - - class PerfTracker { - api; - lastCount = 0; - initialPublishTimeout = 10 * 1000; - publishInterval = 60 * 1000; - system; - constructor(api, initialPublishTimeout, publishInterval) { - this.api = api; - this.initialPublishTimeout = initialPublishTimeout ?? this.initialPublishTimeout; - this.publishInterval = publishInterval ?? this.publishInterval; - this.scheduleCollection(); - this.system = this.api.subSystem("performance", "Performance data published by the web application"); - } - scheduleCollection() { - setTimeout(() => { - this.collect(); - setInterval(() => { - this.collect(); - }, this.publishInterval); - }, this.initialPublishTimeout); - } - collect() { - try { - this.collectMemory(); - this.collectEntries(); - } - catch { - } - } - collectMemory() { - const memory = window.performance.memory; - this.system.stringMetric("memory", JSON.stringify({ - totalJSHeapSize: memory.totalJSHeapSize, - usedJSHeapSize: memory.usedJSHeapSize - })); - } - collectEntries() { - const allEntries = window.performance.getEntries(); - if (allEntries.length <= this.lastCount) { - return; - } - this.lastCount = allEntries.length; - const jsonfiedEntries = allEntries.map((i) => i.toJSON()); - this.system.stringMetric("entries", JSON.stringify(jsonfiedEntries)); - } - } - - var metrics = (options) => { - let protocol; - if (!options.connection || typeof options.connection !== "object") { - protocol = new NullProtocol(); - } - else { - protocol = gw3(options.connection, options); - } - const repo = new Repository(options, protocol); - let rootSystem = repo.root; - if (!options.disableAutoAppSystem) { - rootSystem = rootSystem.subSystem("App"); - } - const api = addFAVSupport(rootSystem); - initPerf(api, options.pagePerformanceMetrics); - return api; - }; - function initPerf(api, config) { - if (typeof window === "undefined") { - return; - } - const perfConfig = window?.glue42gd?.metrics?.pagePerformanceMetrics; - if (perfConfig) { - config = perfConfig; - } - if (config?.enabled) { - new PerfTracker(api, config.initialPublishTimeout, config.publishInterval); - } - } - function addFAVSupport(system) { - const reportingSystem = system.subSystem("reporting"); - const def = { - name: "features" - }; - let featureMetric; - const featureMetricFunc = (name, action, payload) => { - if (typeof name === "undefined" || name === "") { - throw new Error("name is mandatory"); - } - else if (typeof action === "undefined" || action === "") { - throw new Error("action is mandatory"); - } - else if (typeof payload === "undefined" || payload === "") { - throw new Error("payload is mandatory"); - } - if (!featureMetric) { - featureMetric = reportingSystem.objectMetric(def, { name, action, payload }); - } - else { - featureMetric.update({ - name, - action, - payload - }); - } - }; - system.featureMetric = featureMetricFunc; - return system; - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackRegistryFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - class InProcTransport { - gw; - registry = CallbackRegistryFactory(); - client; - constructor(settings, logger) { - this.gw = settings.facade; - this.gw.connect((_client, message) => { - this.messageHandler(message); - }).then((client) => { - this.client = client; - }); - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - if (this.client) { - this.client.send(msg); - return Promise.resolve(undefined); - } - else { - return Promise.reject(`not connected`); - } - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "in-memory"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class SharedWorkerTransport { - logger; - worker; - registry = CallbackRegistryFactory(); - constructor(workerFile, logger) { - this.logger = logger; - this.worker = new SharedWorker(workerFile); - this.worker.port.onmessage = (e) => { - this.messageHandler(e.data); - }; - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - this.worker.port.postMessage(msg); - return Promise.resolve(); - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "shared-worker"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class Utils { - static isNode() { - if (typeof Utils._isNode !== "undefined") { - return Utils._isNode; - } - if (typeof window !== "undefined") { - Utils._isNode = false; - return false; - } - try { - Utils._isNode = Object.prototype.toString.call(global.process) === "[object process]"; - } - catch (e) { - Utils._isNode = false; - } - return Utils._isNode; - } - static _isNode; - } - - class PromiseWrapper { - static delay(time) { - return new Promise((resolve) => setTimeout(resolve, time)); - } - resolve; - reject; - promise; - rejected = false; - resolved = false; - get ended() { - return this.rejected || this.resolved; - } - constructor() { - this.promise = new Promise((resolve, reject) => { - this.resolve = (t) => { - this.resolved = true; - resolve(t); - }; - this.reject = (err) => { - this.rejected = true; - reject(err); - }; - }); - } - } - - const timers = {}; - function getAllTimers() { - return timers; - } - function timer (timerName) { - const existing = timers[timerName]; - if (existing) { - return existing; - } - const marks = []; - function now() { - return new Date().getTime(); - } - const startTime = now(); - mark("start", startTime); - let endTime; - let period; - function stop() { - endTime = now(); - mark("end", endTime); - period = endTime - startTime; - return period; - } - function mark(name, time) { - const currentTime = time ?? now(); - let diff = 0; - if (marks.length > 0) { - diff = currentTime - marks[marks.length - 1].time; - } - marks.push({ name, time: currentTime, diff }); - } - const timerObj = { - get startTime() { - return startTime; - }, - get endTime() { - return endTime; - }, - get period() { - return period; - }, - stop, - mark, - marks - }; - timers[timerName] = timerObj; - return timerObj; - } - - const WebSocketConstructor = Utils.isNode() ? null : window.WebSocket; - class WS { - ws; - logger; - settings; - startupTimer = timer("connection"); - _running = true; - _registry = CallbackRegistryFactory(); - wsRequests = []; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - if (!this.settings.ws) { - throw new Error("ws is missing"); - } - } - onMessage(callback) { - return this._registry.add("onMessage", callback); - } - send(msg, options) { - return new Promise((resolve, reject) => { - this.waitForSocketConnection(() => { - try { - this.ws?.send(msg); - resolve(); - } - catch (e) { - reject(e); - } - }, reject); - }); - } - open() { - this.logger.info("opening ws..."); - this._running = true; - return new Promise((resolve, reject) => { - this.waitForSocketConnection(resolve, reject); - }); - } - close() { - this._running = false; - if (this.ws) { - this.ws.close(); - } - return Promise.resolve(); - } - onConnectedChanged(callback) { - return this._registry.add("onConnectedChanged", callback); - } - name() { - return this.settings.ws; - } - reconnect() { - this.ws?.close(); - const pw = new PromiseWrapper(); - this.waitForSocketConnection(() => { - pw.resolve(); - }); - return pw.promise; - } - waitForSocketConnection(callback, failed) { - failed = failed ?? (() => { }); - if (!this._running) { - failed(`wait for socket on ${this.settings.ws} failed - socket closed by user`); - return; - } - if (this.ws?.readyState === 1) { - callback(); - return; - } - this.wsRequests.push({ callback, failed }); - if (this.wsRequests.length > 1) { - return; - } - this.openSocket(); - } - async openSocket(retryInterval, retriesLeft) { - this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${retryInterval}, retriesLeft: ${retriesLeft}...`); - this.startupTimer.mark("opening-socket"); - if (retryInterval === undefined) { - retryInterval = this.settings.reconnectInterval; - } - if (typeof retriesLeft === "undefined") { - retriesLeft = this.settings.reconnectAttempts; - } - if (retriesLeft !== undefined) { - if (retriesLeft === 0) { - this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`); - return; - } - this.logger.debug(`will retry ${retriesLeft} more times (every ${retryInterval} ms)`); - } - try { - await this.initiateSocket(); - this.startupTimer.mark("socket-initiated"); - this.notifyForSocketState(); - } - catch { - setTimeout(() => { - const retries = retriesLeft === undefined ? undefined : retriesLeft - 1; - this.openSocket(retryInterval, retries); - }, retryInterval); - } - } - initiateSocket() { - const pw = new PromiseWrapper(); - this.logger.debug(`initiating ws to ${this.settings.ws}...`); - this.ws = new WebSocketConstructor(this.settings.ws ?? ""); - let wasOpen = false; - this.ws.onerror = (err) => { - let reason; - try { - reason = JSON.stringify(err); - } - catch (error) { - const seen = new WeakSet(); - const replacer = (key, value) => { - if (typeof value === "object" && value !== null) { - if (seen.has(value)) { - return; - } - seen.add(value); - } - if (value instanceof Error) { - return { - message: value.message, - name: value.name, - stack: value.stack - }; - } - return value; - }; - reason = JSON.stringify(err, replacer); - } - this.logger.info(`ws error - reason: ${reason}`); - pw.reject("error"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("error"); - } - this.notifyStatusChanged(false, reason); - }; - this.ws.onclose = (err) => { - this.logger.info(`ws closed - code: ${err?.code} reason: ${err?.reason}`); - pw.reject("closed"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("closed"); - } - this.notifyStatusChanged(false); - }; - this.ws.onopen = () => { - this.startupTimer.mark("ws-opened"); - this.logger.info(`ws opened ${this.settings.identity?.application}`); - pw.resolve(); - wasOpen = true; - this.notifyStatusChanged(true); - }; - this.ws.onmessage = (message) => { - this._registry.execute("onMessage", message.data); - }; - return pw.promise; - } - notifyForSocketState(error) { - this.wsRequests.forEach((wsRequest) => { - if (error) { - if (wsRequest.failed) { - wsRequest.failed(error); - } - } - else { - wsRequest.callback(); - } - }); - this.wsRequests = []; - } - notifyStatusChanged(status, reason) { - this._registry.execute("onConnectedChanged", status, reason); - } - } - - class MessageReplayerImpl { - specs; - specsNames = []; - messages = {}; - isDone; - subs = {}; - subsRefCount = {}; - connection; - constructor(specs) { - this.specs = {}; - for (const spec of specs) { - this.specs[spec.name] = spec; - this.specsNames.push(spec.name); - } - } - init(connection) { - this.connection = connection; - for (const name of this.specsNames) { - for (const type of this.specs[name].types) { - let refCount = this.subsRefCount[type]; - if (!refCount) { - refCount = 0; - } - refCount += 1; - this.subsRefCount[type] = refCount; - if (refCount > 1) { - continue; - } - const sub = connection.on(type, (msg) => this.processMessage(type, msg)); - this.subs[type] = sub; - } - } - } - processMessage(type, msg) { - if (this.isDone || !msg) { - return; - } - for (const name of this.specsNames) { - if (this.specs[name].types.indexOf(type) !== -1) { - const messages = this.messages[name] || []; - this.messages[name] = messages; - messages.push(msg); - } - } - } - drain(name, callback) { - if (callback) { - (this.messages[name] || []).forEach(callback); - } - delete this.messages[name]; - for (const type of this.specs[name].types) { - this.subsRefCount[type] -= 1; - if (this.subsRefCount[type] <= 0) { - this.connection?.off(this.subs[type]); - delete this.subs[type]; - delete this.subsRefCount[type]; - } - } - delete this.specs[name]; - if (!this.specs.length) { - this.isDone = true; - } - } - } - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet[(Math.random() * 64) | 0]; - } - return id - }; - - const PromisePlus = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WebPlatformTransport { - settings; - logger; - identity; - isPreferredActivated; - _connectionProtocolVersion; - _communicationId; - publicWindowId; - selfAssignedWindowId; - iAmConnected = false; - parentReady = false; - rejected = false; - parentPingResolve; - parentPingInterval; - connectionResolve; - extConnectionResolve; - extConnectionReject; - connectionReject; - port; - myClientId; - extContentAvailable = false; - extContentConnecting = false; - extContentConnected = false; - parentWindowId; - parentInExtMode = false; - webNamespace = "g42_core_web"; - parent; - parentType; - parentPingTimeout = 5000; - connectionRequestTimeout = 7000; - defaultTargetString = "*"; - registry = CallbackRegistryFactory(); - messages = { - connectionAccepted: { name: "connectionAccepted", handle: this.handleConnectionAccepted.bind(this) }, - connectionRejected: { name: "connectionRejected", handle: this.handleConnectionRejected.bind(this) }, - connectionRequest: { name: "connectionRequest", handle: this.handleConnectionRequest.bind(this) }, - parentReady: { - name: "parentReady", handle: () => { - } - }, - parentPing: { name: "parentPing", handle: this.handleParentPing.bind(this) }, - platformPing: { name: "platformPing", handle: this.handlePlatformPing.bind(this) }, - platformReady: { name: "platformReady", handle: this.handlePlatformReady.bind(this) }, - clientUnload: { name: "clientUnload", handle: () => { } }, - manualUnload: { name: "manualUnload", handle: this.handleManualUnload.bind(this) }, - extConnectionResponse: { name: "extConnectionResponse", handle: this.handleExtConnectionResponse.bind(this) }, - extSetupRequest: { name: "extSetupRequest", handle: this.handleExtSetupRequest.bind(this) }, - gatewayDisconnect: { name: "gatewayDisconnect", handle: this.handleGatewayDisconnect.bind(this) }, - gatewayInternalConnect: { name: "gatewayInternalConnect", handle: this.handleGatewayInternalConnect.bind(this) } - }; - constructor(settings, logger, identity) { - this.settings = settings; - this.logger = logger; - this.identity = identity; - this.extContentAvailable = !!window.glue42ext; - this.setUpMessageListener(); - this.setUpUnload(); - this.setupPlatformUnloadListener(); - this.parentType = window.name.includes("#wsp") ? "workspace" : undefined; - } - manualSetReadyState() { - this.iAmConnected = true; - this.parentReady = true; - } - get transportWindowId() { - return this.publicWindowId; - } - get communicationId() { - return this._communicationId; - } - async sendObject(msg) { - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: msg }, window.origin); - } - if (!this.port) { - throw new Error("Cannot send message, because the port was not opened yet"); - } - this.port.postMessage(msg); - } - get isObjectBasedTransport() { - return true; - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - send() { - return Promise.reject("not supported"); - } - onConnectedChanged(callback) { - return this.registry.add("onConnectedChanged", callback); - } - async open() { - this.logger.debug("opening a connection to the web platform gateway."); - await this.connect(); - this.notifyStatusChanged(true); - } - close() { - this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId || "unknown"}, client connected: ${this.iAmConnected}`); - const message = { - glue42core: { - type: this.messages.gatewayDisconnect.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.port?.postMessage(message); - this.parentReady = false; - this.notifyStatusChanged(false, "manual reconnection"); - return Promise.resolve(); - } - name() { - return "web-platform"; - } - async reconnect() { - await this.close(); - return Promise.resolve(); - } - initiateInternalConnection() { - return new Promise((resolve, reject) => { - this.logger.debug("opening an internal web platform connection"); - this.port = this.settings.port; - if (this.iAmConnected) { - this.logger.warn("cannot open a new connection, because this client is currently connected"); - return; - } - this.port.onmessage = (event) => { - if (this.iAmConnected && !event.data?.glue42core) { - this.registry.execute("onMessage", event.data); - return; - } - const data = event.data?.glue42core; - if (!data) { - return; - } - if (data.type === this.messages.gatewayInternalConnect.name && data.success) { - this.publicWindowId = this.settings.windowId; - if (this.identity && this.publicWindowId) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.publicWindowId; - } - resolve(); - } - if (data.type === this.messages.gatewayInternalConnect.name && data.error) { - reject(data.error); - } - }; - this.port.postMessage({ - glue42core: { - type: this.messages.gatewayInternalConnect.name - } - }); - }); - } - initiateRemoteConnection(target) { - return PromisePlus((resolve, reject) => { - this.connectionResolve = resolve; - this.connectionReject = reject; - this.myClientId = this.myClientId ?? nanoid(10); - const bridgeInstanceId = this.getMyWindowId() || nanoid(10); - const request = { - glue42core: { - type: this.messages.connectionRequest.name, - clientId: this.myClientId, - clientType: "child", - bridgeInstanceId, - selfAssignedWindowId: this.selfAssignedWindowId - } - }; - this.logger.debug(`sending connection request - clientId: ${this.myClientId}`); - if (this.extContentConnecting) { - request.glue42core.clientType = "child"; - request.glue42core.bridgeInstanceId = this.myClientId; - request.glue42core.parentWindowId = this.parentWindowId; - return window.postMessage(request, window.origin); - } - if (!target) { - throw new Error("Cannot send a connection request, because no glue target was specified!"); - } - target.postMessage(request, this.defaultTargetString); - }, this.connectionRequestTimeout, "The connection to the target glue window timed out"); - } - async isParentCheckSuccess(parentCheck) { - try { - await parentCheck; - return { success: true }; - } - catch (error) { - return { success: false }; - } - } - setUpMessageListener() { - if (this.settings.port) { - this.logger.debug("skipping generic message listener, because this is an internal client"); - return; - } - this.logger.debug("setting up window message listener"); - window.addEventListener("message", (event) => { - const data = event.data?.glue42core; - if (!data || this.rejected) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - if (!this.checkMessageTypeValid(data.type)) { - this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${data.type}`); - return; - } - const messageType = data.type; - this.logger.debug(`received valid glue42core message of type: ${messageType}`); - this.messages[messageType].handle(event); - }); - } - setUpUnload() { - if (this.settings.port) { - this.logger.debug("skipping unload event listener, because this is an internal client"); - return; - } - this.logger.debug("setting up unload event listeners"); - window.addEventListener("beforeunload", () => { - if (this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - window.addEventListener("pagehide", () => { - if (!this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - } - signalClientDisappearing() { - if (this.extContentConnected) { - return; - } - this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.parent?.postMessage(message, this.defaultTargetString); - this.port?.postMessage(message); - } - handlePlatformReady(event) { - this.logger.debug("the web platform gave the ready signal"); - this.parentReady = true; - if (this.parentPingResolve) { - this.parentPingResolve(); - delete this.parentPingResolve; - } - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - this.parent = event.source; - this.parentType = window.name.includes("#wsp") ? "workspace" : "window"; - } - handleConnectionAccepted(event) { - const data = event.data?.glue42core; - if (this.myClientId !== data.clientId) { - return this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${data.clientId}`); - } - return this.handleAcceptanceOfMyRequest(data); - } - handleAcceptanceOfMyRequest(data) { - this.logger.debug("handling a connection accepted signal targeted at me."); - this.isPreferredActivated = data.isPreferredActivated; - if (this.extContentConnecting) { - return this.processExtContentConnection(data); - } - if (!data.port) { - this.logger.error("cannot set up my connection, because I was not provided with a port"); - return; - } - this._connectionProtocolVersion = data.connectionProtocolVersion; - this.publicWindowId = this.getMyWindowId(); - if (this.identity) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.identity.instance ? this.identity.instance : this.publicWindowId || nanoid(10); - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - this._communicationId = data.communicationId; - this.port = data.port; - this.port.onmessage = (e) => this.registry.execute("onMessage", e.data); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - this.logger.error("unable to call the connection resolve, because no connection promise was found"); - } - processExtContentConnection(data) { - this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."); - this.extContentConnecting = false; - this.extContentConnected = true; - this.publicWindowId = this.parentWindowId || this.myClientId; - if (this.extContentConnecting && this.identity) { - this.identity.windowId = this.publicWindowId; - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - window.addEventListener("message", (event) => { - const extData = event.data?.glue42ExtInc; - if (!extData) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - this.registry.execute("onMessage", extData); - }); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - } - handleConnectionRejected(event) { - this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"); - if (!this.connectionReject) { - return; - } - const errorMsg = typeof event.data.glue42core?.error === "string" - ? `Connection was rejected. ${event.data.glue42core?.error}` - : "The platform connection was rejected. Most likely because this window was not created by a glue API call"; - this.connectionReject(errorMsg); - delete this.connectionReject; - } - handleConnectionRequest() { - if (this.extContentConnecting) { - this.logger.debug("This connection request event is targeted at the extension content"); - return; - } - } - handleParentPing(event) { - if (!this.parentReady) { - this.logger.debug("my parent is not ready, I am ignoring the parent ping"); - return; - } - if (!this.iAmConnected) { - this.logger.debug("i am not fully connected yet, I am ignoring the parent ping"); - return; - } - const message = { - glue42core: { - type: this.messages.parentReady.name - } - }; - if (this.extContentConnected) { - message.glue42core.extMode = { windowId: this.myClientId }; - } - const source = event.source; - this.logger.debug("responding to a parent ping with a ready message"); - source.postMessage(message, event.origin); - } - setupPlatformUnloadListener() { - this.logger.debug("setting up platform unload listener"); - this.onMessage((msg) => { - if (msg.type === "platformUnload") { - this.logger.debug("detected a web platform unload"); - this.parentReady = false; - this.notifyStatusChanged(false, "Gateway unloaded"); - } - }); - } - handleManualUnload() { - this.logger.debug("handling manual unload"); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: message }, window.origin); - } - this.port?.postMessage(message); - } - handlePlatformPing() { - return; - } - notifyStatusChanged(status, reason) { - this.logger.debug(`status changed - connected: ${status}, reason: ${reason || "none"}`); - this.iAmConnected = status; - this.registry.execute("onConnectedChanged", status, reason); - } - checkMessageTypeValid(typeToValidate) { - return typeof typeToValidate === "string" && !!this.messages[typeToValidate]; - } - requestConnectionPermissionFromExt() { - return this.waitForContentScript() - .then(() => PromisePlus((resolve, reject) => { - this.extConnectionResolve = resolve; - this.extConnectionReject = reject; - const message = { - glue42core: { - type: "extSetupRequest" - } - }; - this.logger.debug("permission request to the extension content script was sent"); - window.postMessage(message, window.origin); - }, this.parentPingTimeout, "Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")); - } - handleExtConnectionResponse(event) { - const data = event.data?.glue42core; - if (!data.approved) { - return this.extConnectionReject ? this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected") : undefined; - } - if (this.extConnectionResolve) { - this.extConnectionResolve(); - delete this.extConnectionResolve; - } - this.extContentConnecting = true; - this.parentType = "extension"; - this.logger.debug("The extension connection was approved, proceeding."); - } - handleExtSetupRequest() { - return; - } - handleGatewayDisconnect() { - return; - } - handleGatewayInternalConnect() { - return; - } - waitForContentScript() { - const contentReady = !!window.glue42ext?.content; - if (contentReady) { - return Promise.resolve(); - } - return PromisePlus((resolve) => { - window.addEventListener("Glue42EXTReady", () => { - resolve(); - }); - }, this.connectionRequestTimeout, "The content script was available, but was never heard to be ready"); - } - async connect() { - if (this.settings.port) { - await this.initiateInternalConnection(); - this.logger.debug("internal web platform connection completed"); - return; - } - this.logger.debug("opening a client web platform connection"); - await this.findParent(); - await this.initiateRemoteConnection(this.parent); - this.logger.debug("the client is connected"); - } - async findParent() { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const myInsideParents = this.getPossibleParentsInWindow(window); - const myOutsideParents = this.getPossibleParentsOutsideWindow(window.top?.opener, window.top); - const uniqueParents = new Set([...myInsideParents, ...myOutsideParents]); - if (!uniqueParents.size && !this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - if (!uniqueParents.size && this.extContentAvailable) { - await this.requestConnectionPermissionFromExt(); - return; - } - const defaultParentCheck = await this.isParentCheckSuccess(this.confirmParent(Array.from(uniqueParents))); - if (defaultParentCheck.success) { - this.logger.debug("The default parent was found!"); - return; - } - if (!this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - await this.requestConnectionPermissionFromExt(); - } - getPossibleParentsInWindow(currentWindow) { - return (!currentWindow?.parent || currentWindow === currentWindow.parent) ? [] : [currentWindow.parent, ...this.getPossibleParentsInWindow(currentWindow.parent)]; - } - getPossibleParentsOutsideWindow(opener, current) { - return (!opener || !current || opener === current) ? [] : [opener, ...this.getPossibleParentsInWindow(opener), ...this.getPossibleParentsOutsideWindow(opener.opener, opener)]; - } - confirmParent(targets) { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const parentCheck = PromisePlus((resolve) => { - this.parentPingResolve = resolve; - const message = { - glue42core: { - type: this.messages.platformPing.name - } - }; - this.parentPingInterval = setInterval(() => { - targets.forEach((target) => { - target.postMessage(message, this.defaultTargetString); - }); - }, 1000); - }, this.parentPingTimeout, connectionNotPossibleMsg); - parentCheck.catch(() => { - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - }); - return parentCheck; - } - getMyWindowId() { - if (this.parentType === "workspace") { - return window.name.substring(0, window.name.indexOf("#wsp")); - } - if (window !== window.top) { - return; - } - if (window.name?.includes("g42")) { - return window.name; - } - this.selfAssignedWindowId = this.selfAssignedWindowId || `g42-${nanoid(10)}`; - return this.selfAssignedWindowId; - } - } - - const waitForInvocations = (invocations, callback) => { - let left = invocations; - return () => { - left--; - if (left === 0) { - callback(); - } - }; - }; - - class AsyncSequelizer { - minSequenceInterval; - queue = []; - isExecutingQueue = false; - constructor(minSequenceInterval = 0) { - this.minSequenceInterval = minSequenceInterval; - } - enqueue(action) { - return new Promise((resolve, reject) => { - this.queue.push({ action, resolve, reject }); - this.executeQueue(); - }); - } - async executeQueue() { - if (this.isExecutingQueue) { - return; - } - this.isExecutingQueue = true; - while (this.queue.length) { - const operation = this.queue.shift(); - if (!operation) { - this.isExecutingQueue = false; - return; - } - try { - const actionResult = await operation.action(); - operation.resolve(actionResult); - } - catch (error) { - operation.reject(error); - } - await this.intervalBreak(); - } - this.isExecutingQueue = false; - } - intervalBreak() { - return new Promise((res) => setTimeout(res, this.minSequenceInterval)); - } - } - - function domainSession (domain, connection, logger, successMessages, errorMessages) { - if (domain == null) { - domain = "global"; - } - successMessages = successMessages ?? ["success"]; - errorMessages = errorMessages ?? ["error"]; - let isJoined = domain === "global"; - let tryReconnecting = false; - let _latestOptions; - let _connectionOn = false; - const callbacks = CallbackRegistryFactory(); - connection.disconnected(handleConnectionDisconnected); - connection.loggedIn(handleConnectionLoggedIn); - connection.on("success", (msg) => handleSuccessMessage(msg)); - connection.on("error", (msg) => handleErrorMessage(msg)); - connection.on("result", (msg) => handleSuccessMessage(msg)); - if (successMessages) { - successMessages.forEach((sm) => { - connection.on(sm, (msg) => handleSuccessMessage(msg)); - }); - } - if (errorMessages) { - errorMessages.forEach((sm) => { - connection.on(sm, (msg) => handleErrorMessage(msg)); - }); - } - const requestsMap = {}; - function join(options) { - _latestOptions = options; - return new Promise((resolve, reject) => { - if (isJoined) { - resolve({}); - return; - } - let joinPromise; - if (domain === "global") { - joinPromise = _connectionOn ? Promise.resolve({}) : Promise.reject("not connected to gateway"); - } - else { - logger.debug(`joining domain ${domain}`); - const joinMsg = { - type: "join", - destination: domain, - domain: "global", - options, - }; - joinPromise = send(joinMsg); - } - joinPromise - .then(() => { - handleJoined(); - resolve({}); - }) - .catch((err) => { - logger.debug("error joining " + domain + " domain: " + JSON.stringify(err)); - reject(err); - }); - }); - } - function leave() { - if (domain === "global") { - return Promise.resolve(); - } - logger.debug("stopping session " + domain + "..."); - const leaveMsg = { - type: "leave", - destination: domain, - domain: "global", - }; - tryReconnecting = false; - return send(leaveMsg) - .then(() => { - isJoined = false; - callbacks.execute("onLeft"); - }) - .catch(() => { - isJoined = false; - callbacks.execute("onLeft"); - }); - } - function handleJoined() { - logger.debug("did join " + domain); - isJoined = true; - const wasReconnect = tryReconnecting; - tryReconnecting = false; - callbacks.execute("onJoined", wasReconnect); - } - function handleConnectionDisconnected() { - logger.debug("connection is down"); - _connectionOn = false; - isJoined = false; - tryReconnecting = true; - Object.keys(requestsMap).forEach(requestId => { - const request = requestsMap[requestId]; - if (request) { - logger.trace(`failing pending request ${requestId} due to connection lost`); - request.error({ - err: "Connection lost - gateway connection was disconnected" - }); - } - }); - callbacks.execute("onLeft", { disconnected: true }); - } - async function handleConnectionLoggedIn() { - _connectionOn = true; - if (tryReconnecting) { - logger.debug("connection is now up - trying to reconnect..."); - try { - await join(_latestOptions); - } - catch { - logger.trace(`failed to reconnect`); - } - } - } - function onJoined(callback) { - if (isJoined) { - callback(false); - } - return callbacks.add("onJoined", callback); - } - function onLeft(callback) { - if (!isJoined) { - callback(); - } - return callbacks.add("onLeft", callback); - } - function handleErrorMessage(msg) { - if (domain !== msg.domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.error(msg); - } - function handleSuccessMessage(msg) { - if (msg.domain !== domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.success(msg); - } - function getNextRequestId() { - return nanoid(10); - } - let queuedCalls = []; - function send(msg, tag, options) { - const ignore = ["hello", "join"]; - if (msg.type && ignore.indexOf(msg.type) === -1) { - if (!isJoined) { - console.warn(`trying to send a message (${msg.domain} ${msg.type}) but not connected, will queue`); - const pw = new PromiseWrapper(); - queuedCalls.push({ msg, tag, options, pw }); - if (queuedCalls.length === 1) { - const unsubscribe = onJoined(() => { - logger.info(`joined - will now send queued messages (${queuedCalls.length} -> [${queuedCalls.map((m) => m.msg.type)}])`); - queuedCalls.forEach((qm) => { - send(qm.msg, qm.tag, qm.options) - .then((t) => qm.pw.resolve(t)) - .catch((e) => qm.pw.reject(e)); - }); - queuedCalls = []; - unsubscribe(); - }); - } - return pw.promise; - } - } - options = options ?? {}; - msg.request_id = msg.request_id ?? getNextRequestId(); - msg.domain = msg.domain ?? domain; - if (!options.skipPeerId) { - msg.peer_id = connection.peerId; - } - const requestId = msg.request_id; - return new Promise((resolve, reject) => { - requestsMap[requestId] = { - success: (successMsg) => { - delete requestsMap[requestId]; - successMsg._tag = tag; - resolve(successMsg); - }, - error: (errorMsg) => { - console.warn(`Gateway error - ${JSON.stringify(errorMsg)}`); - delete requestsMap[requestId]; - errorMsg._tag = tag; - reject(errorMsg); - }, - }; - connection - .send(msg, options) - .catch((err) => { - requestsMap[requestId]?.error({ err }); - }); - }); - } - function sendFireAndForget(msg) { - msg.request_id = msg.request_id ? msg.request_id : getNextRequestId(); - msg.domain = msg.domain ?? domain; - msg.peer_id = connection.peerId; - return connection.send(msg); - } - return { - join, - leave, - onJoined, - onLeft, - send, - sendFireAndForget, - on: (type, callback) => { - connection.on(type, (msg) => { - if (msg.domain !== domain) { - return; - } - try { - callback(msg); - } - catch (e) { - logger.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(msg)}`, e); - } - }); - }, - loggedIn: (callback) => connection.loggedIn(callback), - connected: (callback) => connection.connected(callback), - disconnected: (callback) => connection.disconnected(callback), - get peerId() { - return connection.peerId; - }, - get domain() { - return domain; - }, - }; - } - - class Connection { - settings; - logger; - protocolVersion = 3; - peerId; - token; - info; - resolvedIdentity; - availableDomains; - gatewayToken; - replayer; - messageHandlers = {}; - ids = 1; - registry = CallbackRegistryFactory(); - _connected = false; - isTrace = false; - transport; - _defaultTransport; - _defaultAuth; - _targetTransport; - _targetAuth; - _swapTransport = false; - _switchInProgress = false; - _transportSubscriptions = []; - datePrefix = "#T42_DATE#"; - datePrefixLen = this.datePrefix.length; - dateMinLen = this.datePrefixLen + 1; - datePrefixFirstChar = this.datePrefix[0]; - _sequelizer = new AsyncSequelizer(); - _isLoggedIn = false; - shouldTryLogin = true; - pingTimer; - sessions = []; - globalDomain; - initialLogin = true; - initialLoginAttempts = 3; - loginConfig; - loginRetryInProgress = false; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - settings = settings || {}; - settings.reconnectAttempts = settings.reconnectAttempts ?? 10; - settings.reconnectInterval = settings.reconnectInterval ?? 1000; - if (settings.inproc) { - this.transport = new InProcTransport(settings.inproc, logger.subLogger("inMemory")); - } - else if (settings.sharedWorker) { - this.transport = new SharedWorkerTransport(settings.sharedWorker, logger.subLogger("shared-worker")); - } - else if (settings.webPlatform) { - this.transport = new WebPlatformTransport(settings.webPlatform, logger.subLogger("web-platform"), settings.identity); - } - else if (settings.ws !== undefined) { - this.transport = new WS(settings, logger.subLogger("ws")); - } - else { - throw new Error("No connection information specified"); - } - this.isTrace = logger.canPublish("trace"); - logger.debug(`starting with ${this.transport.name()} transport`); - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - this._defaultTransport = this.transport; - this.ping(); - } - async switchTransport(settings) { - return this._sequelizer.enqueue(async () => { - if (!settings || typeof settings !== "object") { - throw new Error("Cannot switch transports, because the settings are missing or invalid."); - } - if (typeof settings.type === "undefined") { - throw new Error("Cannot switch the transport, because the type is not defined"); - } - this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(settings)}`); - const switchTargetTransport = settings.type === "secondary" ? this.getNewSecondaryTransport(settings) : this._defaultTransport; - this._targetTransport = switchTargetTransport; - this._targetAuth = settings.type === "secondary" ? this.getNewSecondaryAuth(settings) : this._defaultAuth; - const verifyPromise = this.verifyConnection(); - this._swapTransport = true; - this._switchInProgress = true; - this.logger.trace("The new transport has been set, closing the current transport"); - await this.transport.close(); - try { - await verifyPromise; - const isSwitchSuccess = this.transport === switchTargetTransport; - this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${isSwitchSuccess}`); - this._switchInProgress = false; - return { success: isSwitchSuccess }; - } - catch (error) { - this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."); - this.switchTransport({ type: "default" }); - this._switchInProgress = false; - return { success: false }; - } - }); - } - onLibReAnnounced(callback) { - return this.registry.add("libReAnnounced", callback); - } - setLibReAnnounced(lib) { - this.registry.execute("libReAnnounced", lib); - } - send(message, options) { - if (this.transport.sendObject && - this.transport.isObjectBasedTransport) { - const msg = this.createObjectMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${JSON.stringify(msg)}`); - } - return this.transport.sendObject(msg, options); - } - else { - const strMessage = this.createStringMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${strMessage}`); - } - return this.transport.send(strMessage, options); - } - } - on(type, messageHandler) { - type = type.toLowerCase(); - if (this.messageHandlers[type] === undefined) { - this.messageHandlers[type] = {}; - } - const id = this.ids++; - this.messageHandlers[type][id] = messageHandler; - return { - type, - id, - }; - } - off(info) { - delete this.messageHandlers[info.type.toLowerCase()][info.id]; - } - get isConnected() { - return this._isLoggedIn; - } - connected(callback) { - return this.loggedIn(() => { - const currentServer = this.transport.name(); - callback(currentServer); - }); - } - disconnected(callback) { - return this.registry.add("disconnected", callback); - } - async login(authRequest, reconnect) { - this.logger.debug(`Login initiated - reconnect: ${reconnect}, transport: ${this.transport.name()}`); - if (!this._defaultAuth) { - this._defaultAuth = authRequest; - } - if (this._swapTransport) { - this.logger.trace("Detected a transport swap, swapping transports"); - const newAuth = this.transportSwap(); - authRequest = newAuth ?? authRequest; - } - try { - await this.transport.open(); - this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`); - timer("connection").mark("transport-opened"); - const identity = await this.loginCore(authRequest, reconnect); - this.logger.debug(`Logged in with identity: ${JSON.stringify(identity)}`); - timer("connection").mark("protocol-logged-in"); - return identity; - } - catch (error) { - if (this._switchInProgress) { - this.logger.debug("An error while logging in after a transport swap, preparing a default swap."); - this.prepareDefaultSwap(); - } - throw new Error(error); - } - } - async logout() { - await this.logoutCore(); - await this.transport.close(); - } - loggedIn(callback) { - if (this._isLoggedIn) { - callback(); - } - return this.registry.add("onLoggedIn", callback); - } - domain(domain, successMessages, errorMessages) { - let session = this.sessions.find((s) => s.domain === domain); - if (!session) { - session = domainSession(domain, this, this.logger.subLogger(`domain=${domain}`), successMessages, errorMessages); - this.sessions.push(session); - } - return session; - } - authToken() { - const createTokenReq = { - domain: "global", - type: "create-token" - }; - if (!this.globalDomain) { - return Promise.reject(new Error("no global domain session")); - } - return this.globalDomain.send(createTokenReq) - .then((res) => { - return res.token; - }); - } - reconnect() { - return this.transport.reconnect(); - } - setLoggedIn(value) { - this._isLoggedIn = value; - if (this._isLoggedIn) { - this.initialLogin = false; - this.registry.execute("onLoggedIn"); - } - } - distributeMessage(message, type) { - const handlers = this.messageHandlers[type.toLowerCase()]; - if (handlers !== undefined) { - Object.keys(handlers).forEach((handlerId) => { - const handler = handlers[handlerId]; - if (handler !== undefined) { - try { - handler(message); - } - catch (error) { - try { - this.logger.error(`Message handler failed with ${error.stack}`, error); - } - catch (loggerError) { - console.log("Message handler failed", error); - } - } - } - }); - } - } - handleConnectionChanged(connected) { - if (this._connected === connected) { - this.logger.trace("connection state unchanged, skipping"); - return; - } - this.logger.info(`connection state changed to ${connected ? "connected" : "disconnected"}`); - this._connected = connected; - if (connected) { - if (this.settings?.replaySpecs?.length) { - this.replayer = new MessageReplayerImpl(this.settings.replaySpecs); - this.replayer.init(this); - } - this.registry.execute("connected"); - } - else { - this.setLoggedIn(false); - if (this.shouldTryLogin) { - this.attemptLoginWithRetry(); - } - this.registry.execute("disconnected"); - } - } - async attemptLoginWithRetry() { - if (!this.loginConfig) { - throw new Error("no login info"); - } - if (this.loginRetryInProgress) { - this.logger.debug("login attempt already in progress, ignoring request..."); - return; - } - if (this._isLoggedIn) { - this.logger.debug("already logged in, ignoring request..."); - return; - } - if (this.initialLogin) { - this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`); - if (this.initialLoginAttempts <= 0) { - this.logger.info("maximum initial login attempts reached, will not try to login again"); - return; - } - this.initialLoginAttempts--; - } - try { - this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`); - this.loginRetryInProgress = true; - await this.login(this.loginConfig, true); - } - catch (e) { - this.logger.error(`error trying to login: ${e?.message}`, e); - setTimeout(this.attemptLoginWithRetry.bind(this), this.settings.reconnectInterval ?? 1000); - } - finally { - this.loginRetryInProgress = false; - } - } - handleTransportMessage(msg) { - let msgObj; - if (typeof msg === "string") { - msgObj = this.processStringMessage(msg); - } - else { - msgObj = this.processObjectMessage(msg); - } - if (this.isTrace) { - this.logger.trace(`<< ${JSON.stringify(msgObj)}`); - } - this.distributeMessage(msgObj.msg, msgObj.msgType); - } - verifyConnection() { - return PromisePlus((resolve) => { - let unsub; - const ready = waitForInvocations(2, () => { - if (unsub) { - unsub(); - } - resolve(); - }); - unsub = this.onLibReAnnounced((lib) => { - if (lib.name === "interop") { - return ready(); - } - if (lib.name === "contexts") { - return ready(); - } - }); - }, 10000, "Transport switch timed out waiting for all libraries to be re-announced"); - } - getNewSecondaryTransport(settings) { - if (!settings.transportConfig?.url) { - throw new Error("Missing secondary transport URL."); - } - return new WS(Object.assign({}, this.settings, { ws: settings.transportConfig.url, reconnectAttempts: 1 }), this.logger.subLogger("ws-secondary")); - } - getNewSecondaryAuth(settings) { - if (!settings.transportConfig?.auth) { - throw new Error("Missing secondary transport auth information."); - } - return settings.transportConfig.auth; - } - transportSwap() { - this._swapTransport = false; - if (!this._targetTransport || !this._targetAuth) { - this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`); - return; - } - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport = this._targetTransport; - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - return this._targetAuth; - } - prepareDefaultSwap() { - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport.close().catch((error) => this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(error)}`)); - this._targetTransport = this._defaultTransport; - this._targetAuth = this._defaultAuth; - this._swapTransport = true; - } - processStringMessage(message) { - const msg = JSON.parse(message, (key, value) => { - if (typeof value !== "string") { - return value; - } - if (value.length < this.dateMinLen) { - return value; - } - if (!value.startsWith(this.datePrefixFirstChar)) { - return value; - } - if (value.substring(0, this.datePrefixLen) !== this.datePrefix) { - return value; - } - try { - const milliseconds = parseInt(value.substring(this.datePrefixLen, value.length), 10); - if (isNaN(milliseconds)) { - return value; - } - return new Date(milliseconds); - } - catch (ex) { - return value; - } - }); - return { - msg, - msgType: msg.type, - }; - } - createStringMessage(message) { - const oldToJson = Date.prototype.toJSON; - try { - const datePrefix = this.datePrefix; - Date.prototype.toJSON = function () { - return datePrefix + this.getTime(); - }; - const result = JSON.stringify(message); - return result; - } - finally { - Date.prototype.toJSON = oldToJson; - } - } - processObjectMessage(message) { - if (!message.type) { - throw new Error("Object should have type property"); - } - return { - msg: message, - msgType: message.type, - }; - } - createObjectMessage(message) { - return message; - } - async loginCore(config, reconnect) { - this.loginConfig = config; - if (!this.loginConfig) { - this.loginConfig = { username: "", password: "" }; - } - this.shouldTryLogin = true; - const authentication = await this.setupAuthConfig(config, reconnect); - const helloMsg = { - type: "hello", - identity: this.settings.identity, - authentication - }; - if (config.sessionId) { - helloMsg.request_id = config.sessionId; - } - if (!this.globalDomain) { - this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [ - "welcome", - "token", - "authentication-request" - ]); - } - const sendOptions = { skipPeerId: true }; - if (this.initialLogin) { - sendOptions.retryInterval = this.settings.reconnectInterval; - sendOptions.maxRetries = this.settings.reconnectAttempts; - } - try { - const welcomeMsg = await this.tryAuthenticate(this.globalDomain, helloMsg, sendOptions, config); - this.logger.info("login successful with peerId " + welcomeMsg.peer_id); - this.peerId = welcomeMsg.peer_id; - this.resolvedIdentity = welcomeMsg.resolved_identity; - this.availableDomains = welcomeMsg.available_domains; - if (welcomeMsg.options) { - this.token = welcomeMsg.options.access_token; - this.info = welcomeMsg.options.info; - } - this.setLoggedIn(true); - return welcomeMsg.resolved_identity; - } - catch (err) { - this.logger.error("error sending hello message - " + (err.message || err.msg || err.reason || err), err); - throw err; - } - finally { - if (config?.flowCallback && config.sessionId) { - config.flowCallback(config.sessionId, null); - } - } - } - async tryAuthenticate(globalDomain, helloMsg, sendOptions, config) { - let welcomeMsg; - while (true) { - const msg = await globalDomain.send(helloMsg, undefined, sendOptions); - if (msg.type === "authentication-request") { - const token = Buffer.from(msg.authentication.token, "base64"); - if (config.flowCallback && config.sessionId) { - helloMsg.authentication.token = - (await config.flowCallback(config.sessionId, token)) - .data - .toString("base64"); - } - helloMsg.request_id = config.sessionId; - } - else if (msg.type === "welcome") { - welcomeMsg = msg; - break; - } - else if (msg.type === "error") { - throw new Error("Authentication failed: " + msg.reason); - } - else { - throw new Error("Unexpected message type during authentication: " + msg.type); - } - } - return welcomeMsg; - } - async setupAuthConfig(config, reconnect) { - const authentication = {}; - this.gatewayToken = config.gatewayToken; - if (config.gatewayToken) { - if (reconnect) { - try { - config.gatewayToken = await this.getNewGWToken(); - } - catch (e) { - this.logger.warn(`failed to get GW token when reconnecting ${e?.message || e}`); - } - } - authentication.method = "gateway-token"; - authentication.token = config.gatewayToken; - this.gatewayToken = config.gatewayToken; - } - else if (config.flowName === "sspi") { - authentication.provider = "win"; - authentication.method = "access-token"; - if (config.flowCallback && config.sessionId) { - authentication.token = - (await config.flowCallback(config.sessionId, null)) - .data - .toString("base64"); - } - else { - throw new Error("Invalid SSPI config"); - } - } - else if (config.token) { - authentication.method = "access-token"; - authentication.token = config.token; - } - else if (config.username) { - authentication.method = "secret"; - authentication.login = config.username; - authentication.secret = config.password; - } - else if (config.provider) { - authentication.provider = config.provider; - authentication.providerContext = config.providerContext; - } - else { - throw new Error("invalid auth message" + JSON.stringify(config)); - } - return authentication; - } - async logoutCore() { - this.logger.debug("core logging out..."); - this.shouldTryLogin = false; - if (this.pingTimer) { - clearTimeout(this.pingTimer); - } - const promises = this.sessions.map((session) => { - return session.leave(); - }); - await Promise.all(promises); - } - getNewGWToken() { - if (typeof window !== "undefined") { - const glue42gd = window.glue42gd; - if (glue42gd) { - return glue42gd.getGWToken(); - } - } - return Promise.reject(new Error("not running in GD")); - } - ping() { - if (!this.shouldTryLogin) { - return; - } - if (this._isLoggedIn) { - this.send({ type: "ping" }); - } - this.pingTimer = setTimeout(() => { - this.ping(); - }, 30 * 1000); - } - } - - const order = ["trace", "debug", "info", "warn", "error", "off"]; - class Logger { - name; - parent; - static Interop; - static InteropMethodName = "T42.AppLogger.Log"; - static Instance; - path; - subLoggers = []; - _consoleLevel; - _publishLevel; - loggerFullName; - includeTimeAndLevel; - logFn = console; - customLogFn = false; - constructor(name, parent, logFn) { - this.name = name; - this.parent = parent; - this.name = name; - if (parent) { - this.path = `${parent.path}.${name}`; - } - else { - this.path = name; - } - this.loggerFullName = `[${this.path}]`; - this.includeTimeAndLevel = !logFn; - if (logFn) { - this.logFn = logFn; - this.customLogFn = true; - } - } - subLogger(name) { - const existingSub = this.subLoggers.filter((subLogger) => { - return subLogger.name === name; - })[0]; - if (existingSub !== undefined) { - return existingSub; - } - Object.keys(this).forEach((key) => { - if (key === name) { - throw new Error("This sub logger name is not allowed."); - } - }); - const sub = new Logger(name, this, this.customLogFn ? this.logFn : undefined); - this.subLoggers.push(sub); - return sub; - } - publishLevel(level) { - if (level) { - this._publishLevel = level; - } - return this._publishLevel || this.parent?.publishLevel(); - } - consoleLevel(level) { - if (level) { - this._consoleLevel = level; - } - return this._consoleLevel || this.parent?.consoleLevel(); - } - log(message, level, error) { - this.publishMessage(level || "info", message, error); - } - trace(message) { - this.log(message, "trace"); - } - debug(message) { - this.log(message, "debug"); - } - info(message) { - this.log(message, "info"); - } - warn(message) { - this.log(message, "warn"); - } - error(message, err) { - this.log(message, "error", err); - } - canPublish(level, compareWith) { - const levelIdx = order.indexOf(level); - const restrictionIdx = order.indexOf(compareWith || this.consoleLevel() || "trace"); - return levelIdx >= restrictionIdx; - } - publishMessage(level, message, error) { - const loggerName = this.loggerFullName; - if (level === "error" && !error) { - const e = new Error(); - if (e.stack) { - message = - message + - "\n" + - e.stack - .split("\n") - .slice(4) - .join("\n"); - } - } - if (this.canPublish(level, this.publishLevel())) { - const interop = Logger.Interop; - if (interop) { - try { - if (interop.methods({ name: Logger.InteropMethodName }).length > 0) { - const args = { - msg: message, - logger: loggerName, - level - }; - if (error && error instanceof Error) { - args.error = { - message: error.message, - stack: error.stack ?? "" - }; - } - interop.invoke(Logger.InteropMethodName, args) - .catch((e) => { - this.logFn.error(`Unable to send log message to the platform: ${e.message}`, e); - }); - } - } - catch { - } - } - } - if (this.canPublish(level)) { - let prefix = ""; - if (this.includeTimeAndLevel) { - const date = new Date(); - const time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`; - prefix = `[${time}] [${level}] `; - } - const toPrint = `${prefix}${loggerName}: ${message}`; - switch (level) { - case "trace": - this.logFn.debug(toPrint); - break; - case "debug": - if (this.logFn.debug) { - this.logFn.debug(toPrint); - } - else { - this.logFn.log(toPrint); - } - break; - case "info": - this.logFn.info(toPrint); - break; - case "warn": - this.logFn.warn(toPrint); - break; - case "error": - if (error) { - this.logFn.error(toPrint, error); - } - else { - this.logFn.error(toPrint); - } - break; - } - } - } - } - - const GW_MESSAGE_CREATE_CONTEXT = "create-context"; - const GW_MESSAGE_ACTIVITY_CREATED = "created"; - const GW_MESSAGE_ACTIVITY_DESTROYED = "destroyed"; - const GW_MESSAGE_CONTEXT_CREATED = "context-created"; - const GW_MESSAGE_CONTEXT_ADDED = "context-added"; - const GW_MESSAGE_SUBSCRIBE_CONTEXT = "subscribe-context"; - const GW_MESSAGE_SUBSCRIBED_CONTEXT = "subscribed-context"; - const GW_MESSAGE_UNSUBSCRIBE_CONTEXT = "unsubscribe-context"; - const GW_MESSAGE_DESTROY_CONTEXT = "destroy-context"; - const GW_MESSAGE_CONTEXT_DESTROYED = "context-destroyed"; - const GW_MESSAGE_UPDATE_CONTEXT = "update-context"; - const GW_MESSAGE_CONTEXT_UPDATED = "context-updated"; - const GW_MESSAGE_JOINED_ACTIVITY = "joined"; - - const ContextMessageReplaySpec = { - get name() { - return "context"; - }, - get types() { - return [ - GW_MESSAGE_CREATE_CONTEXT, - GW_MESSAGE_ACTIVITY_CREATED, - GW_MESSAGE_ACTIVITY_DESTROYED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_SUBSCRIBE_CONTEXT, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - GW_MESSAGE_DESTROY_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_UPDATE_CONTEXT, - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_JOINED_ACTIVITY - ]; - } - }; - - var version = "6.8.1"; - - function prepareConfig (configuration, ext, glue42gd) { - let nodeStartingContext; - if (Utils.isNode()) { - const startingContextString = process.env._GD_STARTING_CONTEXT_; - if (startingContextString) { - try { - nodeStartingContext = JSON.parse(startingContextString); - } - catch { - } - } - } - function getConnection() { - const gwConfig = configuration.gateway; - const protocolVersion = gwConfig?.protocolVersion ?? 3; - const reconnectInterval = gwConfig?.reconnectInterval; - const reconnectAttempts = gwConfig?.reconnectAttempts; - const defaultWs = "ws://localhost:8385"; - let ws = gwConfig?.ws; - const sharedWorker = gwConfig?.sharedWorker; - const inproc = gwConfig?.inproc; - const webPlatform = gwConfig?.webPlatform ?? undefined; - if (glue42gd) { - ws = glue42gd.gwURL; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) { - ws = nodeStartingContext.gwURL; - } - if (!ws && !sharedWorker && !inproc) { - ws = defaultWs; - } - let instanceId; - let windowId; - let pid; - let environment; - let region; - const appName = getApplication(); - let uniqueAppName = appName; - if (typeof glue42gd !== "undefined") { - windowId = glue42gd.windowId; - pid = glue42gd.pid; - if (glue42gd.env) { - environment = glue42gd.env.env; - region = glue42gd.env.region; - } - uniqueAppName = glue42gd.application ?? "glue-app"; - instanceId = glue42gd.appInstanceId; - } - else if (Utils.isNode()) { - pid = process.pid; - if (nodeStartingContext) { - environment = nodeStartingContext.env; - region = nodeStartingContext.region; - instanceId = nodeStartingContext.instanceId; - } - } - else if (typeof window?.glue42electron !== "undefined") { - windowId = window?.glue42electron.instanceId; - pid = window?.glue42electron.pid; - environment = window?.glue42electron.env; - region = window?.glue42electron.region; - uniqueAppName = window?.glue42electron.application ?? "glue-app"; - instanceId = window?.glue42electron.instanceId; - } - else ; - const replaySpecs = configuration.gateway?.replaySpecs ?? []; - replaySpecs.push(ContextMessageReplaySpec); - let identity = { - application: uniqueAppName, - applicationName: appName, - windowId, - instance: instanceId, - process: pid, - region, - environment, - api: ext.version || version - }; - if (configuration.identity) { - identity = Object.assign(identity, configuration.identity); - } - return { - identity, - reconnectInterval, - ws, - sharedWorker, - webPlatform, - inproc, - protocolVersion, - reconnectAttempts, - replaySpecs, - }; - } - function getContexts() { - const defaultConfig = { - reAnnounceKnownContexts: true, - subscribeOnUpdate: true, - subscribeOnGet: true, - onlyReAnnounceSubscribedContexts: true - }; - if (typeof configuration.contexts === "undefined") { - return defaultConfig; - } - if (typeof configuration.contexts === "boolean" && configuration.contexts) { - return defaultConfig; - } - if (typeof configuration.contexts === "object") { - return { ...defaultConfig, ...configuration.contexts }; - } - return false; - } - function getApplication() { - if (configuration.application) { - return configuration.application; - } - if (glue42gd) { - return glue42gd.applicationName; - } - if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") { - return window.glue42electron.application; - } - const uid = nanoid(10); - if (Utils.isNode()) { - if (nodeStartingContext) { - return nodeStartingContext.applicationConfig.name; - } - return "NodeJS" + uid; - } - if (typeof window !== "undefined" && typeof document !== "undefined") { - return document.title + ` (${uid})`; - } - return uid; - } - function getAuth() { - if (typeof configuration.auth === "string") { - return { - token: configuration.auth - }; - } - if (configuration.auth) { - return configuration.auth; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) { - return { - gatewayToken: nodeStartingContext.gwToken - }; - } - if (configuration.gateway?.webPlatform) { - return { - username: "glue42", - password: "" - }; - } - } - function getLogger() { - let config = configuration.logger; - const defaultLevel = "warn"; - if (!config) { - config = defaultLevel; - } - let gdConsoleLevel; - if (glue42gd) { - gdConsoleLevel = glue42gd.consoleLogLevel; - } - if (typeof config === "string") { - return { console: gdConsoleLevel ?? config, publish: defaultLevel }; - } - return { - console: gdConsoleLevel ?? config.console ?? defaultLevel, - publish: config.publish ?? defaultLevel - }; - } - const connection = getConnection(); - let application = getApplication(); - if (typeof window !== "undefined") { - const windowAsAny = window; - const containerApplication = windowAsAny.htmlContainer ? - `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` : - windowAsAny?.glue42gd?.application; - if (containerApplication) { - application = containerApplication; - } - } - return { - bus: configuration.bus ?? false, - application, - auth: getAuth(), - logger: getLogger(), - connection, - metrics: configuration.metrics ?? true, - contexts: getContexts(), - version: ext.version || version, - libs: ext.libs ?? [], - customLogger: configuration.customLogger - }; - } - - class GW3ContextData { - name; - contextId; - context; - isAnnounced; - createdByUs; - joinedActivity; - updateCallbacks = {}; - activityId; - sentExplicitSubscription; - get hasReceivedSnapshot() { - return this.snapshotPromiseWrapper.resolved; - } - set hasReceivedSnapshot(has) { - if (has) { - this.snapshotPromiseWrapper.resolve(); - } - else { - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - } - get snapshotPromise() { - return this.snapshotPromiseWrapper.promise; - } - snapshotPromiseWrapper; - constructor(contextId, name, isAnnounced, activityId) { - this.contextId = contextId; - this.name = name; - this.isAnnounced = isAnnounced; - this.activityId = activityId; - this.context = {}; - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - hasCallbacks() { - return Object.keys(this.updateCallbacks).length > 0; - } - getState() { - if (this.isAnnounced && this.hasCallbacks()) { - return 3; - } - if (this.isAnnounced) { - return 2; - } - if (this.hasCallbacks()) { - return 1; - } - return 0; - } - } - - var lodash_clonedeep = {exports: {}}; - - /** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - lodash_clonedeep.exports; - - (function (module, exports) { - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** - * Adds the key-value `pair` to `map`. - * - * @private - * @param {Object} map The map to modify. - * @param {Array} pair The key-value pair to add. - * @returns {Object} Returns `map`. - */ - function addMapEntry(map, pair) { - // Don't return `map.set` because it's not chainable in IE 11. - map.set(pair[0], pair[1]); - return map; - } - - /** - * Adds `value` to `set`. - * - * @private - * @param {Object} set The set to modify. - * @param {*} value The value to add. - * @returns {Object} Returns `set`. - */ - function addSetEntry(set, value) { - // Don't return `set.add` because it's not chainable in IE 11. - set.add(value); - return set; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array ? array.length : 0; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array ? array.length : 0; - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ - function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var objectToString = objectProto.toString; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined, - Symbol = root.Symbol, - Uint8Array = root.Uint8Array, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeKeys = overArg(Object.keys, Object); - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'), - Map = getNative(root, 'Map'), - Promise = getNative(root, 'Promise'), - Set = getNative(root, 'Set'), - WeakMap = getNative(root, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - this.__data__ = new ListCache(entries); - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - return this.__data__['delete'](key); - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var cache = this.__data__; - if (cache instanceof ListCache) { - var pairs = cache.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - return this; - } - cache = this.__data__ = new MapCache(pairs); - } - cache.set(key, value); - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - - var length = result.length, - skipIndexes = !!length; - - for (var key in value) { - if ((hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {boolean} [isFull] Specify a clone including symbols. - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, isFull, customizer, key, object, stack) { - var result; - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - if (isHostObject(value)) { - return object ? value : {}; - } - result = initCloneObject(isFunc ? {} : value); - if (!isDeep) { - return copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, baseClone, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (!isArr) { - var props = isFull ? getAllKeys(value) : keys(value); - } - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(proto) { - return isObject(proto) ? objectCreate(proto) : {}; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - return objectToString.call(value); - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var result = new buffer.constructor(buffer.length); - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `map`. - * - * @private - * @param {Object} map The map to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned map. - */ - function cloneMap(map, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); - return arrayReduce(array, addMapEntry, new map.constructor); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of `set`. - * - * @private - * @param {Object} set The set to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned set. - */ - function cloneSet(set, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); - return arrayReduce(array, addSetEntry, new set.constructor); - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = undefined; - - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; - } - - /** - * Copies own symbol properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * Creates an array of the own enumerable symbol properties of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11, - // for data views in Edge < 14, and promises in Node.js. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = objectToString.call(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : undefined; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, cloneFunc, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return cloneMap(object, isDeep, cloneFunc); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return cloneSet(object, isDeep, cloneFunc); - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, true, true); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return !!value && typeof value == 'object'; - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - module.exports = cloneDeep; - } (lodash_clonedeep, lodash_clonedeep.exports)); - - var lodash_clonedeepExports = lodash_clonedeep.exports; - var cloneDeep = /*@__PURE__*/getDefaultExportFromCjs(lodash_clonedeepExports); - - function applyContextDelta(context, delta, logger) { - try { - if (logger?.canPublish("trace")) { - logger?.trace(`applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`); - } - if (!delta) { - return context; - } - if (delta.reset) { - context = { ...delta.reset }; - return context; - } - context = deepClone(context, undefined); - if (delta.commands) { - for (const command of delta.commands) { - if (command.type === "remove") { - deletePath(context, command.path); - } - else if (command.type === "set") { - setValueToPath(context, command.value, command.path); - } - } - return context; - } - const added = delta.added; - const updated = delta.updated; - const removed = delta.removed; - if (added) { - Object.keys(added).forEach((key) => { - context[key] = added[key]; - }); - } - if (updated) { - Object.keys(updated).forEach((key) => { - mergeObjectsProperties(key, context, updated); - }); - } - if (removed) { - removed.forEach((key) => { - delete context[key]; - }); - } - return context; - } - catch (e) { - logger?.error(`error applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`, e); - return context; - } - } - function deepClone(obj, hash) { - return cloneDeep(obj); - } - const mergeObjectsProperties = (key, what, withWhat) => { - const right = withWhat[key]; - if (right === undefined) { - return what; - } - const left = what[key]; - if (!left || !right) { - what[key] = right; - return what; - } - if (typeof left === "string" || - typeof left === "number" || - typeof left === "boolean" || - typeof right === "string" || - typeof right === "number" || - typeof right === "boolean" || - Array.isArray(left) || - Array.isArray(right)) { - what[key] = right; - return what; - } - what[key] = Object.assign({}, left, right); - return what; - }; - function deepEqual(x, y) { - if (x === y) { - return true; - } - if (!(x instanceof Object) || !(y instanceof Object)) { - return false; - } - if (x.constructor !== y.constructor) { - return false; - } - for (const p in x) { - if (!x.hasOwnProperty(p)) { - continue; - } - if (!y.hasOwnProperty(p)) { - return false; - } - if (x[p] === y[p]) { - continue; - } - if (typeof (x[p]) !== "object") { - return false; - } - if (!deepEqual(x[p], y[p])) { - return false; - } - } - for (const p in y) { - if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) { - return false; - } - } - return true; - } - function setValueToPath(obj, value, path) { - const pathArr = path.split("."); - const forbiddenKeys = ["__proto__", "constructor", "prototype"]; - let i; - for (i = 0; i < pathArr.length - 1; i++) { - const key = pathArr[i]; - if (forbiddenKeys.includes(key)) { - throw new Error(`The provided path ${path} is invalid. It cannot contain segment/key that is equal to one of the following values: ${forbiddenKeys}.`); - } - if (!obj[key]) { - obj[key] = {}; - } - if (typeof obj[key] !== "object") { - obj[key] = {}; - } - obj = obj[key]; - } - obj[pathArr[i]] = value; - } - function isSubset(superObj, subObj) { - return Object.keys(subObj).every((ele) => { - if (typeof subObj[ele] === "object") { - return isSubset(superObj?.[ele] || {}, subObj[ele] || {}); - } - return subObj[ele] === superObj?.[ele]; - }); - } - function deletePath(obj, path) { - const pathArr = path.split("."); - let i; - for (i = 0; i < pathArr.length - 1; i++) { - if (!obj[pathArr[i]]) { - return; - } - obj = obj[pathArr[i]]; - } - delete obj[pathArr[i]]; - } - - class GW3Bridge { - ERROR_URI_FAILURE = "global.errors.failure"; - ERROR_URI_INVALID_CONTEXT = "global.errors.invalid_context"; - _logger; - _connection; - _trackAllContexts; - _reAnnounceKnownContexts; - _subscribeOnUpdate; - _subscribeOnGet; - _onlyReAnnounceSubscribedContexts; - _gw3Session; - _contextNameToData = {}; - _gw3Subscriptions = []; - _nextCallbackSubscriptionNumber = 0; - _creationPromises = {}; - _contextNameToId = {}; - _contextIdToName = {}; - _protocolVersion = undefined; - _contextsTempCache = {}; - _contextsSubscriptionsCache = []; - _systemContextsSubKey; - get protocolVersion() { - if (!this._protocolVersion) { - const contextsDomainInfo = this._connection.availableDomains.find((d) => d.uri === "context"); - this._protocolVersion = contextsDomainInfo?.version ?? 1; - } - return this._protocolVersion; - } - get setPathSupported() { - return this.protocolVersion >= 2; - } - constructor(config) { - this._connection = config.connection; - this._logger = config.logger; - this._trackAllContexts = config.trackAllContexts; - this._reAnnounceKnownContexts = config.reAnnounceKnownContexts; - this._subscribeOnUpdate = config.subscribeOnUpdate ?? true; - this._subscribeOnGet = config.subscribeOnGet ?? true; - this._onlyReAnnounceSubscribedContexts = config.onlyReAnnounceSubscribedContexts ?? true; - this._gw3Session = this._connection.domain("global", [ - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_CONTEXT_UPDATED, - ]); - this._gw3Session.disconnected(this.resetState.bind(this)); - this._gw3Session.onJoined((wasReconnect) => { - if (!wasReconnect) { - return; - } - if (!this._reAnnounceKnownContexts) { - this._contextsTempCache = {}; - return this._connection.setLibReAnnounced({ name: "contexts" }); - } - this.reInitiateState() - .then(() => this._connection.setLibReAnnounced({ name: "contexts" })) - .catch((err) => { - this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(err)}`); - }); - }); - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - } - dispose() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - this._gw3Subscriptions.length = 0; - for (const contextName in this._contextNameToData) { - if (this._contextNameToId.hasOwnProperty(contextName)) { - delete this._contextNameToData[contextName]; - } - } - } - createContext(name, data) { - if (name in this._creationPromises) { - return this._creationPromises[name]; - } - this._creationPromises[name] = - this._gw3Session - .send({ - type: GW_MESSAGE_CREATE_CONTEXT, - domain: "global", - name, - data, - lifetime: "retained", - }) - .then((createContextMsg) => { - this._contextNameToId[name] = createContextMsg.context_id; - this._contextIdToName[createContextMsg.context_id] = name; - const contextData = this._contextNameToData[name] || new GW3ContextData(createContextMsg.context_id, name, true, undefined); - contextData.isAnnounced = true; - contextData.name = name; - contextData.contextId = createContextMsg.context_id; - contextData.context = createContextMsg.data || deepClone(data); - contextData.hasReceivedSnapshot = true; - this._contextNameToData[name] = contextData; - delete this._creationPromises[name]; - contextData.sentExplicitSubscription = true; - contextData.createdByUs = true; - this.subscribe(name, () => { }); - return createContextMsg.context_id; - }); - return this._creationPromises[name]; - } - all() { - return Object.keys(this._contextNameToData) - .filter((name) => this._contextNameToData[name].isAnnounced); - } - async update(name, delta) { - if (delta) { - delta = deepClone(delta); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - await this.createContext(name, delta); - return; - } - const currentContext = await this.get(contextData.name); - const calculatedDelta = this.setPathSupported ? - this.calculateContextDeltaV2(currentContext, delta) : - this.calculateContextDeltaV1(currentContext, delta); - if (!Object.keys(calculatedDelta.added).length - && !Object.keys(calculatedDelta.updated).length - && !calculatedDelta.removed.length - && !calculatedDelta.commands?.length) { - return Promise.resolve(); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: calculatedDelta, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, calculatedDelta, { - updaterId: gwResponse.peer_id - }); - } - } - async set(name, data) { - if (data) { - data = deepClone(data); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - return this.createContext(name, data); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { reset: data }, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - this.handleUpdated(contextData, { - reset: data, - added: {}, - removed: [], - updated: {} - }, { - updaterId: gwResponse.peer_id - }); - } - } - setPath(name, path, value) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later"); - } - return this.setPaths(name, [{ path, value }]); - } - async setPaths(name, pathValues) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later"); - } - if (pathValues) { - pathValues = deepClone(pathValues); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - const obj = {}; - for (const pathValue of pathValues) { - setValueToPath(obj, pathValue.value, pathValue.path); - } - return this.createContext(name, obj); - } - const commands = []; - for (const pathValue of pathValues) { - if (pathValue.value === null) { - commands.push({ type: "remove", path: pathValue.path }); - } - else { - commands.push({ type: "set", path: pathValue.path, value: pathValue.value }); - } - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { commands } - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, { - added: {}, - removed: [], - updated: {}, - commands - }, { - updaterId: gwResponse.peer_id - }); - } - } - async get(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - if (!contextData && this._subscribeOnGet) { - this.subscribe(name, () => { }); - } - return Promise.resolve({}); - } - if (contextData && !contextData.sentExplicitSubscription) { - return new Promise((resolve, reject) => { - this.subscribe(name, (data, _d, _r, un) => { - if (!this._subscribeOnGet) { - this.unsubscribe(un); - } - resolve(data); - }).catch((e) => { - if (this.isInvalidContextError(e)) { - resolve({}); - return; - } - reject(e); - }); - }); - } - await contextData.snapshotPromise; - const context = contextData?.context ?? {}; - return Promise.resolve(deepClone(context)); - } - isInvalidContextError(e) { - return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT - || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id")); - } - async subscribe(name, callback, subscriptionKey) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const thisCallbackSubscriptionNumber = typeof subscriptionKey === "undefined" ? this._nextCallbackSubscriptionNumber : subscriptionKey; - if (typeof subscriptionKey === "undefined") { - this._nextCallbackSubscriptionNumber += 1; - this._contextsSubscriptionsCache.push({ contextName: name, subKey: thisCallbackSubscriptionNumber, callback }); - } - let contextData = this._contextNameToData[name]; - if (!contextData || - !contextData.isAnnounced) { - contextData = contextData || new GW3ContextData(undefined, name, false, undefined); - this._contextNameToData[name] = contextData; - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - return Promise.resolve(thisCallbackSubscriptionNumber); - } - const hadCallbacks = contextData.hasCallbacks(); - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - if (!hadCallbacks) { - if (!contextData.joinedActivity && !contextData.createdByUs) { - if (contextData.context && contextData.sentExplicitSubscription) { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - return this.sendSubscribe(contextData) - .then(() => thisCallbackSubscriptionNumber, () => { - this.unsubscribe(thisCallbackSubscriptionNumber, true); - return thisCallbackSubscriptionNumber; - }); - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - unsubscribe(subscriptionKey, keepInSubscriptionsCache) { - if (!keepInSubscriptionsCache) { - this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter(x => x.subKey !== subscriptionKey); - } - for (const name of Object.keys(this._contextNameToData)) { - const contextData = this._contextNameToData[name]; - if (!contextData) { - continue; - } - const hadCallbacks = contextData.hasCallbacks(); - delete contextData.updateCallbacks[subscriptionKey]; - if (contextData.isAnnounced && - hadCallbacks && - !contextData.hasCallbacks() && - contextData.sentExplicitSubscription) { - contextData.hasReceivedSnapshot = false; - contextData.context = {}; - this.sendUnsubscribe(contextData).catch(() => { }); - } - if (!contextData.isAnnounced && - !contextData.hasCallbacks()) { - delete this._contextNameToData[name]; - delete this._contextNameToId[name]; - if (contextData.contextId) { - delete this._contextIdToName[contextData.contextId]; - } - } - } - } - async destroy(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - const contextId = contextData?.contextId; - if (!contextData || !contextId) { - return Promise.reject(`context with ${name} does not exist`); - } - return this._gw3Session - .send({ - type: GW_MESSAGE_DESTROY_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }).then(() => undefined); - } - handleUpdated(contextData, delta, extraData) { - const oldContext = contextData.context; - contextData.context = applyContextDelta(contextData.context, delta, this._logger); - if (this._contextNameToData[contextData.name] === contextData && - !deepEqual(oldContext, contextData.context)) { - this.invokeUpdateCallbacks(contextData, delta, extraData); - } - } - subscribeToContextCreatedMessages() { - const createdMessageTypes = [ - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_ACTIVITY_CREATED, - ]; - for (const createdMessageType of createdMessageTypes) { - const sub = this._connection.on(createdMessageType, this.handleContextCreatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextCreatedMessage(contextCreatedMsg) { - const createdMessageType = contextCreatedMsg.type; - if (createdMessageType === GW_MESSAGE_ACTIVITY_CREATED) { - this._contextNameToId[contextCreatedMsg.activity_id] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.activity_id; - } - else if (createdMessageType === GW_MESSAGE_CONTEXT_ADDED) { - this._contextNameToId[contextCreatedMsg.name] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.name; - } - else ; - const name = this._contextIdToName[contextCreatedMsg.context_id]; - if (!name) { - throw new Error("Received created event for context with unknown name: " + contextCreatedMsg.context_id); - } - if (!this._contextNameToId[name]) { - throw new Error("Received created event for context with unknown id: " + contextCreatedMsg.context_id); - } - let contextData = this._contextNameToData[name]; - if (contextData) { - if (contextData.isAnnounced) { - return; - } - else { - if (!contextData.hasCallbacks()) { - throw new Error("Assertion failure: contextData.hasCallbacks()"); - } - contextData.isAnnounced = true; - contextData.contextId = contextCreatedMsg.context_id; - contextData.activityId = contextCreatedMsg.activity_id; - if (!contextData.sentExplicitSubscription) { - this.sendSubscribe(contextData).catch(() => { }); - } - } - } - else { - this._contextNameToData[name] = contextData = - new GW3ContextData(contextCreatedMsg.context_id, name, true, contextCreatedMsg.activity_id); - if (this._trackAllContexts) { - this.subscribe(name, () => { }).then((subKey) => this._systemContextsSubKey = subKey); - } - } - } - subscribeToContextUpdatedMessages() { - const updatedMessageTypes = [ - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_JOINED_ACTIVITY, - ]; - for (const updatedMessageType of updatedMessageTypes) { - const sub = this._connection.on(updatedMessageType, this.handleContextUpdatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextUpdatedMessage(contextUpdatedMsg) { - const updatedMessageType = contextUpdatedMsg.type; - const contextId = contextUpdatedMsg.context_id; - let contextData = this._contextNameToData[this._contextIdToName[contextId]]; - const justSeen = !contextData || !contextData.isAnnounced; - if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - if (!contextData) { - contextData = - this._contextNameToData[contextUpdatedMsg.activity_id] || - new GW3ContextData(contextId, contextUpdatedMsg.activity_id, true, contextUpdatedMsg.activity_id); - } - this._contextNameToData[contextUpdatedMsg.activity_id] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.activity_id; - this._contextNameToId[contextUpdatedMsg.activity_id] = contextId; - contextData.contextId = contextId; - contextData.isAnnounced = true; - contextData.activityId = contextUpdatedMsg.activity_id; - contextData.joinedActivity = true; - } - else { - if (!contextData || !contextData.isAnnounced) { - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData = contextData || new GW3ContextData(contextId, contextUpdatedMsg.name, true, undefined); - contextData.sentExplicitSubscription = true; - this._contextNameToData[contextUpdatedMsg.name] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.name; - this._contextNameToId[contextUpdatedMsg.name] = contextId; - } - else { - this._logger.error(`Received 'update' for unknown context: ${contextId}`); - } - return; - } - } - const oldContext = contextData.context; - contextData.hasReceivedSnapshot = true; - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData.context = contextUpdatedMsg.data ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - contextData.context = contextUpdatedMsg.context_snapshot ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_CONTEXT_UPDATED) { - contextData.context = applyContextDelta(contextData.context, contextUpdatedMsg.delta, this._logger); - } - else { - throw new Error("Unrecognized context update message " + updatedMessageType); - } - if (justSeen || - !deepEqual(contextData.context, oldContext) || - updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta, { updaterId: contextUpdatedMsg.updater_id }); - } - } - invokeUpdateCallbacks(contextData, delta, extraData) { - delta = delta || { added: {}, updated: {}, reset: {}, removed: [] }; - if (delta.commands) { - delta.added = delta.updated = delta.reset = {}; - delta.removed = []; - for (const command of delta.commands) { - if (command.type === "remove") { - if (command.path.indexOf(".") === -1) { - delta.removed.push(command.path); - } - setValueToPath(delta.updated, null, command.path); - } - else if (command.type === "set") { - setValueToPath(delta.updated, command.value, command.path); - } - } - } - for (const updateCallbackIndex in contextData.updateCallbacks) { - if (contextData.updateCallbacks.hasOwnProperty(updateCallbackIndex)) { - try { - const updateCallback = contextData.updateCallbacks[updateCallbackIndex]; - updateCallback(deepClone(contextData.context), deepClone(Object.assign({}, delta.added || {}, delta.updated || {}, delta.reset || {})), delta.removed, parseInt(updateCallbackIndex, 10), extraData); - } - catch (err) { - this._logger.debug("callback error: " + JSON.stringify(err)); - } - } - } - } - subscribeToContextDestroyedMessages() { - const destroyedMessageTypes = [ - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_ACTIVITY_DESTROYED, - ]; - for (const destroyedMessageType of destroyedMessageTypes) { - const sub = this._connection.on(destroyedMessageType, this.handleContextDestroyedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextDestroyedMessage(destroyedMsg) { - const destroyedMessageType = destroyedMsg.type; - let contextId; - let name; - if (destroyedMessageType === GW_MESSAGE_ACTIVITY_DESTROYED) { - name = destroyedMsg.activity_id; - contextId = this._contextNameToId[name]; - if (!contextId) { - this._logger.error(`Received 'destroyed' for unknown activity: ${destroyedMsg.activity_id}`); - return; - } - } - else { - contextId = destroyedMsg.context_id; - name = this._contextIdToName[contextId]; - if (!name) { - this._logger.error(`Received 'destroyed' for unknown context: ${destroyedMsg.context_id}`); - return; - } - } - delete this._contextIdToName[contextId]; - delete this._contextNameToId[name]; - const contextData = this._contextNameToData[name]; - delete this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - this._logger.error(`Received 'destroyed' for unknown context: ${contextId}`); - return; - } - } - async sendSubscribe(contextData) { - contextData.sentExplicitSubscription = true; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_SUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = false; - throw error; - } - } - async sendUnsubscribe(contextData) { - const prev = contextData.sentExplicitSubscription; - contextData.sentExplicitSubscription = false; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = prev; - throw error; - } - } - calculateContextDeltaV1(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined }; - if (from) { - for (const x of Object.keys(from)) { - if (Object.keys(to).indexOf(x) !== -1 - && to[x] !== null - && !deepEqual(from[x], to[x])) { - delta.updated[x] = to[x]; - } - } - } - for (const x of Object.keys(to)) { - if (!from || (Object.keys(from).indexOf(x) === -1)) { - if (to[x] !== null) { - delta.added[x] = to[x]; - } - } - else if (to[x] === null) { - delta.removed.push(x); - } - } - return delta; - } - calculateContextDeltaV2(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined, commands: [] }; - for (const x of Object.keys(to)) { - if (to[x] !== null) { - const fromX = from ? from[x] : null; - if (!deepEqual(fromX, to[x])) { - delta.commands?.push({ type: "set", path: x, value: to[x] }); - } - } - else { - delta.commands?.push({ type: "remove", path: x }); - } - } - return delta; - } - resetState() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - if (this._systemContextsSubKey) { - this.unsubscribe(this._systemContextsSubKey, true); - delete this._systemContextsSubKey; - } - this._gw3Subscriptions = []; - this._contextNameToId = {}; - this._contextIdToName = {}; - delete this._protocolVersion; - this._contextsTempCache = Object.keys(this._contextNameToData).reduce((cacheSoFar, ctxName) => { - const contextData = this._contextNameToData[ctxName]; - const addToCache = !this._onlyReAnnounceSubscribedContexts || contextData.hasReceivedSnapshot; - if (addToCache) { - cacheSoFar[ctxName] = this._contextNameToData[ctxName].context; - } - return cacheSoFar; - }, {}); - this._contextNameToData = {}; - } - async reInitiateState() { - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - await Promise.all(this._contextsSubscriptionsCache.map((subscription) => this.subscribe(subscription.contextName, subscription.callback, subscription.subKey))); - await this.flushQueue(); - for (const ctxName in this._contextsTempCache) { - if (typeof this._contextsTempCache[ctxName] !== "object" || Object.keys(this._contextsTempCache[ctxName]).length === 0) { - continue; - } - const lastKnownData = this._contextsTempCache[ctxName]; - this._logger.info(`Re-announcing known context: ${ctxName}`); - await this.flushQueue(); - await this.update(ctxName, lastKnownData); - } - this._contextsTempCache = {}; - this._logger.info("Contexts are re-announced"); - } - flushQueue() { - return new Promise((resolve) => setTimeout(() => resolve(), 0)); - } - } - - class ContextsModule { - initTime; - initStartTime; - initEndTime; - _bridge; - constructor(config) { - this._bridge = new GW3Bridge(config); - } - all() { - return this._bridge.all(); - } - update(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.update(name, data); - } - set(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.set(name, data); - } - setPath(name, path, data) { - this.checkName(name); - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(data); - return this.set(name, data); - } - return this._bridge.setPath(name, path, data); - } - setPaths(name, paths) { - this.checkName(name); - if (!Array.isArray(paths)) { - throw new Error("Please provide the paths as an array of PathValues!"); - } - for (const { path, value } of paths) { - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(value); - } - } - return this._bridge.setPaths(name, paths); - } - subscribe(name, callback) { - this.checkName(name); - if (typeof callback !== "function") { - throw new Error("Please provide the callback as a function!"); - } - return this._bridge - .subscribe(name, (data, delta, removed, key, extraData) => callback(data, delta, removed, () => this._bridge.unsubscribe(key), extraData)) - .then((key) => () => { - this._bridge.unsubscribe(key); - }); - } - get(name) { - this.checkName(name); - return this._bridge.get(name); - } - ready() { - return Promise.resolve(this); - } - destroy(name) { - this.checkName(name); - return this._bridge.destroy(name); - } - get setPathSupported() { - return this._bridge.setPathSupported; - } - checkName(name) { - if (typeof name !== "string" || name === "") { - throw new Error("Please provide the name as a non-empty string!"); - } - } - checkPath(path) { - if (typeof path !== "string") { - throw new Error("Please provide the path as a dot delimited string!"); - } - } - checkData(data) { - if (typeof data !== "object") { - throw new Error("Please provide the data as an object!"); - } - } - } - - function promisify (promise, successCallback, errorCallback) { - if (typeof successCallback !== "function" && typeof errorCallback !== "function") { - return promise; - } - if (typeof successCallback !== "function") { - successCallback = () => { }; - } - else if (typeof errorCallback !== "function") { - errorCallback = () => { }; - } - return promise.then(successCallback, errorCallback); - } - - function rejectAfter(ms = 0, promise, error) { - let timeout; - const clearTimeoutIfThere = () => { - if (timeout) { - clearTimeout(timeout); - } - }; - promise - .then(() => { - clearTimeoutIfThere(); - }) - .catch(() => { - clearTimeoutIfThere(); - }); - return new Promise((resolve, reject) => { - timeout = setTimeout(() => reject(error), ms); - }); - } - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - Decoder.oneOf; - /** See `Decoder.union` */ - var union = Decoder.union; - /** See `Decoder.intersection` */ - Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - var fail$1 = Decoder.fail; - /** See `Decoder.lazy` */ - Decoder.lazy; - - const functionCheck = (input, propDescription) => { - const providedType = typeof input; - return providedType === "function" ? - anyJson() : - fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${typeof providedType}`); - }; - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number or 0"); - const methodDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - objectTypes: optional(array(nonEmptyStringDecoder)), - displayName: optional(nonEmptyStringDecoder), - accepts: optional(nonEmptyStringDecoder), - returns: optional(nonEmptyStringDecoder), - description: optional(nonEmptyStringDecoder), - version: optional(nonNegativeNumberDecoder), - supportsStreaming: optional(boolean()), - flags: optional(object()), - getServers: optional(anyJson().andThen((result) => functionCheck(result, "method definition getServers"))) - }); - const methodFilterDecoder = union(nonEmptyStringDecoder, methodDefinitionDecoder); - const instanceDecoder = object({ - application: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - pid: optional(nonNegativeNumberDecoder), - machine: optional(nonEmptyStringDecoder), - user: optional(nonEmptyStringDecoder), - environment: optional(nonEmptyStringDecoder), - region: optional(nonEmptyStringDecoder), - service: optional(nonEmptyStringDecoder), - instance: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - peerId: optional(nonEmptyStringDecoder), - isLocal: optional(boolean()), - api: optional(nonEmptyStringDecoder), - getMethods: optional(anyJson().andThen((result) => functionCheck(result, "instance getMethods"))), - getStreams: optional(anyJson().andThen((result) => functionCheck(result, "instance getStreams"))) - }); - const targetDecoder = union(constant("best"), constant("all"), constant("skipMine"), instanceDecoder, array(instanceDecoder)); - const invokeOptionsDecoder = object({ - waitTimeoutMs: optional(nonNegativeNumberDecoder), - methodResponseTimeoutMs: optional(nonNegativeNumberDecoder) - }); - - var InvokeStatus; - (function (InvokeStatus) { - InvokeStatus[InvokeStatus["Success"] = 0] = "Success"; - InvokeStatus[InvokeStatus["Error"] = 1] = "Error"; - })(InvokeStatus || (InvokeStatus = {})); - class Client { - protocol; - repo; - instance; - configuration; - constructor(protocol, repo, instance, configuration) { - this.protocol = protocol; - this.repo = repo; - this.instance = instance; - this.configuration = configuration; - } - subscribe(method, options, successCallback, errorCallback, existingSub) { - const callProtocolSubscribe = (targetServers, stream, successProxy, errorProxy) => { - options.methodResponseTimeout = options.methodResponseTimeout ?? options.waitTimeoutMs; - this.protocol.client.subscribe(stream, options, targetServers, successProxy, errorProxy, existingSub); - }; - const promise = new Promise((resolve, reject) => { - const successProxy = (sub) => { - resolve(sub); - }; - const errorProxy = (err) => { - reject(err); - }; - if (!method) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - let methodDef; - if (typeof method === "string") { - methodDef = { name: method }; - } - else { - methodDef = method; - } - if (!methodDef.name) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - if (options === undefined) { - options = {}; - } - let target = options.target; - if (target === undefined) { - target = "best"; - } - if (typeof target === "string" && target !== "all" && target !== "best") { - reject(new Error(`"${target}" is not a valid target. Valid targets are "all", "best", or an instance.`)); - return; - } - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = options.method_response_timeout; - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = this.configuration.methodResponseTimeout; - } - } - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = options.wait_for_method_timeout; - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - const delayStep = 500; - let delayTillNow = 0; - let currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - callProtocolSubscribe(currentServers, currentServers[0].methods[0], successProxy, errorProxy); - } - else { - const retry = () => { - if (!target || !(options.waitTimeoutMs)) { - return; - } - delayTillNow += delayStep; - currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - const streamInfo = currentServers[0].methods[0]; - callProtocolSubscribe(currentServers, streamInfo, successProxy, errorProxy); - } - else if (delayTillNow >= options.waitTimeoutMs) { - const def = typeof method === "string" ? { name: method } : method; - callProtocolSubscribe(currentServers, def, successProxy, errorProxy); - } - else { - setTimeout(retry, delayStep); - } - }; - setTimeout(retry, delayStep); - } - }); - return promisify(promise, successCallback, errorCallback); - } - servers(methodFilter) { - const filterCopy = methodFilter === undefined - ? undefined - : { ...methodFilter }; - return this.getServers(filterCopy).map((serverMethodMap) => { - return serverMethodMap.server.instance; - }); - } - methods(methodFilter) { - if (typeof methodFilter === "string") { - methodFilter = { name: methodFilter }; - } - else { - methodFilter = { ...methodFilter }; - } - return this.getMethods(methodFilter); - } - methodsForInstance(instance) { - return this.getMethodsForInstance(instance); - } - methodAdded(callback) { - return this.repo.onMethodAdded(callback); - } - methodRemoved(callback) { - return this.repo.onMethodRemoved(callback); - } - serverAdded(callback) { - return this.repo.onServerAdded(callback); - } - serverRemoved(callback) { - return this.repo.onServerRemoved((server, reason) => { - callback(server, reason); - }); - } - serverMethodAdded(callback) { - return this.repo.onServerMethodAdded((server, method) => { - callback({ server, method }); - }); - } - serverMethodRemoved(callback) { - return this.repo.onServerMethodRemoved((server, method) => { - callback({ server, method }); - }); - } - async invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - const getInvokePromise = async () => { - const methodDefinition = typeof methodFilter === "string" ? { name: methodFilter } : { ...methodFilter }; - if (!argumentObj) { - argumentObj = {}; - } - if (!target) { - target = "best"; - } - if (!additionalOptions) { - additionalOptions = {}; - } - const methodFilterDecoderResult = methodFilterDecoder.run(methodDefinition); - if (!methodFilterDecoderResult.ok) { - const message = `The provided 'method' argument is invalid. Error: ${JSON.stringify(methodFilterDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (typeof argumentObj !== "object") { - const message = "The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const targetDecoderResult = targetDecoder.run(target); - if (!targetDecoderResult.ok) { - const message = `The provided 'target' argument is invalid. Error: ${JSON.stringify(targetDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const invokeOptionsDecoderResult = invokeOptionsDecoder.run(additionalOptions); - if (!invokeOptionsDecoderResult.ok) { - const message = `The provided 'options' argument is invalid. Error: ${JSON.stringify(invokeOptionsDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (success && typeof success !== "function") { - const message = "The provided 'success' function is invalid. Error: The success should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (error && typeof error !== "function") { - const message = "The provided 'error' function is invalid. Error: The error should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = additionalOptions.method_response_timeout; - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = this.configuration.methodResponseTimeout; - } - } - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = additionalOptions.wait_for_method_timeout; - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - let serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length === 0) { - try { - serversMethodMap = await this.tryToAwaitForMethods(methodDefinition, target, additionalOptions); - } - catch (err) { - const message = `Can not find a method matching ${JSON.stringify(methodFilter)} with server filter ${JSON.stringify(target)}`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - } - const timeout = additionalOptions.methodResponseTimeoutMs; - const additionalOptionsCopy = additionalOptions; - const invokePromises = serversMethodMap.map((serversMethodPair) => { - const invId = nanoid(10); - const method = serversMethodPair.methods[0]; - const server = serversMethodPair.server; - const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy); - return Promise.race([ - invokePromise, - rejectAfter(timeout, invokePromise, { - invocationId: invId, - message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`, - status: InvokeStatus.Error, - }) - ]); - }); - const invocationMessages = await Promise.all(invokePromises); - const results = this.getInvocationResultObj(invocationMessages, methodDefinition, argumentObj); - const allRejected = invocationMessages.every((result) => result.status === InvokeStatus.Error); - if (allRejected) { - return Promise.reject(results); - } - return results; - }; - return promisify(getInvokePromise(), success, error); - } - generateInvalidInputInvocationResult(message, methodDefinition, argumentObj) { - const method = { - ...methodDefinition, - getServers: () => [], - supportsStreaming: false, - objectTypes: methodDefinition.objectTypes ?? [], - flags: methodDefinition.flags?.metadata ?? {} - }; - const invokeResultMessage = { - invocationId: nanoid(10), - status: InvokeStatus.Error, - message - }; - return this.getInvocationResultObj([invokeResultMessage], method, argumentObj); - } - getInvocationResultObj(invocationResults, method, calledWith) { - const all_return_values = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Success) - .reduce((allValues, currentValue) => { - allValues = [ - ...allValues, - { - executed_by: currentValue.instance, - returned: currentValue.result, - called_with: calledWith, - method, - message: currentValue.message, - status: currentValue.status, - } - ]; - return allValues; - }, []); - const all_errors = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Error) - .reduce((allErrors, currError) => { - allErrors = [ - ...allErrors, - { - executed_by: currError.instance, - called_with: calledWith, - name: method.name, - message: currError.message, - } - ]; - return allErrors; - }, []); - const invResult = invocationResults[0]; - const result = { - method, - called_with: calledWith, - returned: invResult.result, - executed_by: invResult.instance, - all_return_values, - all_errors, - message: invResult.message, - status: invResult.status - }; - return result; - } - tryToAwaitForMethods(methodDefinition, target, additionalOptions) { - return new Promise((resolve, reject) => { - if (additionalOptions.waitTimeoutMs === 0) { - reject(); - return; - } - const delayStep = 500; - let delayTillNow = 0; - const retry = () => { - delayTillNow += delayStep; - const serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length > 0) { - clearInterval(interval); - resolve(serversMethodMap); - } - else if (delayTillNow >= (additionalOptions.waitTimeoutMs || 10000)) { - clearInterval(interval); - reject(); - return; - } - }; - const interval = setInterval(retry, delayStep); - }); - } - filterByTarget(target, serverMethodMap) { - if (typeof target === "string") { - if (target === "all") { - return [...serverMethodMap]; - } - else if (target === "best") { - const localMachine = serverMethodMap - .find((s) => s.server.instance.isLocal); - if (localMachine) { - return [localMachine]; - } - if (serverMethodMap[0] !== undefined) { - return [serverMethodMap[0]]; - } - } - else if (target === "skipMine") { - return serverMethodMap.filter(({ server }) => server.instance.peerId !== this.instance.peerId); - } - } - else { - let targetArray; - if (!Array.isArray(target)) { - targetArray = [target]; - } - else { - targetArray = target; - } - const allServersMatching = targetArray.reduce((matches, filter) => { - const myMatches = serverMethodMap.filter((serverMethodPair) => { - return this.instanceMatch(filter, serverMethodPair.server.instance); - }); - return matches.concat(myMatches); - }, []); - return allServersMatching; - } - return []; - } - instanceMatch(instanceFilter, instanceDefinition) { - if (instanceFilter?.peerId && instanceFilter?.instance) { - instanceFilter = { ...instanceFilter }; - delete instanceFilter.peerId; - } - return this.containsProps(instanceFilter, instanceDefinition); - } - methodMatch(methodFilter, methodDefinition) { - return this.containsProps(methodFilter, methodDefinition); - } - containsProps(filter, repoMethod) { - const filterProps = Object.keys(filter) - .filter((prop) => { - return filter[prop] !== undefined - && filter[prop] !== null - && typeof filter[prop] !== "function" - && prop !== "object_types" - && prop !== "display_name" - && prop !== "id" - && prop !== "gatewayId" - && prop !== "identifier" - && prop[0] !== "_"; - }); - return filterProps.every((prop) => { - let isMatch; - const filterValue = filter[prop]; - const repoMethodValue = repoMethod[prop]; - switch (prop) { - case "objectTypes": - isMatch = (filterValue || []).every((filterValueEl) => { - return (repoMethodValue || []).includes(filterValueEl); - }); - break; - case "flags": - isMatch = isSubset(repoMethodValue || {}, filterValue || {}); - break; - default: - isMatch = String(filterValue).toLowerCase() === String(repoMethodValue).toLowerCase(); - } - return isMatch; - }); - } - getMethods(methodFilter) { - if (methodFilter === undefined) { - return this.repo.getMethods(); - } - const methods = this.repo.getMethods().filter((method) => { - return this.methodMatch(methodFilter, method); - }); - return methods; - } - getMethodsForInstance(instanceFilter) { - const allServers = this.repo.getServers(); - const matchingServers = allServers.filter((server) => { - return this.instanceMatch(instanceFilter, server.instance); - }); - if (matchingServers.length === 0) { - return []; - } - let resultMethodsObject = {}; - if (matchingServers.length === 1) { - resultMethodsObject = matchingServers[0].methods; - } - else { - matchingServers.forEach((server) => { - Object.keys(server.methods).forEach((methodKey) => { - const method = server.methods[methodKey]; - resultMethodsObject[method.identifier] = method; - }); - }); - } - return Object.keys(resultMethodsObject) - .map((key) => { - return resultMethodsObject[key]; - }); - } - getServers(methodFilter) { - const servers = this.repo.getServers(); - if (methodFilter === undefined) { - return servers.map((server) => { - return { server, methods: [] }; - }); - } - return servers.reduce((prev, current) => { - const methodsForServer = Object.values(current.methods); - const matchingMethods = methodsForServer.filter((method) => { - return this.methodMatch(methodFilter, method); - }); - if (matchingMethods.length > 0) { - prev.push({ server: current, methods: matchingMethods }); - } - return prev; - }, []); - } - getServerMethodsByFilterAndTarget(methodFilter, target) { - const serversMethodMap = this.getServers(methodFilter); - return this.filterByTarget(target, serversMethodMap); - } - } - - class ServerSubscription { - protocol; - repoMethod; - subscription; - constructor(protocol, repoMethod, subscription) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.subscription = subscription; - } - get stream() { - if (!this.repoMethod.stream) { - throw new Error("no stream"); - } - return this.repoMethod.stream; - } - get arguments() { return this.subscription.arguments || {}; } - get branchKey() { return this.subscription.branchKey; } - get instance() { - if (!this.subscription.instance) { - throw new Error("no instance"); - } - return this.subscription.instance; - } - close() { - this.protocol.server.closeSingleSubscription(this.repoMethod, this.subscription); - } - push(data) { - this.protocol.server.pushDataToSingle(this.repoMethod, this.subscription, data); - } - } - - class Request { - protocol; - repoMethod; - requestContext; - arguments; - instance; - constructor(protocol, repoMethod, requestContext) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.requestContext = requestContext; - this.arguments = requestContext.arguments; - this.instance = requestContext.instance; - } - accept() { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, ""); - } - acceptOnBranch(branch) { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, branch); - } - reject(reason) { - this.protocol.server.rejectRequest(this.requestContext, this.repoMethod, reason); - } - } - - let ServerStreaming$1 = class ServerStreaming { - protocol; - server; - constructor(protocol, server) { - this.protocol = protocol; - this.server = server; - protocol.server.onSubRequest((rc, rm) => this.handleSubRequest(rc, rm)); - protocol.server.onSubAdded((sub, rm) => this.handleSubAdded(sub, rm)); - protocol.server.onSubRemoved((sub, rm) => this.handleSubRemoved(sub, rm)); - } - handleSubRequest(requestContext, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRequestHandler === "function")) { - return; - } - const request = new Request(this.protocol, repoMethod, requestContext); - repoMethod.streamCallbacks.subscriptionRequestHandler(request); - } - handleSubAdded(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionAddedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionAddedHandler(sub); - } - handleSubRemoved(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRemovedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionRemovedHandler(sub); - } - }; - - class ServerBranch { - key; - protocol; - repoMethod; - constructor(key, protocol, repoMethod) { - this.key = key; - this.protocol = protocol; - this.repoMethod = repoMethod; - } - subscriptions() { - const subList = this.protocol.server.getSubscriptionList(this.repoMethod, this.key); - return subList.map((sub) => { - return new ServerSubscription(this.protocol, this.repoMethod, sub); - }); - } - close() { - this.protocol.server.closeAllSubscriptions(this.repoMethod, this.key); - } - push(data) { - this.protocol.server.pushData(this.repoMethod, data, [this.key]); - } - } - - class ServerStream { - _protocol; - _repoMethod; - _server; - name; - constructor(_protocol, _repoMethod, _server) { - this._protocol = _protocol; - this._repoMethod = _repoMethod; - this._server = _server; - this.name = this._repoMethod.definition.name; - } - branches(key) { - const bList = this._protocol.server.getBranchList(this._repoMethod); - if (key) { - if (bList.indexOf(key) > -1) { - return new ServerBranch(key, this._protocol, this._repoMethod); - } - return undefined; - } - else { - return bList.map((branchKey) => { - return new ServerBranch(branchKey, this._protocol, this._repoMethod); - }); - } - } - branch(key) { - return this.branches(key); - } - subscriptions() { - const subList = this._protocol.server.getSubscriptionList(this._repoMethod); - return subList.map((sub) => { - return new ServerSubscription(this._protocol, this._repoMethod, sub); - }); - } - get definition() { - const def2 = this._repoMethod.definition; - return { - accepts: def2.accepts, - description: def2.description, - displayName: def2.displayName, - name: def2.name, - objectTypes: def2.objectTypes, - returns: def2.returns, - supportsStreaming: def2.supportsStreaming, - flags: def2.flags?.metadata, - }; - } - close() { - this._protocol.server.closeAllSubscriptions(this._repoMethod); - this._server.unregister(this._repoMethod.definition, true); - } - push(data, branches) { - if (typeof branches !== "string" && !Array.isArray(branches) && branches !== undefined) { - throw new Error("invalid branches should be string or string array"); - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - this._protocol.server.pushData(this._repoMethod, data, branches); - } - updateRepoMethod(repoMethod) { - this._repoMethod = repoMethod; - } - } - - class Server { - protocol; - serverRepository; - streaming; - invocations = 0; - currentlyUnregistering = {}; - constructor(protocol, serverRepository) { - this.protocol = protocol; - this.serverRepository = serverRepository; - this.streaming = new ServerStreaming$1(protocol, this); - this.protocol.server.onInvoked(this.onMethodInvoked.bind(this)); - } - createStream(streamDef, callbacks, successCallback, errorCallback, existingStream) { - const promise = new Promise((resolve, reject) => { - if (!streamDef) { - reject("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream."); - return; - } - let streamMethodDefinition; - if (typeof streamDef === "string") { - streamMethodDefinition = { name: "" + streamDef }; - } - else { - streamMethodDefinition = { ...streamDef }; - } - if (!streamMethodDefinition.name) { - return reject(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(streamMethodDefinition)}`); - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === streamMethodDefinition.name); - if (nameAlreadyExists) { - return reject(`A stream with the name "${streamMethodDefinition.name}" already exists! Please, provide a unique name for the stream.`); - } - streamMethodDefinition.supportsStreaming = true; - if (!callbacks) { - callbacks = {}; - } - if (typeof callbacks.subscriptionRequestHandler !== "function") { - callbacks.subscriptionRequestHandler = (request) => { - request.accept(); - }; - } - const repoMethod = this.serverRepository.add({ - definition: streamMethodDefinition, - streamCallbacks: callbacks, - protocolState: {}, - }); - this.protocol.server.createStream(repoMethod) - .then(() => { - let streamUserObject; - if (existingStream) { - streamUserObject = existingStream; - existingStream.updateRepoMethod(repoMethod); - } - else { - streamUserObject = new ServerStream(this.protocol, repoMethod, this); - } - repoMethod.stream = streamUserObject; - resolve(streamUserObject); - }) - .catch((err) => { - if (repoMethod.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - reject(err); - }); - }); - return promisify(promise, successCallback, errorCallback); - } - register(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallbackFunction = async (context, resultCallback) => { - try { - const result = callback(context.args, context.instance); - if (result && typeof result.then === "function") { - const resultValue = await result; - resultCallback(undefined, resultValue); - } - else { - resultCallback(undefined, result); - } - } - catch (e) { - resultCallback(e ?? "", e ?? ""); - } - }; - wrappedCallbackFunction.userCallback = callback; - return this.registerCore(methodDefinition, wrappedCallbackFunction); - } - registerAsync(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallback = async (context, resultCallback) => { - try { - let resultCalled = false; - const success = (result) => { - if (!resultCalled) { - resultCallback(undefined, result); - } - resultCalled = true; - }; - const error = (e) => { - if (!resultCalled) { - if (!e) { - e = ""; - } - resultCallback(e, e); - } - resultCalled = true; - }; - const methodResult = callback(context.args, context.instance, success, error); - if (methodResult && typeof methodResult.then === "function") { - methodResult - .then(success) - .catch(error); - } - } - catch (e) { - resultCallback(e, undefined); - } - }; - wrappedCallback.userCallbackAsync = callback; - return this.registerCore(methodDefinition, wrappedCallback); - } - async unregister(methodFilter, forStream = false) { - if (methodFilter === undefined) { - return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property."); - } - if (typeof methodFilter === "function") { - await this.unregisterWithPredicate(methodFilter, forStream); - return; - } - let methodDefinition; - if (typeof methodFilter === "string") { - methodDefinition = { name: methodFilter }; - } - else { - methodDefinition = methodFilter; - } - if (methodDefinition.name === undefined) { - return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!"); - } - const methodToBeRemoved = this.serverRepository.getList().find((serverMethod) => { - return serverMethod.definition.name === methodDefinition.name - && (serverMethod.definition.supportsStreaming || false) === forStream; - }); - if (!methodToBeRemoved) { - return Promise.reject(`Method with a name "${methodDefinition.name}" does not exist or is not registered by your application!`); - } - await this.removeMethodsOrStreams([methodToBeRemoved]); - } - async unregisterWithPredicate(filterPredicate, forStream) { - const methodsOrStreamsToRemove = this.serverRepository.getList() - .filter((sm) => filterPredicate(sm.definition)) - .filter((serverMethod) => (serverMethod.definition.supportsStreaming || false) === forStream); - if (!methodsOrStreamsToRemove || methodsOrStreamsToRemove.length === 0) { - return Promise.reject(`Could not find a ${forStream ? "stream" : "method"} matching the specified condition!`); - } - await this.removeMethodsOrStreams(methodsOrStreamsToRemove); - } - removeMethodsOrStreams(methodsToRemove) { - const methodUnregPromises = []; - methodsToRemove.forEach((method) => { - const promise = this.protocol.server.unregister(method) - .then(() => { - if (method.repoId) { - this.serverRepository.remove(method.repoId); - } - }); - methodUnregPromises.push(promise); - this.addAsCurrentlyUnregistering(method.definition.name, promise); - }); - return Promise.all(methodUnregPromises); - } - async addAsCurrentlyUnregistering(methodName, promise) { - const timeout = new Promise((resolve) => setTimeout(resolve, 5000)); - this.currentlyUnregistering[methodName] = Promise.race([promise, timeout]).then(() => { - delete this.currentlyUnregistering[methodName]; - }); - } - async registerCore(method, theFunction) { - let methodDefinition; - if (typeof method === "string") { - methodDefinition = { name: "" + method }; - } - else { - methodDefinition = { ...method }; - } - if (!methodDefinition.name) { - return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(method)}`); - } - const unregisterInProgress = this.currentlyUnregistering[methodDefinition.name]; - if (typeof unregisterInProgress !== "undefined") { - await unregisterInProgress; - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === methodDefinition.name); - if (nameAlreadyExists) { - return Promise.reject(`A method with the name "${methodDefinition.name}" already exists! Please, provide a unique name for the method.`); - } - if (methodDefinition.supportsStreaming) { - return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${methodDefinition.name}” to be a stream, please use the “glue.interop.createStream()” method.`); - } - const repoMethod = this.serverRepository.add({ - definition: methodDefinition, - theFunction, - protocolState: {}, - }); - return this.protocol.server.register(repoMethod) - .catch((err) => { - if (repoMethod?.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - throw err; - }); - } - onMethodInvoked(methodToExecute, invocationId, invocationArgs) { - if (!methodToExecute || !methodToExecute.theFunction) { - return; - } - methodToExecute.theFunction(invocationArgs, (err, result) => { - if (err !== undefined && err !== null) { - if (err.message && typeof err.message === "string") { - err = err.message; - } - else if (typeof err !== "string") { - try { - err = JSON.stringify(err); - } - catch (unStrException) { - err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`; - } - } - } - if (!result) { - result = {}; - } - else if (typeof result !== "object" || Array.isArray(result)) { - result = { _value: result }; - } - this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result); - }); - } - } - - class InstanceWrapper { - wrapped = {}; - constructor(API, instance, connection) { - this.wrapped.getMethods = function () { - return API.methodsForInstance(this); - }; - this.wrapped.getStreams = function () { - return API.methodsForInstance(this).filter((m) => m.supportsStreaming); - }; - if (instance) { - this.refreshWrappedObject(instance); - } - if (connection) { - connection.loggedIn(() => { - this.refresh(connection); - }); - this.refresh(connection); - } - } - unwrap() { - return this.wrapped; - } - refresh(connection) { - if (!connection) { - return; - } - const resolvedIdentity = connection?.resolvedIdentity; - const instance = Object.assign({}, resolvedIdentity ?? {}, { peerId: connection?.peerId }); - this.refreshWrappedObject(instance); - } - refreshWrappedObject(resolvedIdentity) { - Object.keys(resolvedIdentity).forEach((key) => { - this.wrapped[key] = resolvedIdentity[key]; - }); - this.wrapped.user = resolvedIdentity.user; - this.wrapped.instance = resolvedIdentity.instance; - this.wrapped.application = resolvedIdentity.application ?? nanoid(10); - this.wrapped.applicationName = resolvedIdentity.applicationName; - this.wrapped.pid = resolvedIdentity.pid ?? resolvedIdentity.process ?? Math.floor(Math.random() * 10000000000); - this.wrapped.machine = resolvedIdentity.machine; - this.wrapped.environment = resolvedIdentity.environment; - this.wrapped.region = resolvedIdentity.region; - this.wrapped.windowId = resolvedIdentity.windowId; - this.wrapped.isLocal = resolvedIdentity.isLocal ?? true; - this.wrapped.api = resolvedIdentity.api; - this.wrapped.service = resolvedIdentity.service; - this.wrapped.peerId = resolvedIdentity.peerId; - } - } - - const hideMethodSystemFlags = (method) => { - return { - ...method, - flags: method.flags.metadata || {} - }; - }; - class ClientRepository { - logger; - API; - servers = {}; - myServer; - methodsCount = {}; - callbacks = CallbackRegistryFactory(); - constructor(logger, API) { - this.logger = logger; - this.API = API; - const peerId = this.API.instance.peerId; - this.myServer = { - id: peerId, - methods: {}, - instance: this.API.instance, - wrapper: this.API.unwrappedInstance, - }; - this.servers[peerId] = this.myServer; - } - addServer(info, serverId) { - this.logger.debug(`adding server ${serverId}`); - const current = this.servers[serverId]; - if (current) { - return current.id; - } - const wrapper = new InstanceWrapper(this.API, info); - const serverEntry = { - id: serverId, - methods: {}, - instance: wrapper.unwrap(), - wrapper, - }; - this.servers[serverId] = serverEntry; - this.callbacks.execute("onServerAdded", serverEntry.instance); - return serverId; - } - removeServerById(id, reason) { - const server = this.servers[id]; - if (!server) { - this.logger.warn(`not aware of server ${id}, my state ${JSON.stringify(Object.keys(this.servers))}`); - return; - } - else { - this.logger.debug(`removing server ${id}`); - } - Object.keys(server.methods).forEach((methodId) => { - this.removeServerMethod(id, methodId); - }); - delete this.servers[id]; - this.callbacks.execute("onServerRemoved", server.instance, reason); - } - addServerMethod(serverId, method) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - if (server.methods[method.id]) { - return; - } - const identifier = this.createMethodIdentifier(method); - const that = this; - const methodDefinition = { - identifier, - gatewayId: method.id, - name: method.name, - displayName: method.display_name, - description: method.description, - version: method.version, - objectTypes: method.object_types || [], - accepts: method.input_signature, - returns: method.result_signature, - supportsStreaming: typeof method.flags !== "undefined" ? method.flags.streaming : false, - flags: method.flags ?? {}, - getServers: () => { - return that.getServersByMethod(identifier); - } - }; - methodDefinition.object_types = methodDefinition.objectTypes; - methodDefinition.display_name = methodDefinition.displayName; - methodDefinition.version = methodDefinition.version; - server.methods[method.id] = methodDefinition; - const clientMethodDefinition = hideMethodSystemFlags(methodDefinition); - if (!this.methodsCount[identifier]) { - this.methodsCount[identifier] = 0; - this.callbacks.execute("onMethodAdded", clientMethodDefinition); - } - this.methodsCount[identifier] = this.methodsCount[identifier] + 1; - this.callbacks.execute("onServerMethodAdded", server.instance, clientMethodDefinition); - return methodDefinition; - } - removeServerMethod(serverId, methodId) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - const method = server.methods[methodId]; - delete server.methods[methodId]; - const clientMethodDefinition = hideMethodSystemFlags(method); - this.methodsCount[method.identifier] = this.methodsCount[method.identifier] - 1; - if (this.methodsCount[method.identifier] === 0) { - this.callbacks.execute("onMethodRemoved", clientMethodDefinition); - } - this.callbacks.execute("onServerMethodRemoved", server.instance, clientMethodDefinition); - } - getMethods() { - return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags); - } - getServers() { - return Object.values(this.servers).map(this.hideServerMethodSystemFlags); - } - onServerAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerAdded", callback); - const serversWithMethodsToReplay = this.getServers().map((s) => s.instance); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, serversWithMethodsToReplay, callback); - } - onMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodAdded", callback); - const methodsToReplay = this.getMethods(); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, methodsToReplay, callback); - } - onServerMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodAdded", callback); - let unsubCalled = false; - const servers = this.getServers(); - setTimeout(() => { - servers.forEach((server) => { - const methods = server.methods; - Object.keys(methods).forEach((methodId) => { - if (!unsubCalled) { - callback(server.instance, methods[methodId]); - } - }); - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - onMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodRemoved", callback); - return unsubscribeFunc; - } - onServerRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerRemoved", callback); - return unsubscribeFunc; - } - onServerMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodRemoved", callback); - return unsubscribeFunc; - } - getServerById(id) { - const server = this.servers[id]; - if (!server) { - return undefined; - } - return this.hideServerMethodSystemFlags(this.servers[id]); - } - reset() { - Object.keys(this.servers).forEach((key) => { - this.removeServerById(key, "reset"); - }); - this.servers = { - [this.myServer.id]: this.myServer - }; - this.methodsCount = {}; - } - createMethodIdentifier(methodInfo) { - const accepts = methodInfo.input_signature ?? ""; - const returns = methodInfo.result_signature ?? ""; - return (methodInfo.name + accepts + returns).toLowerCase(); - } - getServersByMethod(identifier) { - const allServers = []; - Object.values(this.servers).forEach((server) => { - Object.values(server.methods).forEach((method) => { - if (method.identifier === identifier) { - allServers.push(server.instance); - } - }); - }); - return allServers; - } - returnUnsubWithDelayedReplay(unsubscribeFunc, collectionToReplay, callback) { - let unsubCalled = false; - setTimeout(() => { - collectionToReplay.forEach((item) => { - if (!unsubCalled) { - callback(item); - } - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - hideServerMethodSystemFlags(server) { - const clientMethods = {}; - Object.entries(server.methods).forEach(([name, method]) => { - clientMethods[name] = hideMethodSystemFlags(method); - }); - return { - ...server, - methods: clientMethods - }; - } - extractMethodsFromServers(servers) { - const methods = Object.values(servers).reduce((clientMethods, server) => { - return [...clientMethods, ...Object.values(server.methods)]; - }, []); - return methods; - } - } - - class ServerRepository { - nextId = 0; - methods = []; - add(method) { - method.repoId = String(this.nextId); - this.nextId += 1; - this.methods.push(method); - return method; - } - remove(repoId) { - if (typeof repoId !== "string") { - return new TypeError("Expecting a string"); - } - this.methods = this.methods.filter((m) => { - return m.repoId !== repoId; - }); - } - getById(id) { - if (typeof id !== "string") { - return undefined; - } - return this.methods.find((m) => { - return m.repoId === id; - }); - } - getList() { - return this.methods.map((m) => m); - } - length() { - return this.methods.length; - } - reset() { - this.methods = []; - } - } - - const SUBSCRIPTION_REQUEST = "onSubscriptionRequest"; - const SUBSCRIPTION_ADDED = "onSubscriptionAdded"; - const SUBSCRIPTION_REMOVED = "onSubscriptionRemoved"; - class ServerStreaming { - session; - repository; - serverRepository; - logger; - ERR_URI_SUBSCRIPTION_FAILED = "com.tick42.agm.errors.subscription.failure"; - callbacks = CallbackRegistryFactory(); - nextStreamId = 0; - constructor(session, repository, serverRepository, logger) { - this.session = session; - this.repository = repository; - this.serverRepository = serverRepository; - this.logger = logger; - session.on("add-interest", (msg) => { - this.handleAddInterest(msg); - }); - session.on("remove-interest", (msg) => { - this.handleRemoveInterest(msg); - }); - } - acceptRequestOnBranch(requestContext, streamingMethod, branch) { - if (typeof branch !== "string") { - branch = ""; - } - if (typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - throw new TypeError("The streaming method is missing its subscriptions."); - } - if (!Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - throw new TypeError("The streaming method is missing its branches."); - } - const streamId = this.getStreamId(streamingMethod, branch); - const key = requestContext.msg.subscription_id; - const subscription = { - id: key, - arguments: requestContext.arguments, - instance: requestContext.instance, - branchKey: branch, - streamId, - subscribeMsg: requestContext.msg, - }; - streamingMethod.protocolState.subscriptionsMap[key] = subscription; - this.session.sendFireAndForget({ - type: "accepted", - subscription_id: key, - stream_id: streamId, - }).catch((err) => { - this.logger.warn(`Failed to send accepted message for subscription ${key}: ${JSON.stringify(err)}`); - }); - this.callbacks.execute(SUBSCRIPTION_ADDED, subscription, streamingMethod); - } - rejectRequest(requestContext, streamingMethod, reason) { - if (typeof reason !== "string") { - reason = ""; - } - this.sendSubscriptionFailed("Subscription rejected by user. " + reason, requestContext.msg.subscription_id); - } - pushData(streamingMethod, data, branches) { - if (typeof streamingMethod !== "object" || !Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - return; - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - if (typeof branches === "string") { - branches = [branches]; - } - else if (!Array.isArray(branches) || branches.length <= 0) { - branches = []; - } - const streamIdList = streamingMethod.protocolState.branchKeyToStreamIdMap - .filter((br) => { - if (!branches || branches.length === 0) { - return true; - } - return branches.indexOf(br.key) >= 0; - }).map((br) => { - return br.streamId; - }); - streamIdList.forEach((streamId) => { - const publishMessage = { - type: "publish", - stream_id: streamId, - data, - }; - this.session.sendFireAndForget(publishMessage) - .catch((err) => { - this.logger.warn(`Failed to send publish message for stream ${streamId}: ${JSON.stringify(err)}`); - }); - }); - } - pushDataToSingle(method, subscription, data) { - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - const postMessage = { - type: "post", - subscription_id: subscription.id, - data, - }; - this.session.sendFireAndForget(postMessage) - .catch((err) => { - this.logger.warn(`Failed to send post message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - } - closeSingleSubscription(streamingMethod, subscription) { - if (streamingMethod.protocolState.subscriptionsMap) { - delete streamingMethod.protocolState.subscriptionsMap[subscription.id]; - } - const dropSubscriptionMessage = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping a single subscription", - }; - this.session.sendFireAndForget(dropSubscriptionMessage) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - subscription.instance; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - closeMultipleSubscriptions(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object" || typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - let subscriptionsToClose = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey === "string") { - subscriptionsToClose = subscriptionsToClose.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - subscriptionsToClose.forEach((subscription) => { - delete subscriptionsMap[subscription.id]; - const drop = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping all subscriptions on stream_id: " + subscription.streamId, - }; - this.session.sendFireAndForget(drop) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - }); - } - getSubscriptionList(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object") { - return []; - } - let subscriptions = []; - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey !== "string") { - subscriptions = allSubscriptions; - } - else { - subscriptions = allSubscriptions.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - return subscriptions; - } - getBranchList(streamingMethod) { - if (typeof streamingMethod !== "object") { - return []; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - const result = []; - allSubscriptions.forEach((sub) => { - let branch = ""; - if (typeof sub === "object" && typeof sub.branchKey === "string") { - branch = sub.branchKey; - } - if (result.indexOf(branch) === -1) { - result.push(branch); - } - }); - return result; - } - onSubAdded(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED, callback); - } - onSubRequest(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST, callback); - } - onSubRemoved(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED, callback); - } - handleRemoveInterest(msg) { - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (typeof msg.subscription_id !== "string" || - typeof streamingMethod !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - if (typeof streamingMethod.protocolState.subscriptionsMap[msg.subscription_id] !== "object") { - return; - } - const subscription = streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - delete streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - onSubscriptionLifetimeEvent(eventName, handlerFunc) { - this.callbacks.add(eventName, handlerFunc); - } - getNextStreamId() { - return this.nextStreamId++ + ""; - } - handleAddInterest(msg) { - const caller = this.repository.getServerById(msg.caller_id); - const instance = caller?.instance ?? {}; - const requestContext = { - msg, - arguments: msg.arguments_kv || {}, - instance, - }; - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (streamingMethod === undefined) { - const errorMsg = "No method with id " + msg.method_id + " on this server."; - this.sendSubscriptionFailed(errorMsg, msg.subscription_id); - return; - } - if (streamingMethod.protocolState.subscriptionsMap && - streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]) { - this.sendSubscriptionFailed("A subscription with id " + msg.subscription_id + " already exists.", msg.subscription_id); - return; - } - this.callbacks.execute(SUBSCRIPTION_REQUEST, requestContext, streamingMethod); - } - sendSubscriptionFailed(reason, subscriptionId) { - const errorMessage = { - type: "error", - reason_uri: this.ERR_URI_SUBSCRIPTION_FAILED, - reason, - request_id: subscriptionId, - }; - this.session.sendFireAndForget(errorMessage) - .catch((err) => { - this.logger.warn(`Failed to send subscription failed message for subscription ${subscriptionId}: ${JSON.stringify(err)}`); - }); - } - getStreamId(streamingMethod, branchKey) { - if (typeof branchKey !== "string") { - branchKey = ""; - } - if (!streamingMethod.protocolState.branchKeyToStreamIdMap) { - throw new Error(`streaming ${streamingMethod.definition.name} method without protocol state`); - } - const needleBranch = streamingMethod.protocolState.branchKeyToStreamIdMap.filter((branch) => { - return branch.key === branchKey; - })[0]; - let streamId = (needleBranch ? needleBranch.streamId : undefined); - if (typeof streamId !== "string" || streamId === "") { - streamId = this.getNextStreamId(); - streamingMethod.protocolState.branchKeyToStreamIdMap.push({ key: branchKey, streamId }); - } - return streamId; - } - } - - class ServerProtocol { - session; - clientRepository; - serverRepository; - logger; - callbacks = CallbackRegistryFactory(); - streaming; - constructor(session, clientRepository, serverRepository, logger) { - this.session = session; - this.clientRepository = clientRepository; - this.serverRepository = serverRepository; - this.logger = logger; - this.streaming = new ServerStreaming(session, clientRepository, serverRepository, logger.subLogger("streaming")); - this.session.on("invoke", (msg) => this.handleInvokeMessage(msg)); - } - createStream(repoMethod) { - repoMethod.protocolState.subscriptionsMap = {}; - repoMethod.protocolState.branchKeyToStreamIdMap = []; - return this.register(repoMethod, true); - } - register(repoMethod, isStreaming) { - const methodDef = repoMethod.definition; - const flags = Object.assign({}, { metadata: methodDef.flags ?? {} }, { streaming: isStreaming || false }); - const registerMsg = { - type: "register", - methods: [{ - id: repoMethod.repoId, - name: methodDef.name, - display_name: methodDef.displayName, - description: methodDef.description, - version: methodDef.version, - flags, - object_types: methodDef.objectTypes || methodDef.object_types, - input_signature: methodDef.accepts, - result_signature: methodDef.returns, - restrictions: undefined, - }], - }; - return this.session.send(registerMsg, { methodId: repoMethod.repoId }) - .then(() => { - this.logger.debug("registered method " + repoMethod.definition.name + " with id " + repoMethod.repoId); - }) - .catch((msg) => { - this.logger.warn(`failed to register method ${repoMethod.definition.name} with id ${repoMethod.repoId} - ${JSON.stringify(msg)}`); - throw msg; - }); - } - onInvoked(callback) { - this.callbacks.add("onInvoked", callback); - } - methodInvocationResult(method, invocationId, err, result) { - let msg; - if (err || err === "") { - msg = { - type: "error", - request_id: invocationId, - reason_uri: "agm.errors.client_error", - reason: err, - context: result, - peer_id: undefined, - }; - } - else { - msg = { - type: "yield", - invocation_id: invocationId, - peer_id: this.session.peerId, - result, - request_id: undefined, - }; - } - this.session.sendFireAndForget(msg) - .catch((error => { - this.logger.warn(`Failed to send method invocation result for method ${method.definition.name} invocation ${invocationId} - ${JSON.stringify(error)}`); - })); - } - async unregister(method) { - const msg = { - type: "unregister", - methods: [method.repoId], - }; - await this.session.send(msg); - } - getBranchList(method) { - return this.streaming.getBranchList(method); - } - getSubscriptionList(method, branchKey) { - return this.streaming.getSubscriptionList(method, branchKey); - } - closeAllSubscriptions(method, branchKey) { - this.streaming.closeMultipleSubscriptions(method, branchKey); - } - pushData(method, data, branches) { - this.streaming.pushData(method, data, branches); - } - pushDataToSingle(method, subscription, data) { - this.streaming.pushDataToSingle(method, subscription, data); - } - closeSingleSubscription(method, subscription) { - this.streaming.closeSingleSubscription(method, subscription); - } - acceptRequestOnBranch(requestContext, method, branch) { - this.streaming.acceptRequestOnBranch(requestContext, method, branch); - } - rejectRequest(requestContext, method, reason) { - this.streaming.rejectRequest(requestContext, method, reason); - } - onSubRequest(callback) { - this.streaming.onSubRequest(callback); - } - onSubAdded(callback) { - this.streaming.onSubAdded(callback); - } - onSubRemoved(callback) { - this.streaming.onSubRemoved(callback); - } - handleInvokeMessage(msg) { - const invocationId = msg.invocation_id; - const callerId = msg.caller_id; - const methodId = msg.method_id; - const args = msg.arguments_kv; - const methodList = this.serverRepository.getList(); - const method = methodList.filter((m) => { - return m.repoId === methodId; - })[0]; - if (method === undefined) { - return; - } - const client = this.clientRepository.getServerById(callerId)?.instance; - const invocationArgs = { args, instance: client }; - this.callbacks.execute("onInvoked", method, invocationId, invocationArgs); - } - } - - class UserSubscription { - repository; - subscriptionData; - get requestArguments() { - return this.subscriptionData.params.arguments || {}; - } - get servers() { - return this.subscriptionData.trackedServers.reduce((servers, pair) => { - if (pair.subscriptionId) { - const server = this.repository.getServerById(pair.serverId)?.instance; - if (server) { - servers.push(server); - } - } - return servers; - }, []); - } - get serverInstance() { - return this.servers[0]; - } - get stream() { - return this.subscriptionData.method; - } - constructor(repository, subscriptionData) { - this.repository = repository; - this.subscriptionData = subscriptionData; - } - onData(dataCallback) { - if (typeof dataCallback !== "function") { - throw new TypeError("The data callback must be a function."); - } - this.subscriptionData.handlers.onData.push(dataCallback); - if (this.subscriptionData.handlers.onData.length === 1 && this.subscriptionData.queued.data.length > 0) { - this.subscriptionData.queued.data.forEach((dataItem) => { - dataCallback(dataItem); - }); - } - } - onClosed(closedCallback) { - if (typeof closedCallback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onClosed.push(closedCallback); - } - onFailed(callback) { - } - onConnected(callback) { - if (typeof callback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onConnected.push(callback); - } - close() { - this.subscriptionData.close(); - } - setNewSubscription(newSub) { - this.subscriptionData = newSub; - } - } - - class TimedCache { - config; - cache = []; - timeoutIds = []; - constructor(config) { - this.config = config; - } - add(element) { - const id = nanoid(10); - this.cache.push({ id, element }); - const timeoutId = setTimeout(() => { - const elementIdx = this.cache.findIndex((entry) => entry.id === id); - if (elementIdx < 0) { - return; - } - this.cache.splice(elementIdx, 1); - }, this.config.ELEMENT_TTL_MS); - this.timeoutIds.push(timeoutId); - } - flush() { - const elements = this.cache.map((entry) => entry.element); - this.timeoutIds.forEach((id) => clearInterval(id)); - this.cache = []; - this.timeoutIds = []; - return elements; - } - } - - const STATUS_AWAITING_ACCEPT = "awaitingAccept"; - const STATUS_SUBSCRIBED = "subscribed"; - const ERR_MSG_SUB_FAILED = "Subscription failed."; - const ERR_MSG_SUB_REJECTED = "Subscription rejected."; - const ON_CLOSE_MSG_SERVER_INIT = "ServerInitiated"; - const ON_CLOSE_MSG_CLIENT_INIT = "ClientInitiated"; - class ClientStreaming { - session; - repository; - logger; - subscriptionsList = {}; - timedCache = new TimedCache({ ELEMENT_TTL_MS: 10000 }); - subscriptionIdToLocalKeyMap = {}; - nextSubLocalKey = 0; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("subscribed", this.handleSubscribed); - session.on("event", this.handleEventData); - session.on("subscription-cancelled", this.handleSubscriptionCancelled); - } - subscribe(streamingMethod, params, targetServers, success, error, existingSub) { - if (targetServers.length === 0) { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " No available servers matched the target params.", - }); - return; - } - const subLocalKey = this.getNextSubscriptionLocalKey(); - const pendingSub = this.registerSubscription(subLocalKey, streamingMethod, params, success, error, params.methodResponseTimeout || 10000, existingSub); - if (typeof pendingSub !== "object") { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Unable to register the user callbacks.", - }); - return; - } - targetServers.forEach((target) => { - const serverId = target.server.id; - const method = target.methods.find((m) => m.name === streamingMethod.name); - if (!method) { - this.logger.error(`can not find method ${streamingMethod.name} for target ${target.server.id}`); - return; - } - pendingSub.trackedServers.push({ - serverId, - subscriptionId: undefined, - }); - const msg = { - type: "subscribe", - server_id: serverId, - method_id: method.gatewayId, - arguments_kv: params.arguments, - }; - this.session.send(msg, { serverId, subLocalKey }) - .then((m) => this.handleSubscribed(m)) - .catch((err) => this.handleErrorSubscribing(err)); - }); - } - drainSubscriptions() { - const existing = Object.values(this.subscriptionsList); - this.subscriptionsList = {}; - this.subscriptionIdToLocalKeyMap = {}; - return existing; - } - drainSubscriptionsCache() { - return this.timedCache.flush(); - } - getNextSubscriptionLocalKey() { - const current = this.nextSubLocalKey; - this.nextSubLocalKey += 1; - return current; - } - registerSubscription(subLocalKey, method, params, success, error, timeout, existingSub) { - const subsInfo = { - localKey: subLocalKey, - status: STATUS_AWAITING_ACCEPT, - method, - params, - success, - error, - trackedServers: [], - handlers: { - onData: existingSub?.handlers.onData || [], - onClosed: existingSub?.handlers.onClosed || [], - onConnected: existingSub?.handlers.onConnected || [], - }, - queued: { - data: [], - closers: [], - }, - timeoutId: undefined, - close: () => this.closeSubscription(subLocalKey), - subscription: existingSub?.subscription - }; - if (!existingSub) { - if (params.onData) { - subsInfo.handlers.onData.push(params.onData); - } - if (params.onClosed) { - subsInfo.handlers.onClosed.push(params.onClosed); - } - if (params.onConnected) { - subsInfo.handlers.onConnected.push(params.onConnected); - } - } - this.subscriptionsList[subLocalKey] = subsInfo; - subsInfo.timeoutId = setTimeout(() => { - if (this.subscriptionsList[subLocalKey] === undefined) { - return; - } - const pendingSub = this.subscriptionsList[subLocalKey]; - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - error({ - method, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Subscription attempt timed out after " + timeout + " ms.", - }); - delete this.subscriptionsList[subLocalKey]; - } - else if (pendingSub.status === STATUS_SUBSCRIBED && pendingSub.trackedServers.length > 0) { - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return (typeof server.subscriptionId !== "undefined"); - }); - delete pendingSub.timeoutId; - if (pendingSub.trackedServers.length <= 0) { - this.callOnClosedHandlers(pendingSub); - delete this.subscriptionsList[subLocalKey]; - } - } - }, timeout); - return subsInfo; - } - handleErrorSubscribing = (errorResponse) => { - const tag = errorResponse._tag; - const subLocalKey = tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return server.serverId !== tag.serverId; - }); - if (pendingSub.trackedServers.length <= 0) { - clearTimeout(pendingSub.timeoutId); - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - const reason = (typeof errorResponse.reason === "string" && errorResponse.reason !== "") ? - ' Publisher said "' + errorResponse.reason + '".' : - " No reason given."; - const callArgs = typeof pendingSub.params.arguments === "object" ? - JSON.stringify(pendingSub.params.arguments) : - "{}"; - pendingSub.error({ - message: ERR_MSG_SUB_REJECTED + reason + " Called with:" + callArgs, - called_with: pendingSub.params.arguments, - method: pendingSub.method, - }); - } - else if (pendingSub.status === STATUS_SUBSCRIBED) { - this.callOnClosedHandlers(pendingSub); - } - delete this.subscriptionsList[subLocalKey]; - } - }; - handleSubscribed = (msg) => { - const subLocalKey = msg._tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - const serverId = msg._tag.serverId; - const acceptingServer = pendingSub.trackedServers - .filter((server) => { - return server.serverId === serverId; - })[0]; - if (typeof acceptingServer !== "object") { - return; - } - acceptingServer.subscriptionId = msg.subscription_id; - this.subscriptionIdToLocalKeyMap[msg.subscription_id] = subLocalKey; - const isFirstResponse = (pendingSub.status === STATUS_AWAITING_ACCEPT); - pendingSub.status = STATUS_SUBSCRIBED; - if (isFirstResponse) { - let reconnect = false; - let sub = pendingSub.subscription; - if (sub) { - sub.setNewSubscription(pendingSub); - pendingSub.success(sub); - reconnect = true; - } - else { - sub = new UserSubscription(this.repository, pendingSub); - pendingSub.subscription = sub; - pendingSub.success(sub); - } - for (const handler of pendingSub.handlers.onConnected) { - try { - handler(sub.serverInstance, reconnect); - } - catch (e) { - } - } - } - }; - handleEventData = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const trackedServersFound = subscription.trackedServers.filter((s) => { - return s.subscriptionId === msg.subscription_id; - }); - if (trackedServersFound.length !== 1) { - return; - } - const isPrivateData = msg.oob; - const sendingServerId = trackedServersFound[0].serverId; - const server = this.repository.getServerById(sendingServerId); - const receivedStreamData = () => { - return { - data: msg.data, - server: server?.instance ?? {}, - requestArguments: subscription.params.arguments, - message: undefined, - private: isPrivateData, - }; - }; - const onDataHandlers = subscription.handlers.onData; - const queuedData = subscription.queued.data; - if (onDataHandlers.length > 0) { - onDataHandlers.forEach((callback) => { - if (typeof callback === "function") { - callback(receivedStreamData()); - } - }); - } - else { - queuedData.push(receivedStreamData()); - } - }; - handleSubscriptionCancelled = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const expectedNewLength = subscription.trackedServers.length - 1; - subscription.trackedServers = subscription.trackedServers.filter((server) => { - if (server.subscriptionId === msg.subscription_id) { - subscription.queued.closers.push(server.serverId); - return false; - } - else { - return true; - } - }); - if (subscription.trackedServers.length !== expectedNewLength) { - return; - } - if (subscription.trackedServers.length <= 0) { - this.timedCache.add(subscription); - clearTimeout(subscription.timeoutId); - this.callOnClosedHandlers(subscription); - delete this.subscriptionsList[subLocalKey]; - } - delete this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - }; - callOnClosedHandlers(subscription, reason) { - const closersCount = subscription.queued.closers.length; - const closingServerId = (closersCount > 0) ? subscription.queued.closers[closersCount - 1] : null; - let closingServer; - if (closingServerId !== undefined && typeof closingServerId === "string") { - closingServer = this.repository.getServerById(closingServerId)?.instance ?? {}; - } - subscription.handlers.onClosed.forEach((callback) => { - if (typeof callback !== "function") { - return; - } - callback({ - message: reason || ON_CLOSE_MSG_SERVER_INIT, - requestArguments: subscription.params.arguments || {}, - server: closingServer, - stream: subscription.method, - }); - }); - } - closeSubscription(subLocalKey) { - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - subscription.trackedServers.forEach((server) => { - if (typeof server.subscriptionId === "undefined") { - return; - } - subscription.queued.closers.push(server.serverId); - this.session.sendFireAndForget({ - type: "unsubscribe", - subscription_id: server.subscriptionId, - reason_uri: "", - reason: ON_CLOSE_MSG_CLIENT_INIT, - }).catch((err) => { - this.logger.warn(`Error sending unsubscribe for subscription id ${server.subscriptionId}: ${JSON.stringify(err)}`); - }); - delete this.subscriptionIdToLocalKeyMap[server.subscriptionId]; - }); - subscription.trackedServers = []; - this.callOnClosedHandlers(subscription, ON_CLOSE_MSG_CLIENT_INIT); - delete this.subscriptionsList[subLocalKey]; - } - } - - class ClientProtocol { - session; - repository; - logger; - streaming; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("peer-added", (msg) => this.handlePeerAdded(msg)); - session.on("peer-removed", (msg) => this.handlePeerRemoved(msg)); - session.on("methods-added", (msg) => this.handleMethodsAddedMessage(msg)); - session.on("methods-removed", (msg) => this.handleMethodsRemovedMessage(msg)); - this.streaming = new ClientStreaming(session, repository, logger); - } - subscribe(stream, options, targetServers, success, error, existingSub) { - this.streaming.subscribe(stream, options, targetServers, success, error, existingSub); - } - invoke(id, method, args, target) { - const serverId = target.id; - const methodId = method.gatewayId; - const msg = { - type: "call", - server_id: serverId, - method_id: methodId, - arguments_kv: args, - }; - return this.session.send(msg, { invocationId: id, serverId }) - .then((m) => this.handleResultMessage(m)) - .catch((err) => this.handleInvocationError(err)); - } - drainSubscriptions() { - return this.streaming.drainSubscriptions(); - } - drainSubscriptionsCache() { - return this.streaming.drainSubscriptionsCache(); - } - handlePeerAdded(msg) { - const newPeerId = msg.new_peer_id; - const remoteId = msg.identity; - const isLocal = msg.meta ? msg.meta.local : true; - const pid = Number(remoteId.process); - const serverInfo = { - machine: remoteId.machine, - pid: isNaN(pid) ? remoteId.process : pid, - instance: remoteId.instance, - application: remoteId.application, - applicationName: remoteId.applicationName, - environment: remoteId.environment, - region: remoteId.region, - user: remoteId.user, - windowId: remoteId.windowId, - peerId: newPeerId, - api: remoteId.api, - isLocal - }; - this.repository.addServer(serverInfo, newPeerId); - } - handlePeerRemoved(msg) { - const removedPeerId = msg.removed_id; - const reason = msg.reason; - this.repository.removeServerById(removedPeerId, reason); - } - handleMethodsAddedMessage(msg) { - const serverId = msg.server_id; - const methods = msg.methods; - methods.forEach((method) => { - this.repository.addServerMethod(serverId, method); - }); - } - handleMethodsRemovedMessage(msg) { - const serverId = msg.server_id; - const methodIdList = msg.methods; - const server = this.repository.getServerById(serverId); - if (server) { - const serverMethodKeys = Object.keys(server.methods); - serverMethodKeys.forEach((methodKey) => { - const method = server.methods[methodKey]; - if (methodIdList.indexOf(method.gatewayId) > -1) { - this.repository.removeServerMethod(serverId, methodKey); - } - }); - } - } - handleResultMessage(msg) { - const invocationId = msg._tag.invocationId; - const result = msg.result; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - return { - invocationId, - result, - instance: server?.instance, - status: InvokeStatus.Success, - message: "" - }; - } - handleInvocationError(msg) { - this.logger.debug(`handle invocation error ${JSON.stringify(msg)}`); - if ("_tag" in msg) { - const invocationId = msg._tag.invocationId; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - const message = msg.reason; - const context = msg.context; - return { - invocationId, - result: context, - instance: server?.instance, - status: InvokeStatus.Error, - message - }; - } - else { - return { - invocationId: "", - message: msg.message, - status: InvokeStatus.Error, - error: msg - }; - } - } - } - - function gW3ProtocolFactory (instance, connection, clientRepository, serverRepository, libConfig, interop) { - const logger = libConfig.logger.subLogger("gw3-protocol"); - let resolveReadyPromise; - const readyPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - const session = connection.domain("agm", ["subscribed"]); - const server = new ServerProtocol(session, clientRepository, serverRepository, logger.subLogger("server")); - const client = new ClientProtocol(session, clientRepository, logger.subLogger("client")); - async function handleReconnect() { - logger.info("reconnected - will replay registered methods and subscriptions"); - client.drainSubscriptionsCache().forEach((sub) => { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to soft-re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`soft-subscribing to method ${methodInfo.name} DONE`)).catch((error) => logger.warn(`subscribing to method ${methodInfo.name} failed: ${JSON.stringify(error)}}`)); - }); - const reconnectionPromises = []; - const existingSubscriptions = client.drainSubscriptions(); - for (const sub of existingSubscriptions) { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - reconnectionPromises.push(interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`subscribing to method ${methodInfo.name} DONE`))); - } - const registeredMethods = serverRepository.getList(); - serverRepository.reset(); - for (const method of registeredMethods) { - const def = method.definition; - if (method.stream) { - reconnectionPromises.push(interop.server.createStream(def, method.streamCallbacks, undefined, undefined, method.stream) - .then(() => logger.info(`subscribing to method ${def.name} DONE`)) - .catch(() => logger.warn(`subscribing to method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallback) { - reconnectionPromises.push(interop.register(def, method.theFunction.userCallback) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallbackAsync) { - reconnectionPromises.push(interop.registerAsync(def, method.theFunction.userCallbackAsync) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - } - await Promise.all(reconnectionPromises); - logger.info("Interop is re-announced"); - } - function handleInitialJoin() { - if (resolveReadyPromise) { - resolveReadyPromise({ - client, - server, - }); - resolveReadyPromise = undefined; - } - } - session.onJoined((reconnect) => { - clientRepository.addServer(instance, connection.peerId); - if (reconnect) { - handleReconnect().then(() => connection.setLibReAnnounced({ name: "interop" })).catch((error) => logger.warn(`Error while re-announcing interop: ${JSON.stringify(error)}`)); - } - else { - handleInitialJoin(); - } - }); - session.onLeft(() => { - clientRepository.reset(); - }); - session.join(); - return readyPromise; - } - - class Interop { - instance; - readyPromise; - client; - server; - unwrappedInstance; - protocol; - clientRepository; - serverRepository; - constructor(configuration) { - if (typeof configuration === "undefined") { - throw new Error("configuration is required"); - } - if (typeof configuration.connection === "undefined") { - throw new Error("configuration.connections is required"); - } - const connection = configuration.connection; - if (typeof configuration.methodResponseTimeout !== "number") { - configuration.methodResponseTimeout = 30 * 1000; - } - if (typeof configuration.waitTimeoutMs !== "number") { - configuration.waitTimeoutMs = 30 * 1000; - } - this.unwrappedInstance = new InstanceWrapper(this, undefined, connection); - this.instance = this.unwrappedInstance.unwrap(); - this.clientRepository = new ClientRepository(configuration.logger.subLogger("cRep"), this); - this.serverRepository = new ServerRepository(); - let protocolPromise; - if (connection.protocolVersion === 3) { - protocolPromise = gW3ProtocolFactory(this.instance, connection, this.clientRepository, this.serverRepository, configuration, this); - } - else { - throw new Error(`protocol ${connection.protocolVersion} not supported`); - } - this.readyPromise = protocolPromise.then((protocol) => { - this.protocol = protocol; - this.client = new Client(this.protocol, this.clientRepository, this.instance, configuration); - this.server = new Server(this.protocol, this.serverRepository); - return this; - }); - } - ready() { - return this.readyPromise; - } - serverRemoved(callback) { - return this.client.serverRemoved(callback); - } - serverAdded(callback) { - return this.client.serverAdded(callback); - } - serverMethodRemoved(callback) { - return this.client.serverMethodRemoved(callback); - } - serverMethodAdded(callback) { - return this.client.serverMethodAdded(callback); - } - methodRemoved(callback) { - return this.client.methodRemoved(callback); - } - methodAdded(callback) { - return this.client.methodAdded(callback); - } - methodsForInstance(instance) { - return this.client.methodsForInstance(instance); - } - methods(methodFilter) { - return this.client.methods(methodFilter); - } - servers(methodFilter) { - return this.client.servers(methodFilter); - } - subscribe(method, options, successCallback, errorCallback) { - return this.client.subscribe(method, options, successCallback, errorCallback); - } - createStream(streamDef, callbacks, successCallback, errorCallback) { - return this.server.createStream(streamDef, callbacks, successCallback, errorCallback); - } - unregister(methodFilter) { - return this.server.unregister(methodFilter); - } - registerAsync(methodDefinition, callback) { - return this.server.registerAsync(methodDefinition, callback); - } - register(methodDefinition, callback) { - return this.server.register(methodDefinition, callback); - } - invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - return this.client.invoke(methodFilter, argumentObj, target, additionalOptions, success, error); - } - waitForMethod(name) { - const pw = new PromiseWrapper(); - const unsubscribe = this.client.methodAdded((m) => { - if (m.name === name) { - unsubscribe(); - pw.resolve(m); - } - }); - return pw.promise; - } - } - - const successMessages = ["subscribed", "success"]; - class MessageBus { - connection; - logger; - peerId; - session; - subscriptions; - readyPromise; - constructor(connection, logger) { - this.connection = connection; - this.logger = logger; - this.peerId = connection.peerId; - this.subscriptions = []; - this.session = connection.domain("bus", successMessages); - this.readyPromise = this.session.join(); - this.readyPromise.then(() => { - this.watchOnEvent(); - }); - } - ready() { - return this.readyPromise; - } - publish = (topic, data, options) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "publish", - topic, - data, - peer_id: this.peerId, - routing_key: routingKey, - target_identity: target - }); - this.session.send(args) - .catch((err) => { - this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`); - }); - }; - subscribe = (topic, callback, options) => { - return new Promise((resolve, reject) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "subscribe", - topic, - peer_id: this.peerId, - routing_key: routingKey, - source: target - }); - this.session.send(args) - .then((response) => { - const { subscription_id } = response; - this.subscriptions.push({ subscription_id, topic, callback, source: target }); - resolve({ - unsubscribe: () => { - this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId }) - .then(() => { - this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id); - }).catch((err) => { - this.logger.warn(`Failed to send unsubscribe request for ${subscription_id}: ${JSON.stringify(err)}`); - }); - return Promise.resolve(); - } - }); - }) - .catch((error) => reject(error)); - }); - }; - watchOnEvent = () => { - this.session.on("event", (args) => { - const { data, subscription_id } = args; - const source = args["publisher-identity"]; - const subscription = this.subscriptions.find((s) => s.subscription_id === subscription_id); - if (subscription) { - if (!subscription.source) { - subscription.callback(data, subscription.topic, source); - } - else { - if (this.keysMatch(subscription.source, source)) { - subscription.callback(data, subscription.topic, source); - } - } - } - }); - }; - removeEmptyValues(obj) { - const cleaned = {}; - Object.keys(obj).forEach((key) => { - if (obj[key] !== undefined && obj[key] !== null) { - cleaned[key] = obj[key]; - } - }); - return cleaned; - } - keysMatch(obj1, obj2) { - const keysObj1 = Object.keys(obj1); - let allMatch = true; - keysObj1.forEach((key) => { - if (obj1[key] !== obj2[key]) { - allMatch = false; - } - }); - return allMatch; - } - } - - const IOConnectCoreFactory = (userConfig, ext) => { - const iodesktop = typeof window === "object" ? (window.iodesktop ?? window.glue42gd) : undefined; - const preloadPromise = typeof window === "object" ? (window.gdPreloadPromise ?? Promise.resolve()) : Promise.resolve(); - const glueInitTimer = timer("glue"); - userConfig = userConfig || {}; - ext = ext || {}; - const internalConfig = prepareConfig(userConfig, ext, iodesktop); - let _connection; - let _interop; - let _logger; - let _metrics; - let _contexts; - let _bus; - let _allowTrace; - const libs = {}; - function registerLib(name, inner, t) { - _allowTrace = _logger.canPublish("trace"); - if (_allowTrace) { - _logger.trace(`registering ${name} module`); - } - const done = (e) => { - inner.initTime = t.stop(); - inner.initEndTime = t.endTime; - inner.marks = t.marks; - if (!_allowTrace) { - return; - } - const traceMessage = e ? - `${name} failed - ${e.message}` : - `${name} is ready - ${t.endTime - t.startTime}`; - _logger.trace(traceMessage); - }; - inner.initStartTime = t.startTime; - if (inner.ready) { - inner.ready() - .then(() => { - done(); - }) - .catch((e) => { - const error = typeof e === "string" ? new Error(e) : e; - done(error); - }); - } - else { - done(); - } - if (!Array.isArray(name)) { - name = [name]; - } - name.forEach((n) => { - libs[n] = inner; - IOConnectCoreFactory[n] = inner; - }); - } - function setupConnection() { - const initTimer = timer("connection"); - _connection = new Connection(internalConfig.connection, _logger.subLogger("connection")); - let authPromise = Promise.resolve(internalConfig.auth); - if (internalConfig.connection && !internalConfig.auth) { - if (iodesktop) { - authPromise = iodesktop.getGWToken() - .then((token) => { - return { - gatewayToken: token - }; - }); - } - else if (typeof window !== "undefined" && window?.glue42electron) { - if (typeof window.glue42electron.gwToken === "string") { - authPromise = Promise.resolve({ - gatewayToken: window.glue42electron.gwToken - }); - } - } - else { - authPromise = Promise.reject("You need to provide auth information"); - } - } - return authPromise - .then((authConfig) => { - initTimer.mark("auth-promise-resolved"); - let authRequest; - if (Object.prototype.toString.call(authConfig) === "[object Object]") { - authRequest = authConfig; - } - else { - throw new Error("Invalid auth object - " + JSON.stringify(authConfig)); - } - return _connection.login(authRequest); - }) - .then(() => { - registerLib("connection", _connection, initTimer); - return internalConfig; - }) - .catch((e) => { - if (_connection) { - _connection.logout(); - } - throw e; - }); - } - function setupLogger() { - const initTimer = timer("logger"); - _logger = new Logger(`${internalConfig.connection.identity?.application}`, undefined, internalConfig.customLogger); - _logger.consoleLevel(internalConfig.logger.console); - _logger.publishLevel(internalConfig.logger.publish); - if (_logger.canPublish("debug")) { - _logger.debug("initializing glue..."); - } - registerLib("logger", _logger, initTimer); - return Promise.resolve(undefined); - } - function setupMetrics() { - const initTimer = timer("metrics"); - const config = internalConfig.metrics; - const metricsPublishingEnabledFunc = iodesktop?.getMetricsPublishingEnabled; - const identity = internalConfig.connection.identity; - const canUpdateMetric = metricsPublishingEnabledFunc ? metricsPublishingEnabledFunc : () => true; - const disableAutoAppSystem = (typeof config !== "boolean" && config.disableAutoAppSystem) ?? false; - _metrics = metrics({ - connection: config ? _connection : undefined, - logger: _logger.subLogger("metrics"), - canUpdateMetric, - system: "Glue42", - service: identity?.service ?? iodesktop?.applicationName ?? internalConfig.application, - instance: identity?.instance ?? identity?.windowId ?? nanoid(10), - disableAutoAppSystem, - pagePerformanceMetrics: typeof config !== "boolean" ? config?.pagePerformanceMetrics : undefined - }); - registerLib("metrics", _metrics, initTimer); - return Promise.resolve(); - } - function setupInterop() { - const initTimer = timer("interop"); - const agmConfig = { - connection: _connection, - logger: _logger.subLogger("interop"), - }; - _interop = new Interop(agmConfig); - Logger.Interop = _interop; - registerLib(["interop", "agm"], _interop, initTimer); - return Promise.resolve(); - } - function setupContexts() { - const hasActivities = (internalConfig.activities && _connection.protocolVersion === 3); - const needsContexts = internalConfig.contexts || hasActivities; - if (needsContexts) { - const initTimer = timer("contexts"); - _contexts = new ContextsModule({ - connection: _connection, - logger: _logger.subLogger("contexts"), - trackAllContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.trackAllContexts : false, - reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false, - subscribeOnGet: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnGet : true, - subscribeOnUpdate: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnUpdate : true, - onlyReAnnounceSubscribedContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.onlyReAnnounceSubscribedContexts : true - }); - registerLib("contexts", _contexts, initTimer); - } - else { - const replayer = _connection.replayer; - if (replayer) { - replayer.drain(ContextMessageReplaySpec.name); - } - } - return Promise.resolve(); - } - async function setupBus() { - if (!internalConfig.bus) { - return Promise.resolve(); - } - const initTimer = timer("bus"); - _bus = new MessageBus(_connection, _logger.subLogger("bus")); - registerLib("bus", _bus, initTimer); - return Promise.resolve(); - } - function setupExternalLibs(externalLibs) { - try { - externalLibs.forEach((lib) => { - setupExternalLib(lib.name, lib.create); - }); - return Promise.resolve(); - } - catch (e) { - return Promise.reject(e); - } - } - function setupExternalLib(name, createCallback) { - const initTimer = timer(name); - const lib = createCallback(libs); - if (lib) { - registerLib(name, lib, initTimer); - } - } - function waitForLibs() { - const libsReadyPromises = Object.keys(libs).map((key) => { - const lib = libs[key]; - return lib.ready ? - lib.ready() : Promise.resolve(); - }); - return Promise.all(libsReadyPromises); - } - function constructGlueObject() { - const feedbackFunc = (feedbackInfo) => { - if (!_interop) { - return; - } - _interop.invoke("T42.ACS.Feedback", feedbackInfo, "best"); - }; - const info = { - coreVersion: version, - version: internalConfig.version - }; - glueInitTimer.stop(); - const glue = { - feedback: feedbackFunc, - info, - logger: _logger, - interop: _interop, - agm: _interop, - connection: _connection, - metrics: _metrics, - contexts: _contexts, - bus: _bus, - version: internalConfig.version, - userConfig, - done: () => { - _logger?.info("done called by user..."); - return _connection.logout(); - } - }; - glue.performance = { - get glueVer() { - return internalConfig.version; - }, - get glueConfig() { - return JSON.stringify(userConfig); - }, - get browser() { - return window.performance.timing.toJSON(); - }, - get memory() { - return window.performance.memory; - }, - get initTimes() { - const all = getAllTimers(); - return Object.keys(all).map((key) => { - const t = all[key]; - return { - name: key, - duration: t.endTime - t.startTime, - marks: t.marks, - startTime: t.startTime, - endTime: t.endTime - }; - }); - } - }; - Object.keys(libs).forEach((key) => { - const lib = libs[key]; - glue[key] = lib; - }); - glue.config = {}; - Object.keys(internalConfig).forEach((k) => { - glue.config[k] = internalConfig[k]; - }); - if (ext && ext.extOptions) { - Object.keys(ext.extOptions).forEach((k) => { - glue.config[k] = ext?.extOptions[k]; - }); - } - if (ext?.enrichGlue) { - ext.enrichGlue(glue); - } - if (iodesktop && iodesktop.updatePerfData) { - iodesktop.updatePerfData(glue.performance); - } - if (glue.agm) { - const deprecatedDecorator = (fn, wrong, proper) => { - return function () { - glue.logger.warn(`glue.js - 'glue.agm.${wrong}' method is deprecated, use 'glue.interop.${proper}' instead.`); - return fn.apply(glue.agm, arguments); - }; - }; - const agmAny = glue.agm; - agmAny.method_added = deprecatedDecorator(glue.agm.methodAdded, "method_added", "methodAdded"); - agmAny.method_removed = deprecatedDecorator(glue.agm.methodRemoved, "method_removed", "methodRemoved"); - agmAny.server_added = deprecatedDecorator(glue.agm.serverAdded, "server_added", "serverAdded"); - agmAny.server_method_aded = deprecatedDecorator(glue.agm.serverMethodAdded, "server_method_aded", "serverMethodAdded"); - agmAny.server_method_removed = deprecatedDecorator(glue.agm.serverMethodRemoved, "server_method_removed", "serverMethodRemoved"); - } - return glue; - } - async function registerInstanceIfNeeded() { - const RegisterInstanceMethodName = "T42.ACS.RegisterInstance"; - if (Utils.isNode() && typeof process.env._GD_STARTING_CONTEXT_ === "undefined" && typeof userConfig?.application !== "undefined") { - const isMethodAvailable = _interop.methods({ name: RegisterInstanceMethodName }).length > 0; - if (isMethodAvailable) { - try { - await _interop.invoke(RegisterInstanceMethodName, { appName: userConfig?.application, pid: process.pid }); - } - catch (error) { - const typedError = error; - _logger.error(`Cannot register as an instance: ${JSON.stringify(typedError.message)}`); - } - } - } - } - return preloadPromise - .then(setupLogger) - .then(setupConnection) - .then(() => Promise.all([setupMetrics(), setupInterop(), setupContexts(), setupBus()])) - .then(() => _interop.readyPromise) - .then(() => registerInstanceIfNeeded()) - .then(() => { - return setupExternalLibs(internalConfig.libs || []); - }) - .then(waitForLibs) - .then(constructGlueObject) - .catch((err) => { - return Promise.reject({ - err, - libs - }); - }); - }; - if (typeof window !== "undefined") { - window.IOConnectCore = IOConnectCoreFactory; - } - IOConnectCoreFactory.version = version; - IOConnectCoreFactory.default = IOConnectCoreFactory; - - const iOConnectBrowserFactory = createFactoryFunction(IOConnectCoreFactory); - if (typeof window !== "undefined") { - const windowAny = window; - windowAny.IOBrowser = iOConnectBrowserFactory; - delete windowAny.GlueCore; - delete windowAny.IOConnectCore; - } - const legacyGlobal = window.glue42gd || window.glue42core; - const ioGlobal = window.iodesktop || window.iobrowser; - if (!legacyGlobal && !ioGlobal) { - window.iobrowser = { webStarted: false }; - } - if (!window.iodesktop && !window.iobrowser.system) { - window.iobrowser.system = setupGlobalSystem(); - } - iOConnectBrowserFactory.version = version$1; - - return iOConnectBrowserFactory; - -})); -//# sourceMappingURL=browser.umd.js.map diff --git a/javascript/start/client-details/lib/workspaces.umd.js b/javascript/start/client-details/lib/workspaces.umd.js deleted file mode 100644 index 8d833a0..0000000 --- a/javascript/start/client-details/lib/workspaces.umd.js +++ /dev/null @@ -1,5618 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.workspaces = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder.oneOf; - /** See `Decoder.union` */ - Decoder.union; - /** See `Decoder.intersection` */ - var intersection = Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - Decoder.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder.lazy; - - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number"); - const positiveNumberDecoder = number().where((num) => num > 0, "Expected a positive number"); - const windowDragModeDecoder = oneOf(constant("keepInside"), constant("autoEject")); - const isWindowInSwimlaneResultDecoder = object({ - inWorkspace: boolean() - }); - const frameVisibilityResultDecoder = object({ - isVisible: boolean() - }); - const iconDecoder = object({ - base64Image: nonEmptyStringDecoder - }); - const setIconArgumentsDecoder = object({ - icon: iconDecoder, - frameId: nonEmptyStringDecoder - }); - const allParentDecoder = oneOf(constant("workspace"), constant("row"), constant("column"), constant("group")); - const subParentDecoder = oneOf(constant("row"), constant("column"), constant("group")); - const frameStateDecoder = oneOf(constant("maximized"), constant("minimized"), constant("normal")); - const loadingAnimationTypeDecoder = oneOf(constant("workspace")); - const checkThrowCallback = (callback, allowUndefined) => { - const argumentType = typeof callback; - if (allowUndefined && argumentType !== "function" && argumentType !== "undefined") { - throw new Error(`Provided argument must be either undefined or of type function, provided: ${argumentType}`); - } - if (!allowUndefined && argumentType !== "function") { - throw new Error(`Provided argument must be of type function, provided: ${argumentType}`); - } - }; - const workspaceBuilderCreateConfigDecoder = optional(object({ - saveLayout: optional(boolean()) - })); - const deleteLayoutConfigDecoder = object({ - name: nonEmptyStringDecoder - }); - const windowDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const groupDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropHeader: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()) - }); - const rowDefinitionConfigDecoder = object({ - minHeight: optional(number()), - maxHeight: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const columnDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const swimlaneWindowDefinitionDecoder = object({ - type: optional(constant("window")), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const strictSwimlaneWindowDefinitionDecoder = object({ - type: constant("window"), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const parentDefinitionDecoder = optional(object({ - type: optional(subParentDecoder), - children: optional(lazy(() => array(oneOf(swimlaneWindowDefinitionDecoder, parentDefinitionDecoder)))), - config: optional(anyJson()) - })); - const strictColumnDefinitionDecoder = object({ - type: constant("column"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(columnDefinitionConfigDecoder) - }); - const strictRowDefinitionDecoder = object({ - type: constant("row"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(rowDefinitionConfigDecoder) - }); - const strictGroupDefinitionDecoder = object({ - type: constant("group"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(groupDefinitionConfigDecoder) - }); - const strictParentDefinitionDecoder = oneOf(strictGroupDefinitionDecoder, strictColumnDefinitionDecoder, strictRowDefinitionDecoder); - oneOf(string().where((s) => s.toLowerCase() === "maximized", "Expected a case insensitive variation of 'maximized'"), string().where((s) => s.toLowerCase() === "normal", "Expected a case insensitive variation of 'normal'")); - const newFrameConfigDecoder = object({ - bounds: optional(object({ - left: optional(number()), - top: optional(number()), - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - })), - isVisible: optional(boolean()), - frameId: optional(nonEmptyStringDecoder) - }); - const loadingStrategyDecoder = oneOf(constant("direct"), constant("delayed"), constant("lazy")); - const restoreWorkspaceConfigDecoder = optional(object({ - app: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - loadingStrategy: optional(loadingStrategyDecoder), - title: optional(nonEmptyStringDecoder), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - frameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - lockdown: optional(boolean()), - activateFrame: optional(boolean()), - newFrame: optional(oneOf(newFrameConfigDecoder, boolean())), - noTabHeader: optional(boolean()), - inMemoryLayout: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - allowSystemHibernation: optional(boolean()) - })); - const openWorkspaceConfigDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const workspaceDefinitionDecoder = object({ - children: optional(array(oneOf(swimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder))), - context: optional(anyJson()), - config: optional(object({ - title: optional(nonEmptyStringDecoder), - position: optional(nonNegativeNumberDecoder), - isFocused: optional(boolean()), - noTabHeader: optional(boolean()), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - loadingStrategy: optional(loadingStrategyDecoder), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showCloseButton: optional(boolean()), - allowSplitters: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - windowDragMode: optional(windowDragModeDecoder) - })), - frame: optional(object({ - activate: optional(boolean()), - reuseFrameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - newFrame: optional(oneOf(boolean(), newFrameConfigDecoder)) - })) - }); - const workspaceSelectorDecoder = object({ - workspaceId: nonEmptyStringDecoder - }); - const restoreWorkspaceDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const emptyFrameDefinitionDecoder = optional(object({ - applicationName: optional(string()), - frameConfig: optional(newFrameConfigDecoder), - context: optional(object()), - layoutComponentId: optional(nonEmptyStringDecoder) - })); - const frameInitConfigDecoder = object({ - workspaces: array(oneOf(optional(workspaceDefinitionDecoder), optional(restoreWorkspaceDefinitionDecoder))) - }); - const frameInitProtocolConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaces: array(oneOf(workspaceDefinitionDecoder, restoreWorkspaceDefinitionDecoder)) - }); - const builderConfigDecoder = object({ - type: allParentDecoder, - definition: optional(oneOf(workspaceDefinitionDecoder, parentDefinitionDecoder)) - }); - const workspaceCreateConfigDecoder = intersection(workspaceDefinitionDecoder, object({ - saveConfig: optional(object({ - saveLayout: optional(boolean()) - })) - })); - const getFrameSummaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const frameInitializationContextDecoder = object({ - context: optional(object()) - }); - const frameSummaryDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - object({ - type: subParentDecoder, - id: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number() - }); - const eventTypeDecoder = oneOf(constant("frame"), constant("workspace"), constant("container"), constant("window")); - const streamRequestArgumentsDecoder = object({ - type: eventTypeDecoder, - branch: nonEmptyStringDecoder - }); - const workspaceEventActionDecoder = oneOf(constant("opened"), constant("closing"), constant("closed"), constant("focus"), constant("added"), constant("loaded"), constant("removed"), constant("childrenUpdate"), constant("containerChange"), constant("maximized"), constant("restored"), constant("minimized"), constant("normal"), constant("selected"), constant("lock-configuration-changed"), constant("hibernated"), constant("resumed")); - const workspaceConfigResultDecoder = object({ - frameId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder, - positionIndex: nonNegativeNumberDecoder, - name: nonEmptyStringDecoder, - layoutName: optional(nonEmptyStringDecoder), - isHibernated: optional(boolean()), - isSelected: optional(boolean()), - allowDrop: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - widthInPx: optional(number()), - heightInPx: optional(number()), - isPinned: optional(boolean()), - windowDragMode: optional(windowDragModeDecoder), - loadingStrategy: optional(loadingStrategyDecoder) - }); - const baseChildSnapshotConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number(), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()) - }); - const parentSnapshotConfigDecoder = anyJson(); - const swimlaneWindowSnapshotConfigDecoder = intersection(baseChildSnapshotConfigDecoder, object({ - windowId: optional(nonEmptyStringDecoder), - isMaximized: optional(boolean()), - isFocused: boolean(), - isSelected: optional(boolean()), - title: optional(string()), - appName: optional(nonEmptyStringDecoder), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - widthInPx: optional(number()), - heightInPx: optional(number()), - context: optional(anyJson()) - })); - const customWorkspaceSubParentSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: parentSnapshotConfigDecoder, - children: optional(lazy(() => array(customWorkspaceChildSnapshotDecoder))), - type: oneOf(constant("row"), constant("column"), constant("group")) - }); - const customWorkspaceWindowSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: swimlaneWindowSnapshotConfigDecoder, - type: constant("window") - }); - const customWorkspaceChildSnapshotDecoder = oneOf(customWorkspaceWindowSnapshotDecoder, customWorkspaceSubParentSnapshotDecoder); - const childSnapshotResultDecoder = customWorkspaceChildSnapshotDecoder; - const workspaceSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder, - children: array(childSnapshotResultDecoder), - frameSummary: frameSummaryDecoder, - context: optional(anyJson()) - }); - const windowLayoutItemDecoder = object({ - type: constant("window"), - config: object({ - appName: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - url: optional(nonEmptyStringDecoder), - title: optional(string()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - isMaximized: optional(boolean()) - }) - }); - const groupLayoutItemDecoder = object({ - type: constant("group"), - config: anyJson(), - children: array(oneOf(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object({ - type: constant("column"), - config: anyJson(), - children: array(oneOf(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object({ - type: constant("row"), - config: anyJson(), - children: array(oneOf(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutDecoder = object({ - name: nonEmptyStringDecoder, - type: constant("Workspace"), - metadata: optional(anyJson()), - components: array(object({ - type: constant("Workspace"), - application: optional(string()), - state: object({ - config: anyJson(), - context: anyJson(), - children: array(oneOf(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }) - })) - }); - const workspacesImportLayoutDecoder = object({ - layout: workspaceLayoutDecoder, - mode: oneOf(constant("replace"), constant("merge")) - }); - const workspacesImportLayoutsDecoder = object({ - layouts: array(workspaceLayoutDecoder), - mode: oneOf(constant("replace"), constant("merge")) - }); - const exportedLayoutsResultDecoder = object({ - layouts: array(workspaceLayoutDecoder) - }); - const frameSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - const frameSummariesResultDecoder = object({ - summaries: array(frameSummaryResultDecoder) - }); - const workspaceSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder - }); - const workspaceSummariesResultDecoder = object({ - summaries: array(workspaceSummaryResultDecoder) - }); - const frameSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: anyJson(), - workspaces: array(workspaceSnapshotResultDecoder) - }); - const layoutSummaryDecoder = object({ - name: nonEmptyStringDecoder, - applicationName: optional(string()) - }); - const layoutSummariesDecoder = object({ - summaries: array(layoutSummaryDecoder) - }); - const simpleWindowOperationSuccessResultDecoder = object({ - windowId: nonEmptyStringDecoder - }); - const voidResultDecoder = anyJson(); - const frameStateResultDecoder = object({ - state: frameStateDecoder - }); - const frameBoundsDecoder = object({ - top: number(), - left: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const frameBoundsResultDecoder = object({ - bounds: frameBoundsDecoder - }); - const getWorkspaceIconResultDecoder = object({ - icon: optional(nonEmptyStringDecoder) - }); - const getPlatformFrameIdResultDecoder = object({ - id: optional(nonEmptyStringDecoder) - }); - const operationCheckResultDecoder = object({ - isSupported: boolean() - }); - const resizeConfigDecoder = object({ - width: optional(positiveNumberDecoder), - height: optional(positiveNumberDecoder), - relative: optional(boolean()) - }); - const moveConfigDecoder = object({ - top: optional(number()), - left: optional(number()), - relative: optional(boolean()) - }); - const simpleItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const closeOptionsDecoder = object({ - allowPrevent: optional(boolean()), - showDialog: optional(boolean()), - }); - const closeItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - closeOptions: optional(closeOptionsDecoder) - }); - const frameSnapshotConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - excludeIds: optional(boolean()) - }); - const frameStateConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - requestedState: frameStateDecoder - }); - const setItemTitleConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder - }); - const moveWindowConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - containerId: nonEmptyStringDecoder - }); - const resizeItemConfigDecoder = intersection(simpleItemConfigDecoder, resizeConfigDecoder); - const setMaximizationBoundaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - enabled: boolean() - }); - const moveFrameConfigDecoder = intersection(simpleItemConfigDecoder, moveConfigDecoder); - object({ - id: nonEmptyStringDecoder, - type: subParentDecoder - }); - const addWindowConfigDecoder = object({ - definition: swimlaneWindowDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addContainerConfigDecoder = object({ - definition: strictParentDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addItemResultDecoder = object({ - itemId: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder) - }); - const pingResultDecoder = object({ - live: boolean() - }); - const bundleWorkspaceConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - workspaceId: nonEmptyStringDecoder - }); - const bundleItemConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - itemId: nonEmptyStringDecoder - }); - const containerSummaryResultDecoder = object({ - itemId: nonEmptyStringDecoder, - config: parentSnapshotConfigDecoder - }); - const frameStreamDataDecoder = object({ - frameSummary: frameSummaryDecoder, - frameBounds: optional(frameBoundsDecoder) - }); - const workspaceStreamDataDecoder = object({ - workspaceSummary: workspaceSummaryResultDecoder, - frameSummary: frameSummaryDecoder, - workspaceSnapshot: optional(workspaceSnapshotResultDecoder), - frameBounds: optional(frameBoundsDecoder) - }); - const containerStreamDataDecoder = object({ - containerSummary: containerSummaryResultDecoder - }); - const windowStreamDataDecoder = object({ - windowSummary: object({ - itemId: nonEmptyStringDecoder, - parentId: nonEmptyStringDecoder, - config: swimlaneWindowSnapshotConfigDecoder - }) - }); - const workspaceLayoutSaveConfigDecoder = object({ - name: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - saveContext: optional(boolean()), - allowMultiple: optional(boolean()), - metadata: optional(object()) - }); - const workspaceLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - }); - const lockWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - config: optional(workspaceLockConfigDecoder) - }); - const windowLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const elementResizeConfigDecoder = object({ - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - }); - const lockWindowDecoder = object({ - windowPlacementId: nonEmptyStringDecoder, - config: optional(windowLockConfigDecoder) - }); - const rowLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const columnLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const groupLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - allowDropHeader: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()), - }); - const lockRowDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("row"), - config: optional(rowLockConfigDecoder) - }); - const lockColumnDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("column"), - config: optional(columnLockConfigDecoder) - }); - const lockGroupDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("group"), - config: optional(groupLockConfigDecoder) - }); - const lockContainerDecoder = oneOf(lockRowDecoder, lockColumnDecoder, lockGroupDecoder); - const pinWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const setWorkspaceIconDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const workspacePinOptionsDecoder = optional(object({ - icon: optional(nonEmptyStringDecoder) - })); - const frameShowConfigDecoder = optional(object({ - activate: optional(boolean()) - })); - const shortcutConfigDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const shortcutClickedDataDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const frameClosingDataDecoder = object({ - frameId: nonEmptyStringDecoder, - }); - const setMaximizationBoundaryAPIConfigDecoder = object({ - enabled: boolean() - }); - const loadingAnimationConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - type: loadingAnimationTypeDecoder - }); - const operationCheckConfigDecoder = object({ - operation: nonEmptyStringDecoder - }); - const setWindowDragModeDecoder = object({ - itemId: nonEmptyStringDecoder, - dragMode: windowDragModeDecoder - }); - const setLoadingStrategyDecoder = object({ - itemId: nonEmptyStringDecoder, - strategy: loadingStrategyDecoder - }); - const frameClosingResultDecoder = object({ - prevent: boolean() - }); - const sizeDecoder = object({ - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const boundsDecoder = object({ - left: number(), - top: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const popupTargetLocationDecoder = oneOf(constant("none"), constant("left"), constant("right"), constant("top"), constant("bottom")); - const popupConfigDecoder = object({ - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const ShowPopupConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const changeFrameVisibilityConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - activate: optional(boolean()), - isVisible: boolean() - }); - const frameDialogOptionsDecoder = object({ - mode: optional(oneOf(constant("Global"), constant("WindowContainer"))), - type: string(), - size: optional(sizeDecoder), - message: nonEmptyStringDecoder, - messageTitle: optional(nonEmptyStringDecoder), - movable: optional(boolean()), - transparent: optional(boolean()), - title: nonEmptyStringDecoder, - context: optional(anyJson()), - affirmativeButtonName: optional(nonEmptyStringDecoder), - showAffirmativeButton: optional(boolean()), - cancelButtonName: optional(nonEmptyStringDecoder), - showCancelButton: optional(boolean()), - negativeButtonName: optional(nonEmptyStringDecoder), - showNegativeButton: optional(boolean()), - defaultAction: optional(oneOf(constant("affirmative"), constant("negative"), constant("cancel"))), - timerDuration: optional(positiveNumberDecoder), - showTimer: optional(boolean()), - inputMaxLength: optional(positiveNumberDecoder), - inputPattern: optional(nonEmptyStringDecoder), - inputPatternErrorMessage: optional(nonEmptyStringDecoder), - inputPlaceholder: optional(string()), - blur: optional(boolean()) - }); - const showFrameDialogConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - options: frameDialogOptionsDecoder - }); - - const webPlatformMethodName = "T42.Web.Platform.Control"; - const webPlatformWspStreamName = "T42.Web.Platform.WSP.Stream"; - const OUTGOING_METHODS = { - control: { name: "T42.Workspaces.Control", isStream: false }, - frameStream: { name: "T42.Workspaces.Stream.Frame", isStream: true }, - workspaceStream: { name: "T42.Workspaces.Stream.Workspace", isStream: true }, - containerStream: { name: "T42.Workspaces.Stream.Container", isStream: true }, - windowStream: { name: "T42.Workspaces.Stream.Window", isStream: true } - }; - const INCOMING_METHODS = { - control: { name: "T42.Workspaces.Client.Control", isStream: false }, - }; - const STREAMS = { - frame: { name: "T42.Workspaces.Stream.Frame", payloadDecoder: frameStreamDataDecoder }, - workspace: { name: "T42.Workspaces.Stream.Workspace", payloadDecoder: workspaceStreamDataDecoder }, - container: { name: "T42.Workspaces.Stream.Container", payloadDecoder: containerStreamDataDecoder }, - window: { name: "T42.Workspaces.Stream.Window", payloadDecoder: windowStreamDataDecoder } - }; - const CLIENT_OPERATIONS = { - shortcutClicked: { name: "shortcutClicked", argsDecoder: shortcutClickedDataDecoder, resultDecoder: voidResultDecoder }, - frameClosing: { name: "frameClosing", argsDecoder: frameClosingDataDecoder, resultDecoder: frameClosingResultDecoder }, - }; - const OPERATIONS = { - ping: { name: "ping", resultDecoder: pingResultDecoder }, - isWindowInWorkspace: { name: "isWindowInWorkspace", argsDecoder: simpleItemConfigDecoder, resultDecoder: isWindowInSwimlaneResultDecoder }, - createWorkspace: { name: "createWorkspace", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: workspaceCreateConfigDecoder }, - createFrame: { name: "createFrame", resultDecoder: frameSummaryResultDecoder, argsDecoder: emptyFrameDefinitionDecoder }, - initFrame: { name: "initFrame", resultDecoder: voidResultDecoder, argsDecoder: frameInitProtocolConfigDecoder }, - getAllFramesSummaries: { name: "getAllFramesSummaries", resultDecoder: frameSummariesResultDecoder }, - getFrameSummary: { name: "getFrameSummary", resultDecoder: frameSummaryDecoder, argsDecoder: getFrameSummaryConfigDecoder }, - getAllWorkspacesSummaries: { name: "getAllWorkspacesSummaries", resultDecoder: workspaceSummariesResultDecoder }, - getWorkspaceSnapshot: { name: "getWorkspaceSnapshot", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: simpleItemConfigDecoder }, - getAllLayoutsSummaries: { name: "getAllLayoutsSummaries", resultDecoder: layoutSummariesDecoder }, - openWorkspace: { name: "openWorkspace", argsDecoder: openWorkspaceConfigDecoder, resultDecoder: workspaceSnapshotResultDecoder }, - deleteLayout: { name: "deleteLayout", resultDecoder: voidResultDecoder, argsDecoder: deleteLayoutConfigDecoder }, - saveLayout: { name: "saveLayout", resultDecoder: workspaceLayoutDecoder, argsDecoder: workspaceLayoutSaveConfigDecoder }, - importLayout: { name: "importLayout", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutDecoder }, - importLayouts: { name: "importLayouts", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutsDecoder }, - exportAllLayouts: { name: "exportAllLayouts", resultDecoder: exportedLayoutsResultDecoder }, - restoreItem: { name: "restoreItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - maximizeItem: { name: "maximizeItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - focusItem: { name: "focusItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeItem: { name: "closeItem", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeWorkspace: { name: "closeWorkspace", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - resizeItem: { name: "resizeItem", argsDecoder: resizeItemConfigDecoder, resultDecoder: voidResultDecoder }, - setMaximizationBoundary: { name: "setMaximizationBoundary", argsDecoder: setMaximizationBoundaryConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameState: { name: "changeFrameState", argsDecoder: frameStateConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameState: { name: "getFrameState", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameStateResultDecoder }, - getFrameBounds: { name: "getFrameBounds", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameBoundsResultDecoder }, - moveFrame: { name: "moveFrame", argsDecoder: moveFrameConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameSnapshot: { name: "getFrameSnapshot", argsDecoder: frameSnapshotConfigDecoder, resultDecoder: frameSnapshotResultDecoder }, - forceLoadWindow: { name: "forceLoadWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - ejectWindow: { name: "ejectWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - setItemTitle: { name: "setItemTitle", argsDecoder: setItemTitleConfigDecoder, resultDecoder: voidResultDecoder }, - moveWindowTo: { name: "moveWindowTo", argsDecoder: moveWindowConfigDecoder, resultDecoder: voidResultDecoder }, - addWindow: { name: "addWindow", argsDecoder: addWindowConfigDecoder, resultDecoder: addItemResultDecoder }, - addContainer: { name: "addContainer", argsDecoder: addContainerConfigDecoder, resultDecoder: addItemResultDecoder }, - bundleWorkspace: { name: "bundleWorkspace", argsDecoder: bundleWorkspaceConfigDecoder, resultDecoder: voidResultDecoder }, - bundleItem: { name: "bundleItem", argsDecoder: bundleItemConfigDecoder, resultDecoder: voidResultDecoder }, - hibernateWorkspace: { name: "hibernateWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - resumeWorkspace: { name: "resumeWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - lockWorkspace: { name: "lockWorkspace", argsDecoder: lockWorkspaceDecoder, resultDecoder: voidResultDecoder }, - lockWindow: { name: "lockWindow", argsDecoder: lockWindowDecoder, resultDecoder: voidResultDecoder }, - lockContainer: { name: "lockContainer", argsDecoder: lockContainerDecoder, resultDecoder: voidResultDecoder }, - pinWorkspace: { name: "pinWorkspace", argsDecoder: pinWorkspaceDecoder, resultDecoder: voidResultDecoder }, - unpinWorkspace: { name: "unpinWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - getWorkspaceIcon: { name: "getWorkspaceIcon", argsDecoder: workspaceSelectorDecoder, resultDecoder: getWorkspaceIconResultDecoder }, - setWorkspaceIcon: { name: "setWorkspaceIcon", argsDecoder: setWorkspaceIconDecoder, resultDecoder: voidResultDecoder }, - registerShortcut: { name: "registerShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - unregisterShortcut: { name: "unregisterShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - showLoadingAnimation: { name: "showLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - hideLoadingAnimation: { name: "hideLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - getPlatformFrameId: { name: "getPlatformFrameId", resultDecoder: getPlatformFrameIdResultDecoder }, - operationCheck: { name: "operationCheck", argsDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - setWindowDragMode: { name: "setWindowDragMode", argsDecoder: setWindowDragModeDecoder, resultDecoder: voidResultDecoder }, - setLoadingStrategy: { name: "setLoadingStrategy", argsDecoder: setLoadingStrategyDecoder, resultDecoder: voidResultDecoder }, - getTaskbarIcon: { name: "getTaskbarIcon", resultDecoder: iconDecoder }, - setTaskbarIcon: { name: "setTaskbarIcon", argsDecoder: setIconArgumentsDecoder, resultDecoder: voidResultDecoder }, - subscribeToFrameClosing: { name: "subscribeToFrameClosing", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - showPopup: { name: "showPopup", argsDecoder: ShowPopupConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameVisibility: { name: "changeFrameVisibility", argsDecoder: changeFrameVisibilityConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameVisibility: { name: "getFrameVisibility", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameVisibilityResultDecoder }, - showFrameDialog: { name: "showFrameDialog", argsDecoder: showFrameDialogConfigDecoder, resultDecoder: anyJson() } - }; - - class PromiseWrapper { - resolve; - reject; - promise; - constructor() { - this.promise = new Promise((res, rej) => { - this.resolve = res; - this.reject = rej; - }); - } - } - - class Bridge { - transport; - registry; - activeSubscriptions = []; - pendingSubScriptions = []; - constructor(transport, registry) { - this.transport = transport; - this.registry = registry; - } - async createCoreEventSubscription() { - await this.transport.coreSubscriptionReady(this.handleCoreEvent.bind(this)); - } - handleCoreSubscription(config) { - const registryKey = `${config.eventType}-${config.action}`; - const scope = config.scope; - const scopeId = config.scopeId; - return this.registry.add(registryKey, (args) => { - const scopeConfig = { - type: scope, - id: scopeId - }; - const receivedIds = { - frame: args.frameSummary?.id || args.windowSummary?.config.frameId, - workspace: args.workspaceSummary?.id || args.windowSummary?.config.workspaceId, - container: args.containerSummary?.itemId, - window: args.windowSummary?.itemId - }; - const shouldInvokeCallback = this.checkScopeMatch(scopeConfig, receivedIds); - if (!shouldInvokeCallback) { - return; - } - config.callback(args); - }); - } - async send(operationName, operationArgs, invocationOptions) { - const operationDefinition = Object.values(OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - try { - const operationResult = await this.transport.transmitControl(operationDefinition.name, operationArgs, invocationOptions); - operationDefinition.resultDecoder.runWithException(operationResult); - return operationResult; - } - catch (error) { - if (error.kind) { - throw new Error(`Unexpected internal incoming validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - throw new Error(error.message); - } - } - async subscribe(config) { - const pendingSub = this.getPendingSubscription(config); - if (pendingSub) { - await pendingSub.promise; - } - let activeSub = this.getActiveSubscription(config); - const registryKey = this.getRegistryKey(config); - if (!activeSub) { - const pendingPromise = new PromiseWrapper(); - const pendingSubscription = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - promise: pendingPromise.promise - }; - this.pendingSubScriptions.push(pendingSubscription); - try { - const stream = STREAMS[config.eventType]; - const gdSub = await this.transport.subscribe(stream.name, this.getBranchKey(config), config.eventType); - gdSub.onData((streamData) => { - const data = streamData.data; - const requestedArgumentsResult = streamRequestArgumentsDecoder.run(streamData.requestArguments); - const actionResult = workspaceEventActionDecoder.run(data.action); - if (!requestedArgumentsResult.ok || !actionResult.ok) { - return; - } - const streamType = requestedArgumentsResult.result.type; - const branch = requestedArgumentsResult.result.branch; - const keyToExecute = `${streamType}-${branch}-${actionResult.result}`; - const validatedPayload = STREAMS[streamType].payloadDecoder.run(data.payload); - if (!validatedPayload.ok) { - return; - } - this.registry.execute(keyToExecute, validatedPayload.result); - }); - activeSub = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - callbacksCount: 0, - gdSub - }; - this.activeSubscriptions.push(activeSub); - pendingPromise.resolve(); - } - catch (error) { - pendingPromise.reject(error); - throw error; - } - finally { - this.removePendingSubscription(pendingSubscription); - } - } - const unsubscribe = this.registry.add(registryKey, config.callback); - ++activeSub.callbacksCount; - return () => { - unsubscribe(); - --activeSub.callbacksCount; - if (activeSub.callbacksCount === 0) { - activeSub.gdSub.close(); - this.activeSubscriptions.splice(this.activeSubscriptions.indexOf(activeSub), 1); - } - }; - } - onOperation(callback) { - const wrappedCallback = (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - callback(payload, caller); - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - onOperationWithResponse(callback) { - const wrappedCallback = async (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - const result = await callback(payload, caller); - if (operationDefinition.resultDecoder) { - try { - operationDefinition.resultDecoder.runWithException(result); - } - catch (error) { - throw new Error(`Unexpected internal outgoing result validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - return result; - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - checkScopeMatch(scope, receivedIds) { - if (scope.type === "global") { - return true; - } - if (scope.type === "frame" && scope.id === receivedIds.frame) { - return true; - } - if (scope.type === "workspace" && scope.id === receivedIds.workspace) { - return true; - } - if (scope.type === "container" && scope.id === receivedIds.container) { - return true; - } - if (scope.type === "window" && scope.id === receivedIds.window) { - return true; - } - return false; - } - handleCoreEvent(args) { - const data = args.data; - try { - const verifiedAction = workspaceEventActionDecoder.runWithException(data.action); - const verifiedType = eventTypeDecoder.runWithException(data.type); - const verifiedPayload = STREAMS[verifiedType].payloadDecoder.runWithException(data.payload); - const registryKey = `${verifiedType}-${verifiedAction}`; - this.registry.execute(registryKey, verifiedPayload); - } - catch (error) { - console.warn(`Cannot handle event with data ${JSON.stringify(data)}, because of validation error: ${error.message}`); - } - } - getBranchKey(config) { - return config.scope === "global" ? config.scope : `${config.scope}_${config.scopeId}`; - } - getRegistryKey(config) { - return `${config.eventType}-${this.getBranchKey(config)}-${config.action}`; - } - getActiveSubscription(config) { - return this.activeSubscriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - getPendingSubscription(config) { - return this.pendingSubScriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - removePendingSubscription(pendingSubscription) { - const index = this.pendingSubScriptions.indexOf(pendingSubscription); - if (index >= 0) { - this.pendingSubScriptions.splice(index, 1); - } - } - } - - const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage; - reject(message); - }, timeoutMilliseconds); - promise() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - - const isDesktop = () => { - return typeof window === "undefined" ? - true : - window.glue42gd || window.iodesktop; - }; - const browserGlobal = () => { - return typeof window === "undefined" ? null : - window.glue42core || window.iobrowser; - }; - - class InteropTransport { - agm; - registry; - defaultTransportTimeout = 120000; - coreEventMethodInitiated = false; - corePlatformSubPromise; - constructor(agm, registry) { - this.agm = agm; - this.registry = registry; - } - async initiate(actualWindowId) { - if (isDesktop()) { - await Promise.all(Object.values(OUTGOING_METHODS).map((method) => { - return this.verifyMethodLive(method.name); - })); - await Promise.all(Object.keys(INCOMING_METHODS).map((method) => { - return this.registerMethod(method); - })); - return; - } - const systemId = browserGlobal().communicationId; - await Promise.all([ - this.verifyMethodLive(webPlatformMethodName, systemId), - this.verifyMethodLive(webPlatformWspStreamName, systemId) - ]); - await this.transmitControl("frameHello", { windowId: actualWindowId }); - } - coreSubscriptionReady(eventCallback) { - if (!this.coreEventMethodInitiated) { - this.subscribePlatform(eventCallback); - } - return this.corePlatformSubPromise; - } - subscribePlatform(eventCallback) { - this.coreEventMethodInitiated = true; - const systemId = browserGlobal().communicationId; - this.corePlatformSubPromise = this.agm.subscribe(webPlatformWspStreamName, systemId ? { target: { instance: systemId } } : undefined); - this.corePlatformSubPromise - .then((sub) => { - sub.onData((data) => eventCallback(data.data)); - }); - } - async subscribe(streamName, streamBranch, streamType) { - const subscriptionArgs = { - branch: streamBranch, - type: streamType - }; - let subscription; - try { - subscription = await this.agm.subscribe(streamName, { arguments: subscriptionArgs }); - } - catch (error) { - const message = `Internal subscription error! Error details: stream - ${streamName}, branch: ${streamBranch}. Internal message: ${error.message}`; - throw new Error(message); - } - return subscription; - } - async transmitControl(operation, operationArguments, invocationOptions) { - const invocationArguments = isDesktop() ? { operation, operationArguments } : { operation, domain: "workspaces", data: operationArguments }; - const methodName = isDesktop() ? OUTGOING_METHODS.control.name : webPlatformMethodName; - const platformTarget = isDesktop() ? undefined : browserGlobal().communicationId; - let invocationResult; - const baseErrorMessage = `Internal Workspaces Communication Error. Attempted operation: ${JSON.stringify(invocationArguments)}. `; - try { - invocationResult = await this.agm.invoke(methodName, invocationArguments, platformTarget ? { instance: platformTarget } : "best", { methodResponseTimeoutMs: invocationOptions?.timeout ?? this.defaultTransportTimeout }); - if (!invocationResult) { - throw new Error("Received unsupported result from GD - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from GD - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - onInternalMethodInvoked(key, callback) { - return this.registry.add(key, callback); - } - verifyMethodLive(name, systemId) { - return promisePlus(() => { - return new Promise((resolve) => { - const hasMethod = this.agm.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = systemId ? - method.getServers().some((server) => server.instance === systemId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - resolve(); - return; - } - const unSub = this.agm.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = systemId ? - server.instance === systemId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }); - }, 15000, "Timeout waiting for the Workspaces communication channels"); - } - registerMethod(key) { - const method = INCOMING_METHODS[key]; - return this.agm.register(method.name, (args, caller) => { - return Promise.all(this.registry.execute(key, args, caller)); - }); - } - } - - const privateData$4 = new WeakMap(); - class ParentBuilder { - constructor(definition, base) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$4.set(this, { base, children, definition }); - } - get type() { - return privateData$4.get(this).definition.type; - } - addColumn(definition) { - const base = privateData$4.get(this).base; - return base.add("column", privateData$4.get(this).children, definition); - } - addRow(definition) { - const base = privateData$4.get(this).base; - return base.add("row", privateData$4.get(this).children, definition); - } - addGroup(definition) { - const base = privateData$4.get(this).base; - return base.add("group", privateData$4.get(this).children, definition); - } - addWindow(definition) { - const base = privateData$4.get(this).base; - base.addWindow(privateData$4.get(this).children, definition); - return this; - } - serialize() { - const definition = privateData$4.get(this).definition; - definition.children = privateData$4.get(this).base.serializeChildren(privateData$4.get(this).children); - return definition; - } - } - - class BaseBuilder { - getBuilder; - constructor(getBuilder) { - this.getBuilder = getBuilder; - } - wrapChildren(children) { - return children.map((child) => { - if (child.type === "window") { - return child; - } - return this.getBuilder({ type: child.type, definition: child }); - }); - } - add(type, children, definition) { - const validatedDefinition = parentDefinitionDecoder.runWithException(definition); - const childBuilder = this.getBuilder({ type, definition: validatedDefinition }); - children.push(childBuilder); - return childBuilder; - } - addWindow(children, definition) { - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - validatedDefinition.type = "window"; - children.push(validatedDefinition); - } - serializeChildren(children) { - return children.map((child) => { - if (child instanceof ParentBuilder) { - return child.serialize(); - } - else { - return child; - } - }); - } - } - - const privateData$3 = new WeakMap(); - class WorkspaceBuilder { - constructor(definition, base, controller) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$3.set(this, { base, children, definition, controller }); - } - addColumn(definition) { - const children = privateData$3.get(this).children; - const areAllColumns = children.every((child) => child instanceof ParentBuilder && child.type === "column"); - if (!areAllColumns) { - throw new Error("Cannot add a column to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("column", children, definition); - } - addRow(definition) { - const children = privateData$3.get(this).children; - const areAllRows = children.every((child) => child instanceof ParentBuilder && child.type === "row"); - if (!areAllRows) { - throw new Error("Cannot add a row to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("row", children, definition); - } - addGroup(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a group to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - return base.add("group", children, definition); - } - addWindow(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a window to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - base.addWindow(children, definition); - return this; - } - getChildAt(index) { - nonNegativeNumberDecoder.runWithException(index); - const data = privateData$3.get(this).children; - return data[index]; - } - async create(config) { - const saveConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - const definition = privateData$3.get(this).definition; - definition.children = privateData$3.get(this).base.serializeChildren(privateData$3.get(this).children); - const controller = privateData$3.get(this).controller; - return controller.createWorkspace(definition, saveConfig); - } - } - - const privateData$2 = new WeakMap(); - const getBase$2 = (model) => { - return privateData$2.get(model).base; - }; - class Row { - constructor(base) { - privateData$2.set(this, { base }); - } - get type() { - return "row"; - } - get id() { - return getBase$2(this).getId(this); - } - get frameId() { - return getBase$2(this).getFrameId(this); - } - get workspaceId() { - return getBase$2(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$2(this).getPositionIndex(this); - } - get children() { - return getBase$2(this).getAllChildren(this); - } - get parent() { - return getBase$2(this).getMyParent(this); - } - get frame() { - return getBase$2(this).getMyFrame(this); - } - get workspace() { - return getBase$2(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$2(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$2(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$2(this).getMinWidth(this); - } - get minHeight() { - return getBase$2(this).getMinHeight(this); - } - get maxWidth() { - return getBase$2(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$2(this).getMaxHeight(this); - } - get width() { - return getBase$2(this).getWidthInPx(this); - } - get height() { - return getBase$2(this).getHeightInPx(this); - } - get isPinned() { - return getBase$2(this).getIsPinned(this); - } - get isMaximized() { - return getBase$2(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$2(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$2(this).addWindow(this, definition, "row"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "group", "row", definition); - } - async addColumn(definition) { - if (definition?.type && definition.type !== "column") { - throw new Error(`Expected a column definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "column", "row", definition); - } - async addRow() { - throw new Error("Adding rows as row children is not supported"); - } - removeChild(predicate) { - return getBase$2(this).removeChild(this, predicate); - } - maximize() { - return getBase$2(this).maximize(this); - } - restore() { - return getBase$2(this).restore(this); - } - close() { - return getBase$2(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : rowLockConfigDecoder.runWithException(lockConfigResult); - return getBase$2(this).lockContainer(this, verifiedConfig); - } - async setHeight(height) { - nonNegativeNumberDecoder.runWithException(height); - return getBase$2(this).setHeight(this, height); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$2(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$2(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData$1 = new WeakMap(); - const getBase$1 = (model) => { - return privateData$1.get(model).base; - }; - class Column { - constructor(base) { - privateData$1.set(this, { base }); - } - get type() { - return "column"; - } - get id() { - return getBase$1(this).getId(this); - } - get frameId() { - return getBase$1(this).getFrameId(this); - } - get workspaceId() { - return getBase$1(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$1(this).getPositionIndex(this); - } - get children() { - return getBase$1(this).getAllChildren(this); - } - get parent() { - return getBase$1(this).getMyParent(this); - } - get frame() { - return getBase$1(this).getMyFrame(this); - } - get workspace() { - return getBase$1(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$1(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$1(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$1(this).getMinWidth(this); - } - get minHeight() { - return getBase$1(this).getMinHeight(this); - } - get maxWidth() { - return getBase$1(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$1(this).getMaxHeight(this); - } - get width() { - return getBase$1(this).getWidthInPx(this); - } - get height() { - return getBase$1(this).getHeightInPx(this); - } - get isPinned() { - return getBase$1(this).getIsPinned(this); - } - get isMaximized() { - return getBase$1(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$1(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$1(this).addWindow(this, definition, "column"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "group", "column", definition); - } - async addColumn() { - throw new Error("Adding columns as column children is not supported"); - } - async addRow(definition) { - if (definition?.type && definition.type !== "row") { - throw new Error(`Expected a row definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "row", "column", definition); - } - removeChild(predicate) { - return getBase$1(this).removeChild(this, predicate); - } - maximize() { - return getBase$1(this).maximize(this); - } - restore() { - return getBase$1(this).restore(this); - } - close() { - return getBase$1(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : columnLockConfigDecoder.runWithException(lockConfigResult); - return getBase$1(this).lockContainer(this, verifiedConfig); - } - async setWidth(width) { - nonNegativeNumberDecoder.runWithException(width); - return getBase$1(this).setWidth(this, width); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$1(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$1(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData = new WeakMap(); - const getBase = (model) => { - return privateData.get(model).base; - }; - class Group { - constructor(base) { - privateData.set(this, { base }); - } - get type() { - return "group"; - } - get id() { - return getBase(this).getId(this); - } - get frameId() { - return getBase(this).getFrameId(this); - } - get workspaceId() { - return getBase(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase(this).getPositionIndex(this); - } - get children() { - return getBase(this).getAllChildren(this); - } - get parent() { - return getBase(this).getMyParent(this); - } - get frame() { - return getBase(this).getMyFrame(this); - } - get workspace() { - return getBase(this).getMyWorkspace(this); - } - get allowExtract() { - return getBase(this).getAllowExtract(this); - } - get allowReorder() { - return getBase(this).getAllowReorder(this); - } - get allowDropLeft() { - return getBase(this).getAllowDropLeft(this); - } - get allowDropRight() { - return getBase(this).getAllowDropRight(this); - } - get allowDropTop() { - return getBase(this).getAllowDropTop(this); - } - get allowDropBottom() { - return getBase(this).getAllowDropBottom(this); - } - get allowDropHeader() { - return getBase(this).getAllowDropHeader(this); - } - get allowDrop() { - return getBase(this).getAllowDrop(this); - } - get showMaximizeButton() { - return getBase(this).getShowMaximizeButton(this); - } - get showEjectButton() { - return getBase(this).getShowEjectButton(this); - } - get showAddWindowButton() { - return getBase(this).getShowAddWindowButton(this); - } - get minWidth() { - return getBase(this).getMinWidth(this); - } - get minHeight() { - return getBase(this).getMinHeight(this); - } - get maxWidth() { - return getBase(this).getMaxWidth(this); - } - get maxHeight() { - return getBase(this).getMaxHeight(this); - } - get width() { - return getBase(this).getWidthInPx(this); - } - get height() { - return getBase(this).getHeightInPx(this); - } - get isMaximized() { - return getBase(this).getIsMaximized(this); - } - addWindow(definition) { - return getBase(this).addWindow(this, definition, "group"); - } - async addGroup() { - throw new Error("Adding groups as group child is not supported"); - } - async addColumn() { - throw new Error("Adding columns as group child is not supported"); - } - async addRow() { - throw new Error("Adding rows as group child is not supported"); - } - removeChild(predicate) { - return getBase(this).removeChild(this, predicate); - } - maximize() { - return getBase(this).maximize(this); - } - restore() { - return getBase(this).restore(this); - } - close() { - return getBase(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropRight: this.allowDropRight, - allowDropTop: this.allowDropTop, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : groupLockConfigDecoder.runWithException(lockConfigResult); - return getBase(this).lockContainer(this, verifiedConfig); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - return getBase(this).setSize(this, config.width, config.height); - } - async bundleToRow() { - await getBase(this).bundleTo(this, "row"); - await this.workspace.refreshReference(); - } - async bundleToColumn() { - await getBase(this).bundleTo(this, "column"); - await this.workspace.refreshReference(); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase(this).processLocalSubscription(this, config); - return unsubscribe; - } - } - - const DEFAULT_WINDOW_DRAG_MODE = "keepInside"; - const ONE_DAY_MS = 86_400_000; - - const data$3 = new WeakMap(); - const getData$3 = (model) => { - return data$3.get(model).manager.getWorkspaceData(model); - }; - const getDataManager = (model) => { - return data$3.get(model).manager; - }; - class Workspace { - constructor(dataManager) { - data$3.set(this, { manager: dataManager }); - } - get id() { - return getData$3(this).id; - } - get frameId() { - return getData$3(this).config.frameId; - } - get positionIndex() { - return getData$3(this).config.positionIndex; - } - get title() { - return getData$3(this).config.title; - } - get layoutName() { - return getData$3(this).config.layoutName; - } - get isHibernated() { - return getData$3(this).config.isHibernated; - } - get isSelected() { - return getData$3(this).config.isSelected; - } - get children() { - return getData$3(this).children; - } - get frame() { - return getData$3(this).frame; - } - get allowSplitters() { - return getData$3(this).config.allowSplitters; - } - get allowSystemHibernation() { - return getData$3(this).config.allowSystemHibernation; - } - get allowDrop() { - return getData$3(this).config.allowDrop; - } - get allowDropLeft() { - return getData$3(this).config.allowDropLeft; - } - get allowDropTop() { - return getData$3(this).config.allowDropTop; - } - get allowDropRight() { - return getData$3(this).config.allowDropRight; - } - get allowDropBottom() { - return getData$3(this).config.allowDropBottom; - } - get allowExtract() { - return getData$3(this).config.allowExtract; - } - get allowWindowReorder() { - return getData$3(this).config.allowWindowReorder; - } - get showCloseButton() { - return getData$3(this).config.showCloseButton; - } - get showSaveButton() { - return getData$3(this).config.showSaveButton; - } - get allowWorkspaceTabReorder() { - return getData$3(this).config.allowWorkspaceTabReorder; - } - get allowWorkspaceTabExtract() { - return getData$3(this).config.allowWorkspaceTabExtract; - } - get minWidth() { - return getData$3(this).config.minWidth; - } - get minHeight() { - return getData$3(this).config.minHeight; - } - get maxWidth() { - return getData$3(this).config.maxWidth; - } - get maxHeight() { - return getData$3(this).config.maxHeight; - } - get width() { - return getData$3(this).config.widthInPx; - } - get height() { - return getData$3(this).config.heightInPx; - } - get showWindowCloseButtons() { - return getData$3(this).config.showWindowCloseButtons; - } - get showEjectButtons() { - return getData$3(this).config.showEjectButtons; - } - get showAddWindowButtons() { - return getData$3(this).config.showAddWindowButtons; - } - get isPinned() { - return getData$3(this).config.isPinned; - } - get windowDragMode() { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - return DEFAULT_WINDOW_DRAG_MODE; - } - return getData$3(this).config.windowDragMode; - } - get loadingStrategy() { - if (!isDesktop()) { - console.warn("The workspace.loadingStrategy property is not supported in IO Connect Browser"); - } - return getData$3(this).config.loadingStrategy; - } - async setLoadingStrategy(strategy) { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - const controller = getData$3(this).controller; - await controller.setLoadingStrategy(this.id, strategy); - await this.refreshReference(); - } - async removeChild(predicate) { - checkThrowCallback(predicate); - const child = this.children.find(predicate); - if (!child) { - return; - } - await child.close(); - await this.refreshReference(); - } - async remove(predicate) { - checkThrowCallback(predicate); - const controller = getData$3(this).controller; - const child = controller.iterateFindChild(this.children, predicate); - await child.close(); - await this.refreshReference(); - } - async focus() { - await getData$3(this).controller.focusItem(this.id); - await this.refreshReference(); - } - async close() { - const controller = getData$3(this).controller; - await controller.closeWorkspace(this.id, this.frameId); - } - snapshot() { - return getData$3(this).controller.getSnapshot(this.id, "workspace"); - } - async saveLayout(name, config) { - nonEmptyStringDecoder.runWithException(name); - await getData$3(this).controller.saveLayout({ name, workspaceId: this.id, saveContext: config?.saveContext, metadata: config?.metadata, allowMultiple: config?.allowMultiple }); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const controller = getData$3(this).controller; - await controller.setItemTitle(this.id, title); - await this.refreshReference(); - } - getContext() { - const controller = getData$3(this).controller; - return controller.getWorkspaceContext(this.id); - } - setContext(data) { - const controller = getData$3(this).controller; - return controller.setWorkspaceContext(this.id, data); - } - updateContext(data) { - const controller = getData$3(this).controller; - return controller.updateWorkspaceContext(this.id, data); - } - onContextUpdated(callback) { - const controller = getData$3(this).controller; - return controller.subscribeWorkspaceContextUpdated(this.id, callback); - } - async refreshReference() { - const newSnapshot = (await getData$3(this).controller.getSnapshot(this.id, "workspace")); - const currentChildrenFlat = getData$3(this).controller.flatChildren(getData$3(this).children); - const newChildren = getData$3(this).controller.refreshChildren({ - existingChildren: currentChildrenFlat, - workspace: this, - parent: this, - children: newSnapshot.children - }); - const currentFrame = this.frame; - let actualFrame; - if (currentFrame.id === newSnapshot.config.frameId) { - getDataManager(this).remapFrame(currentFrame, newSnapshot.frameSummary); - actualFrame = currentFrame; - } - else { - const frameCreateConfig = { - summary: newSnapshot.frameSummary - }; - const newFrame = getData$3(this).ioc.getModel("frame", frameCreateConfig); - actualFrame = newFrame; - } - getDataManager(this).remapWorkspace(this, { - config: newSnapshot.config, - children: newChildren, - frame: actualFrame - }); - } - async getIcon() { - const controller = getData$3(this).controller; - return controller.getWorkspaceIcon(this.id); - } - async setIcon(icon) { - const controller = getData$3(this).controller; - return controller.setWorkspaceIcon(this.id, icon); - } - getBox(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type !== "window" && predicate(child)); - } - getAllBoxes(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allParents = controller.iterateFilterChildren(children, (child) => child.type !== "window"); - if (!predicate) { - return allParents; - } - return allParents.filter(predicate); - } - getRow(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "row" && predicate(parent)); - } - getAllRows(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "row" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "row"); - } - getColumn(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "column" && predicate(parent)); - } - getAllColumns(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "column" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "column"); - } - getGroup(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "group" && predicate(parent)); - } - getAllGroups(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "group" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "group"); - } - getWindow(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type === "window" && predicate(child)); - } - getAllWindows(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allWindows = controller.iterateFilterChildren(children, (child) => child.type === "window"); - if (!predicate) { - return allWindows; - } - return allWindows.filter(predicate); - } - addRow(definition) { - return getData$3(this).base.addParent(this, "row", "workspace", definition); - } - addColumn(definition) { - return getData$3(this).base.addParent(this, "column", "workspace", definition); - } - addGroup(definition) { - return getData$3(this).base.addParent(this, "group", "workspace", definition); - } - addWindow(definition) { - return getData$3(this).base.addWindow(this, definition, "workspace"); - } - async bundleToRow() { - await getData$3(this).controller.bundleWorkspaceTo("row", this.id); - await this.refreshReference(); - } - async bundleToColumn() { - await getData$3(this).controller.bundleWorkspaceTo("column", this.id); - await this.refreshReference(); - } - async hibernate() { - await getData$3(this).controller.hibernateWorkspace(this.id); - await this.refreshReference(); - } - async resume() { - await getData$3(this).controller.resumeWorkspace(this.id); - await this.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowWindowReorder: this.allowWindowReorder, - allowSplitters: this.allowSplitters, - showCloseButton: this.showCloseButton, - showSaveButton: this.showSaveButton, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - showAddWindowButtons: this.showAddWindowButtons, - showEjectButtons: this.showEjectButtons, - showWindowCloseButtons: this.showWindowCloseButtons - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : workspaceLockConfigDecoder.runWithException(lockConfigResult); - await getData$3(this).controller.lockWorkspace(this.id, verifiedConfig); - await this.refreshReference(); - } - async pin(options) { - workspacePinOptionsDecoder.runWithException(options); - await getData$3(this).controller.pinWorkspace(this.id, options?.icon); - await this.refreshReference(); - } - async unpin() { - await getData$3(this).controller.unpinWorkspace(this.id); - await this.refreshReference(); - } - async showLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.showWorkspaceLoadingAnimation(this.id); - } - async hideLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.hideWorkspaceLoadingAnimation(this.id); - } - async setWindowDragMode(mode) { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - throw new Error("Not supported in IO Connect Browser"); - } - windowDragModeDecoder.runWithException(mode); - await getData$3(this).controller.setWindowDragMode(this.id, mode); - await this.refreshReference(); - } - async onClosed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - action: "closed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onHibernated(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "hibernated", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onResumed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "resumed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "added", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - action: "removed", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const foundWindow = this.getWindow((win) => { - return win.id && win.id === payload.windowSummary.config.windowId; - }); - callback(foundWindow); - }; - const config = { - action: "loaded", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowMaximized(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "maximized", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRestored(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "restored", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowSelected(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "selected", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowSplitters: this.allowSplitters, - allowWindowReorder: this.allowWindowReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - showAddWindowButtons: this.showAddWindowButtons, - showCloseButton: this.showCloseButton, - showEjectButtons: this.showEjectButtons, - showSaveButton: this.showSaveButton, - showWindowCloseButtons: this.showWindowCloseButtons - }); - }; - const config = { - action: "lock-configuration-changed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$2 = new WeakMap(); - const getData$2 = (model) => { - return data$2.get(model).manager.getWindowData(model); - }; - class Window { - constructor(dataManager) { - data$2.set(this, { manager: dataManager }); - } - get id() { - return getData$2(this).config.windowId; - } - get elementId() { - return getData$2(this).id; - } - get type() { - return "window"; - } - get frameId() { - return getData$2(this).frame.id; - } - get workspaceId() { - return getData$2(this).workspace.id; - } - get positionIndex() { - return getData$2(this).config.positionIndex; - } - get isMaximized() { - return getData$2(this).config.isMaximized; - } - get isLoaded() { - return getData$2(this).controller.checkIsWindowLoaded(this.id); - } - get isSelected() { - return getData$2(this).config.isSelected; - } - get focused() { - return this.getGdWindow().isFocused; - } - get title() { - return getData$2(this).config.title; - } - get allowExtract() { - return getData$2(this).config.allowExtract; - } - get allowReorder() { - return getData$2(this).config.allowReorder; - } - get showCloseButton() { - return getData$2(this).config.showCloseButton; - } - get width() { - return getData$2(this).config.widthInPx; - } - get height() { - return getData$2(this).config.heightInPx; - } - get minWidth() { - return getData$2(this).config.minWidth; - } - get minHeight() { - return getData$2(this).config.minHeight; - } - get maxWidth() { - return getData$2(this).config.maxWidth; - } - get maxHeight() { - return getData$2(this).config.maxHeight; - } - get workspace() { - return getData$2(this).workspace; - } - get frame() { - return getData$2(this).frame; - } - get parent() { - return getData$2(this).parent; - } - get appName() { - return getData$2(this).config.appName; - } - async forceLoad() { - if (this.isLoaded) { - return; - } - const controller = getData$2(this).controller; - const itemId = getData$2(this).id; - const windowId = await controller.forceLoadWindow(itemId); - getData$2(this).config.windowId = windowId; - await this.workspace.refreshReference(); - } - async focus() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.focusItem(id); - await this.workspace.refreshReference(); - } - async close() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.closeItem(id); - await getData$2(this) - .parent - .removeChild((child) => child.id === id); - await this.workspace.refreshReference(); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const itemId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.setItemTitle(itemId, title); - await this.workspace.refreshReference(); - } - async maximize() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.maximizeItem(id); - await this.workspace.refreshReference(); - } - async restore() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.restoreItem(id); - await this.workspace.refreshReference(); - } - async eject() { - if (!this.isLoaded) { - throw new Error("Cannot eject this window, because it is not loaded yet"); - } - const itemId = getData$2(this).id; - const windowId = getData$2(this).config.windowId; - const newWindowId = await getData$2(this).controller.ejectWindow(itemId, windowId); - getData$2(this).config.windowId = newWindowId; - await this.workspace.refreshReference(); - return this.getGdWindow(); - } - getGdWindow() { - if (!this.isLoaded) { - throw new Error("Cannot fetch this GD window, because the window is not yet loaded"); - } - const myId = getData$2(this).config.windowId; - const controller = getData$2(this).controller; - return controller.getGDWindow(myId); - } - async moveTo(parent) { - if (!(parent instanceof Row || parent instanceof Column || parent instanceof Group)) { - throw new Error("Cannot add to the provided parent, because the provided parent is not an instance of Row, Column or Group"); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - const foundParent = await controller.getParent((p) => p.id === parent.id); - if (!foundParent) { - throw new Error("Cannot move the window to the selected parent, because this parent does not exist."); - } - await controller.moveWindowTo(myId, parent.id); - await this.workspace.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : windowLockConfigDecoder.runWithException(lockConfigResult); - const windowPlacementId = getData$2(this).id; - await getData$2(this).controller.lockWindow(windowPlacementId, verifiedConfig); - await this.workspace.refreshReference(); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.resizeItem(myId, { - height: verifiedConfig.height, - width: verifiedConfig.width, - relative: false - }); - await this.workspace.refreshReference(); - } - async onRemoved(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback(); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$1 = new WeakMap(); - const getData$1 = (model) => { - return data$1.get(model).manager.getFrameData(model); - }; - class Frame { - constructor(dataManager) { - data$1.set(this, { manager: dataManager }); - } - async registerShortcut(shortcut, callback) { - nonEmptyStringDecoder.runWithException(shortcut); - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const unsubscribe = await getData$1(this).controller.registerShortcut(shortcut, myId, callback); - return unsubscribe; - } - get id() { - return getData$1(this).summary.id; - } - get isInitialized() { - return getData$1(this).summary.isInitialized; - } - getBounds() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameBounds(myId); - } - async resize(config) { - const validatedConfig = resizeConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.resizeItem(myId, validatedConfig); - } - async move(config) { - const validatedConfig = moveConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.moveFrame(myId, validatedConfig); - } - focus() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.focusItem(myId); - } - async state() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameState(myId); - } - setIcon(icon) { - if (!isDesktop()) { - throw new Error("frame.setIcon() is not supported in IO Connect Browser"); - } - iconDecoder.runWithException(icon); - const frameId = this.id; - return getData$1(this).controller.setTaskbarIcon(icon, frameId); - } - getIcon() { - if (!isDesktop()) { - throw new Error("frame.getIcon() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getTaskbarIcon(frameId); - } - isVisible() { - if (!isDesktop()) { - throw new Error("frame.isVisible() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getFrameVisibility(frameId); - } - async minimize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "minimized"); - } - async maximize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "maximized"); - } - async restore() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "normal"); - } - close(options) { - const validatedOptions = optional(closeOptionsDecoder).runWithException(options); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.closeFrame(myId, validatedOptions); - } - snapshot() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getSnapshot(myId, "frame"); - } - async workspaces() { - const controller = getData$1(this).controller; - return controller.getWorkspacesByFrameId(this.id); - } - async getConstraints() { - const controller = getData$1(this).controller; - const myId = getData$1(this).summary.id; - return controller.getFrameConstraints(myId); - } - async restoreWorkspace(name, options) { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return getData$1(this).controller.restoreWorkspace(name, validatedOptions); - } - createWorkspace(definition, config) { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - return getData$1(this).controller.createWorkspace(validatedDefinition, validatedConfig); - } - async init(config) { - frameInitConfigDecoder.runWithException(config); - if (getData$1(this).summary.isInitialized) { - throw new Error("The frame has already been initialized"); - } - return getData$1(this).controller.initFrame(this.id, config); - } - async showPopup(config) { - if (!isDesktop()) { - throw new Error("Popup operations are not supported in IO Connect Browser"); - } - const validatedConfig = popupConfigDecoder.runWithException(config); - const controller = getData$1(this).controller; - await controller.showPopup(validatedConfig, this.id); - return controller.getGDWindow(validatedConfig.windowId); - } - async show(config) { - if (!isDesktop()) { - throw new Error("The show operation is not supported in IO Connect Browser"); - } - const validatedConfig = frameShowConfigDecoder.runWithException(config); - return getData$1(this).controller.showFrame(this.id, validatedConfig); - } - async hide() { - if (!isDesktop()) { - throw new Error("The hide operation is not supported in IO Connect Browser"); - } - return getData$1(this).controller.hideFrame(this.id); - } - async showDialog(options) { - if (!isDesktop()) { - throw new Error("The showModal operation is not supported in IO Connect Browser"); - } - frameDialogOptionsDecoder.runWithException(options); - return getData$1(this).controller.showFrameDialog(this.id, options); - } - async onClosing(callback) { - if (!isDesktop()) { - throw new Error("Frame closing operations are not supported in io.Connect Browser"); - } - checkThrowCallback(callback); - const wrappedCallback = async () => { - let shouldPrevent = false; - const preventClose = () => shouldPrevent = true; - await callback({ prevent: preventClose }); - return { prevent: shouldPrevent }; - }; - const unsubscribe = await getData$1(this).controller.registerFrameOnClosing(this.id, wrappedCallback); - return unsubscribe; - } - async onClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMaximized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "maximized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMinimized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "minimized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onNormal(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "normal", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceOpened(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "opened", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceSelected(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.getWorkspaceById(payload.workspaceSummary.id); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "selected", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "added", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => { - return parent.id === payload.windowSummary.parentId; - }); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "loaded", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onInitializationRequested(callback) { - checkThrowCallback(callback); - if (!this.isInitialized) { - callback(getData$1(this).summary.initializationContext); - } - return () => { }; - } - async onFocusChanged(callback) { - checkThrowCallback(callback); - const myData = getData$1(this); - const { id } = myData.summary; - const wrappedCallback = (args) => { - callback({ isFocused: args.frameSummary.isFocused }); - }; - const config = { - callback: wrappedCallback, - action: "focus", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await myData.controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - class PrivateDataManager { - parentsData = new WeakMap(); - workspacesData = new WeakMap(); - windowsData = new WeakMap(); - framesData = new WeakMap(); - deleteData(model) { - if (model instanceof Window) { - this.windowsData.delete(model); - } - if (model instanceof Workspace) { - this.workspacesData.delete(model); - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - this.parentsData.delete(model); - } - if (model instanceof Frame) { - this.framesData.delete(model); - } - } - setWindowData(model, data) { - this.windowsData.set(model, data); - } - setWorkspaceData(model, data) { - this.workspacesData.set(model, data); - } - setParentData(model, data) { - this.parentsData.set(model, data); - } - setFrameData(model, data) { - this.framesData.set(model, data); - } - getWindowData(model) { - return this.windowsData.get(model); - } - getWorkspaceData(model) { - return this.workspacesData.get(model); - } - getParentData(model) { - return this.parentsData.get(model); - } - getFrameData(model) { - return this.framesData.get(model); - } - remapChild(model, newData) { - if (model instanceof Window) { - const data = this.windowsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - const data = this.parentsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - remapFrame(model, newData) { - const data = this.framesData.get(model); - data.summary = newData; - } - remapWorkspace(model, newData) { - const data = this.workspacesData.get(model); - data.frame = newData.frame || data.frame; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - - const data = new WeakMap(); - const getData = (base, model) => { - const manager = data.get(base).manager; - if (model instanceof Workspace) { - return manager.getWorkspaceData(model); - } - return data.get(base).manager.getParentData(model); - }; - class Base { - frameId; - workspaceId; - positionIndex; - constructor(dataManager) { - data.set(this, { manager: dataManager }); - } - getId(model) { - return getData(this, model).id; - } - getPositionIndex(model) { - return getData(this, model).config.positionIndex; - } - getWorkspaceId(model) { - const privateData = getData(this, model); - return privateData.config.workspaceId || privateData.workspace.id; - } - getFrameId(model) { - return getData(this, model).frame.id; - } - getAllChildren(model, predicate) { - checkThrowCallback(predicate, true); - const children = getData(this, model).children; - if (typeof predicate === "undefined") { - return children; - } - return children.filter(predicate); - } - getMyParent(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).parent; - } - getMyFrame(model) { - return getData(this, model).frame; - } - getMyWorkspace(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).workspace; - } - async addWindow(model, definition, parentType) { - if (!definition.appName && !definition.windowId) { - throw new Error("The window definition should contain either an appName or a windowId"); - } - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - const controller = getData(this, model).controller; - const operationResult = await controller.add("window", getData(this, model).id, parentType, validatedDefinition); - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getWindow(w => w.elementId === operationResult.itemId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getWindow(w => w.elementId === operationResult.itemId); - } - async addParent(model, typeToAdd, parentType, definition) { - const parentDefinition = this.transformDefinition(typeToAdd, definition); - const controller = getData(this, model).controller; - const newParentId = (await controller.add("container", getData(this, model).id, parentType, parentDefinition)).itemId; - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getBox((parent) => parent.id === newParentId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getBox((parent) => parent.id === newParentId); - } - async removeChild(model, predicate) { - checkThrowCallback(predicate); - const child = this.getAllChildren(model).find(predicate); - if (!child) { - return; - } - await child.close(); - if (model instanceof Workspace) { - await model.refreshReference(); - return; - } - await this.getMyWorkspace(model).refreshReference(); - } - async maximize(model) { - const { controller, id } = getData(this, model); - await controller.maximizeItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async restore(model) { - const { controller, id } = getData(this, model); - await controller.restoreItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async close(model) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.closeItem(modelData.id); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async lockContainer(model, config) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.lockContainer(modelData.id, model.type, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - getAllowDrop(model) { - return getData(this, model).config.allowDrop; - } - getAllowDropLeft(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropLeft is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropLeft; - } - getAllowDropRight(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropRight is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropRight; - } - getAllowDropTop(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropTop is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropTop; - } - getAllowDropBottom(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropBottom is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropBottom; - } - getAllowDropHeader(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropHeader is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropHeader; - } - getAllowSplitters(model) { - const privateData = getData(this, model); - if (privateData.type === "group") { - throw new Error(`Cannot get allow splitters from private data ${privateData.type}`); - } - return privateData.config.allowSplitters; - } - getAllowExtract(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowExtract; - } - getAllowReorder(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowReorder; - } - getShowMaximizeButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show maximize button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showMaximizeButton; - } - getShowEjectButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show eject button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showEjectButton; - } - getShowAddWindowButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get add window button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showAddWindowButton; - } - getMinWidth(model) { - const privateData = getData(this, model); - return privateData.config.minWidth; - } - getMaxWidth(model) { - const privateData = getData(this, model); - return privateData.config.maxWidth; - } - getMinHeight(model) { - const privateData = getData(this, model); - return privateData.config.minHeight; - } - getMaxHeight(model) { - const privateData = getData(this, model); - return privateData.config.maxHeight; - } - getWidthInPx(model) { - const privateData = getData(this, model); - return privateData.config.widthInPx; - } - getHeightInPx(model) { - const privateData = getData(this, model); - return privateData.config.heightInPx; - } - getIsPinned(model) { - const privateData = getData(this, model); - return privateData.config.isPinned; - } - getIsMaximized(model) { - const privateData = getData(this, model); - return privateData.config.isMaximized; - } - getMaximizationBoundary(model) { - const privateData = getData(this, model); - return privateData.config.maximizationBoundary; - } - async setHeight(model, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setWidth(model, width) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setSize(model, width, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width, - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setMaximizationBoundary(model, config) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.setMaximizationBoundary(id, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async bundleTo(model, type) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.bundleItemTo(type, id); - } - async processLocalSubscription(model, subscriptionConfig) { - return getData(this, model).controller.processLocalSubscription(subscriptionConfig, this.getId(model)); - } - transformDefinition(type, definition) { - let parentDefinition; - if (typeof definition === "undefined") { - parentDefinition = { type, children: [] }; - } - else if (definition instanceof ParentBuilder) { - parentDefinition = definition.serialize(); - } - else { - if (typeof definition.type === "undefined") { - definition.type = type; - } - parentDefinition = strictParentDefinitionDecoder.runWithException(definition); - parentDefinition.children = parentDefinition.children || []; - } - return parentDefinition; - } - } - - class BaseController { - ioc; - windows; - contexts; - layouts; - constructor(ioc, windows, contexts, layouts) { - this.ioc = ioc; - this.windows = windows; - this.contexts = contexts; - this.layouts = layouts; - } - get bridge() { - return this.ioc.bridge; - } - get privateDataManager() { - return this.ioc.privateDataManager; - } - checkIsWindowLoaded(windowId) { - return (!!windowId) && this.windows.list().some((win) => win.id === windowId); - } - async createWorkspace(createConfig) { - const snapshot = await this.bridge.send(OPERATIONS.createWorkspace.name, createConfig); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async createEmptyFrame(definition) { - const frameSummary = await this.bridge.send(OPERATIONS.createFrame.name, definition); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - async initFrame(frameId, config) { - await this.bridge.send(OPERATIONS.initFrame.name, { frameId, ...config }); - } - async restoreWorkspace(name, options) { - const snapshot = await this.bridge.send(OPERATIONS.openWorkspace.name, { name, restoreOptions: options }); - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: snapshot.config.frameId }); - const frameConfig = { - summary: frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async add(type, parentId, parentType, definition) { - let operationName; - const operationArgs = { definition, parentId, parentType }; - if (type === "window") { - operationName = OPERATIONS.addWindow.name; - } - else if (type === "container") { - operationName = OPERATIONS.addContainer.name; - } - else { - throw new Error(`Unrecognized add type: ${type}`); - } - return await this.bridge.send(operationName, operationArgs); - } - async getFrame(windowId) { - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: windowId }); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - getFrames(allFrameSummaries, predicate) { - return allFrameSummaries.reduce((frames, frameSummary) => { - const frameConfig = { - summary: frameSummary - }; - const frameToCheck = this.ioc.getModel("frame", frameConfig); - if (!predicate || predicate(frameToCheck)) { - frames.push(frameToCheck); - } - return frames; - }, []); - } - getAllWorkspaceSummaries(...bridgeResults) { - const allSummaries = bridgeResults.reduce((summaries, summaryResult) => { - summaries.push(...summaryResult.summaries); - return summaries; - }, []); - return allSummaries.map((summary) => { - return Object.assign({}, { id: summary.id, width: summary.config.widthInPx, height: summary.config.heightInPx }, summary.config); - }); - } - handleOnSaved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - const addedUnSub = this.layouts.onAdded(wrappedCallback); - const changedUnSub = this.layouts.onChanged(wrappedCallback); - return () => { - addedUnSub(); - changedUnSub(); - }; - } - handleOnRemoved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - return this.layouts.onRemoved(wrappedCallback); - } - async importLayouts(layouts, mode) { - await this.layouts.import(layouts, mode); - } - async transformStreamPayloadToWorkspace(payload) { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const snapshot = payload.workspaceSnapshot || (await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId: payload.workspaceSummary.id })); - const workspaceConfig = { frame, snapshot }; - const workspace = this.ioc.getModel("workspace", workspaceConfig); - return workspace; - } - async fetchWorkspace(itemId) { - const snapshot = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async bundleWorkspaceTo(type, workspaceId) { - await this.bridge.send(OPERATIONS.bundleWorkspace.name, { type, workspaceId }); - } - async bundleItemTo(type, itemId) { - const isSupported = await this.isOperationSupported(OPERATIONS.bundleItem.name); - if (!isSupported) { - throw new Error(`Operation ${OPERATIONS.bundleItem.name} is not supported. Ensure that you are running the latest version of all packages`); - } - await this.bridge.send(OPERATIONS.bundleItem.name, { type, itemId }); - } - async getTaskbarIcon(frameId) { - return await this.bridge.send(OPERATIONS.getTaskbarIcon.name, { frameId }); - } - async setTaskbarIcon(icon, frameId) { - await this.bridge.send(OPERATIONS.setTaskbarIcon.name, { icon, frameId }); - } - getWorkspaceContext(workspaceId) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.get(contextName); - } - setWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.set(contextName, data); - } - updateWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.update(contextName, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.subscribe(contextName, callback); - } - async restoreItem(itemId) { - await this.bridge.send(OPERATIONS.restoreItem.name, { itemId }); - } - async maximizeItem(itemId) { - await this.bridge.send(OPERATIONS.maximizeItem.name, { itemId }); - } - async focusItem(itemId) { - await this.bridge.send(OPERATIONS.focusItem.name, { itemId }); - } - async closeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.closeWorkspace.name, { itemId: workspaceId }); - } - async closeItem(itemId) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId }); - } - async closeFrame(itemId, closeOptions) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId, closeOptions }); - } - async resizeItem(itemId, config) { - await this.bridge.send(OPERATIONS.resizeItem.name, Object.assign({}, { itemId }, config)); - } - async setMaximizationBoundary(itemId, config) { - await this.bridge.send(OPERATIONS.setMaximizationBoundary.name, Object.assign({}, { itemId }, config)); - } - async showWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.showLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.hideLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async setWindowDragMode(workspaceId, dragMode) { - await this.bridge.send(OPERATIONS.setWindowDragMode.name, { itemId: workspaceId, dragMode }); - } - async moveFrame(itemId, config) { - await this.bridge.send(OPERATIONS.moveFrame.name, Object.assign({}, { itemId }, config)); - } - getGDWindow(itemId) { - return this.windows.list().find((gdWindow) => gdWindow.id === itemId); - } - async forceLoadWindow(itemId) { - const controlResult = await this.bridge.send(OPERATIONS.forceLoadWindow.name, { itemId }); - return controlResult.windowId; - } - async ejectWindow(itemId, windowId) { - return await this.bridge.send(OPERATIONS.ejectWindow.name, { itemId, windowId }); - } - async moveWindowTo(itemId, newParentId) { - await this.bridge.send(OPERATIONS.moveWindowTo.name, { itemId, containerId: newParentId }); - } - async getSnapshot(itemId, type) { - let result; - if (type === "workspace") { - result = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - } - else if (type === "frame") { - result = await this.bridge.send(OPERATIONS.getFrameSnapshot.name, { itemId }); - } - return result; - } - async setItemTitle(itemId, title) { - await this.bridge.send(OPERATIONS.setItemTitle.name, { itemId, title }); - } - refreshChildren(config) { - const { parent, children, existingChildren, workspace } = config; - if (parent instanceof Window || parent.type === "window") { - return; - } - const newChildren = children.map((newChildSnapshot) => { - let childToAdd = existingChildren.find((child) => { - return child.type === "window" ? child.elementId === newChildSnapshot.id : child.id === newChildSnapshot.id; - }); - if (childToAdd) { - this.privateDataManager.remapChild(childToAdd, { - parent: parent, - children: [], - config: newChildSnapshot.config - }); - } - else { - let createConfig; - if (newChildSnapshot.type === "window") { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - }; - } - else { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - children: [] - }; - } - childToAdd = this.ioc.getModel(newChildSnapshot.type, createConfig); - } - if (newChildSnapshot.type !== "window") { - this.refreshChildren({ - workspace, existingChildren, - children: newChildSnapshot.children, - parent: childToAdd - }); - } - return childToAdd; - }); - if (parent instanceof Workspace) { - return newChildren; - } - else { - this.privateDataManager.remapChild(parent, { children: newChildren }); - return newChildren; - } - } - iterateFindChild(children, predicate) { - let foundChild = children.find((child) => predicate(child)); - if (foundChild) { - return foundChild; - } - children.some((child) => { - if (child instanceof Window) { - return false; - } - foundChild = this.iterateFindChild(child.children, predicate); - if (foundChild) { - return true; - } - }); - return foundChild; - } - iterateFilterChildren(children, predicate) { - const foundChildren = children.filter((child) => predicate(child)); - const grandChildren = children.reduce((innerFound, child) => { - if (child instanceof Window) { - return innerFound; - } - innerFound.push(...this.iterateFilterChildren(child.children, predicate)); - return innerFound; - }, []); - foundChildren.push(...grandChildren); - return foundChildren; - } - notifyWindowAdded(windowId) { - return new Promise((resolve) => { - const alreadyPresent = this.windows.list().some((win) => win.id === windowId); - if (alreadyPresent) { - return resolve(); - } - const unsubscribe = this.windows.onWindowAdded((win) => { - if (win.id !== windowId) { - return; - } - if (unsubscribe) { - unsubscribe(); - } - resolve(); - }); - }); - } - async hibernateWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.hibernateWorkspace.name, { workspaceId }); - } - async resumeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.resumeWorkspace.name, { workspaceId }); - } - async lockWorkspace(workspaceId, config) { - await this.bridge.send(OPERATIONS.lockWorkspace.name, { workspaceId, config }); - } - async lockWindow(windowPlacementId, config) { - await this.bridge.send(OPERATIONS.lockWindow.name, { windowPlacementId, config }); - } - async lockContainer(itemId, type, config) { - await this.bridge.send(OPERATIONS.lockContainer.name, { itemId, type, config }); - } - async pinWorkspace(workspaceId, icon) { - await this.bridge.send(OPERATIONS.pinWorkspace.name, { workspaceId, icon }); - } - async unpinWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.unpinWorkspace.name, { workspaceId }); - } - async getWorkspaceIcon(workspaceId) { - const result = await this.bridge.send(OPERATIONS.getWorkspaceIcon.name, { workspaceId }); - return result.icon; - } - setWorkspaceIcon(workspaceId, icon) { - return this.bridge.send(OPERATIONS.setWorkspaceIcon.name, { workspaceId, icon }); - } - async getPlatformFrameId() { - try { - const result = await this.bridge.send(OPERATIONS.getPlatformFrameId.name, {}); - return result; - } - catch (error) { - return {}; - } - } - async setLoadingStrategy(workspaceId, strategy) { - await this.isOperationSupported(OPERATIONS.setLoadingStrategy.name); - return this.bridge.send(OPERATIONS.setLoadingStrategy.name, { itemId: workspaceId, strategy }); - } - async showFrame(frameId, config) { - const payload = { frameId, isVisible: true, ...config }; - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, payload); - } - async hideFrame(frameId) { - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, { frameId, isVisible: false }); - } - async getFrameVisibility(frameId) { - const result = await this.bridge.send(OPERATIONS.getFrameVisibility.name, { itemId: frameId }); - return result.isVisible; - } - async showFrameDialog(frameId, options) { - const result = await this.bridge.send(OPERATIONS.showFrameDialog.name, { frameId, options }, { timeout: ONE_DAY_MS }); - return result; - } - async isOperationSupported(operation) { - if (isDesktop()) { - return { isSupported: true }; - } - return await this.bridge.send(OPERATIONS.operationCheck.name, { operation }); - } - async showPopup(config, frameId) { - return this.bridge.send(OPERATIONS.showPopup.name, { ...config, frameId }); - } - } - - class MainController { - bridge; - base; - shortcutsController; - closingController; - constructor(bridge, base, shortcutsController, closingController) { - this.bridge = bridge; - this.base = base; - this.shortcutsController = shortcutsController; - this.closingController = closingController; - } - setTaskbarIcon(icon, frameId) { - return this.base.setTaskbarIcon(icon, frameId); - } - getTaskbarIcon(frameId) { - return this.base.getTaskbarIcon(frameId); - } - checkIsWindowLoaded(windowId) { - return this.base.checkIsWindowLoaded(windowId); - } - async checkIsInSwimlane(windowId) { - const controlResult = await this.bridge.send(OPERATIONS.isWindowInWorkspace.name, { itemId: windowId }); - return controlResult.inWorkspace; - } - async createWorkspace(definition, saveConfig) { - const createConfig = Object.assign({}, definition, { saveConfig }); - return await this.base.createWorkspace(createConfig); - } - async createEmptyFrame(definition) { - return await this.base.createEmptyFrame(definition); - } - async initFrame(frameId, config) { - return this.base.initFrame(frameId, config); - } - async restoreWorkspace(name, options) { - const allLayouts = await this.getLayoutSummaries(); - const layoutExists = allLayouts.some((summary) => summary.name === name); - if (!layoutExists) { - throw new Error(`This layout: ${name} cannot be restored, because it doesn't exist.`); - } - if (options?.frameId) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - const foundMatchingFrame = allFrameSummaries.summaries.some((summary) => summary.id === options.frameId); - if (!foundMatchingFrame) { - throw new Error(`Cannot reuse the frame with id: ${options.frameId}, because there is no frame with that ID found`); - } - } - return await this.base.restoreWorkspace(name, options); - } - async add(type, parentId, parentType, definition) { - return await this.base.add(type, parentId, parentType, definition); - } - processLocalSubscription(config, levelId) { - return isDesktop() ? - this.handleEnterpriseLocalSubscription(config, levelId) : - this.handleCoreLocalSubscription(config, levelId); - } - processGlobalSubscription(callback, eventType, action) { - return isDesktop() ? - this.handleEnterpriseGlobalSubscription(callback, eventType, action) : - this.handleCoreGlobalSubscription(callback, eventType, action); - } - async getFrame(selector) { - if (selector.windowId) { - return await this.base.getFrame(selector.windowId); - } - if (selector.predicate) { - return (await this.getFrames(selector.predicate))[0]; - } - throw new Error(`The provided selector is not valid: ${JSON.stringify(selector)}`); - } - async getFrames(predicate) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - return this.base.getFrames(allFrameSummaries.summaries, predicate); - } - getWorkspaceById(workspaceId) { - return this.base.fetchWorkspace(workspaceId); - } - async getWorkspaceByWindowId(itemId) { - if (!isDesktop()) { - return (await this.getWorkspaces((wsp) => !!wsp.getWindow((w) => w.id === itemId)))[0]; - } - return this.base.fetchWorkspace(itemId); - } - transformStreamPayloadToWorkspace(payload) { - return this.base.transformStreamPayloadToWorkspace(payload); - } - async getWorkspace(predicate) { - let foundWorkspace; - await this.iterateWorkspaces((wsp, end) => { - if (predicate(wsp)) { - foundWorkspace = wsp; - end(); - } - }); - return foundWorkspace; - } - async getWorkspaces(predicate) { - const matchingWorkspaces = []; - await this.iterateWorkspaces((wsp) => { - if (!predicate || predicate(wsp)) { - matchingWorkspaces.push(wsp); - } - }); - return matchingWorkspaces; - } - async getWorkspacesByFrameId(frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - const workspacesForFrame = await Promise.all(summariesForFrame.map((summary) => { - return this.base.fetchWorkspace(summary.id); - })); - return workspacesForFrame; - } - async isLastWorkspaceInFrame(workspaceId, frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - return summariesForFrame.length === 1 && summariesForFrame[0].id === workspaceId; - } - async getAllWorkspaceSummaries() { - const allSummariesResult = await this.bridge.send(OPERATIONS.getAllWorkspacesSummaries.name, {}); - return this.base.getAllWorkspaceSummaries(allSummariesResult); - } - async getWindow(predicate) { - let resultWindow; - await this.iterateWorkspaces((wsp, end) => { - const foundWindow = wsp.getWindow(predicate); - if (foundWindow) { - resultWindow = foundWindow; - end(); - } - }); - return resultWindow; - } - async getParent(predicate) { - let resultParent; - await this.iterateWorkspaces((wsp, end) => { - const foundParent = wsp.getBox(predicate); - if (foundParent) { - resultParent = foundParent; - end(); - } - }); - return resultParent; - } - async getLayoutSummaries() { - const allLayouts = await this.bridge.send(OPERATIONS.getAllLayoutsSummaries.name); - return allLayouts.summaries; - } - async deleteLayout(name) { - await this.bridge.send(OPERATIONS.deleteLayout.name, { name }); - } - async exportLayout(predicate) { - const allLayoutsResult = await this.bridge.send(OPERATIONS.exportAllLayouts.name); - return allLayoutsResult.layouts.reduce((matchingLayouts, layout) => { - if (!predicate || predicate(layout)) { - matchingLayouts.push(layout); - } - return matchingLayouts; - }, []); - } - async saveLayout(config) { - return await this.bridge.send(OPERATIONS.saveLayout.name, config); - } - async importLayouts(layouts, mode) { - if (isDesktop()) { - try { - await this.bridge.send(OPERATIONS.importLayouts.name, { layouts, mode }); - } - catch (error) { - await Promise.all(layouts.map((layout) => this.bridge.send(OPERATIONS.importLayout.name, { layout, mode }))); - } - return; - } - await this.base.importLayouts(layouts, mode); - } - handleOnSaved(callback) { - return this.base.handleOnSaved(callback); - } - handleOnRemoved(callback) { - return this.base.handleOnRemoved(callback); - } - async bundleWorkspaceTo(type, workspaceId) { - return await this.base.bundleWorkspaceTo(type, workspaceId); - } - async bundleItemTo(type, id) { - return await this.base.bundleItemTo(type, id); - } - getWorkspaceContext(workspaceId) { - return this.base.getWorkspaceContext(workspaceId); - } - setWorkspaceContext(workspaceId, data) { - return this.base.setWorkspaceContext(workspaceId, data); - } - updateWorkspaceContext(workspaceId, data) { - return this.base.updateWorkspaceContext(workspaceId, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - return this.base.subscribeWorkspaceContextUpdated(workspaceId, callback); - } - async restoreItem(itemId) { - return await this.base.restoreItem(itemId); - } - async maximizeItem(itemId) { - return await this.base.maximizeItem(itemId); - } - async focusItem(itemId) { - return await this.base.focusItem(itemId); - } - async changeFrameState(frameId, state) { - await this.bridge.send(OPERATIONS.changeFrameState.name, { frameId, requestedState: state }); - } - async getFrameBounds(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameBounds.name, { itemId: frameId }); - return frameResult.bounds; - } - async getFrameState(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameState.name, { itemId: frameId }); - return frameResult.state; - } - async closeWorkspace(workspaceId, frameId) { - if (isDesktop()) { - return await this.closeItem(workspaceId); - } - let closeWorkspaceCommandExists = false; - try { - const { isSupported } = await this.base.isOperationSupported(OPERATIONS.closeWorkspace.name); - closeWorkspaceCommandExists = isSupported; - } - catch (error) { - closeWorkspaceCommandExists = false; - } - if (closeWorkspaceCommandExists) { - return await this.base.closeWorkspace(workspaceId); - } - return await this.legacyCloseWorkspace(workspaceId, frameId); - } - async closeItem(itemId) { - return await this.base.closeItem(itemId); - } - async closeFrame(itemId, closeOptions) { - return await this.base.closeFrame(itemId, closeOptions); - } - async resizeItem(itemId, config) { - return await this.base.resizeItem(itemId, config); - } - async setMaximizationBoundary(itemId, config) { - return await this.base.setMaximizationBoundary(itemId, config); - } - async showWorkspaceLoadingAnimation(workspaceId) { - return await this.base.showWorkspaceLoadingAnimation(workspaceId); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - return await this.base.hideWorkspaceLoadingAnimation(workspaceId); - } - async setWindowDragMode(workspaceId, dragMode) { - return await this.base.setWindowDragMode(workspaceId, dragMode); - } - async moveFrame(itemId, config) { - return await this.base.moveFrame(itemId, config); - } - getGDWindow(itemId) { - return this.base.getGDWindow(itemId); - } - async forceLoadWindow(itemId) { - const windowId = await this.base.forceLoadWindow(itemId); - await this.base.notifyWindowAdded(windowId); - return windowId; - } - async ejectWindow(itemId, windowId) { - const id = (await this.base.ejectWindow(itemId, windowId)).windowId; - await this.base.notifyWindowAdded(id); - return id; - } - async moveWindowTo(itemId, newParentId) { - return await this.base.moveWindowTo(itemId, newParentId); - } - async getSnapshot(itemId, type) { - return await this.base.getSnapshot(itemId, type); - } - async setItemTitle(itemId, title) { - return await this.base.setItemTitle(itemId, title); - } - flatChildren(children) { - return children.reduce((soFar, child) => { - soFar.push(child); - if (child.type !== "window") { - soFar.push(...this.flatChildren(child.children)); - } - return soFar; - }, []); - } - refreshChildren(config) { - return this.base.refreshChildren(config); - } - iterateFindChild(children, predicate) { - return this.base.iterateFindChild(children, predicate); - } - iterateFilterChildren(children, predicate) { - return this.base.iterateFilterChildren(children, predicate); - } - hibernateWorkspace(workspaceId) { - return this.base.hibernateWorkspace(workspaceId); - } - resumeWorkspace(workspaceId) { - return this.base.resumeWorkspace(workspaceId); - } - lockWorkspace(workspaceId, config) { - return this.base.lockWorkspace(workspaceId, config); - } - lockWindow(windowPlacementId, config) { - return this.base.lockWindow(windowPlacementId, config); - } - lockContainer(itemId, type, config) { - return this.base.lockContainer(itemId, type, config); - } - pinWorkspace(workspaceId, icon) { - return this.base.pinWorkspace(workspaceId, icon); - } - unpinWorkspace(workspaceId) { - return this.base.unpinWorkspace(workspaceId); - } - getWorkspaceIcon(workspaceId) { - return this.base.getWorkspaceIcon(workspaceId); - } - setWorkspaceIcon(workspaceId, icon) { - return this.base.setWorkspaceIcon(workspaceId, icon); - } - async getFrameConstraints(frameId) { - const frameSnapshot = await this.getSnapshot(frameId, "frame"); - return { - minWidth: frameSnapshot.config.minWidth, - maxWidth: frameSnapshot.config.maxWidth, - minHeight: frameSnapshot.config.minHeight, - maxHeight: frameSnapshot.config.maxHeight, - }; - } - registerShortcut(shortcut, frameId, callback) { - return this.shortcutsController.registerShortcut(shortcut, frameId, callback); - } - getPlatformFrameId() { - return this.base.getPlatformFrameId(); - } - setLoadingStrategy(workspaceId, strategy) { - return this.base.setLoadingStrategy(workspaceId, strategy); - } - registerFrameOnClosing(frameId, callback) { - return this.closingController.registerFrameOnClosing(frameId, callback); - } - showPopup(config, frameId) { - return this.base.showPopup(config, frameId); - } - async showFrame(frameId, config) { - return this.base.showFrame(frameId, config); - } - async hideFrame(frameId) { - return this.base.hideFrame(frameId); - } - async getFrameVisibility(frameId) { - return this.base.getFrameVisibility(frameId); - } - async showFrameDialog(frameId, options) { - return this.base.showFrameDialog(frameId, options); - } - async handleCoreLocalSubscription(config, levelId) { - await this.bridge.createCoreEventSubscription(); - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseLocalSubscription(config, levelId) { - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async handleCoreGlobalSubscription(callback, eventType, action) { - await this.bridge.createCoreEventSubscription(); - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseGlobalSubscription(callback, eventType, action) { - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async iterateWorkspaces(callback) { - let ended = false; - const end = () => { ended = true; }; - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - for (const summary of workspaceSummaries) { - if (ended) { - return; - } - const wsp = await this.base.fetchWorkspace(summary.id); - callback(wsp, end); - } - } - async legacyCloseWorkspace(workspaceId, frameId) { - const isLastWorkspaceInFrame = await this.isLastWorkspaceInFrame(workspaceId, frameId); - const platformFrameId = (await this.getPlatformFrameId()).id; - const shouldCloseFrame = isLastWorkspaceInFrame && - platformFrameId !== frameId; - if (shouldCloseFrame) { - return await this.closeFrame(frameId, {}); - } - await this.closeItem(workspaceId); - } - } - - class ShortcutsController { - bridge; - _shortcuts = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.bridge.onOperation((payload) => { - if (payload.operation === CLIENT_OPERATIONS.shortcutClicked.name) { - const data = payload.data; - this._shortcuts.execute(`${data.frameId}-${data.shortcut}`); - } - }); - } - async registerShortcut(shortcut, frameId, callback) { - await this.bridge.send(OPERATIONS.registerShortcut.name, { shortcut, frameId }); - const un = this._shortcuts.add(`${frameId}-${shortcut}`, callback); - return () => { - un(); - this.bridge.send(OPERATIONS.unregisterShortcut.name, { shortcut, frameId }); - }; - } - } - - class ClosingController { - bridge; - registry = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.subscribeToFrameClosing(); - } - async registerFrameOnClosing(frameId, callback) { - await this.bridge.send(OPERATIONS.subscribeToFrameClosing.name, { itemId: frameId }); - return this.registry.add(frameId, callback); - } - subscribeToFrameClosing() { - this.bridge.onOperationWithResponse(async (payload) => { - if (payload.operation !== CLIENT_OPERATIONS.frameClosing.name) { - return; - } - const data = payload.data; - const frameClosingResult = await Promise.all(this.registry.execute(data.frameId)); - return this.aggregateFrameClosingResult(frameClosingResult); - }); - } - aggregateFrameClosingResult(results) { - return { - prevent: results.some((result) => result?.prevent) - }; - } - } - - class IoC { - agm; - windows; - layouts; - contexts; - _controllerInstance; - _bridgeInstance; - _transportInstance; - _privateDataManagerInstance; - _parentBaseInstance; - _baseController; - _shortcutsController; - _closingController; - constructor(agm, windows, layouts, contexts) { - this.agm = agm; - this.windows = windows; - this.layouts = layouts; - this.contexts = contexts; - } - get baseController() { - if (!this._baseController) { - this._baseController = new BaseController(this, this.windows, this.contexts, this.layouts); - } - return this._baseController; - } - get controller() { - if (!this._controllerInstance) { - this._controllerInstance = new MainController(this.bridge, this.baseController, this.shortcutsController, this.closingController); - } - return this._controllerInstance; - } - get shortcutsController() { - if (!this._shortcutsController) { - this._shortcutsController = new ShortcutsController(this.bridge); - } - return this._shortcutsController; - } - get closingController() { - if (!this._closingController) { - this._closingController = new ClosingController(this.bridge); - } - return this._closingController; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new Bridge(this.transport, CallbackFactory()); - } - return this._bridgeInstance; - } - get transport() { - if (!this._transportInstance) { - this._transportInstance = new InteropTransport(this.agm, CallbackFactory()); - } - return this._transportInstance; - } - get privateDataManager() { - if (!this._privateDataManagerInstance) { - this._privateDataManagerInstance = new PrivateDataManager(); - } - return this._privateDataManagerInstance; - } - get parentBase() { - if (!this._parentBaseInstance) { - this._parentBaseInstance = new Base(this.privateDataManager); - } - return this._parentBaseInstance; - } - async initiate(actualWindowId) { - await this.transport.initiate(actualWindowId); - } - getModel(type, createConfig) { - switch (type) { - case "frame": { - const newFrame = new Frame(this.privateDataManager); - const { summary } = createConfig; - const frameData = { summary, controller: this.controller }; - this.privateDataManager.setFrameData(newFrame, frameData); - return newFrame; - } - case "window": { - const { id, parent, frame, workspace, config } = createConfig; - const windowPrivateData = { - type: "window", - controller: this.controller, - config, id, parent, frame, workspace - }; - const newWindow = new Window(this.privateDataManager); - this.privateDataManager.setWindowData(newWindow, windowPrivateData); - return newWindow; - } - case "row": - case "column": - case "group": { - const { id, children, parent, frame, workspace, config } = createConfig; - const newParent = type === "column" ? new Column(this.parentBase) : - type === "row" ? new Row(this.parentBase) : new Group(this.parentBase); - const builtChildren = this.buildChildren(children, frame, workspace, newParent); - const parentPrivateData = { - id, parent, frame, workspace, - config, - type, - controller: this.controller, - children: builtChildren, - }; - this.privateDataManager.setParentData(newParent, parentPrivateData); - return newParent; - } - case "workspace": { - const { snapshot, frame } = createConfig; - const newWorkspace = new Workspace(this.privateDataManager); - const children = this.buildChildren(snapshot.children, frame, newWorkspace, newWorkspace); - const workspacePrivateData = { - id: snapshot.id, - type: "workspace", - config: snapshot.config, - base: this.parentBase, - controller: this.controller, - children, frame, ioc: this - }; - this.privateDataManager.setWorkspaceData(newWorkspace, workspacePrivateData); - return newWorkspace; - } - default: throw new Error(`Unrecognized type: ${type}`); - } - } - getBuilder(config) { - config.definition = config.definition || {}; - if (!Array.isArray(config.definition.children)) { - config.definition.children = []; - } - const baseBuilder = new BaseBuilder(this.getBuilder.bind(this)); - switch (config.type) { - case "workspace": { - return new WorkspaceBuilder(config.definition, baseBuilder, this.controller); - } - case "row": - case "column": - case "group": { - config.definition.type = config.type; - return new ParentBuilder(config.definition, baseBuilder); - } - default: throw new Error(`Unexpected Builder creation error, provided config: ${JSON.stringify(config)}`); - } - } - buildChildren(children, frame, workspace, parent) { - return children.map((child) => { - switch (child.type) { - case "window": return this.getModel("window", { - id: child.id, - config: child.config, - frame, workspace, parent - }); - case "column": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "row": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "group": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - default: throw new Error(`Unsupported child type: ${child.type}`); - } - }); - } - } - - var version = "4.2.3"; - - const composeAPI = (glue, ioc) => { - const controller = ioc.controller; - const inWorkspace = () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - return controller.checkIsInSwimlane(myId); - }; - const getBuilder = (config) => { - const validatedConfig = builderConfigDecoder.runWithException(config); - return ioc.getBuilder(validatedConfig); - }; - const getMyFrame = async () => { - const windowId = glue.windows.my().id; - if (!windowId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(windowId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your frame, because this window is not in a workspace"); - } - return controller.getFrame({ windowId }); - }; - const getFrame = async (predicate) => { - checkThrowCallback(predicate); - return controller.getFrame({ predicate }); - }; - const getAllFrames = async (predicate) => { - checkThrowCallback(predicate, true); - return controller.getFrames(predicate); - }; - const getAllWorkspacesSummaries = () => { - return controller.getAllWorkspaceSummaries(); - }; - const getMyWorkspace = async () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my workspace, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(myId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your workspace, because this window is not in a workspace"); - } - return await controller.getWorkspaceByWindowId(myId); - }; - const getWorkspace = async (predicate) => { - checkThrowCallback(predicate); - return (await controller.getWorkspaces(predicate))[0]; - }; - const getWorkspaceById = async (workspaceId) => { - nonEmptyStringDecoder.runWithException(workspaceId); - return controller.getWorkspaceById(workspaceId); - }; - const getAllWorkspaces = (predicate) => { - checkThrowCallback(predicate, true); - return controller.getWorkspaces(predicate); - }; - const getWindow = async (predicate) => { - checkThrowCallback(predicate); - return controller.getWindow(predicate); - }; - const getParent = async (predicate) => { - checkThrowCallback(predicate); - return controller.getParent(predicate); - }; - const restoreWorkspace = async (name, options) => { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return controller.restoreWorkspace(name, validatedOptions); - }; - const createWorkspace = async (definition, saveConfig) => { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(saveConfig); - return controller.createWorkspace(validatedDefinition, validatedConfig); - }; - const createEmptyFrame = async (definition) => { - const validatedDefinition = emptyFrameDefinitionDecoder.runWithException(definition); - return controller.createEmptyFrame(validatedDefinition ?? {}); - }; - const layouts = { - getSummaries: () => { - return controller.getLayoutSummaries(); - }, - delete: async (name) => { - nonEmptyStringDecoder.runWithException(name); - return controller.deleteLayout(name); - }, - export: async (predicate) => { - checkThrowCallback(predicate, true); - return controller.exportLayout(predicate); - }, - import: async (layouts, mode = "replace") => { - if (!Array.isArray(layouts)) { - throw new Error(`The provided layouts argument is not an array: ${JSON.stringify(layouts)}`); - } - layouts.forEach((layout) => workspaceLayoutDecoder.runWithException(layout)); - return controller.importLayouts(layouts, mode); - }, - save: async (config) => { - const verifiedConfig = workspaceLayoutSaveConfigDecoder.runWithException(config); - return controller.saveLayout(verifiedConfig); - }, - onSaved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnSaved(callback); - }, - onRemoved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnRemoved(callback); - } - }; - const onFrameOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - callback(frame); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "opened"); - return unsubscribe; - }; - const onFrameClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "closed"); - return unsubscribe; - }; - const onWorkspaceOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "opened"); - return unsubscribe; - }; - const onWorkspaceClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "closed"); - return unsubscribe; - }; - const onWorkspaceHibernated = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "hibernated"); - return unsubscribe; - }; - const onWorkspaceResumed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "resumed"); - return unsubscribe; - }; - const onWindowAdded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "added"); - return unsubscribe; - }; - const onWindowLoaded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const foundWindow = workspace.getWindow((win) => win.id && win.id === payload.windowSummary.config.windowId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "loaded"); - return unsubscribe; - }; - const onWindowRemoved = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "removed"); - return unsubscribe; - }; - const onWindowMaximized = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "maximized"); - return unsubscribe; - }; - const onWindowRestored = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "restored"); - return unsubscribe; - }; - const onWindowSelected = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "selected"); - return unsubscribe; - }; - const waitForFrame = async (id) => { - nonEmptyStringDecoder.runWithException(id); - return new Promise((res, rej) => { - let unsub = () => { - }; - onFrameOpened((f) => { - if (f.id === id) { - res(f); - unsub(); - } - }).then((u) => { - unsub = u; - return getAllFrames(); - }).then((frames) => { - const myFrame = frames.find((f) => f.id === id); - if (myFrame) { - res(myFrame); - unsub(); - } - }).catch(rej); - }); - }; - return { - inWorkspace, - getBuilder, - getMyFrame, - getFrame, - getAllFrames, - getAllWorkspacesSummaries, - getMyWorkspace, - getWorkspace, - getWorkspaceById, - getAllWorkspaces, - getWindow, - getBox: getParent, - restoreWorkspace, - createWorkspace, - createEmptyFrame, - waitForFrame, - layouts, - onFrameOpened, - onFrameClosed, - onWorkspaceOpened, - onWorkspaceClosed, - onWorkspaceHibernated, - onWorkspaceResumed, - onWindowAdded, - onWindowLoaded, - onWindowRemoved, - onWindowMaximized, - onWindowRestored, - onWindowSelected, - version - }; - }; - - const factoryFunction = async (io) => { - const ioc = new IoC(io.agm, io.windows, io.layouts, io.contexts); - const actualWindowId = io.interop.instance.windowId; - await ioc.initiate(actualWindowId); - io.workspaces = composeAPI(io, ioc); - }; - if (typeof window !== "undefined") { - window.IOWorkspaces = factoryFunction; - } - - return factoryFunction; - -})); -//# sourceMappingURL=workspaces.umd.js.map diff --git a/javascript/start/client-details/package-lock.json b/javascript/start/client-details/package-lock.json new file mode 100644 index 0000000..8a3a524 --- /dev/null +++ b/javascript/start/client-details/package-lock.json @@ -0,0 +1,1280 @@ +{ + "name": "client-details", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "client-details", + "version": "1.0.0", + "dependencies": { + "@interopio/browser": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@interopio/browser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser/-/browser-4.2.4.tgz", + "integrity": "sha512-BPgkwH6N8HyGf7st99ZJwQ7arijz9j1bGu7pUAXBrtbv6cu4zH5GR7JKPGANZmFl0uefNPQyAQ4hc7C/i1i++A==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0", + "@interopio/search-api": "^3.2.1", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.2" + } + }, + "node_modules/@interopio/core": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@interopio/core/-/core-6.8.1.tgz", + "integrity": "sha512-WFWIV8JilNuAcxXaB+81IjL9j82sU73ABMUUEOWpvWoyqxhPlneOS+rSYViFX5gdk5pLH3fM6T/MmRGn3UFLwQ==", + "license": "MIT", + "dependencies": { + "callback-registry": "^2.7.2", + "ws": "^8.18.0" + } + }, + "node_modules/@interopio/desktop": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/@interopio/desktop/-/desktop-6.18.0.tgz", + "integrity": "sha512-YqRHRiCymbY2fOCT2HHJnLY4780JSRI1fUtaWEoIa5Z3djZk/3xRgVxIjOVw9Y/TAFGCwyIeW142a7HYnSGD5Q==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/schemas": "^10.1.0", + "@interopio/utils": "^1.4.2", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.1" + } + }, + "node_modules/@interopio/schemas": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@interopio/schemas/-/schemas-10.1.0.tgz", + "integrity": "sha512-8uDEoOAZenTr4a3O8vLq6JyS/LutkT/gh9EjuOrS9fOmHEUfJaS2u+qPo5em9/8MtjKgblZEJStSsW1gr34CtQ==", + "license": "ISC", + "dependencies": { + "ajv": "^6.12.6", + "ajv-keywords": "^3.4.1" + }, + "peerDependencies": { + "log4js": "^6.4.2" + }, + "peerDependenciesMeta": { + "log4js": { + "optional": true + } + } + }, + "node_modules/@interopio/search-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@interopio/search-api/-/search-api-3.2.1.tgz", + "integrity": "sha512-raUZzqBQoidm/6Mvgao2wFWlTDu9D4jghiX1dqor1LdsIfUpelJkkuFGeDl0z/3DWneaxDF8Vc/uoBtLz7qJLw==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1" + } + }, + "node_modules/@interopio/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@interopio/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-14Bb2WI9Cwf9zjhTurP4qP9AVY4cxR1AOrwrOtHrTGAeeHp88mALFWfMEv1QnRhlQ06To2vQcRgebNrPlHDZ8Q==", + "license": "ISC", + "dependencies": { + "decoder-validate": "^0.0.2" + } + }, + "node_modules/@interopio/workspaces-api": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@interopio/workspaces-api/-/workspaces-api-4.2.3.tgz", + "integrity": "sha512-5wrR1yhETKuX4txVrmS5q3G+8KI6GW4yOxsrVdf5qErO2HxN938XUdiAHIesarwlQoncrgnVx7uTn6IeOWUoXg==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/callback-registry": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/callback-registry/-/callback-registry-2.7.2.tgz", + "integrity": "sha512-VVrtF21DaH0VHeNMkLDd4VGuxsYM3V3l3lwYneKVMU/6X3TRtcQszUwlAcqj2HrLcbP1NyS12LsanUwCykaz/Q==", + "license": "ISC" + }, + "node_modules/decoder-validate": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/decoder-validate/-/decoder-validate-0.0.2.tgz", + "integrity": "sha512-9BsqAH9Zq6CvlxKHkSrZrH2iYlhuhHcrh6uTnDvcsa9P5YEweEzt1ci+X/9STgSCE7b9BA7/QIiwhfUDDWmjxw==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/javascript/start/client-details/package.json b/javascript/start/client-details/package.json new file mode 100644 index 0000000..dd18425 --- /dev/null +++ b/javascript/start/client-details/package.json @@ -0,0 +1,14 @@ +{ + "name": "client-details", + "version": "1.0.0", + "scripts": { + "start": "vite --port 9200" + }, + "dependencies": { + "@interopio/browser": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } +} diff --git a/javascript/start/clients/index.html b/javascript/start/clients/index.html index 8f93fb5..166b057 100644 --- a/javascript/start/clients/index.html +++ b/javascript/start/clients/index.html @@ -13,12 +13,7 @@ - - - - - - + diff --git a/javascript/start/clients/index.js b/javascript/start/clients/index.js index bd82468..7147a9d 100644 --- a/javascript/start/clients/index.js +++ b/javascript/start/clients/index.js @@ -1,3 +1,12 @@ +// TODO: Chapter 2 +// import IOBrowserPlatform from '@interopio/browser-platform'; +// TODO: Chapter 9.3 +// import IOWorkspaces from '@interopio/workspaces-api'; +// TODO: Chapter 8.2 +// import { setupApplications } from './plugins/applicationsPlugin.js'; +// TODO: Chapter 9.2 +// import { setupLayouts } from './plugins/layoutsPlugin.js'; + const setupClients = (clients) => { const table = document.getElementById("clientsTable").getElementsByTagName("tbody")[0]; diff --git a/javascript/start/clients/lib/browser.platform.umd.js b/javascript/start/clients/lib/browser.platform.umd.js deleted file mode 100644 index afae729..0000000 --- a/javascript/start/clients/lib/browser.platform.umd.js +++ /dev/null @@ -1,34 +0,0 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).IoConnectBrowserPlatform=t()}(this,function(){"use strict";const global=window;function getDefaultExportFromCjs$1$1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var isMergeableObject$1=function(e){return isNonNullObject$1(e)&&!isSpecial$1(e)};function isNonNullObject$1(e){return!!e&&"object"==typeof e}function isSpecial$1(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||isReactElement$1(e)}var canUseSymbol$1="function"==typeof Symbol&&Symbol.for,REACT_ELEMENT_TYPE$1=canUseSymbol$1?Symbol.for("react.element"):60103;function isReactElement$1(e){return e.$$typeof===REACT_ELEMENT_TYPE$1}function emptyTarget$1(e){return Array.isArray(e)?[]:{}}function cloneUnlessOtherwiseSpecified$1(e,t){return!1!==t.clone&&t.isMergeableObject(e)?deepmerge$1(emptyTarget$1(e),e,t):e}function defaultArrayMerge$1(e,t,r){return e.concat(t).map(function(e){return cloneUnlessOtherwiseSpecified$1(e,r)})}function getMergeFunction$1(e,t){if(!t.customMerge)return deepmerge$1;var r=t.customMerge(e);return"function"==typeof r?r:deepmerge$1}function getEnumerableOwnPropertySymbols$1(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}function getKeys$1(e){return Object.keys(e).concat(getEnumerableOwnPropertySymbols$1(e))}function propertyIsOnObject$1(e,t){try{return t in e}catch(e){return!1}}function propertyIsUnsafe$1(e,t){return propertyIsOnObject$1(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}function mergeObject$1(e,t,r){var n={};return r.isMergeableObject(e)&&getKeys$1(e).forEach(function(t){n[t]=cloneUnlessOtherwiseSpecified$1(e[t],r)}),getKeys$1(t).forEach(function(i){propertyIsUnsafe$1(e,i)||(propertyIsOnObject$1(e,i)&&r.isMergeableObject(t[i])?n[i]=getMergeFunction$1(i,r)(e[i],t[i],r):n[i]=cloneUnlessOtherwiseSpecified$1(t[i],r))}),n}function deepmerge$1(e,t,r){(r=r||{}).arrayMerge=r.arrayMerge||defaultArrayMerge$1,r.isMergeableObject=r.isMergeableObject||isMergeableObject$1,r.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified$1;var n=Array.isArray(t);return n===Array.isArray(e)?n?r.arrayMerge(e,t,r):mergeObject$1(e,t,r):cloneUnlessOtherwiseSpecified$1(t,r)}deepmerge$1.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,r){return deepmerge$1(e,r,t)},{})};var deepmerge_1$1=deepmerge$1,cjs$1=deepmerge_1$1,deepmerge$1$1=getDefaultExportFromCjs$1$1(cjs$1),ok$2$1=function(e){return{ok:!0,result:e}},err$2$1=function(e){return{ok:!1,error:e}},asPromise$2$1=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$2$1=function(e,t){return!0===t.ok?t.result:e},withException$2$1=function(e){if(!0===e.ok)return e.result;throw e.error},map$2$1=function(e,t){return!0===t.ok?ok$2$1(e(t.result)):t},map2$2$1=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$2$1(e(t.result,r.result))},mapError$2$1=function(e,t){return!0===t.ok?t:err$2$1(e(t.error))},andThen$2$1=function(e,t){return!0===t.ok?e(t.result):t},__assign$2$1=function(){return __assign$2$1=Object.assign||function(e){for(var t,r=1,n=arguments.length;r"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),runDecoderWithIOError$1=(e,t)=>{try{return e.runWithException(t)}catch(e){return ioError$1.raiseError(e,!0)}},getSupportedOperationsNames=e=>Object.keys(e).filter(t=>e[t].execute),handleOperationCheck=(e,t)=>({isSupported:e.some(e=>e.toLowerCase()===t.toLowerCase())}),getSafeTimeoutDelay$1=e=>Math.min(e,MAX_SET_TIMEOUT_DELAY$1),wrapPromise=()=>{let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}};let IOError$1=class{raiseError(e,t){const r=extractErrorMsg$2(e);if(errorChannel$1.port1.postMessage(r),t)throw e;throw new Error(r)}};const ioError$1=new IOError$1,connectBrowserAppProps$1=["name","title","version","customProperties","icon","caption","type"],fdc3v2AppProps$1=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var ok$1$1=function(e){return{ok:!0,result:e}},err$1$1=function(e){return{ok:!1,error:e}},asPromise$1$1=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$1$1=function(e,t){return!0===t.ok?t.result:e},withException$1$1=function(e){if(!0===e.ok)return e.result;throw e.error},map$1$1=function(e,t){return!0===t.ok?ok$1$1(e(t.result)):t},map2$1$1=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$1$1(e(t.result,r.result))},mapError$1$1=function(e,t){return!0===t.ok?t:err$1$1(e(t.error))},andThen$1$1=function(e,t){return!0===t.ok?e(t.result):t},__assign$1$1=function(){return __assign$1$1=Object.assign||function(e){for(var t,r=1,n=arguments.length;re.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$3$1=number$1$1().where(e=>e>=0,"Expected a non-negative number"),regexDecoder$2=anyJson$1$1().andThen(e=>e instanceof RegExp?anyJson$1$1():fail("expected a regex, got a "+typeof e)),intentDefinitionDecoder$1$1=object$1$1({name:nonEmptyStringDecoder$3$1,displayName:optional$1$1(string$1$1()),contexts:optional$1$1(array$1$1(string$1$1())),customConfig:optional$1$1(object$1$1())}),v2TypeDecoder$1=oneOf$3(constant$1$1("web"),constant$1$1("native"),constant$1$1("citrix"),constant$1$1("onlineNative"),constant$1$1("other")),v2DetailsDecoder$1=object$1$1({url:nonEmptyStringDecoder$3$1}),v2IconDecoder$1=object$1$1({src:nonEmptyStringDecoder$3$1,size:optional$1$1(nonEmptyStringDecoder$3$1),type:optional$1$1(nonEmptyStringDecoder$3$1)}),v2ScreenshotDecoder$1=object$1$1({src:nonEmptyStringDecoder$3$1,size:optional$1$1(nonEmptyStringDecoder$3$1),type:optional$1$1(nonEmptyStringDecoder$3$1),label:optional$1$1(nonEmptyStringDecoder$3$1)}),v2ListensForIntentDecoder$1=object$1$1({contexts:array$1$1(nonEmptyStringDecoder$3$1),displayName:optional$1$1(nonEmptyStringDecoder$3$1),resultType:optional$1$1(nonEmptyStringDecoder$3$1),customConfig:optional$1$1(anyJson$1$1())}),v2IntentsDecoder$1=object$1$1({listensFor:optional$1$1(dict$1(v2ListensForIntentDecoder$1)),raises:optional$1$1(dict$1(array$1$1(nonEmptyStringDecoder$3$1)))}),v2UserChannelDecoder$1=object$1$1({broadcasts:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1)),listensFor:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1))}),v2AppChannelDecoder$1=object$1$1({name:nonEmptyStringDecoder$3$1,description:optional$1$1(nonEmptyStringDecoder$3$1),broadcasts:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1)),listensFor:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1))}),v2InteropDecoder$1=object$1$1({intents:optional$1$1(v2IntentsDecoder$1),userChannels:optional$1$1(v2UserChannelDecoder$1),appChannels:optional$1$1(array$1$1(v2AppChannelDecoder$1))}),glue42ApplicationDetailsDecoder$1=object$1$1({url:optional$1$1(nonEmptyStringDecoder$3$1),top:optional$1$1(number$1$1()),left:optional$1$1(number$1$1()),width:optional$1$1(nonNegativeNumberDecoder$3$1),height:optional$1$1(nonNegativeNumberDecoder$3$1)}),glue42HostManifestsBrowserDecoder$1=object$1$1({name:optional$1$1(nonEmptyStringDecoder$3$1),type:optional$1$1(nonEmptyStringDecoder$3$1.where(e=>"window"===e,"Expected a value of window")),title:optional$1$1(nonEmptyStringDecoder$3$1),version:optional$1$1(nonEmptyStringDecoder$3$1),customProperties:optional$1$1(anyJson$1$1()),icon:optional$1$1(string$1$1()),caption:optional$1$1(string$1$1()),details:optional$1$1(glue42ApplicationDetailsDecoder$1),intents:optional$1$1(array$1$1(intentDefinitionDecoder$1$1)),hidden:optional$1$1(boolean$1$1())}),v1DefinitionDecoder$1=object$1$1({name:nonEmptyStringDecoder$3$1,appId:nonEmptyStringDecoder$3$1,title:optional$1$1(nonEmptyStringDecoder$3$1),version:optional$1$1(nonEmptyStringDecoder$3$1),manifest:nonEmptyStringDecoder$3$1,manifestType:nonEmptyStringDecoder$3$1,tooltip:optional$1$1(nonEmptyStringDecoder$3$1),description:optional$1$1(nonEmptyStringDecoder$3$1),contactEmail:optional$1$1(nonEmptyStringDecoder$3$1),supportEmail:optional$1$1(nonEmptyStringDecoder$3$1),publisher:optional$1$1(nonEmptyStringDecoder$3$1),images:optional$1$1(array$1$1(object$1$1({url:optional$1$1(nonEmptyStringDecoder$3$1)}))),icons:optional$1$1(array$1$1(object$1$1({icon:optional$1$1(nonEmptyStringDecoder$3$1)}))),customConfig:anyJson$1$1(),intents:optional$1$1(array$1$1(intentDefinitionDecoder$1$1))}),v2LocalizedDefinitionDecoder$1=object$1$1({appId:optional$1$1(nonEmptyStringDecoder$3$1),name:optional$1$1(nonEmptyStringDecoder$3$1),details:optional$1$1(v2DetailsDecoder$1),version:optional$1$1(nonEmptyStringDecoder$3$1),title:optional$1$1(nonEmptyStringDecoder$3$1),tooltip:optional$1$1(nonEmptyStringDecoder$3$1),lang:optional$1$1(nonEmptyStringDecoder$3$1),description:optional$1$1(nonEmptyStringDecoder$3$1),categories:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1)),icons:optional$1$1(array$1$1(v2IconDecoder$1)),screenshots:optional$1$1(array$1$1(v2ScreenshotDecoder$1)),contactEmail:optional$1$1(nonEmptyStringDecoder$3$1),supportEmail:optional$1$1(nonEmptyStringDecoder$3$1),moreInfo:optional$1$1(nonEmptyStringDecoder$3$1),publisher:optional$1$1(nonEmptyStringDecoder$3$1),customConfig:optional$1$1(array$1$1(anyJson$1$1())),hostManifests:optional$1$1(anyJson$1$1()),interop:optional$1$1(v2InteropDecoder$1)}),v2DefinitionDecoder$1=object$1$1({appId:nonEmptyStringDecoder$3$1,name:optional$1$1(nonEmptyStringDecoder$3$1),type:v2TypeDecoder$1,details:v2DetailsDecoder$1,version:optional$1$1(nonEmptyStringDecoder$3$1),title:optional$1$1(nonEmptyStringDecoder$3$1),tooltip:optional$1$1(nonEmptyStringDecoder$3$1),lang:optional$1$1(nonEmptyStringDecoder$3$1),description:optional$1$1(nonEmptyStringDecoder$3$1),categories:optional$1$1(array$1$1(nonEmptyStringDecoder$3$1)),icons:optional$1$1(array$1$1(v2IconDecoder$1)),screenshots:optional$1$1(array$1$1(v2ScreenshotDecoder$1)),contactEmail:optional$1$1(nonEmptyStringDecoder$3$1),supportEmail:optional$1$1(nonEmptyStringDecoder$3$1),moreInfo:optional$1$1(nonEmptyStringDecoder$3$1),publisher:optional$1$1(nonEmptyStringDecoder$3$1),customConfig:optional$1$1(array$1$1(anyJson$1$1())),hostManifests:optional$1$1(anyJson$1$1()),interop:optional$1$1(v2InteropDecoder$1),localizedVersions:optional$1$1(dict$1(v2LocalizedDefinitionDecoder$1))}),allDefinitionsDecoder$1=oneOf$3(v1DefinitionDecoder$1,v2DefinitionDecoder$1),parseDecoderErrorToStringMessage$1=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;let FDC3Service$1=class{fdc3ToDesktopDefinitionType={web:"window",native:"exe",citrix:"citrix",onlineNative:"clickonce",other:"window"};toApi(){return{isFdc3Definition:this.isFdc3Definition.bind(this),parseToBrowserBaseAppData:this.parseToBrowserBaseAppData.bind(this),parseToDesktopAppConfig:this.parseToDesktopAppConfig.bind(this)}}isFdc3Definition(e){const t=allDefinitionsDecoder$1.run(e);return t.ok?e.appId&&e.details?{isFdc3:!0,version:"2.0"}:e.manifest?{isFdc3:!0,version:"1.2"}:{isFdc3:!1,reason:"The passed definition is not FDC3"}:{isFdc3:!1,reason:parseDecoderErrorToStringMessage$1(t.error)}}parseToBrowserBaseAppData(e){const{isFdc3:t,version:r}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const n=allDefinitionsDecoder$1.run(e);if(!n.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage$1(n.error)}`);const i=this.getUserPropertiesFromDefinition(e,r),o={url:this.getUrl(e,r)},s={name:e.appId,type:"window",createOptions:o,userProperties:{...i,intents:"1.2"===r?i.intents:this.getIntentsFromV2AppDefinition(e),details:o},title:e.title,version:e.version,icon:this.getIconFromDefinition(e,r),caption:e.description,fdc3:"2.0"===r?{...e,definitionVersion:"2.0"}:void 0},a=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!a)return s;const c=glue42HostManifestsBrowserDecoder$1.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage$1(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(s,c.result):s}parseToDesktopAppConfig(e){const{isFdc3:t,version:r}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const n=allDefinitionsDecoder$1.run(e);if(!n.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage$1(n.error)}`);if("1.2"===r){const t=e;return{name:t.appId,type:"window",details:{url:this.getUrl(e,r)},version:t.version,title:t.title,tooltip:t.tooltip,caption:t.description,icon:t.icons?.[0].icon,intents:t.intents,customProperties:{manifestType:t.manifestType,images:t.images,contactEmail:t.contactEmail,supportEmail:t.supportEmail,publisher:t.publisher,icons:t.icons,customConfig:t.customConfig}}}const i=e,o={name:i.appId,type:this.fdc3ToDesktopDefinitionType[i.type],details:i.details,version:i.version,title:i.title,tooltip:i.tooltip,caption:i.description,icon:this.getIconFromDefinition(i,"2.0"),intents:this.getIntentsFromV2AppDefinition(i),fdc3:{...i,definitionVersion:"2.0"}},s=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!s)return o;if("object"!=typeof s||Array.isArray(s))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(o,s)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!connectBrowserAppProps$1.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!connectBrowserAppProps$1.includes(e)&&!fdc3v2AppProps$1.includes(e)))}getUrl(e,t){let r;if("1.2"===t){const t=JSON.parse(e.manifest);r=t.details?.url||t.url}else r=e.details?.url;if(!r||"string"!=typeof r)throw new Error(`Invalid FDC3 ${t} definition. Provide valid 'url' under '${"1.2"===t?"manifest":"details"}' key`);return r}getIntentsFromV2AppDefinition(e){const t=e.interop?.intents?.listensFor;if(!t)return;return Object.entries(t).map(e=>{const[t,r]=e;return{name:t,...r}})}getIconFromDefinition(e,t){return"1.2"===t?e.icons?.find(e=>e.icon)?.icon||void 0:e.icons?.find(e=>e.src)?.src||void 0}mergeBaseAppDataWithGlueManifest(e,t){let r=e;if(t.customProperties&&(r.userProperties={...e.userProperties,...t.customProperties}),t.details){const n={...e.createOptions,...t.details};r.createOptions=n,r.userProperties.details=n}return Array.isArray(t.intents)&&(r.userProperties.intents=(r.userProperties.intents||[]).concat(t.intents)),r={...r,...t},delete r.details,delete r.intents,r}mergeDesktopConfigWithGlueManifest(e,t){const r=Object.assign({},e,t,{details:{...e.details,...t.details}});return Array.isArray(t.intents)&&(r.intents=(e.intents||[]).concat(t.intents)),r}};const decoders$1$1={common:{nonEmptyStringDecoder:nonEmptyStringDecoder$3$1,nonNegativeNumberDecoder:nonNegativeNumberDecoder$3$1,regexDecoder:regexDecoder$2},fdc3:{allDefinitionsDecoder:allDefinitionsDecoder$1,v1DefinitionDecoder:v1DefinitionDecoder$1,v2DefinitionDecoder:v2DefinitionDecoder$1}};var INTENTS_ERRORS$1;!function(e){e.USER_CANCELLED="User Closed Intents Resolver UI without choosing a handler",e.CALLER_NOT_DEFINED="Caller Id is not defined",e.TIMEOUT_HIT="Timeout hit",e.INTENT_NOT_FOUND="Cannot find Intent",e.HANDLER_NOT_FOUND="Cannot find Intent Handler",e.TARGET_INSTANCE_UNAVAILABLE="Cannot start Target Instance",e.INTENT_DELIVERY_FAILED="Target Instance did not add a listener",e.RESOLVER_UNAVAILABLE="Intents Resolver UI unavailable",e.RESOLVER_TIMEOUT="User did not choose a handler",e.INVALID_RESOLVER_RESPONSE="Intents Resolver UI returned invalid response",e.INTENT_HANDLER_REJECTION="Intent Handler function processing the raised intent threw an error or rejected the promise it returned"}(INTENTS_ERRORS$1||(INTENTS_ERRORS$1={}));let IoC$1$1=class{_fdc3;_decoders=decoders$1$1;_errors={intents:INTENTS_ERRORS$1};get fdc3(){return this._fdc3||(this._fdc3=(new FDC3Service$1).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};const ioc$1=new IoC$1$1;ioc$1.fdc3;const decoders$2=ioc$1.decoders;ioc$1.errors;const nonEmptyStringDecoder$2$1=string$2$1().where(e=>e.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$2$1=number$2$1().where(e=>e>=0,"Expected a non-negative number"),optionalNonEmptyStringDecoder=optional$2$1(nonEmptyStringDecoder$2$1),libDomainDecoder$1=oneOf$1$1(constant$2$1("system"),constant$2$1("windows"),constant$2$1("appManager"),constant$2$1("layouts"),constant$2$1("intents"),constant$2$1("notifications"),constant$2$1("channels"),constant$2$1("extension"),constant$2$1("themes"),constant$2$1("prefs"),constant$2$1("ui")),windowOperationTypesDecoder=oneOf$1$1(constant$2$1("openWindow"),constant$2$1("windowHello"),constant$2$1("windowAdded"),constant$2$1("windowRemoved"),constant$2$1("getBounds"),constant$2$1("getFrameBounds"),constant$2$1("getUrl"),constant$2$1("moveResize"),constant$2$1("focus"),constant$2$1("close"),constant$2$1("getTitle"),constant$2$1("setTitle"),constant$2$1("focusChange"),constant$2$1("getChannel"),constant$2$1("notifyChannelsChanged"),constant$2$1("setZoomFactor"),constant$2$1("zoomFactorChange"),constant$2$1("refresh"),constant$2$1("operationCheck")),appManagerOperationTypesDecoder$1=oneOf$1$1(constant$2$1("appHello"),constant$2$1("appDirectoryStateChange"),constant$2$1("instanceStarted"),constant$2$1("instanceStopped"),constant$2$1("applicationStart"),constant$2$1("instanceStop"),constant$2$1("clear"),constant$2$1("operationCheck")),layoutsOperationTypesDecoder$1=oneOf$1$1(constant$2$1("layoutAdded"),constant$2$1("layoutChanged"),constant$2$1("layoutRemoved"),constant$2$1("layoutRenamed"),constant$2$1("get"),constant$2$1("getAll"),constant$2$1("export"),constant$2$1("import"),constant$2$1("remove"),constant$2$1("rename"),constant$2$1("clientSaveRequest"),constant$2$1("getGlobalPermissionState"),constant$2$1("checkGlobalActivated"),constant$2$1("requestGlobalPermission"),constant$2$1("getDefaultGlobal"),constant$2$1("setDefaultGlobal"),constant$2$1("clearDefaultGlobal"),constant$2$1("updateMetadata"),constant$2$1("operationCheck"),constant$2$1("getCurrent"),constant$2$1("defaultLayoutChanged"),constant$2$1("layoutRestored")),notificationsOperationTypesDecoder=oneOf$1$1(constant$2$1("raiseNotification"),constant$2$1("requestPermission"),constant$2$1("notificationShow"),constant$2$1("notificationClick"),constant$2$1("getPermission"),constant$2$1("list"),constant$2$1("notificationRaised"),constant$2$1("notificationClosed"),constant$2$1("click"),constant$2$1("clear"),constant$2$1("clearAll"),constant$2$1("configure"),constant$2$1("getConfiguration"),constant$2$1("configurationChanged"),constant$2$1("setState"),constant$2$1("clearOld"),constant$2$1("activeCountChange"),constant$2$1("stateChange"),constant$2$1("operationCheck"),constant$2$1("getActiveCount")),systemOperationTypesDecoder$1=oneOf$1$1(constant$2$1("getEnvironment"),constant$2$1("getBase"),constant$2$1("platformShutdown"),constant$2$1("isFdc3DataWrappingSupported"),constant$2$1("clientError"),constant$2$1("systemHello"),constant$2$1("operationCheck")),windowRelativeDirectionDecoder$1=oneOf$1$1(constant$2$1("top"),constant$2$1("left"),constant$2$1("right"),constant$2$1("bottom")),windowBoundsDecoder$1=object$2$1({top:number$2$1(),left:number$2$1(),width:nonNegativeNumberDecoder$2$1,height:nonNegativeNumberDecoder$2$1}),windowOpenSettingsDecoder$1=optional$2$1(object$2$1({top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),context:optional$2$1(anyJson$2$1()),relativeTo:optional$2$1(nonEmptyStringDecoder$2$1),relativeDirection:optional$2$1(windowRelativeDirectionDecoder$1),windowId:optional$2$1(nonEmptyStringDecoder$2$1),layoutComponentId:optional$2$1(nonEmptyStringDecoder$2$1)})),openWindowConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,url:nonEmptyStringDecoder$2$1,options:windowOpenSettingsDecoder$1}),windowHelloDecoder=object$2$1({windowId:optional$2$1(nonEmptyStringDecoder$2$1)}),coreWindowDataDecoder=object$2$1({windowId:nonEmptyStringDecoder$2$1,name:nonEmptyStringDecoder$2$1}),simpleWindowDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1}),helloSuccessDecoder=object$2$1({windows:array$2$1(coreWindowDataDecoder),isWorkspaceFrame:boolean$2$1()}),windowTitleConfigDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,title:string$2$1()}),focusEventDataDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,hasFocus:boolean$2$1()}),windowMoveResizeConfigDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),relative:optional$2$1(boolean$2$1())}),windowBoundsResultDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,bounds:object$2$1({top:number$2$1(),left:number$2$1(),width:nonNegativeNumberDecoder$2$1,height:nonNegativeNumberDecoder$2$1})}),frameWindowBoundsResultDecoder$1=object$2$1({bounds:object$2$1({top:number$2$1(),left:number$2$1(),width:nonNegativeNumberDecoder$2$1,height:nonNegativeNumberDecoder$2$1})}),windowUrlResultDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,url:nonEmptyStringDecoder$2$1}),windowZoomFactorConfigDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,factorIndex:nonNegativeNumberDecoder$2$1}),anyDecoder$1=anyJson$2$1(),boundsDecoder=object$2$1({top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1)}),instanceDataDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1,applicationName:nonEmptyStringDecoder$2$1}),iframePermissionsPolicyConfigDecoder$1=object$2$1({flags:string$2$1()}),workspacesSandboxDecoder$1=object$2$1({flags:string$2$1()}),requestChannelSelectorConfigDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1,channelsNames:array$2$1(nonEmptyStringDecoder$2$1)}),channelSelectorDecoder$1=object$2$1({enabled:boolean$2$1()}),applicationDetailsDecoder$1=object$2$1({url:nonEmptyStringDecoder$2$1,top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),workspacesSandbox:optional$2$1(workspacesSandboxDecoder$1),channelSelector:optional$2$1(channelSelectorDecoder$1),iframePermissionsPolicy:optional$2$1(iframePermissionsPolicyConfigDecoder$1)}),intentDefinitionDecoder$2=object$2$1({name:nonEmptyStringDecoder$2$1,displayName:optional$2$1(string$2$1()),contexts:optional$2$1(array$2$1(string$2$1())),customConfig:optional$2$1(object$2$1()),resultType:optional$2$1(string$2$1())}),applicationDefinitionDecoder=object$2$1({name:nonEmptyStringDecoder$2$1,type:nonEmptyStringDecoder$2$1.where(e=>"window"===e,"Expected a value of window"),title:optional$2$1(nonEmptyStringDecoder$2$1),version:optional$2$1(nonEmptyStringDecoder$2$1),customProperties:optional$2$1(anyJson$2$1()),icon:optional$2$1(string$2$1()),caption:optional$2$1(string$2$1()),details:applicationDetailsDecoder$1,intents:optional$2$1(array$2$1(intentDefinitionDecoder$2)),hidden:optional$2$1(boolean$2$1()),fdc3:optional$2$1(decoders$2.fdc3.v2DefinitionDecoder)}),appRemoveConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1}),appsExportOperationDecoder$1=object$2$1({definitions:array$2$1(applicationDefinitionDecoder)}),applicationDataDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,type:nonEmptyStringDecoder$2$1.where(e=>"window"===e,"Expected a value of window"),instances:array$2$1(instanceDataDecoder$1),userProperties:optional$2$1(anyJson$2$1()),title:optional$2$1(nonEmptyStringDecoder$2$1),version:optional$2$1(nonEmptyStringDecoder$2$1),icon:optional$2$1(string$2$1()),caption:optional$2$1(nonEmptyStringDecoder$2$1)}),baseApplicationDataDecoder=object$2$1({name:nonEmptyStringDecoder$2$1,type:nonEmptyStringDecoder$2$1.where(e=>"window"===e,"Expected a value of window"),userProperties:anyJson$2$1(),title:optional$2$1(nonEmptyStringDecoder$2$1),version:optional$2$1(nonEmptyStringDecoder$2$1),icon:optional$2$1(string$2$1()),caption:optional$2$1(nonEmptyStringDecoder$2$1)}),appDirectoryStateChangeDecoder=object$2$1({appsAdded:array$2$1(baseApplicationDataDecoder),appsChanged:array$2$1(baseApplicationDataDecoder),appsRemoved:array$2$1(baseApplicationDataDecoder)}),appHelloSuccessDecoder$2=object$2$1({apps:array$2$1(applicationDataDecoder$1),initialChannelId:optional$2$1(nonEmptyStringDecoder$2$1)}),basicInstanceDataDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1}),layoutTypeDecoder$1=oneOf$1$1(constant$2$1("Global"),constant$2$1("Activity"),constant$2$1("ApplicationDefault"),constant$2$1("Swimlane"),constant$2$1("Workspace")),componentTypeDecoder$1=oneOf$1$1(constant$2$1("application"),constant$2$1("activity")),windowComponentStateDecoder$1=object$2$1({context:optional$2$1(anyJson$2$1()),bounds:windowBoundsDecoder$1,createArgs:object$2$1({name:optional$2$1(nonEmptyStringDecoder$2$1),url:optional$2$1(nonEmptyStringDecoder$2$1),context:optional$2$1(anyJson$2$1())}),windowState:optional$2$1(nonEmptyStringDecoder$2$1),restoreState:optional$2$1(nonEmptyStringDecoder$2$1),instanceId:nonEmptyStringDecoder$2$1,isCollapsed:optional$2$1(boolean$2$1()),isSticky:optional$2$1(boolean$2$1()),restoreSettings:object$2$1({groupId:optional$2$1(nonEmptyStringDecoder$2$1),groupZOrder:optional$2$1(number$2$1())}),channelId:optional$2$1(nonEmptyStringDecoder$2$1)}),windowLayoutComponentDecoder$1=object$2$1({type:constant$2$1("window"),componentType:optional$2$1(componentTypeDecoder$1),application:nonEmptyStringDecoder$2$1,state:windowComponentStateDecoder$1}),windowLayoutItemDecoder$1=object$2$1({type:constant$2$1("window"),config:object$2$1({appName:nonEmptyStringDecoder$2$1,url:optional$2$1(nonEmptyStringDecoder$2$1),title:optional$2$1(string$2$1()),allowExtract:optional$2$1(boolean$2$1()),allowReorder:optional$2$1(boolean$2$1()),showCloseButton:optional$2$1(boolean$2$1()),isMaximized:optional$2$1(boolean$2$1())})}),groupLayoutItemDecoder$2=object$2$1({type:constant$2$1("group"),config:anyJson$2$1(),children:array$2$1(oneOf$1$1(windowLayoutItemDecoder$1))}),columnLayoutItemDecoder$2=object$2$1({type:constant$2$1("column"),config:anyJson$2$1(),children:array$2$1(oneOf$1$1(groupLayoutItemDecoder$2,windowLayoutItemDecoder$1,lazy$2(()=>columnLayoutItemDecoder$2),lazy$2(()=>rowLayoutItemDecoder$2)))}),rowLayoutItemDecoder$2=object$2$1({type:constant$2$1("row"),config:anyJson$2$1(),children:array$2$1(oneOf$1$1(columnLayoutItemDecoder$2,groupLayoutItemDecoder$2,windowLayoutItemDecoder$1,lazy$2(()=>rowLayoutItemDecoder$2)))}),workspaceLayoutComponentStateDecoder$1=object$2$1({config:anyJson$2$1(),context:anyJson$2$1(),children:array$2$1(oneOf$1$1(rowLayoutItemDecoder$2,columnLayoutItemDecoder$2,groupLayoutItemDecoder$2,windowLayoutItemDecoder$1))}),workspaceLayoutComponentDecoder$1=object$2$1({type:constant$2$1("Workspace"),application:optional$2$1(nonEmptyStringDecoder$2$1),state:workspaceLayoutComponentStateDecoder$1}),workspaceFrameComponentStateDecoder$1=object$2$1({bounds:windowBoundsDecoder$1,instanceId:nonEmptyStringDecoder$2$1,selectedWorkspace:nonNegativeNumberDecoder$2$1,workspaces:array$2$1(workspaceLayoutComponentStateDecoder$1),windowState:optional$2$1(nonEmptyStringDecoder$2$1),restoreState:optional$2$1(nonEmptyStringDecoder$2$1),context:optional$2$1(anyJson$2$1())}),workspaceFrameComponentDecoder$1=object$2$1({type:constant$2$1("workspaceFrame"),application:nonEmptyStringDecoder$2$1,componentType:optional$2$1(componentTypeDecoder$1),state:workspaceFrameComponentStateDecoder$1}),glueLayoutDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,type:layoutTypeDecoder$1,token:optional$2$1(nonEmptyStringDecoder$2$1),components:array$2$1(oneOf$1$1(windowLayoutComponentDecoder$1,workspaceLayoutComponentDecoder$1,workspaceFrameComponentDecoder$1)),context:optional$2$1(anyJson$2$1()),metadata:optional$2$1(anyJson$2$1()),version:optional$2$1(number$2$1())}),renamedLayoutNotificationDecoder=object$2$1({name:nonEmptyStringDecoder$2$1,type:layoutTypeDecoder$1,token:optional$2$1(nonEmptyStringDecoder$2$1),components:array$2$1(oneOf$1$1(windowLayoutComponentDecoder$1,workspaceLayoutComponentDecoder$1,workspaceFrameComponentDecoder$1)),context:optional$2$1(anyJson$2$1()),metadata:optional$2$1(anyJson$2$1()),version:optional$2$1(number$2$1()),prevName:nonEmptyStringDecoder$2$1}),newLayoutOptionsDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,context:optional$2$1(anyJson$2$1()),metadata:optional$2$1(anyJson$2$1()),instances:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),ignoreInstances:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),setAsCurrent:optional$2$1(boolean$2$1()),ignoreContexts:optional$2$1(boolean$2$1())}),restoreOptionsDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,context:optional$2$1(anyJson$2$1()),closeRunningInstance:optional$2$1(boolean$2$1()),closeMe:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$2$1)}),layoutSummaryDecoder$2=object$2$1({name:nonEmptyStringDecoder$2$1,type:layoutTypeDecoder$1,context:optional$2$1(anyJson$2$1()),metadata:optional$2$1(anyJson$2$1())}),simpleLayoutConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,type:layoutTypeDecoder$1}),saveLayoutConfigDecoder$1=object$2$1({layout:newLayoutOptionsDecoder$1}),renameLayoutConfigDecoder$1=object$2$1({layout:glueLayoutDecoder$1,newName:nonEmptyStringDecoder$2$1}),layoutResultDecoder$1=object$2$1({status:nonEmptyStringDecoder$2$1}),updateLayoutMetadataConfigDecoder$1=object$2$1({layout:glueLayoutDecoder$1}),restoreLayoutConfigDecoder$1=object$2$1({layout:restoreOptionsDecoder$1}),getAllLayoutsConfigDecoder$1=object$2$1({type:layoutTypeDecoder$1}),allLayoutsFullConfigDecoder$1=object$2$1({layouts:array$2$1(glueLayoutDecoder$1)}),defaultGlobalChangedDecoder=optional$2$1(object$2$1({name:nonEmptyStringDecoder$2$1})),importModeDecoder$1=oneOf$1$1(constant$2$1("replace"),constant$2$1("merge")),layoutsImportConfigDecoder$1=object$2$1({layouts:array$2$1(glueLayoutDecoder$1),mode:importModeDecoder$1,skipManagerRequest:optional$2$1(boolean$2$1())}),allLayoutsSummariesResultDecoder$1=object$2$1({summaries:array$2$1(layoutSummaryDecoder$2)}),simpleLayoutResultDecoder=object$2$1({layout:glueLayoutDecoder$1}),optionalSimpleLayoutResult$1=object$2$1({layout:optional$2$1(glueLayoutDecoder$1)}),setDefaultGlobalConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1}),intentsOperationTypesDecoder$1=oneOf$1$1(constant$2$1("findIntent"),constant$2$1("getIntents"),constant$2$1("getIntentsByHandler"),constant$2$1("raise"),constant$2$1("filterHandlers")),intentHandlerDecoder$1=object$2$1({applicationName:nonEmptyStringDecoder$2$1,applicationTitle:optional$2$1(string$2$1()),applicationDescription:optional$2$1(string$2$1()),applicationIcon:optional$2$1(string$2$1()),type:oneOf$1$1(constant$2$1("app"),constant$2$1("instance")),displayName:optional$2$1(string$2$1()),contextTypes:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),instanceId:optional$2$1(string$2$1()),instanceTitle:optional$2$1(string$2$1()),resultType:optional$2$1(string$2$1()),customConfig:optional$2$1(object$2$1())});object$2$1({applicationName:string$2$1(),applicationIcon:optional$2$1(string$2$1()),instanceId:optional$2$1(string$2$1())}),object$2$1({intent:nonEmptyStringDecoder$2$1,handler:intentHandlerDecoder$1});const intentDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,handlers:array$2$1(intentHandlerDecoder$1)}),intentTargetDecoder$1=oneOf$1$1(constant$2$1("startNew"),constant$2$1("reuse"),object$2$1({app:optional$2$1(nonEmptyStringDecoder$2$1),instance:optional$2$1(nonEmptyStringDecoder$2$1)})),intentContextDecoder$1=object$2$1({type:optional$2$1(nonEmptyStringDecoder$2$1),data:optional$2$1(anyJson$2$1())}),intentsDecoder$1=array$2$1(intentDecoder$1),wrappedIntentsDecoder$1=object$2$1({intents:intentsDecoder$1}),intentFilterDecoder=object$2$1({name:optional$2$1(nonEmptyStringDecoder$2$1),contextType:optional$2$1(nonEmptyStringDecoder$2$1),resultType:optional$2$1(nonEmptyStringDecoder$2$1)}),findFilterDecoder=oneOf$1$1(nonEmptyStringDecoder$2$1,intentFilterDecoder),wrappedIntentFilterDecoder$1=object$2$1({filter:optional$2$1(intentFilterDecoder)}),applicationStartOptionsDecoder$1=object$2$1({top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),relativeTo:optional$2$1(nonEmptyStringDecoder$2$1),relativeDirection:optional$2$1(windowRelativeDirectionDecoder$1),waitForAGMReady:optional$2$1(boolean$2$1()),channelId:optional$2$1(nonEmptyStringDecoder$2$1)}),intentRequestDecoder$1=object$2$1({intent:nonEmptyStringDecoder$2$1,target:optional$2$1(intentTargetDecoder$1),context:optional$2$1(intentContextDecoder$1),options:optional$2$1(applicationStartOptionsDecoder$1),handlers:optional$2$1(array$2$1(intentHandlerDecoder$1)),timeout:optional$2$1(nonNegativeNumberDecoder$2$1),waitUserResponseIndefinitely:optional$2$1(boolean$2$1()),clearSavedHandler:optional$2$1(boolean$2$1())}),originAppDecoder$1=object$2$1({interopInstance:nonEmptyStringDecoder$2$1,name:optional$2$1(nonEmptyStringDecoder$2$1)}),startReasonDecoder$1=object$2$1({originApp:originAppDecoder$1,intentRequest:optional$2$1(intentRequestDecoder$1)}),applicationStartConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,waitForAGMReady:boolean$2$1(),id:optional$2$1(nonEmptyStringDecoder$2$1),context:optional$2$1(anyJson$2$1()),top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),relativeTo:optional$2$1(nonEmptyStringDecoder$2$1),relativeDirection:optional$2$1(windowRelativeDirectionDecoder$1),forceChromeTab:optional$2$1(boolean$2$1()),layoutComponentId:optional$2$1(nonEmptyStringDecoder$2$1),channelId:optional$2$1(nonEmptyStringDecoder$2$1),startReason:startReasonDecoder$1}),raiseRequestDecoder=oneOf$1$1(nonEmptyStringDecoder$2$1,intentRequestDecoder$1),resolverConfigDecoder$1=object$2$1({enabled:boolean$2$1(),appName:nonEmptyStringDecoder$2$1,waitResponseTimeout:number$2$1()}),handlerExclusionCriteriaApplicationNameDecoder$1=object$2$1({applicationName:nonEmptyStringDecoder$2$1}),handlerExclusionCriteriaInstanceIdDecoder$1=object$2$1({instanceId:nonEmptyStringDecoder$2$1}),handlerExclusionCriteriaDecoder$1=oneOf$1$1(handlerExclusionCriteriaApplicationNameDecoder$1,handlerExclusionCriteriaInstanceIdDecoder$1),handlerFilterDecoder$1=object$2$1({title:optional$2$1(nonEmptyStringDecoder$2$1),openResolver:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$2$1),intent:optional$2$1(nonEmptyStringDecoder$2$1),contextTypes:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),resultType:optional$2$1(nonEmptyStringDecoder$2$1),applicationNames:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),excludeList:optional$2$1(array$2$1(handlerExclusionCriteriaDecoder$1))}),embeddedResolverConfigDecoder$1=object$2$1({enabled:boolean$2$1(),initialCaller:object$2$1({instanceId:nonEmptyStringDecoder$2$1})}),raiseIntentRequestDecoder$1=object$2$1({intentRequest:intentRequestDecoder$1,resolverConfig:resolverConfigDecoder$1,embeddedResolverConfig:optional$2$1(embeddedResolverConfigDecoder$1)}),intentResultDecoder$1=object$2$1({request:intentRequestDecoder$1,handler:intentHandlerDecoder$1,result:anyJson$2$1()}),filterHandlersResultDecoder$1=object$2$1({handlers:array$2$1(intentHandlerDecoder$1)}),filterHandlersWithResolverConfigDecoder$1=object$2$1({filterHandlersRequest:handlerFilterDecoder$1,resolverConfig:resolverConfigDecoder$1,embeddedResolverConfig:optional$2$1(embeddedResolverConfigDecoder$1)}),AddIntentListenerRequestDecoder=object$2$1({intent:nonEmptyStringDecoder$2$1,contextTypes:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),displayName:optional$2$1(string$2$1()),icon:optional$2$1(string$2$1()),description:optional$2$1(string$2$1()),resultType:optional$2$1(string$2$1()),customConfig:optional$2$1(object$2$1())}),AddIntentListenerDecoder=oneOf$1$1(nonEmptyStringDecoder$2$1,AddIntentListenerRequestDecoder),intentInfoDecoder$1=object$2$1({intent:nonEmptyStringDecoder$2$1,contextTypes:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),description:optional$2$1(nonEmptyStringDecoder$2$1),displayName:optional$2$1(nonEmptyStringDecoder$2$1),icon:optional$2$1(nonEmptyStringDecoder$2$1),resultType:optional$2$1(nonEmptyStringDecoder$2$1)}),getIntentsResultDecoder$1=object$2$1({intents:array$2$1(intentInfoDecoder$1)}),channelNameDecoder=e=>nonEmptyStringDecoder$2$1.where(t=>e.includes(t),"Expected a valid channel name"),fdc3OptionsDecoder=object$2$1({contextType:optional$2$1(nonEmptyStringDecoder$2$1)}),publishOptionsDecoder=optional$2$1(oneOf$1$1(nonEmptyStringDecoder$2$1,object$2$1({name:optional$2$1(nonEmptyStringDecoder$2$1),fdc3:optional$2$1(boolean$2$1())}))),leaveChannelsConfig=object$2$1({windowId:optionalNonEmptyStringDecoder,channel:optionalNonEmptyStringDecoder}),fdc3ContextDecoder=anyJson$2$1().where(e=>"string"==typeof e.type,"Expected a valid FDC3 Context with compulsory 'type' field"),interopActionSettingsDecoder$1=object$2$1({method:nonEmptyStringDecoder$2$1,arguments:optional$2$1(anyJson$2$1()),target:optional$2$1(oneOf$1$1(constant$2$1("all"),constant$2$1("best")))}),glue42NotificationActionDecoder$1=object$2$1({action:string$2$1(),title:nonEmptyStringDecoder$2$1,icon:optional$2$1(string$2$1()),interop:optional$2$1(interopActionSettingsDecoder$1)}),notificationStateDecoder$1=oneOf$1$1(constant$2$1("Active"),constant$2$1("Acknowledged"),constant$2$1("Seen"),constant$2$1("Closed"),constant$2$1("Stale"),constant$2$1("Snoozed"),constant$2$1("Processing")),activeNotificationsCountChangeDecoder=object$2$1({count:number$2$1()}),notificationDefinitionDecoder=object$2$1({badge:optional$2$1(string$2$1()),body:optional$2$1(string$2$1()),data:optional$2$1(anyJson$2$1()),dir:optional$2$1(oneOf$1$1(constant$2$1("auto"),constant$2$1("ltr"),constant$2$1("rtl"))),icon:optional$2$1(string$2$1()),image:optional$2$1(string$2$1()),lang:optional$2$1(string$2$1()),renotify:optional$2$1(boolean$2$1()),requireInteraction:optional$2$1(boolean$2$1()),silent:optional$2$1(boolean$2$1()),tag:optional$2$1(string$2$1()),timestamp:optional$2$1(nonNegativeNumberDecoder$2$1),vibrate:optional$2$1(array$2$1(number$2$1()))}),glue42NotificationOptionsDecoder$1=object$2$1({title:nonEmptyStringDecoder$2$1,clickInterop:optional$2$1(interopActionSettingsDecoder$1),actions:optional$2$1(array$2$1(glue42NotificationActionDecoder$1)),focusPlatformOnDefaultClick:optional$2$1(boolean$2$1()),badge:optional$2$1(string$2$1()),body:optional$2$1(string$2$1()),data:optional$2$1(anyJson$2$1()),dir:optional$2$1(oneOf$1$1(constant$2$1("auto"),constant$2$1("ltr"),constant$2$1("rtl"))),icon:optional$2$1(string$2$1()),image:optional$2$1(string$2$1()),lang:optional$2$1(string$2$1()),renotify:optional$2$1(boolean$2$1()),requireInteraction:optional$2$1(boolean$2$1()),silent:optional$2$1(boolean$2$1()),tag:optional$2$1(string$2$1()),timestamp:optional$2$1(nonNegativeNumberDecoder$2$1),vibrate:optional$2$1(array$2$1(number$2$1())),severity:optional$2$1(oneOf$1$1(constant$2$1("Low"),constant$2$1("None"),constant$2$1("Medium"),constant$2$1("High"),constant$2$1("Critical"))),showToast:optional$2$1(boolean$2$1()),showInPanel:optional$2$1(boolean$2$1()),state:optional$2$1(notificationStateDecoder$1)}),notificationSetStateRequestDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1,state:notificationStateDecoder$1});object$2$1().where(e=>!e.fdc3||"string"==typeof e.fdc3.type,"Expected a valid FDC3 Context with compulsory 'type' field");const channelFDC3DisplayMetadataDecoder$1=object$2$1({color:optional$2$1(nonEmptyStringDecoder$2$1),icon:optional$2$1(nonEmptyStringDecoder$2$1),name:optional$2$1(nonEmptyStringDecoder$2$1),glyph:optional$2$1(nonEmptyStringDecoder$2$1)}),channelFdc3MetaDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1,displayMetadata:optional$2$1(channelFDC3DisplayMetadataDecoder$1)}),channelMetaDecoder$2=object$2$1({color:nonEmptyStringDecoder$2$1,fdc3:optional$2$1(channelFdc3MetaDecoder$1)}),channelDefinitionDecoder$2=object$2$1({name:nonEmptyStringDecoder$2$1,meta:channelMetaDecoder$2,data:optional$2$1(object$2$1())}),pathValueDecoder=object$2$1({path:nonEmptyStringDecoder$2$1,value:anyJson$2$1()}),pathsValueDecoder=array$2$1(pathValueDecoder),removeChannelDataDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1}),channelRestrictionsDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,read:boolean$2$1(),write:boolean$2$1(),windowId:optional$2$1(nonEmptyStringDecoder$2$1)}),channelRestrictionConfigWithWindowIdDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1,read:boolean$2$1(),write:boolean$2$1(),windowId:nonEmptyStringDecoder$2$1}),restrictionConfigDataDecoder$1=object$2$1({config:channelRestrictionConfigWithWindowIdDecoder$1}),restrictionsDecoder$1=object$2$1({channels:array$2$1(channelRestrictionsDecoder$1)}),getRestrictionsDataDecoder$1=object$2$1({windowId:nonEmptyStringDecoder$2$1}),restrictionsConfigDecoder$1=object$2$1({read:boolean$2$1(),write:boolean$2$1(),windowId:optional$2$1(nonEmptyStringDecoder$2$1)}),restrictAllDataDecoder$1=object$2$1({restrictions:restrictionsConfigDecoder$1}),raiseNotificationDecoder$1=object$2$1({settings:glue42NotificationOptionsDecoder$1,id:nonEmptyStringDecoder$2$1}),raiseNotificationResultDecoder$1=object$2$1({settings:glue42NotificationOptionsDecoder$1}),permissionRequestResultDecoder$1=object$2$1({permissionGranted:boolean$2$1()}),permissionQueryResultDecoder$1=object$2$1({permission:oneOf$1$1(constant$2$1("default"),constant$2$1("granted"),constant$2$1("denied"))}),notificationEventPayloadDecoder=object$2$1({definition:notificationDefinitionDecoder,action:optional$2$1(string$2$1()),id:optional$2$1(nonEmptyStringDecoder$2$1)}),notificationFilterDecoder$1=object$2$1({allowed:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),blocked:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1))}),notificationsConfigurationDecoder$1=object$2$1({enable:optional$2$1(boolean$2$1()),enableToasts:optional$2$1(boolean$2$1()),sourceFilter:optional$2$1(notificationFilterDecoder$1),showNotificationBadge:optional$2$1(boolean$2$1())}),notificationsConfigurationProtocolDecoder$1=object$2$1({configuration:notificationsConfigurationDecoder$1}),strictNotificationsConfigurationProtocolDecoder=object$2$1({configuration:object$2$1({enable:boolean$2$1(),enableToasts:boolean$2$1(),sourceFilter:object$2$1({allowed:array$2$1(nonEmptyStringDecoder$2$1),blocked:array$2$1(nonEmptyStringDecoder$2$1)})})}),platformSaveRequestConfigDecoder=object$2$1({layoutType:oneOf$1$1(constant$2$1("Global"),constant$2$1("Workspace")),layoutName:nonEmptyStringDecoder$2$1,context:optional$2$1(anyJson$2$1())}),saveRequestClientResponseDecoder=object$2$1({windowContext:optional$2$1(anyJson$2$1())}),permissionStateResultDecoder$1=object$2$1({state:oneOf$1$1(constant$2$1("prompt"),constant$2$1("denied"),constant$2$1("granted"))}),simpleAvailabilityResultDecoder$1=object$2$1({isAvailable:boolean$2$1()}),simpleItemIdDecoder=object$2$1({itemId:nonEmptyStringDecoder$2$1}),operationCheckResultDecoder$1=object$2$1({isSupported:boolean$2$1()}),operationCheckConfigDecoder$1=object$2$1({operation:nonEmptyStringDecoder$2$1}),workspaceFrameBoundsResultDecoder=object$2$1({bounds:windowBoundsDecoder$1}),themeDecoder$1=object$2$1({displayName:nonEmptyStringDecoder$2$1,name:nonEmptyStringDecoder$2$1}),simpleThemeResponseDecoder$1=object$2$1({theme:themeDecoder$1}),allThemesResponseDecoder$1=object$2$1({themes:array$2$1(themeDecoder$1)}),selectThemeConfigDecoder$1=object$2$1({name:nonEmptyStringDecoder$2$1}),notificationsDataDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1,title:nonEmptyStringDecoder$2$1,clickInterop:optional$2$1(interopActionSettingsDecoder$1),actions:optional$2$1(array$2$1(glue42NotificationActionDecoder$1)),focusPlatformOnDefaultClick:optional$2$1(boolean$2$1()),badge:optional$2$1(string$2$1()),body:optional$2$1(string$2$1()),data:optional$2$1(anyJson$2$1()),dir:optional$2$1(oneOf$1$1(constant$2$1("auto"),constant$2$1("ltr"),constant$2$1("rtl"))),icon:optional$2$1(string$2$1()),image:optional$2$1(string$2$1()),lang:optional$2$1(string$2$1()),renotify:optional$2$1(boolean$2$1()),requireInteraction:optional$2$1(boolean$2$1()),silent:optional$2$1(boolean$2$1()),tag:optional$2$1(string$2$1()),timestamp:optional$2$1(nonNegativeNumberDecoder$2$1),vibrate:optional$2$1(array$2$1(number$2$1())),severity:optional$2$1(oneOf$1$1(constant$2$1("Low"),constant$2$1("None"),constant$2$1("Medium"),constant$2$1("High"),constant$2$1("Critical"))),showToast:optional$2$1(boolean$2$1()),showInPanel:optional$2$1(boolean$2$1()),state:optional$2$1(notificationStateDecoder$1)}),simpleNotificationDataDecoder=object$2$1({notification:notificationsDataDecoder$1}),allNotificationsDataDecoder$1=object$2$1({notifications:array$2$1(notificationsDataDecoder$1)}),simpleNotificationSelectDecoder$1=object$2$1({id:nonEmptyStringDecoder$2$1}),getWindowIdsOnChannelDataDecoder$1=object$2$1({channel:nonEmptyStringDecoder$2$1}),getWindowIdsOnChannelResultDecoder$1=object$2$1({windowIds:array$2$1(nonEmptyStringDecoder$2$1)}),channelsOperationTypesDecoder=oneOf$1$1(constant$2$1("appHello"),constant$2$1("addChannel"),constant$2$1("getMyChannel"),constant$2$1("getWindowIdsOnChannel"),constant$2$1("getWindowIdsWithChannels"),constant$2$1("joinChannel"),constant$2$1("restrict"),constant$2$1("getRestrictions"),constant$2$1("restrictAll"),constant$2$1("notifyChannelsChanged"),constant$2$1("leaveChannel"),constant$2$1("getMode"),constant$2$1("operationCheck")),modeDecoder$1=oneOf$1$1(constant$2$1("single"),constant$2$1("multi")),getChannelsModeDecoder$1=object$2$1({mode:modeDecoder$1}),channelsAppHelloDataDecoder=object$2$1({windowId:nonEmptyStringDecoder$2$1}),channelsAppHelloSuccessDecoder=object$2$1({mode:modeDecoder$1,channels:array$2$1(nonEmptyStringDecoder$2$1),restrictions:array$2$1(channelRestrictionsDecoder$1)}),getMyChanelResultDecoder$1=object$2$1({channel:optional$2$1(nonEmptyStringDecoder$2$1)}),windowWithChannelFilterDecoder$1=object$2$1({application:optional$2$1(nonEmptyStringDecoder$2$1),channels:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1)),windowIds:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1))}),wrappedWindowWithChannelFilterDecoder$1=object$2$1({filter:optional$2$1(windowWithChannelFilterDecoder$1)}),getWindowIdsWithChannelsResultDecoder$1=object$2$1({windowIdsWithChannels:array$2$1(object$2$1({application:nonEmptyStringDecoder$2$1,channel:optional$2$1(nonEmptyStringDecoder$2$1),windowId:nonEmptyStringDecoder$2$1}))}),startApplicationContextDecoder=optional$2$1(anyJson$2$1()),startApplicationOptionsDecoder=optional$2$1(object$2$1({top:optional$2$1(number$2$1()),left:optional$2$1(number$2$1()),width:optional$2$1(nonNegativeNumberDecoder$2$1),height:optional$2$1(nonNegativeNumberDecoder$2$1),relativeTo:optional$2$1(nonEmptyStringDecoder$2$1),relativeDirection:optional$2$1(windowRelativeDirectionDecoder$1),waitForAGMReady:optional$2$1(boolean$2$1()),channelId:optional$2$1(nonEmptyStringDecoder$2$1),reuseId:optional$2$1(nonEmptyStringDecoder$2$1),originIntentRequest:optional$2$1(intentRequestDecoder$1)})),joinChannelDataDecoder$1=object$2$1({channel:nonEmptyStringDecoder$2$1,windowId:nonEmptyStringDecoder$2$1}),leaveChannelDataDecoder=object$2$1({windowId:nonEmptyStringDecoder$2$1,channelName:optional$2$1(nonEmptyStringDecoder$2$1)}),channelsChangedDataDecoder=object$2$1({windowId:nonEmptyStringDecoder$2$1,channelNames:array$2$1(nonEmptyStringDecoder$2$1)}),windowChannelResultDecoder$1=object$2$1({channel:optional$2$1(nonEmptyStringDecoder$2$1)}),prefsOperationTypesDecoder$1=oneOf$1$1(constant$2$1("clear"),constant$2$1("clearAll"),constant$2$1("get"),constant$2$1("getAll"),constant$2$1("set"),constant$2$1("update"),constant$2$1("prefsChanged"),constant$2$1("prefsHello"),constant$2$1("operationCheck"),constant$2$1("registerSubscriber")),appPreferencesDecoder$1=object$2$1({app:nonEmptyStringDecoder$2$1,data:object$2$1(),lastUpdate:optional$2$1(nonEmptyStringDecoder$2$1)}),basePrefsConfigDecoder$1=object$2$1({app:nonEmptyStringDecoder$2$1}),getPrefsResultDecoder$1=object$2$1({prefs:appPreferencesDecoder$1}),getAllPrefsResultDecoder$1=object$2$1({all:array$2$1(appPreferencesDecoder$1)}),subscriberRegisterConfigDecoder$1=object$2$1({interopId:nonEmptyStringDecoder$2$1,appName:optional$2$1(nonEmptyStringDecoder$2$1)}),changePrefsDataDecoder$1=object$2$1({app:nonEmptyStringDecoder$2$1,data:object$2$1()}),prefsHelloSuccessDecoder$1=object$2$1({platform:object$2$1({app:nonEmptyStringDecoder$2$1}),validNonExistentApps:optional$2$1(array$2$1(nonEmptyStringDecoder$2$1))}),clientErrorDataDecoder$1=object$2$1({message:nonEmptyStringDecoder$2$1}),systemHelloSuccessDecoder$1=object$2$1({isClientErrorOperationSupported:boolean$2$1()}),nonEmptyStringDecoder$1$1=decoders$2.common.nonEmptyStringDecoder,nonNegativeNumberDecoder$1$1=decoders$2.common.nonNegativeNumberDecoder,widgetSourcesDecoder=object$2$1({bundle:nonEmptyStringDecoder$1$1,styles:array$2$1(nonEmptyStringDecoder$1$1),fonts:optional$2$1(array$2$1(nonEmptyStringDecoder$1$1))}),modalsSourcesDecoder=object$2$1({bundle:nonEmptyStringDecoder$1$1,styles:array$2$1(nonEmptyStringDecoder$1$1),fonts:optional$2$1(array$2$1(nonEmptyStringDecoder$1$1))}),intentResolverSourcesDecoder=object$2$1({bundle:nonEmptyStringDecoder$1$1,styles:array$2$1(nonEmptyStringDecoder$1$1),fonts:optional$2$1(array$2$1(nonEmptyStringDecoder$1$1))}),channelSelectorTypeDecoder$1=oneOf$1$1(constant$2$1("directional"),constant$2$1("default")),channelSelectorDecoder$2=object$2$1({type:optional$2$1(channelSelectorTypeDecoder$1),enable:optional$2$1(boolean$2$1())}),positionDecoder$1=oneOf$1$1(constant$2$1("top-left"),constant$2$1("top-center"),constant$2$1("top-right"),constant$2$1("center-left"),constant$2$1("center-right"),constant$2$1("bottom-left"),constant$2$1("bottom-center"),constant$2$1("bottom-right")),displayModeDecoder$1=oneOf$1$1(constant$2$1("all"),constant$2$1("fdc3")),widgetChannelsDecoder$1=object$2$1({selector:optional$2$1(channelSelectorDecoder$2),displayMode:optional$2$1(displayModeDecoder$1)}),platformWidgetDefaultConfigDecoder=object$2$1({channels:optional$2$1(widgetChannelsDecoder$1),position:optional$2$1(positionDecoder$1),displayInWorkspace:optional$2$1(boolean$2$1()),restoreLastKnownPosition:optional$2$1(boolean$2$1())}),widgetConfigDecoder$1=object$2$1({enable:boolean$2$1(),awaitFactory:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$1$1),channels:optional$2$1(widgetChannelsDecoder$1),position:optional$2$1(positionDecoder$1),displayInWorkspace:optional$2$1(boolean$2$1()),restoreLastKnownPosition:optional$2$1(boolean$2$1())}),modalsConfigDecoder$1=object$2$1({alerts:optional$2$1(object$2$1({enabled:boolean$2$1()})),dialogs:optional$2$1(object$2$1({enabled:boolean$2$1()})),awaitFactory:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$1$1)}),uiOperationTypesDecoder$1=oneOf$1$1(constant$2$1("getResources"),constant$2$1("operationCheck"),constant$2$1("showAlert"),constant$2$1("showDialog"),constant$2$1("alertInteropAction"),constant$2$1("showResolver")),getResourcesDataDecoder$1=object$2$1({origin:nonEmptyStringDecoder$1$1}),blockedResourcesDecoder$1=object$2$1({blockedOrigin:constant$2$1(!0)}),availableWidgetResourcesDecoder$1=object$2$1({blockedOrigin:constant$2$1(!1),config:platformWidgetDefaultConfigDecoder,sources:widgetSourcesDecoder}),widgetResourcesDecoder$1=union$1$1(blockedResourcesDecoder$1,availableWidgetResourcesDecoder$1),availableModalsResourcesDecoder$1=object$2$1({blockedOrigin:constant$2$1(!1),sources:modalsSourcesDecoder}),modalsResourcesDecoder$1=union$1$1(blockedResourcesDecoder$1,availableModalsResourcesDecoder$1),availableIntentResolverResourcesDecoder=object$2$1({blockedOrigin:constant$2$1(!1),sources:intentResolverSourcesDecoder}),intentResolverResourcesDecoder=union$1$1(blockedResourcesDecoder$1,availableIntentResolverResourcesDecoder),resourcesDecoder$1=object$2$1({widget:optional$2$1(widgetResourcesDecoder$1),modals:optional$2$1(modalsResourcesDecoder$1),intentResolver:optional$2$1(intentResolverResourcesDecoder)}),getResourcesResultDecoder$1=object$2$1({resources:resourcesDecoder$1}),alertsInteropSettingsDecoder$1=object$2$1({method:nonEmptyStringDecoder$1$1,arguments:optional$2$1(anyJson$2$1()),target:optional$2$1(oneOf$1$1(constant$2$1("best"),constant$2$1("all"),nonEmptyStringDecoder$1$1))}),modalRequestTargetDecoder$1=oneOf$1$1(constant$2$1("Global"),constant$2$1("WindowContainer"),nonEmptyStringDecoder$1$1),modalRequestMessageTargetDecoder$1=object$2$1({instance:nonEmptyStringDecoder$1$1,container:optional$2$1(oneOf$1$1(constant$2$1("Global"),constant$2$1("WindowContainer")))}),alertRequestConfigDecoder$1=object$2$1({variant:oneOf$1$1(constant$2$1("default"),constant$2$1("success"),constant$2$1("critical"),constant$2$1("info"),constant$2$1("warning")),text:nonEmptyStringDecoder$1$1,showCloseButton:optional$2$1(boolean$2$1()),clickInterop:optional$2$1(alertsInteropSettingsDecoder$1),onCloseInterop:optional$2$1(alertsInteropSettingsDecoder$1),actions:optional$2$1(array$2$1(object$2$1({id:nonEmptyStringDecoder$1$1,title:nonEmptyStringDecoder$1$1,clickInterop:alertsInteropSettingsDecoder$1}))),data:optional$2$1(anyJson$2$1()),ttl:optional$2$1(nonNegativeNumberDecoder$1$1),target:optional$2$1(modalRequestTargetDecoder$1)}),uiAlertRequestMessageDecoder$1=object$2$1({config:alertRequestConfigDecoder$1,target:modalRequestMessageTargetDecoder$1}),dialogRequestConfigDecoder$1=object$2$1({templateName:nonEmptyStringDecoder$1$1,variables:anyJson$2$1(),target:optional$2$1(modalRequestTargetDecoder$1),timer:optional$2$1(object$2$1({duration:nonNegativeNumberDecoder$1$1})),size:optional$2$1(object$2$1({width:nonNegativeNumberDecoder$1$1,height:nonNegativeNumberDecoder$1$1})),movable:optional$2$1(boolean$2$1()),transparent:optional$2$1(boolean$2$1())}),dialogResponseDecoder$1=object$2$1({isExpired:optional$2$1(boolean$2$1()),isClosed:optional$2$1(boolean$2$1()),isEnterPressed:optional$2$1(boolean$2$1()),responseButtonClicked:optional$2$1(object$2$1({id:nonEmptyStringDecoder$1$1,text:nonEmptyStringDecoder$1$1})),inputs:optional$2$1(array$2$1(object$2$1({type:oneOf$1$1(constant$2$1("checkbox"),constant$2$1("email"),constant$2$1("number"),constant$2$1("password"),constant$2$1("text")),id:nonEmptyStringDecoder$1$1,checked:optional$2$1(boolean$2$1()),value:optional$2$1(string$2$1())})))});object$2$1({result:dialogResponseDecoder$1});const uiDialogRequestMessageDecoder$1=object$2$1({config:dialogRequestConfigDecoder$1,target:modalRequestMessageTargetDecoder$1}),openAlertResultDecoder=object$2$1({id:nonEmptyStringDecoder$1$1}),openDialogResultDecoder=object$2$1({id:nonEmptyStringDecoder$1$1,responsePromise:anyJson$2$1()}),dialogOnCompletionConfigDecoder=object$2$1({response:dialogResponseDecoder$1}),alertInteropActionDecoder$1=object$2$1({name:nonEmptyStringDecoder$1$1,settings:alertsInteropSettingsDecoder$1}),alertOnClickConfigDecoder=object$2$1({interopAction:alertInteropActionDecoder$1}),alertInteropActionDataDecoder$1=object$2$1({interopAction:alertInteropActionDecoder$1}),intentResolverConfigDecoder$1=object$2$1({enable:boolean$2$1(),awaitFactory:optional$2$1(boolean$2$1()),timeout:optional$2$1(nonNegativeNumberDecoder$1$1)}),openResolverResultDecoder=object$2$1({id:nonEmptyStringDecoder$1$1}),userSettingsDecoder=object$2$1({preserveChoice:boolean$2$1()}),userChoiceResponseDecoder=object$2$1({intent:nonEmptyStringDecoder$1$1,handler:intentHandlerDecoder$1,userSettings:userSettingsDecoder}),intentResolverResponseDecoder=object$2$1({isExpired:optional$2$1(boolean$2$1()),isClosed:optional$2$1(boolean$2$1()),userChoice:optional$2$1(userChoiceResponseDecoder)}),onUserResponseResponseDecoder=object$2$1({response:intentResolverResponseDecoder}),openConfigWithIntentRequestDecoder=object$2$1({intentRequest:intentRequestDecoder$1}),openConfigWithHandlerFilterDecoder=object$2$1({handlerFilter:handlerFilterDecoder$1}),intentResolverOpenConfigDecoder=union$1$1(openConfigWithIntentRequestDecoder,openConfigWithHandlerFilterDecoder),uiResolverRequestMessageConfigDecoder=intersection$2(intentResolverOpenConfigDecoder,object$2$1({timeout:nonNegativeNumberDecoder$1$1})),uiResolverRequestMessageDecoder=object$2$1({config:uiResolverRequestMessageConfigDecoder}),uiResolverResponseMessageDecoder=object$2$1({result:intentResolverResponseDecoder}),parseConfig=(e={})=>{const t=!!e?.gateway?.webPlatform?.port,r=optional$2$1(widgetConfigDecoder$1).run(e.widget);if(!r.ok)throw ioError$1.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(r.error)}`);const n=optional$2$1(modalsConfigDecoder$1).run(e.modals);if(!n.ok)throw ioError$1.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(n.error)}`);const i=optional$2$1(intentResolverConfigDecoder$1).run(e.intentResolver);if(!i.ok)throw ioError$1.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(i.error)}`);return{...defaultConfig,...e,isPlatformInternal:t,logger:e.systemLogger?.level??"info",customLogger:e.systemLogger?.customLogger,widget:deepmerge$1$1(defaultWidgetConfig$1,r.result??{}),modals:deepmerge$1$1(defaultModalsConfig,n.result??{}),intentResolver:deepmerge$1$1(defaultIntentResolverConfig,i.result??{})}},checkSingleton$1=()=>{const e=window.glue42core||window.iobrowser;if(e&&e.webStarted)return ioError$1.raiseError("IoConnect Browser has already been started for this application.");e?e.webStarted=!0:window.iobrowser={webStarted:!0}},enterprise=e=>{const t={windows:!0,layouts:"full",appManager:"full",channels:!0,libraries:e?.libraries??[],logger:e?.systemLogger?.level??"warn"};return(window.IODesktop||window.Glue)(t)},operations$a={openWindow:{name:"openWindow",dataDecoder:openWindowConfigDecoder$1,resultDecoder:coreWindowDataDecoder},windowHello:{name:"windowHello",dataDecoder:windowHelloDecoder,resultDecoder:helloSuccessDecoder},windowAdded:{name:"windowAdded",dataDecoder:coreWindowDataDecoder},windowRemoved:{name:"windowRemoved",dataDecoder:simpleWindowDecoder$1},getBounds:{name:"getBounds",dataDecoder:simpleWindowDecoder$1,resultDecoder:windowBoundsResultDecoder$1},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleWindowDecoder$1,resultDecoder:frameWindowBoundsResultDecoder$1},getUrl:{name:"getUrl",dataDecoder:simpleWindowDecoder$1,resultDecoder:windowUrlResultDecoder$1},moveResize:{name:"moveResize",dataDecoder:windowMoveResizeConfigDecoder$1},focus:{name:"focus",dataDecoder:simpleWindowDecoder$1},close:{name:"close",dataDecoder:simpleWindowDecoder$1},getTitle:{name:"getTitle",dataDecoder:simpleWindowDecoder$1,resultDecoder:windowTitleConfigDecoder$1},setTitle:{name:"setTitle",dataDecoder:windowTitleConfigDecoder$1},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder$1},getChannel:{name:"getChannel",dataDecoder:simpleWindowDecoder$1,resultDecoder:windowChannelResultDecoder$1},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:channelsChangedDataDecoder},setZoomFactor:{name:"setZoomFactor",dataDecoder:windowZoomFactorConfigDecoder$1},zoomFactorChange:{name:"zoomFactorChange",dataDecoder:windowZoomFactorConfigDecoder$1},refresh:{name:"refresh",dataDecoder:simpleWindowDecoder$1},operationCheck:{name:"operationCheck"}};function createRegistry$1$1(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;ithis.registry.execute("context-updated",e)),this.me={id:this.id,name:this.name,isFocused:!1,zoomFactor:this.zoomFactor,getURL:this.getURL.bind(this),moveResize:this.moveResize.bind(this),resizeTo:this.resizeTo.bind(this),moveTo:this.moveTo.bind(this),focus:this.focus.bind(this),close:this.close.bind(this),getTitle:this.getTitle.bind(this),setTitle:this.setTitle.bind(this),getBounds:this.getBounds.bind(this),getContext:this.getContext.bind(this),updateContext:this.updateContext.bind(this),setContext:this.setContext.bind(this),refresh:this.refresh.bind(this),onContextUpdated:this.onContextUpdated.bind(this),onFocusChanged:this.onFocusChanged.bind(this),getChannel:this.getChannel.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),zoomIn:this.zoomIn.bind(this),zoomOut:this.zoomOut.bind(this),setZoomFactor:this.setZoomFactor.bind(this),onZoomFactorChanged:this.onZoomFactorChanged.bind(this)},Object.defineProperties(this.me,{id:READONLY_PROPERTY_DESCRIPTOR,name:READONLY_PROPERTY_DESCRIPTOR,zoomFactor:{get:()=>this.zoomFactor,enumerable:!0}}),this.me}async getURL(){return(await this._bridge.send("windows",operations$a.getUrl,{windowId:this.id})).url}onFocusChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"):this.registry.add("focus-change",e)}async moveResize(e){const t=runDecoderWithIOError$1(boundsDecoder,e),r=Object.assign({},t,{windowId:this.id,relative:!1});return await this._bridge.send("windows",operations$a.moveResize,r),this.me}async resizeTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&runDecoderWithIOError$1(nonNegativeNumberDecoder$2$1,e),void 0!==t&&runDecoderWithIOError$1(nonNegativeNumberDecoder$2$1,t);const r=Object.assign({},{width:e,height:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",operations$a.moveResize,r),this.me}async moveTo(e,t){if(void 0===e&&void 0===t)return this.me;void 0!==e&&runDecoderWithIOError$1(number$2$1(),e),void 0!==t&&runDecoderWithIOError$1(number$2$1(),t);const r=Object.assign({},{top:e,left:t},{windowId:this.id,relative:!0});return await this._bridge.send("windows",operations$a.moveResize,r),this.me}async focus(){return"Platform"===this.name?window.open(void 0,this.id):await this._bridge.send("windows",operations$a.focus,{windowId:this.id}),this.me}async close(){return await this._bridge.send("windows",operations$a.close,{windowId:this.id}),this.me}async getTitle(){return(await this._bridge.send("windows",operations$a.getTitle,{windowId:this.id})).title}async setTitle(e){const t=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e);return await this._bridge.send("windows",operations$a.setTitle,{windowId:this.id,title:t}),this.me}async getBounds(){return(await this._bridge.send("windows",operations$a.getBounds,{windowId:this.id})).bounds}async getContext(){const e=await this._bridge.contextLib.get(this.myCtxKey),{___io___:t,...r}=e;return r}async updateContext(e){const t=runDecoderWithIOError$1(anyDecoder$1,e);return await this._bridge.contextLib.update(this.myCtxKey,t),this.me}async setContext(e){const t=runDecoderWithIOError$1(anyDecoder$1,e),r=await this._bridge.contextLib.get(this.myCtxKey),n=r.___io___?{...t,___io___:r.___io___}:t;return await this._bridge.contextLib.set(this.myCtxKey,n),this.me}onContextUpdated(e){if("function"!=typeof e)return ioError$1.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!");return this.registry.add("context-updated",t=>{const{___io___:r,...n}=t;e(n,this.me)})}async getChannel(){return(await this._bridge.send("windows",operations$a.getChannel,{windowId:this.id},void 0,{includeOperationCheck:!0})).channel}onChannelsChanged(e){return this.registry.add("channels-changed",e)}getClosestZoomFactorIndex(e){const t=Object.entries(ZOOM_FACTORS$1).reduce((t,[r,n])=>Math.abs(n-e)<=Math.abs(ZOOM_FACTORS$1[t]-e)?parseInt(r):t,0),r=ZOOM_FACTORS$1[t];return r!==e&&this._logger.warn(`Zoom factor ${e} is not available, using closest value ${r} instead.`),t}async zoom(e){e!==this.zoomFactorIndex&&e in ZOOM_FACTORS$1&&(await this._bridge.send("windows",operations$a.setZoomFactor,{windowId:this.id,factorIndex:e},void 0,{includeOperationCheck:!0}),this.zoomFactorIndex=e)}async zoomIn(){return await this.zoom(this.zoomFactorIndex+1),this.me}async zoomOut(){return await this.zoom(this.zoomFactorIndex-1),this.me}async setZoomFactor(e){const t=runDecoderWithIOError$1(number$2$1(),e),r=this.getClosestZoomFactorIndex(t);return await this.zoom(r),this.me}onZoomFactorChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"):this.registry.add("zoom-factor-changed",e)}async refresh(){return await this._bridge.send("windows",operations$a.refresh,{windowId:this.id},void 0,{includeOperationCheck:!0}),this.me}}const commonOperations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder$1,resultDecoder:operationCheckResultDecoder$1},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:workspaceFrameBoundsResultDecoder,dataDecoder:simpleItemIdDecoder}},PromiseWrap$1=(e,t,r)=>new Promise((n,i)=>{let o=!0;const s=setTimeout(()=>{if(!o)return;o=!1;i(r||`Promise timeout hit: ${t}`)},t);e().then(e=>{o&&(o=!1,clearTimeout(s),n(e))}).catch(e=>{o&&(o=!1,clearTimeout(s),i(e))})}),PromisePlus$1$1=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});let WindowsController$1=class{supportedOperationsNames=[];focusEventHandler;registry=CallbackRegistryFactory$1$1();platformRegistration;ioc;bridge;publicWindowId;allWindowProjections=[];me;logger;isWorkspaceFrame;instanceId;channelsController;async start(e,t){this.logger=e.logger.subLogger("windows.controller.web"),this.logger.trace("starting the web windows controller"),this.publicWindowId=t.publicWindowId,this.addWindowOperationExecutors(),this.ioc=t,this.bridge=t.bridge,this.instanceId=e.interop.instance.instance,this.channelsController=t.channelsController,this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`),this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,await this.initializeFocusTracking(),this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning");const r=this.toApi();e.windows=r}handlePlatformShutdown(){this.registry.clear(),this.allWindowProjections=[],this.focusEventHandler&&(document.removeEventListener("visibilityChange",this.focusEventHandler),window.removeEventListener("focus",this.focusEventHandler),window.removeEventListener("blur",this.focusEventHandler))}async handleBridgeMessage(e){await this.platformRegistration;const t=runDecoderWithIOError$1(windowOperationTypesDecoder,e.operation),r=operations$a[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async open(e,t,r){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,t);const n=runDecoderWithIOError$1(windowOpenSettingsDecoder$1,r),i=await this.bridge.send("windows",operations$a.openWindow,{name:e,url:t,options:n});return this.waitForWindowAdded(i.windowId)}list(){return this.allWindowProjections.map(e=>e.api)}findById(e){return runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),this.allWindowProjections.find(t=>t.id===e)?.api}toApi(){return{open:this.open.bind(this),my:this.my.bind(this),list:this.list.bind(this),findById:this.findById.bind(this),onWindowAdded:this.onWindowAdded.bind(this),onWindowRemoved:this.onWindowRemoved.bind(this),onWindowGotFocus:this.onWindowGotFocus.bind(this),onWindowLostFocus:this.onWindowLostFocus.bind(this)}}addWindowOperationExecutors(){operations$a.focusChange.execute=this.handleFocusChangeEvent.bind(this),operations$a.windowAdded.execute=this.handleWindowAdded.bind(this),operations$a.windowRemoved.execute=this.handleWindowRemoved.bind(this),operations$a.getBounds.execute=this.handleGetBounds.bind(this),operations$a.getFrameBounds.execute=this.handleGetBounds.bind(this),operations$a.getTitle.execute=this.handleGetTitle.bind(this),operations$a.getUrl.execute=this.handleGetUrl.bind(this),operations$a.moveResize.execute=this.handleMoveResize.bind(this),operations$a.setTitle.execute=this.handleSetTitle.bind(this),operations$a.getChannel.execute=this.handleGetChannel.bind(this),operations$a.notifyChannelsChanged.execute=this.handleChannelsChanged.bind(this),operations$a.setZoomFactor.execute=this.handleSetZoomFactor.bind(this),operations$a.zoomFactorChange.execute=this.handleZoomFactorChanged.bind(this),operations$a.refresh.execute=this.handleRefresh.bind(this),operations$a.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$a)}my(){return Object.assign({},this.me)}onWindowAdded(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"):this.registry.add("window-added",e)}onWindowRemoved(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"):this.registry.add("window-removed",e)}onWindowGotFocus(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"):this.registry.add("window-got-focus",e)}onWindowLostFocus(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"):this.registry.add("window-lost-focus",e)}async sayHello(){return await this.bridge.send("windows",operations$a.windowHello,{windowId:this.publicWindowId})}async registerWithPlatform(){const{windows:e,isWorkspaceFrame:t}=await this.sayHello();if(this.isWorkspaceFrame=t,this.logger.trace("the platform responded to the hello message"),!this.isWorkspaceFrame&&this.publicWindowId){this.logger.trace("i am not treated as a workspace frame, setting my window");const t=e.find(e=>e.windowId===this.publicWindowId);if(!t){const t=e.map(e=>`${e.windowId}:${e.name}`).join(", ");return ioError$1.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${t}`)}const r=await this.ioc.buildWebWindow(this.publicWindowId,t.name,this.logger);this.me=r.api,this.allWindowProjections.push(r)}const r=await Promise.all(e.filter(e=>e.windowId!==this.publicWindowId).map(e=>this.ioc.buildWebWindow(e.windowId,e.name,this.logger)));this.logger.trace("all windows projections are completed, building the list collection"),this.allWindowProjections.push(...r)}async handleFocusChangeEvent(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);if(!t)return;t.model.processSelfFocusEvent(e.hasFocus);const r=e.hasFocus?"window-got-focus":"window-lost-focus";this.registry.execute(r,t.api)}async handleWindowAdded(e){if(this.allWindowProjections.some(t=>t.id===e.windowId))return;const t=await this.ioc.buildWebWindow(e.windowId,e.name,this.logger);this.allWindowProjections.push(t),this.registry.execute("window-added",t.api)}async handleWindowRemoved(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&(this.allWindowProjections=this.allWindowProjections.filter(t=>t.id!==e.windowId),t.model.clean(),this.registry.execute("window-removed",t.api))}async handleGetBounds(){return this.me||this.isWorkspaceFrame?{windowId:this.isWorkspaceFrame?"noop":this.me.id,bounds:{top:window.screenTop,left:window.screenLeft,width:window.innerWidth,height:window.innerHeight}}:ioError$1.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe")}async handleGetTitle(){return this.me?{windowId:this.me.id,title:document.title}:ioError$1.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe")}async handleGetUrl(){return this.me?{windowId:this.me.id,url:window.location.href}:ioError$1.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe")}async handleMoveResize(e){const t="number"==typeof e.top?e.top:e.relative?0:window.screenTop,r="number"==typeof e.left?e.left:e.relative?0:window.screenLeft,n="number"==typeof e.height?e.height:e.relative?0:window.innerHeight,i="number"==typeof e.width?e.width:e.relative?0:window.innerWidth,o=e.relative?window.moveBy:window.moveTo,s=e.relative?window.resizeBy:window.resizeTo;o(r,t),s(i,n)}async handleSetTitle(e){document.title=e.title}async initializeFocusTracking(){if(this.isWorkspaceFrame)return void this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame");try{await this.bridge.send("windows",commonOperations.operationCheck,{operation:"focusChange"})}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client.")}const e=document.hasFocus();await this.transmitFocusChange(!0),e||await this.transmitFocusChange(!1),this.defineEventListeners()}processFocusEvent(){const e=document.hasFocus();this.transmitFocusChange(e)}waitForWindowAdded(e){const t=this.allWindowProjections.find(t=>t.id===e);return t?Promise.resolve(t.api):PromisePlus$1$1(t=>{const r=this.onWindowAdded(n=>{n.id===e&&(r(),t(n))})},3e4,`Timed out waiting for ${e} to be announced`)}async transmitFocusChange(e){const t={windowId:this.me?.id||`iframe-${this.instanceId}`,hasFocus:e};this.me&&(this.me.isFocused=e),await this.bridge.send("windows",operations$a.focusChange,t)}defineEventListeners(){this.focusEventHandler=this.processFocusEvent.bind(this),document.addEventListener("visibilityChange",this.focusEventHandler),window.addEventListener("focus",this.focusEventHandler),window.addEventListener("blur",this.focusEventHandler)}async handleGetChannel(){if(!this.me)return ioError$1.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe");const e=this.channelsController.my();return{...e?{channel:e}:{}}}async handleRefresh(){if(!this.me)return ioError$1.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe");setTimeout(()=>{window.location.reload()},0)}async handleChannelsChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t?.model.processChannelsChangedEvent(e.channelNames)}async handleSetZoomFactor(e){if(!this.me)return ioError$1.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe");document.body.style.zoom=`${ZOOM_FACTORS$1[e.factorIndex]}%`}async handleZoomFactorChanged(e){const t=this.allWindowProjections.find(t=>t.id===e.windowId);t&&t.model.processSelfZoomFactorChangedEvent(e.factorIndex)}};const GlueWebPlatformControlName$1="T42.Web.Platform.Control",GlueWebPlatformStreamName$1="T42.Web.Platform.Stream",GlueClientControlName$1="T42.Web.Client.Control",GlueCorePlusThemesStream$1="T42.Core.Plus.Themes.Stream";class GlueBridge{coreGlue;communicationId;platformMethodTimeoutMs=1e4;controllers;sub;running;constructor(e,t){this.coreGlue=e,this.communicationId=t}get contextLib(){return this.coreGlue.contexts}get interopInstance(){return this.coreGlue.interop.instance.instance}async stop(){this.running=!1,this.sub.close(),await this.coreGlue.interop.unregister(GlueClientControlName$1)}async start(e){this.running=!0,this.controllers=e,await Promise.all([this.checkWaitMethod(GlueWebPlatformControlName$1),this.checkWaitMethod(GlueWebPlatformStreamName$1)]);const t=this.communicationId,[r]=await Promise.all([this.coreGlue.interop.subscribe(GlueWebPlatformStreamName$1,t?{target:{instance:this.communicationId}}:void 0),this.coreGlue.interop.registerAsync(GlueClientControlName$1,(e,t,r,n)=>this.passMessageController(e,r,n))]);this.sub=r,this.sub.onData(e=>this.passMessageController(e.data))}getInteropInstance(e){const t=this.coreGlue.interop.servers().find(t=>t.windowId&&t.windowId===e);return{application:t?.application,applicationName:t?.applicationName,peerId:t?.peerId,instance:t?.instance,windowId:t?.windowId}}async send(e,t,r,n,i){if(t.dataDecoder)try{t.dataDecoder.runWithException(r)}catch(e){return ioError$1.raiseError(`Unexpected Web->Platform outgoing validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`)}if(!(!i?.includeOperationCheck||(await this.checkOperationSupported(e,t)).isSupported))return ioError$1.raiseError(`Cannot complete operation: ${t.name} for domain: ${e} because this client is connected to a platform which does not support it`);try{const i=await this.transmitMessage(e,t,r,n);return t.resultDecoder&&t.resultDecoder.runWithException(i),i}catch(e){return e?.kind?ioError$1.raiseError(`Unexpected Web<-Platform incoming validation error: ${e.message}, for operation: ${t.name} and input: ${JSON.stringify(e.input)}`):ioError$1.raiseError(e)}}async createNotificationsSteam(){return this.coreGlue.interop.methods().some(e=>e.name===GlueCorePlusThemesStream$1)?this.coreGlue.interop.subscribe(GlueCorePlusThemesStream$1,this.communicationId?{target:{instance:this.communicationId}}:void 0):ioError$1.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus.")}async checkOperationSupported(e,t){try{return await this.send(e,commonOperations.operationCheck,{operation:t.name})}catch(e){return{isSupported:!1}}}checkWaitMethod(e){return PromisePlus$1$1(t=>{if(this.coreGlue.interop.methods().some(t=>{const r=t.name===e,n=!this.communicationId||t.getServers().some(e=>e.instance===this.communicationId);return r&&n}))return t();const r=this.coreGlue.interop.serverMethodAdded(n=>{const i=n.method,o=n.server,s=!this.communicationId||o.instance===this.communicationId;i.name===e&&s&&(r(),t())})},this.platformMethodTimeoutMs,`Cannot initiate Glue Web, because a system method's discovery timed out: ${e}`)}passMessageController(e,t,r){const n=libDomainDecoder$1.run(e.domain);if(!n.ok)return void(r&&r(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(n.error)}`));const i=n.result;this.controllers[i].handleBridgeMessage(e).then(e=>{t&&t(e)}).catch(e=>{r&&r(e),console.warn(e)})}async transmitMessage(e,t,r,n){const i={domain:e,data:r,operation:t.name};let o;const s=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(t.name)} with data: ${JSON.stringify(r)}. `,a=this.communicationId;try{if(!this.running)throw new Error("Cannot send a control message, because the platform shut down");if(o=await this.coreGlue.interop.invoke(GlueWebPlatformControlName$1,i,a?{instance:this.communicationId}:void 0,n),!o)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(o.all_return_values)||0===o.all_return_values.length)throw new Error("Received unsupported result from the platform - empty values collection")}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;throw new Error(`${s} -> Inner message: ${t}`)}throw new Error(`${s} -> Inner message: ${e.message}`)}return o.all_return_values[0].returned}}const operations$9={appHello:{name:"appHello",dataDecoder:windowHelloDecoder,resultDecoder:appHelloSuccessDecoder$2},appDirectoryStateChange:{name:"appDirectoryStateChange",dataDecoder:appDirectoryStateChangeDecoder},instanceStarted:{name:"instanceStarted",dataDecoder:instanceDataDecoder$1},instanceStopped:{name:"instanceStopped",dataDecoder:instanceDataDecoder$1},applicationStart:{name:"applicationStart",dataDecoder:applicationStartConfigDecoder$1,resultDecoder:instanceDataDecoder$1},instanceStop:{name:"instanceStop",dataDecoder:basicInstanceDataDecoder$1},import:{name:"import"},remove:{name:"remove",dataDecoder:appRemoveConfigDecoder$1},export:{name:"export",resultDecoder:appsExportOperationDecoder$1},clear:{name:"clear"},operationCheck:{name:"operationCheck"}};class AppManagerController{me;supportedOperationsNames=[];baseApplicationsTimeoutMS=6e4;appImportTimeoutMS=20;registry=CallbackRegistryFactory$1$1();ioc;bridge;publicWindowId;applications=[];instances=[];platformRegistration;logger;channelsController;interop;initialChannelId;handlePlatformShutdown(){this.registry.clear(),this.applications=[],this.instances=[],delete this.me}async start(e,t){this.logger=e.logger.subLogger("appManger.controller.web"),this.logger.trace("starting the web appManager controller"),this.publicWindowId=t.publicWindowId,this.addOperationsExecutors(),this.ioc=t,this.bridge=t.bridge,this.channelsController=t.channelsController,this.interop=e.interop,this.platformRegistration=this.registerWithPlatform(),await this.platformRegistration,this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning");const r=this.toApi();e.appManager=r}async postStart(){this.initialChannelId&&await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId)}async handleBridgeMessage(e){await this.platformRegistration;const t=runDecoderWithIOError$1(appManagerOperationTypesDecoder$1,e.operation),r=operations$9[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}onInstanceStarted(e){return"function"!=typeof e?ioError$1.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e,this.instances)}onInstanceStopped(e){return"function"!=typeof e?ioError$1.raiseError("onInstanceStopped requires a single argument of type function"):this.registry.add("instance-stopped",e)}async startApplication(e,t,r){const n=await this.channelsController.all();if(r?.channelId&&!n.includes(r.channelId))return ioError$1.raiseError(`The channel with name "${r.channelId}" doesn't exist!`);const i={name:e,waitForAGMReady:r?.waitForAGMReady??!0,context:t,top:r?.top,left:r?.left,width:r?.width,height:r?.height,relativeTo:r?.relativeTo,relativeDirection:r?.relativeDirection,id:r?.reuseId,forceChromeTab:r?.forceTab,layoutComponentId:r?.layoutComponentId,channelId:r?.channelId,startReason:{originApp:{name:this.me?.application.name,interopInstance:this.interop.instance.instance}}};r?.originIntentRequest&&(i.startReason.intentRequest=r.originIntentRequest);const o=await this.bridge.send("appManager",operations$9.applicationStart,i),s=this.applications.find(e=>e.name===o.applicationName);return this.ioc.buildInstance(o,s)}getApplication(e){const t=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e);return this.applications.find(e=>e.name===t)}getInstances(){return this.instances.slice()}onAppAdded(e){return"function"!=typeof e?ioError$1.raiseError("onAppAdded requires a single argument of type function"):this.registry.add("application-added",e,this.applications)}onAppRemoved(e){return"function"!=typeof e?ioError$1.raiseError("onAppRemoved requires a single argument of type function"):this.registry.add("application-removed",e)}toApi(){return{myInstance:this.me,inMemory:{import:this.importApps.bind(this),remove:this.remove.bind(this),export:this.exportApps.bind(this),clear:this.clear.bind(this)},application:this.getApplication.bind(this),applications:this.getApplications.bind(this),instances:this.getInstances.bind(this),onAppAdded:this.onAppAdded.bind(this),onAppChanged:this.onAppChanged.bind(this),onAppRemoved:this.onAppRemoved.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)}}addOperationsExecutors(){operations$9.appDirectoryStateChange.execute=this.handleAppDirectoryStateChange.bind(this),operations$9.instanceStarted.execute=this.handleInstanceStartedMessage.bind(this),operations$9.instanceStopped.execute=this.handleInstanceStoppedMessage.bind(this),operations$9.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$9)}async handleAppDirectoryStateChange(e){e.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)),e.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)),e.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this))}onAppChanged(e){return"function"!=typeof e?ioError$1.raiseError("onAppChanged requires a single argument of type function"):this.registry.add("application-changed",e)}async handleApplicationAddedMessage(e){if(this.applications.some(t=>t.name===e.name))return;const t=await this.ioc.buildApplication(e,[]),r=this.instances.filter(e=>e.application.name===t.name);t.instances.push(...r),this.applications.push(t),this.registry.execute("application-added",t)}async handleApplicationRemovedMessage(e){const t=this.applications.findIndex(t=>t.name===e.name);if(t<0)return;const r=this.applications[t];this.applications.splice(t,1),this.registry.execute("application-removed",r)}async handleApplicationChangedMessage(e){const t=this.applications.find(t=>t.name===e.name);if(!t)return this.handleApplicationAddedMessage(e);t.title=e.title,t.version=e.version,t.icon=e.icon,t.caption=e.caption,t.userProperties=e.userProperties,this.registry.execute("application-changed",t)}async handleInstanceStartedMessage(e){if(this.instances.some(t=>t.id===e.id))return;const t=this.applications.find(t=>t.name===e.applicationName);if(!t)return ioError$1.raiseError(`Cannot add instance: ${e.id}, because there is no application definition associated with it`);const r=this.ioc.buildInstance(e,t);this.instances.push(r),t.instances.push(r),this.registry.execute("instance-started",r)}async handleInstanceStoppedMessage(e){const t=this.instances.find(t=>t.id===e.id);if(t){const t=this.instances.findIndex(t=>t.id===e.id);this.instances.splice(t,1)}const r=this.applications.find(t=>t.instances.some(t=>t.id===e.id));if(r){const t=r.instances.findIndex(t=>t.id===e.id);r.instances.splice(t,1)}t&&this.registry.execute("instance-stopped",t)}async importApps(e,t="replace"){if(runDecoderWithIOError$1(importModeDecoder$1,t),!Array.isArray(e))return ioError$1.raiseError("Import must be called with an array of definitions");if(e.length>1e4)return ioError$1.raiseError("Cannot import more than 10000 app definitions in Glue42 Core.");const r=e.reduce((e,t)=>{const{isValid:r,error:n}=this.isValidDefinition(t);return r?e.valid.push(t):e.invalid.push({app:t?.name,error:n??`Provided definition is invalid ${JSON.stringify(t)}`}),e},{valid:[],invalid:[]}),n=this.baseApplicationsTimeoutMS+this.appImportTimeoutMS*r.valid.length;return await this.bridge.send("appManager",operations$9.import,{definitions:r.valid,mode:t},{methodResponseTimeoutMs:n}),{imported:r.valid.map(e=>e.name),errors:r.invalid}}isValidDefinition(e){if(e?.appId&&e?.details){const t=decoders$2.fdc3.v2DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v2 definition. Error: ${JSON.stringify(t.error)}`}}if(e?.appId&&e?.manifest){const t=decoders$2.fdc3.v1DefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid FDC3 v1 definition. Error: ${JSON.stringify(t.error)}`}}const t=applicationDefinitionDecoder.run(e);return{isValid:t.ok,error:t.ok?void 0:`Received invalid definition. Error: ${JSON.stringify(t.error)}`}}async remove(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),await this.bridge.send("appManager",operations$9.remove,{name:e},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async clear(){await this.bridge.send("appManager",operations$9.clear,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})}async exportApps(){return(await this.bridge.send("appManager",operations$9.export,void 0,{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS})).definitions}getApplications(){return this.applications.slice()}async registerWithPlatform(){const e=await this.bridge.send("appManager",operations$9.appHello,{windowId:this.publicWindowId},{methodResponseTimeoutMs:this.baseApplicationsTimeoutMS});this.logger.trace("the platform responded to the hello message with a full list of apps"),this.applications=await Promise.all(e.apps.map(e=>this.ioc.buildApplication(e,e.instances))),this.instances=this.applications.reduce((e,t)=>(e.push(...t.instances),e),[]),this.me=this.findMyInstance(),this.logger.trace(`all applications were parsed and saved. I am ${this.me?"NOT a":"a"} valid instance`),this.initialChannelId=e.initialChannelId}findMyInstance(){for(const e of this.applications){const t=e.instances.find(e=>e.id===this.publicWindowId);if(t)return t}}}class InstanceModel{data;bridge;application;me;myCtxKey;constructor(e,t,r){this.data=e,this.bridge=t,this.application=r,this.myCtxKey=`___instance___${this.data.id}`}toApi(){const e=this.bridge.getInteropInstance(this.data.id),t={id:this.data.id,agm:e,application:this.application,stop:this.stop.bind(this),getContext:this.getContext.bind(this)};return this.me=Object.freeze(t),this.me}async getContext(){return this.bridge.contextLib.get(this.myCtxKey)}async stop(){await this.bridge.send("appManager",operations$9.instanceStop,{id:this.data.id})}}class ApplicationModel{data;instances;controller;me;constructor(e,t,r){this.data=e,this.instances=t,this.controller=r}toApi(){const e={name:this.data.name,title:this.data.title,version:this.data.version,icon:this.data.icon,caption:this.data.caption,userProperties:this.data.userProperties,instances:this.instances,start:this.start.bind(this),onInstanceStarted:this.onInstanceStarted.bind(this),onInstanceStopped:this.onInstanceStopped.bind(this)};return this.me=e,this.me}onInstanceStarted(e){return"function"!=typeof e?ioError$1.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStarted(t=>{t.application.name===this.data.name&&e(t)})}onInstanceStopped(e){return"function"!=typeof e?ioError$1.raiseError("OnInstanceStarted requires a single argument of type function"):this.controller.onInstanceStopped(t=>{t.application.name===this.data.name&&e(t)})}async start(e,t){const r=runDecoderWithIOError$1(startApplicationContextDecoder,e),n=runDecoderWithIOError$1(startApplicationOptionsDecoder,t);return this.controller.startApplication(this.data.name,r,n)}}const operations$8={layoutAdded:{name:"layoutAdded",dataDecoder:glueLayoutDecoder$1},layoutChanged:{name:"layoutChanged",dataDecoder:glueLayoutDecoder$1},layoutRemoved:{name:"layoutRemoved",dataDecoder:glueLayoutDecoder$1},layoutRestored:{name:"layoutRestored",dataDecoder:glueLayoutDecoder$1},defaultLayoutChanged:{name:"defaultLayoutChanged",dataDecoder:defaultGlobalChangedDecoder},layoutRenamed:{name:"layoutRenamed",dataDecoder:renamedLayoutNotificationDecoder},get:{name:"get",dataDecoder:simpleLayoutConfigDecoder$1,resultDecoder:optionalSimpleLayoutResult$1},getAll:{name:"getAll",dataDecoder:getAllLayoutsConfigDecoder$1,resultDecoder:allLayoutsSummariesResultDecoder$1},export:{name:"export",dataDecoder:getAllLayoutsConfigDecoder$1,resultDecoder:allLayoutsFullConfigDecoder$1},import:{name:"import",dataDecoder:layoutsImportConfigDecoder$1},remove:{name:"remove",dataDecoder:simpleLayoutConfigDecoder$1},rename:{name:"rename",dataDecoder:renameLayoutConfigDecoder$1,resultDecoder:layoutResultDecoder$1},save:{name:"save",dataDecoder:saveLayoutConfigDecoder$1,resultDecoder:simpleLayoutResultDecoder},restore:{name:"restore",dataDecoder:restoreLayoutConfigDecoder$1},clientSaveRequest:{name:"clientSaveRequest",dataDecoder:platformSaveRequestConfigDecoder,resultDecoder:saveRequestClientResponseDecoder},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:permissionStateResultDecoder$1},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:simpleAvailabilityResultDecoder$1},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:simpleAvailabilityResultDecoder$1},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:optionalSimpleLayoutResult$1},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:setDefaultGlobalConfigDecoder$1},clearDefaultGlobal:{name:"clearDefaultGlobal"},getCurrent:{name:"getCurrent",resultDecoder:optionalSimpleLayoutResult$1},updateMetadata:{name:"updateMetadata",dataDecoder:updateLayoutMetadataConfigDecoder$1},operationCheck:{name:"operationCheck"}};let LayoutsController$1=class{supportedOperationsNames=[];defaultLayoutRestoreTimeoutMS=12e4;registry=CallbackRegistryFactory$1$1();bridge;logger;windowsController;saveRequestSubscription;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("layouts.controller.web"),this.logger.trace("starting the web layouts controller"),this.bridge=t.bridge,this.windowsController=t.windowsController,this.addOperationsExecutors();const r=this.toApi();this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"),e.layouts=r}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(layoutsOperationTypesDecoder$1,e.operation),r=operations$8[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}toApi(){const e={get:this.get.bind(this),getAll:this.getAll.bind(this),getCurrentLayout:this.getCurrentLayout.bind(this),export:this.exportLayouts.bind(this),import:this.importLayouts.bind(this),save:this.save.bind(this),restore:this.restore.bind(this),remove:this.remove.bind(this),onAdded:this.onAdded.bind(this),onChanged:this.onChanged.bind(this),onRemoved:this.onRemoved.bind(this),onDefaultGlobalChanged:this.onDefaultGlobalChanged.bind(this),onSaveRequested:this.subscribeOnSaveRequested.bind(this),getMultiScreenPermissionState:this.getGlobalPermissionState.bind(this),requestMultiScreenPermission:this.requestGlobalPermission.bind(this),getGlobalTypeState:this.checkGlobalActivated.bind(this),getDefaultGlobal:this.getDefaultGlobal.bind(this),setDefaultGlobal:this.setDefaultGlobal.bind(this),clearDefaultGlobal:this.clearDefaultGlobal.bind(this),rename:this.rename.bind(this),onRenamed:this.onRenamed.bind(this),onRestored:this.onRestored.bind(this),updateMetadata:this.updateMetadata.bind(this)};return Object.freeze(e)}addOperationsExecutors(){operations$8.layoutAdded.execute=this.handleOnAdded.bind(this),operations$8.layoutChanged.execute=this.handleOnChanged.bind(this),operations$8.layoutRemoved.execute=this.handleOnRemoved.bind(this),operations$8.layoutRenamed.execute=this.handleOnRenamed.bind(this),operations$8.layoutRestored.execute=this.handleOnRestored.bind(this),operations$8.defaultLayoutChanged.execute=this.handleOnDefaultChanged.bind(this),operations$8.clientSaveRequest.execute=this.handleSaveRequest.bind(this),operations$8.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$8)}async get(e,t){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),runDecoderWithIOError$1(layoutTypeDecoder$1,t);return(await this.bridge.send("layouts",operations$8.get,{name:e,type:t})).layout}async getCurrentLayout(){return(await this.bridge.send("layouts",operations$8.getCurrent,void 0)).layout}async getAll(e){runDecoderWithIOError$1(layoutTypeDecoder$1,e);return(await this.bridge.send("layouts",operations$8.getAll,{type:e})).summaries}async exportLayouts(e){runDecoderWithIOError$1(layoutTypeDecoder$1,e);return(await this.bridge.send("layouts",operations$8.export,{type:e})).layouts}async importLayouts(e,t="replace"){if(runDecoderWithIOError$1(importModeDecoder$1,t),!Array.isArray(e))return ioError$1.raiseError("Import must be called with an array of layouts");if(e.length>1e3)return ioError$1.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core.");const r=e.reduce((e,t)=>{const r=glueLayoutDecoder$1.run(t);return r.ok?e.valid.push(t):this.logger.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]}),n=e.filter(e=>r.valid.some(t=>t.name===e.name));await this.bridge.send("layouts",operations$8.import,{layouts:n,mode:t})}async save(e){runDecoderWithIOError$1(newLayoutOptionsDecoder$1,e);return(await this.bridge.send("layouts",operations$8.save,{layout:e})).layout}async restore(e){runDecoderWithIOError$1(restoreOptionsDecoder$1,e);const t=e.timeout?2*e.timeout:this.defaultLayoutRestoreTimeoutMS;await this.bridge.send("layouts",operations$8.restore,{layout:e},{methodResponseTimeoutMs:t})}async remove(e,t){runDecoderWithIOError$1(layoutTypeDecoder$1,e),runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,t),await this.bridge.send("layouts",operations$8.remove,{type:e,name:t})}async handleSaveRequest(e){const t={};if(this.saveRequestSubscription)try{const r=this.saveRequestSubscription(e);t.windowContext=r?.windowContext}catch(e){this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(e)}`)}return t}async getGlobalPermissionState(){return await this.bridge.send("layouts",operations$8.getGlobalPermissionState,void 0)}async requestGlobalPermission(){const e=(await this.getGlobalPermissionState()).state;if("denied"===e)return{permissionGranted:!1};if("granted"===e)return{permissionGranted:!0};const t=this.windowsController.my(),r=(window.glue42core||window.iobrowser).isPlatformFrame;if("Platform"!==t.name&&!r)return ioError$1.raiseError("Cannot request permission for multi-window placement from any app other than the Platform.");return{permissionGranted:(await this.bridge.send("layouts",operations$8.requestGlobalPermission,void 0,{methodResponseTimeoutMs:18e4})).isAvailable}}async checkGlobalActivated(){return{activated:(await this.bridge.send("layouts",operations$8.checkGlobalActivated,void 0)).isAvailable}}async getDefaultGlobal(){return(await this.bridge.send("layouts",operations$8.getDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})).layout}async setDefaultGlobal(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),await this.bridge.send("layouts",operations$8.setDefaultGlobal,{name:e},void 0,{includeOperationCheck:!0})}async clearDefaultGlobal(){await this.bridge.send("layouts",operations$8.clearDefaultGlobal,void 0,void 0,{includeOperationCheck:!0})}async rename(e,t){runDecoderWithIOError$1(glueLayoutDecoder$1,e),runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,t);return await this.bridge.send("layouts",operations$8.rename,{layout:e,newName:t},void 0,{includeOperationCheck:!0})}async updateMetadata(e){runDecoderWithIOError$1(glueLayoutDecoder$1,e),await this.bridge.send("layouts",operations$8.updateMetadata,{layout:e},void 0,{includeOperationCheck:!0})}onAdded(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"):(this.exportLayouts("Global").then(t=>t.forEach(t=>e(t))).catch(()=>{}),this.exportLayouts("Workspace").then(t=>t.forEach(t=>e(t))).catch(()=>{}),this.registry.add(operations$8.layoutAdded.name,e))}onChanged(e){return this.registry.add(operations$8.layoutChanged.name,e)}onDefaultGlobalChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"):(this.getDefaultGlobal().then(t=>e(t?{name:t.name}:void 0)).catch(()=>{}),this.registry.add(operations$8.defaultLayoutChanged.name,e))}onRemoved(e){return this.registry.add(operations$8.layoutRemoved.name,e)}onRenamed(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"):this.registry.add(operations$8.layoutRenamed.name,e)}onRestored(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"):this.registry.add(operations$8.layoutRestored.name,e)}subscribeOnSaveRequested(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."):this.saveRequestSubscription?ioError$1.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."):(this.saveRequestSubscription=e,()=>{delete this.saveRequestSubscription})}async handleOnAdded(e){this.registry.execute(operations$8.layoutAdded.name,e)}async handleOnChanged(e){this.registry.execute(operations$8.layoutChanged.name,e)}async handleOnDefaultChanged(e){this.registry.execute(operations$8.defaultLayoutChanged.name,e)}async handleOnRemoved(e){this.registry.execute(operations$8.layoutRemoved.name,e)}async handleOnRestored(e){this.registry.execute(operations$8.layoutRestored.name,e)}async handleOnRenamed(e){const{prevName:t,...r}=e;this.registry.execute(operations$8.layoutRenamed.name,r,{name:t})}};const operations$7={raiseNotification:{name:"raiseNotification",dataDecoder:raiseNotificationDecoder$1,resultDecoder:raiseNotificationResultDecoder$1},requestPermission:{name:"requestPermission",resultDecoder:permissionRequestResultDecoder$1},notificationShow:{name:"notificationShow",dataDecoder:notificationEventPayloadDecoder},notificationClick:{name:"notificationClick",dataDecoder:notificationEventPayloadDecoder},getPermission:{name:"getPermission",resultDecoder:permissionQueryResultDecoder$1},list:{name:"list",resultDecoder:allNotificationsDataDecoder$1},notificationRaised:{name:"notificationRaised",dataDecoder:simpleNotificationDataDecoder},notificationClosed:{name:"notificationClosed",dataDecoder:simpleNotificationSelectDecoder$1},click:{name:"click"},clear:{name:"clear"},clearAll:{name:"clearAll"},clearOld:{name:"clearOld"},configure:{name:"configure",dataDecoder:notificationsConfigurationProtocolDecoder$1},getConfiguration:{name:"getConfiguration",resultDecoder:strictNotificationsConfigurationProtocolDecoder},getActiveCount:{name:"getActiveCount",resultDecoder:activeNotificationsCountChangeDecoder},configurationChanged:{name:"configurationChanged",resultDecoder:strictNotificationsConfigurationProtocolDecoder},setState:{name:"setState",dataDecoder:notificationSetStateRequestDecoder$1},activeCountChange:{name:"activeCountChange",resultDecoder:activeNotificationsCountChangeDecoder},stateChange:{name:"stateChange",resultDecoder:notificationSetStateRequestDecoder$1},operationCheck:{name:"operationCheck"}};let urlAlphabet$1$1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$1$1=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$1$1[64*Math.random()|0];return t},NotificationsController$1=class{supportedOperationsNames=[];registry=CallbackRegistryFactory$1$1();logger;bridge;notificationsSettings;notifications={};coreGlue;buildNotificationFunc;notificationsConfiguration;notificationsActiveCount=0;handlePlatformShutdown(){this.notifications={},this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("notifications.controller.web"),this.logger.trace("starting the web notifications controller"),this.bridge=t.bridge,this.coreGlue=e,this.notificationsSettings=t.config.notifications,this.buildNotificationFunc=t.buildNotification,this.notificationsConfiguration=await this.getConfiguration(),this.notificationsActiveCount=await this.getActiveCount();const r=this.toApi();this.addOperationExecutors(),e.notifications=r,this.logger.trace("notifications are ready")}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(notificationsOperationTypesDecoder,e.operation),r=operations$7[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}toApi(){const e={raise:this.raise.bind(this),requestPermission:this.requestPermission.bind(this),getPermission:this.getPermission.bind(this),list:this.list.bind(this),onRaised:this.onRaised.bind(this),onClosed:this.onClosed.bind(this),click:this.click.bind(this),clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearOld:this.clearOld.bind(this),configure:this.configure.bind(this),getConfiguration:this.getConfiguration.bind(this),getFilter:this.getFilter.bind(this),setFilter:this.setFilter.bind(this),setState:this.setState.bind(this),onConfigurationChanged:this.onConfigurationChanged.bind(this),onActiveCountChanged:this.onActiveCountChanged.bind(this),onCounterChanged:this.onActiveCountChanged.bind(this),onStateChanged:this.onStateChanged.bind(this)};return Object.freeze(e)}async getPermission(){return(await this.bridge.send("notifications",operations$7.getPermission,void 0)).permission}async requestPermission(){return(await this.bridge.send("notifications",operations$7.requestPermission,void 0)).permissionGranted}async raise(e){const t=runDecoderWithIOError$1(glue42NotificationOptionsDecoder$1,e);t.showToast="boolean"!=typeof t.showToast||t.showToast,t.showInPanel="boolean"!=typeof t.showInPanel||t.showInPanel;if(!await this.requestPermission())return ioError$1.raiseError("Cannot raise the notification, because the user has declined the permission request");const r=nanoid$1$1(10),n=await this.bridge.send("notifications",operations$7.raiseNotification,{settings:t,id:r}),i=this.buildNotificationFunc(n.settings,r);return this.notifications[r]=i,i}async list(){return(await this.bridge.send("notifications",operations$7.list,void 0,void 0,{includeOperationCheck:!0})).notifications}onRaised(e){return"function"!=typeof e?ioError$1.raiseError("onRaised expects a callback of type function"):this.registry.add("notification-raised",e)}onClosed(e){return"function"!=typeof e?ioError$1.raiseError("onClosed expects a callback of type function"):this.registry.add("notification-closed",e)}async click(e,t){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),t&&runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,t),await this.bridge.send("notifications",operations$7.click,{id:e,action:t},void 0,{includeOperationCheck:!0})}async clear(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),await this.bridge.send("notifications",operations$7.clear,{id:e},void 0,{includeOperationCheck:!0})}async clearAll(){await this.bridge.send("notifications",operations$7.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearOld(){await this.bridge.send("notifications",operations$7.clearOld,void 0,void 0,{includeOperationCheck:!0})}async configure(e){const t=runDecoderWithIOError$1(notificationsConfigurationDecoder$1,e);await this.bridge.send("notifications",operations$7.configure,{configuration:t},void 0,{includeOperationCheck:!0})}async getConfiguration(){return(await this.bridge.send("notifications",operations$7.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration}async getActiveCount(){try{return(await this.bridge.send("notifications",operations$7.getActiveCount,void 0,void 0,{includeOperationCheck:!0})).count}catch(e){return console.warn("Failed to get accurate active notifications count",e),0}}async getFilter(){return(await this.bridge.send("notifications",operations$7.getConfiguration,void 0,void 0,{includeOperationCheck:!0})).configuration.sourceFilter}async setFilter(e){const t=runDecoderWithIOError$1(notificationFilterDecoder$1,e);return await this.bridge.send("notifications",operations$7.configure,{configuration:{sourceFilter:t}},void 0,{includeOperationCheck:!0}),t}async setState(e,t){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),runDecoderWithIOError$1(notificationStateDecoder$1,t),await this.bridge.send("notifications",operations$7.setState,{id:e,state:t},void 0,{includeOperationCheck:!0})}onConfigurationChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"):(setTimeout(()=>e(this.notificationsConfiguration),0),this.registry.add("notifications-config-changed",e))}onActiveCountChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"):(setTimeout(()=>e({count:this.notificationsActiveCount}),0),this.registry.add("notifications-active-count-changed",e))}onStateChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"):this.registry.add("notification-state-changed",e)}addOperationExecutors(){operations$7.notificationShow.execute=this.handleNotificationShow.bind(this),operations$7.notificationClick.execute=this.handleNotificationClick.bind(this),operations$7.notificationRaised.execute=this.handleNotificationRaised.bind(this),operations$7.notificationClosed.execute=this.handleNotificationClosed.bind(this),operations$7.configurationChanged.execute=this.handleConfigurationChanged.bind(this),operations$7.activeCountChange.execute=this.handleActiveCountChanged.bind(this),operations$7.stateChange.execute=this.handleNotificationStateChanged.bind(this),operations$7.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$7)}async handleConfigurationChanged(e){this.notificationsConfiguration=e.configuration,this.registry.execute("notifications-config-changed",e.configuration)}async handleActiveCountChanged(e){this.notificationsActiveCount=e.count,this.registry.execute("notifications-active-count-changed",e)}async handleNotificationStateChanged(e){this.registry.execute("notification-state-changed",{id:e.id},e.state)}async handleNotificationShow(e){if(!e.id)return;const t=this.notifications[e.id];t&&t.onshow&&t.onshow()}async handleNotificationClick(e){if(!e.action&&this.notificationsSettings?.defaultClick&&this.notificationsSettings.defaultClick(this.coreGlue,e.definition),e.action&&this.notificationsSettings?.actionClicks?.some(t=>t.action===e.action)){const t=this.notificationsSettings?.actionClicks?.find(t=>t.action===e.action);t.handler(this.coreGlue,e.definition)}if(!e.id)return;const t=this.notifications[e.id];t&&t.onclick&&(t.onclick(),delete this.notifications[e.id])}async handleNotificationRaised(e){this.registry.execute("notification-raised",e.notification)}async handleNotificationClosed(e){this.registry.execute("notification-closed",e)}};const operations$6={getIntents:{name:"getIntents",resultDecoder:wrappedIntentsDecoder$1},findIntent:{name:"findIntent",dataDecoder:wrappedIntentFilterDecoder$1,resultDecoder:wrappedIntentsDecoder$1},raise:{name:"raise",dataDecoder:raiseIntentRequestDecoder$1,resultDecoder:intentResultDecoder$1},filterHandlers:{name:"filterHandlers",dataDecoder:filterHandlersWithResolverConfigDecoder$1,resultDecoder:filterHandlersResultDecoder$1},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:intentHandlerDecoder$1,resultDecoder:getIntentsResultDecoder$1}},GLUE42_FDC3_INTENTS_METHOD_PREFIX="Tick42.FDC3.Intents.",INTENTS_RESOLVER_APP_NAME="intentsResolver",DEFAULT_RESOLVER_RESPONSE_TIMEOUT=6e4,ADDITIONAL_BRIDGE_OPERATION_TIMEOUT=3e4,DEFAULT_PICK_HANDLER_BY_TIMEOUT=9e4;let IntentsController$1=class{bridge;logger;interop;appManagerController;windowsController;myIntents=new Set;prefsController;uiController;useIntentsResolverUI=!0;intentsResolverAppName;intentResolverResponseTimeout=DEFAULT_RESOLVER_RESPONSE_TIMEOUT;unregisterIntentPromises=[];async start(e,t){this.logger=e.logger.subLogger("intents.controller.web"),this.logger.trace("starting the web intents controller"),this.bridge=t.bridge,this.interop=e.interop,this.appManagerController=t.appManagerController,this.windowsController=t.windowsController,this.prefsController=t.prefsController,this.uiController=t.uiController,this.checkIfIntentsResolverIsEnabled(t.config);const r=this.toApi();this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"),e.intents=r}handlePlatformShutdown(){this.myIntents=new Set,this.unregisterIntentPromises=[]}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(intentsOperationTypesDecoder$1,e.operation),r=operations$6[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}toApi(){return{raise:this.raise.bind(this),all:this.all.bind(this),addIntentListener:this.addIntentListener.bind(this),register:this.register.bind(this),find:this.find.bind(this),filterHandlers:this.filterHandlers.bind(this),getIntents:this.getIntentsByHandler.bind(this),clearSavedHandlers:this.clearSavedHandlers.bind(this),onHandlerAdded:this.onHandlerAdded.bind(this),onHandlerRemoved:this.onHandlerRemoved.bind(this)}}async raise(e){const t=runDecoderWithIOError$1(raiseRequestDecoder,e),r="string"==typeof t?{intent:t}:t;await Promise.all(this.unregisterIntentPromises),r.clearSavedHandler&&(this.logger.trace(`User removes saved handler for intent ${r.intent}`),await this.removeRememberedHandler(r.intent));const n=await this.checkHandleRaiseWithRememberedHandler(r);if(n)return n;const i={intentRequest:r,resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:r}),embeddedResolverConfig:this.getEmbeddedResolverConfig()},o=r.waitUserResponseIndefinitely?MAX_SET_TIMEOUT_DELAY$1:(r.timeout||this.intentResolverResponseTimeout)+ADDITIONAL_BRIDGE_OPERATION_TIMEOUT;this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(e)} and method response timeout of ${o}ms`);const s=await this.bridge.send("intents",operations$6.raise,i,{methodResponseTimeoutMs:o,waitTimeoutMs:o});return this.logger.trace(`Raise operation completed with response: ${JSON.stringify(s)}`),s}getLegacyResolverConfigByRequest(e){if(e.handlerFilter)return{enabled:"boolean"==typeof e.handlerFilter?.openResolver?e.handlerFilter?.openResolver:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:e.handlerFilter?.timeout||DEFAULT_PICK_HANDLER_BY_TIMEOUT};const t=e.intentRequest?.waitUserResponseIndefinitely?MAX_SET_TIMEOUT_DELAY$1:this.intentResolverResponseTimeout;return{enabled:this.useIntentsResolverUI,appName:this.intentsResolverAppName,waitResponseTimeout:t}}getEmbeddedResolverConfig(){return{enabled:this.uiController.isIntentResolverEnabled(),initialCaller:{instanceId:this.interop.instance.instance}}}async all(){await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",operations$6.getIntents,void 0)).intents}addIntentListener(e,t){if(runDecoderWithIOError$1(AddIntentListenerDecoder,e),"function"!=typeof t)return ioError$1.raiseError("Cannot add intent listener, because the provided handler is not a function!");let r;const n="string"==typeof e?e:e.intent,i=this.buildInteropMethodName(n);if(this.myIntents.has(n))return ioError$1.raiseError(`Intent listener for intent ${n} already registered!`);this.myIntents.add(n);const o={unsubscribe:()=>{this.myIntents.delete(n),r.then(()=>this.interop.unregister(i)).catch(e=>this.logger.trace(`Unregistration of a method with name ${i} failed with reason: ${e}`))}};let s={};if("object"==typeof e){const{intent:t,...r}=e;s=r}return r=this.interop.register({name:i,flags:{intent:s}},e=>{if(this.myIntents.has(n)){const{_initialCallerId:r,...n}=e;return t(n)}}),r.catch(e=>{this.myIntents.delete(n),this.logger.warn(`Registration of a method with name ${i} failed with reason: ${e}`)}),o}async register(e,t){if(runDecoderWithIOError$1(AddIntentListenerDecoder,e),"function"!=typeof t)return ioError$1.raiseError("Cannot add intent listener, because the provided handler is not a function!");await Promise.all(this.unregisterIntentPromises);const r="string"==typeof e?e:e.intent,n=this.buildInteropMethodName(r);if(this.myIntents.has(r))return ioError$1.raiseError(`Intent listener for intent ${r} already registered!`);this.myIntents.add(r);let i={};if("object"==typeof e){const{intent:t,...r}=e;i=r}try{await this.interop.register({name:n,flags:{intent:i}},e=>{if(this.myIntents.has(r)){const{_initialCallerId:r,...n}=e,i=this.interop.servers().find(e=>e.instance===r);return t(n,i)}})}catch(e){return this.myIntents.delete(r),ioError$1.raiseError(`Registration of a method with name ${n} failed with reason: ${JSON.stringify(e)}`)}return{unsubscribe:()=>this.unsubscribeIntent(r)}}async find(e){let t;if(void 0!==e){const r=runDecoderWithIOError$1(findFilterDecoder,e);"string"==typeof r?t={filter:{name:r}}:"object"==typeof r&&(t={filter:r})}await Promise.all(this.unregisterIntentPromises);return(await this.bridge.send("intents",operations$6.findIntent,t)).intents}onHandlerAdded(e){if("function"!=typeof e)return ioError$1.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppAdded",e),r=this.subscribeForServerMethodEvent("serverMethodAdded",e);return()=>{t(),r()}}onHandlerRemoved(e){if("function"!=typeof e)return ioError$1.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!");const t=this.subscribeForAppEvent("onAppRemoved",e),r=this.subscribeForServerMethodEvent("serverMethodRemoved",e);return()=>{t(),r()}}subscribeForAppEvent(e,t){return this.appManagerController[e](e=>{const r=e.userProperties.intents;r?.length&&r.forEach(r=>{const n=this.buildIntentHandlerFromApp(e,r);t(n,r.name)})})}subscribeForServerMethodEvent(e,t){return this.interop[e](async({server:r,method:n})=>{if(!n.name.startsWith(GLUE42_FDC3_INTENTS_METHOD_PREFIX))return;const i=n.name.replace(GLUE42_FDC3_INTENTS_METHOD_PREFIX,""),o=await this.buildIntentHandlerFromServerMethod(e,r,n,i);t(o,i)})}buildIntentHandlerFromApp(e,t){return{applicationName:e.name,type:"app",applicationDescription:e.caption,applicationIcon:e.icon,applicationTitle:e.title,contextTypes:t.contexts,displayName:t.displayName,resultType:t.resultType,customConfig:t.customConfig}}async buildIntentHandlerFromServerMethod(e,t,r,n){const i=r.flags.intent,o=this.appManagerController.getApplication(t.application||t.applicationName);let s;"serverMethodAdded"===e&&t.windowId&&(s=await(this.windowsController.findById(t.windowId)?.getTitle()));const a=o?.userProperties?.intents?.find(e=>e.name===n);return{applicationName:t.application||t.applicationName||"",instanceId:t.windowId||t.instance,type:"instance",applicationIcon:i?.icon||o?.icon,applicationTitle:o?.title,applicationDescription:i?.description||o?.caption,contextTypes:i?.contextTypes||a?.contexts,instanceTitle:s,displayName:i?.displayName||a?.displayName,resultType:i?.resultType||a?.resultType,customConfig:i?.customConfig}}async clearSavedHandlers(){this.logger.trace("Removing all saved handlers from prefs storage for current app"),await this.prefsController.update({intents:void 0})}checkIfIntentsResolverIsEnabled(e){this.useIntentsResolverUI="boolean"!=typeof e.intents?.enableIntentsResolverUI||e.intents.enableIntentsResolverUI,this.intentsResolverAppName=e.intents?.intentsResolverAppName??INTENTS_RESOLVER_APP_NAME,this.intentResolverResponseTimeout=e.intents?.methodResponseTimeoutMs??DEFAULT_RESOLVER_RESPONSE_TIMEOUT}clearUnregistrationPromise(e){this.unregisterIntentPromises=this.unregisterIntentPromises.filter(t=>t!==e)}buildInteropMethodName(e){return`${GLUE42_FDC3_INTENTS_METHOD_PREFIX}${e}`}unsubscribeIntent(e){this.myIntents.delete(e);const t=this.buildInteropMethodName(e),r=this.interop.unregister(t);this.unregisterIntentPromises.push(r),r.then(()=>{this.clearUnregistrationPromise(r)}).catch(e=>{this.logger.error(`Unregistration of a method with name ${t} failed with reason: ${e}`),this.clearUnregistrationPromise(r)})}async filterHandlers(e){runDecoderWithIOError$1(handlerFilterDecoder$1,e),this.checkIfAtLeastOneFilterIsPresent(e);const t=this.getEmbeddedResolverConfig();if(e.openResolver&&!this.useIntentsResolverUI&&!t.enabled)return ioError$1.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled");const r=(e.timeout||DEFAULT_PICK_HANDLER_BY_TIMEOUT)+ADDITIONAL_BRIDGE_OPERATION_TIMEOUT,n={filterHandlersRequest:e,resolverConfig:this.getLegacyResolverConfigByRequest({handlerFilter:e}),embeddedResolverConfig:t};return await this.bridge.send("intents",operations$6.filterHandlers,n,{methodResponseTimeoutMs:r,waitTimeoutMs:r},{includeOperationCheck:!0})}checkIfAtLeastOneFilterIsPresent(e){const t="Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'";if(!Object.keys(e).length)return ioError$1.raiseError(t);const{intent:r,resultType:n,contextTypes:i,applicationNames:o}=e,s=i?.length,a=o?.length;return r||n||s||a?void 0:ioError$1.raiseError(t)}async getIntentsByHandler(e){runDecoderWithIOError$1(intentHandlerDecoder$1,e);return await this.bridge.send("intents",operations$6.getIntentsByHandler,e,void 0,{includeOperationCheck:!0})}async removeRememberedHandler(e){let t;this.logger.trace(`Removing saved handler from prefs storage for intent ${e}`);try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const r=t.data?.intents;if(!r)return void this.logger.trace("No app prefs found for current app");delete r[e];const n={...t.data,intents:r};try{await this.prefsController.update(n)}catch(e){return void this.logger.warn(`prefs.update() threw the following error: ${e}`)}this.logger.trace(`Handler saved choice for intent ${e} removed successfully`)}async checkForRememberedHandler(e){let t;try{t=await this.prefsController.get()}catch(e){return void this.logger.warn(`prefs.get() threw the following error: ${e}`)}const r=t.data?.intents?.[e.intent];return r?.handler}async checkHandleRaiseWithRememberedHandler(e){if(e.target)return;const t=await this.checkForRememberedHandler(e);if(!t)return;const r={intentRequest:{...e,target:{app:t.applicationName,instance:t.instanceId}},resolverConfig:this.getLegacyResolverConfigByRequest({intentRequest:e}),embeddedResolverConfig:this.getEmbeddedResolverConfig()};try{return await this.bridge.send("intents",operations$6.raise,r)}catch(t){this.logger.trace(`Could not raise intent to remembered handler. Reason: ${t}. Removing it from Prefs store`),await this.removeRememberedHandler(e.intent)}}};const operations$5={appHello:{name:"appHello",dataDecoder:channelsAppHelloDataDecoder,resultDecoder:channelsAppHelloSuccessDecoder},addChannel:{name:"addChannel",dataDecoder:channelDefinitionDecoder$2},removeChannel:{name:"removeChannel",dataDecoder:removeChannelDataDecoder$1},getMyChannel:{name:"getMyChannel",resultDecoder:getMyChanelResultDecoder$1},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",dataDecoder:getWindowIdsOnChannelDataDecoder$1,resultDecoder:getWindowIdsOnChannelResultDecoder$1},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",dataDecoder:wrappedWindowWithChannelFilterDecoder$1,resultDecoder:getWindowIdsWithChannelsResultDecoder$1},joinChannel:{name:"joinChannel",dataDecoder:joinChannelDataDecoder$1},restrict:{name:"restrict",dataDecoder:restrictionConfigDataDecoder$1},getRestrictions:{name:"getRestrictions",dataDecoder:getRestrictionsDataDecoder$1,resultDecoder:restrictionsDecoder$1},restrictAll:{name:"restrictAll",dataDecoder:restrictAllDataDecoder$1},notifyChannelsChanged:{name:"notifyChannelsChanged",dataDecoder:channelsChangedDataDecoder},leaveChannel:{name:"leaveChannel",dataDecoder:leaveChannelDataDecoder},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:requestChannelSelectorConfigDecoder$1},getMode:{name:"getMode",resultDecoder:getChannelsModeDecoder$1},operationCheck:{name:"operationCheck"}},DEFAULT_MODE="single",CHANNELS_PREFIX="___channel___",SUBS_KEY="subs",CHANGED_KEY="changed",CHANNELS_CHANGED="channels_changed",STORAGE_NAMESPACE="io_connect_channels",DEFAULT_STORAGE_MODE="inMemory";let ChannelsController$1=class{supportedOperationsNames=[];registry=CallbackRegistryFactory$1$1();logger;contexts;interop;bridge;windowsController;_mode;myWindowId;storage;handlePlatformShutdown(){this.registry.clear(),this.storage.clear()}addOperationsExecutors(){operations$5.getMyChannel.execute=this.handleGetMyChannel.bind(this),operations$5.joinChannel.execute=this.handleJoinChannel.bind(this),operations$5.leaveChannel.execute=this.handleLeaveChannel.bind(this),operations$5.restrict.execute=this.handleRestrict.bind(this),operations$5.getRestrictions.execute=({windowId:e})=>this.getRestrictions(e),operations$5.restrictAll.execute=this.handleRestrictAll.bind(this),operations$5.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$5)}async start(e,t){this.logger=e.logger.subLogger("channels.controller.web"),this.logger.trace("starting the web channels controller"),this.contexts=e.contexts,this.interop=e.interop,this.addOperationsExecutors(),this.bridge=t.bridge,this.windowsController=t.windowsController,this.storage=t.channelsStorage,this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"),this.myWindowId=this.windowsController.my().id??this.interop.instance.instance,await this.initialize();const r=this.toApi();e.channels=r}async postStart(e,t){try{await this.requestChannelSelector(e.appManager.myInstance)}catch(e){this.logger.warn(`Failed to display channel selector: ${extractErrorMsg$2(e)}`)}}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(channelsOperationTypesDecoder,e.operation),r=operations$5[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async list(){const e=this.getAllChannelNames();return await Promise.all(e.map(e=>this.get(e)))}my(){return this.current()}async handleGetMyChannel(){const e=this.my();return e?{channel:e}:{}}async join(e,t){const r=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(r),e),runDecoderWithIOError$1(optionalNonEmptyStringDecoder,t);const n={channel:e,windowId:t??this.myWindowId};await this.bridge.send("channels",operations$5.joinChannel,n,void 0,{includeOperationCheck:!0})}handleJoinChannel({channel:e}){return"single"===this._mode?this.switchToChannel(e):this.joinAdditionalChannel(e)}onChanged(e){return this.changed(e)}async leave(e={}){if(runDecoderWithIOError$1(leaveChannelsConfig,e),e.channel){const t=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(t),e.channel)}const t={channelName:e.channel,windowId:e.windowId??this.myWindowId};await this.bridge.send("channels",operations$5.leaveChannel,t,void 0,{includeOperationCheck:!0})}async handleAppManagerInitialChannelId(e){if("inMemory"!==this.storage.mode&&!this.storage.getSessionStorageData())return this.handleJoinChannel({channel:e,windowId:this.myWindowId})}async handleLeaveChannel({channelName:e}){const t=e?[e]:this.storage.channels;t.forEach(e=>this.storage.invokeUnsubscribes(e)),this.storage.channels=this.storage.channels.filter(e=>!t.includes(e)),this.executeChangedEvents(),await this.notifyChannelsChanged()}toApi(){const e={mode:this._mode,subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),publish:this.publish.bind(this),all:this.all.bind(this),list:this.list.bind(this),get:this.get.bind(this),getMyChannels:this.getMyChannels.bind(this),myChannels:this.myChannels.bind(this),onChannelsChanged:this.onChannelsChanged.bind(this),join:this.join.bind(this),leave:this.leave.bind(this),current:this.current.bind(this),my:this.my.bind(this),changed:this.changed.bind(this),onChanged:this.onChanged.bind(this),add:this.add.bind(this),remove:this.remove.bind(this),getMy:this.getMy.bind(this),getWindowsOnChannel:this.getWindowsOnChannel.bind(this),getWindowsWithChannels:this.getWindowsWithChannels.bind(this),restrict:this.restrict.bind(this),getRestrictions:this.getRestrictions.bind(this),restrictAll:this.restrictAll.bind(this),clearChannelData:this.clearChannelData.bind(this),setPath:this.setPath.bind(this),setPaths:this.setPaths.bind(this)};return Object.freeze(e)}createContextName(e){return`${CHANNELS_PREFIX}${e}`}getAllChannelNames(){return this.contexts.all().filter(e=>e.startsWith(CHANNELS_PREFIX)).map(e=>e.replace(CHANNELS_PREFIX,""))}async joinAdditionalChannel(e){if(this.storage.channels.includes(e))return;this.storage.channels=[...this.storage.channels,e];const t=this.createContextName(e),r=await this.contexts.subscribe(t,(e,t,r,n,i)=>{this.registry.execute(SUBS_KEY,e.data,e,t,i?.updaterId)});this.storage.addUnsubscribe(e,r),this.executeChangedEvents(e),await this.notifyChannelsChanged()}async switchToChannel(e){const t=this.storage.channels[0];if(e===t)return;this.storage.invokeUnsubscribes(t),this.storage.channels=[e];const r=this.createContextName(e),n=await this.contexts.subscribe(r,(e,t,r,n,i)=>{this.registry.execute(SUBS_KEY,e.data,e,t,i?.updaterId)});this.storage.addUnsubscribe(e,n),this.executeChangedEvents(e),await this.notifyChannelsChanged()}executeChangedEvents(e){this.registry.execute(CHANGED_KEY,e),this.registry.execute(CHANNELS_CHANGED,this.storage.channels)}async notifyChannelsChanged(){const e=this.windowsController.my().id;if(e)try{await this.bridge.send("channels",operations$5.notifyChannelsChanged,{channelNames:this.storage.channels,windowId:e},void 0,{includeOperationCheck:!0})}catch(e){this.logger.warn(`Failed to notify channel changed: ${extractErrorMsg$2(e)}`)}}async updateData(e,t){const r=this.createContextName(e),n=this.getFDC3Type(t);if(this.contexts.setPathSupported){const e=Object.keys(t).map(e=>({path:`data.${e}`,value:t[e]}));n&&e.push({path:latestFDC3Type,value:n}),await this.contexts.setPaths(r,e)}else n&&(t[latestFDC3Type]=n),await this.contexts.update(r,{data:t})}getFDC3Type(e){const t=Object.keys(e).filter(e=>0===e.indexOf("fdc3_"));if(0!==t.length)return t.length>1?ioError$1.raiseError("FDC3 does not support updating of multiple context keys"):t[0].split("_").slice(1).join("_")}subscribe(e,t){if("function"!=typeof e)return ioError$1.raiseError("Cannot subscribe to channels, because the provided callback is not a function!");t&&runDecoderWithIOError$1(fdc3OptionsDecoder,t);const r=this.current(),n=t?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(e,t.contextType):this.getWrappedSubscribeCallback(e);return r&&this.replaySubscribe(n,r),this.registry.add(SUBS_KEY,n)}async subscribeFor(e,t,r){const n=this.getAllChannelNames();if(runDecoderWithIOError$1(channelNameDecoder(n),e),"function"!=typeof t)return ioError$1.raiseError(`Cannot subscribe to channel ${e}, because the provided callback is not a function!`);r&&runDecoderWithIOError$1(fdc3OptionsDecoder,r);const i=this.createContextName(e),o=r?.contextType?this.getWrappedSubscribeCallbackWithFdc3Type(t,r.contextType):this.getWrappedSubscribeCallback(t);return this.contexts.subscribe(i,(e,t,r,n,i)=>{o(e.data,e,t,i?.updaterId)})}async publish(e,t){if("object"!=typeof e)return ioError$1.raiseError("Cannot publish to channel, because the provided data is not an object!");if(runDecoderWithIOError$1(publishOptionsDecoder,t),"object"==typeof t)return this.publishWithOptions(e,t);if("string"==typeof t){const e=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(e),t)}if(!t&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e);const r="string"==typeof t?t:this.storage.channels[0];if(!r)return ioError$1.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(r,"write")?this.updateData(r,e):ioError$1.raiseError(`Cannot publish on channel ${r} due to restrictions`)}async all(){return this.getAllChannelNames()}async get(e,t){const r=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(r),e),t&&runDecoderWithIOError$1(fdc3OptionsDecoder,t);const n=this.createContextName(e),i=await this.contexts.get(n);return t?.contextType?this.getContextForFdc3Type(i,t.contextType):i.latest_fdc3_type?this.getContextWithFdc3Data(i):i}async getMyChannels(){return Promise.all(this.storage.channels.map(e=>{const t=this.createContextName(e);return this.contexts.get(t)}))}myChannels(){return this.storage.channels}getContextForFdc3Type(e,t){const r=`fdc3_${t.split(".").join("&")}`;if(!e.data[r])return{name:e.name,meta:e.meta,data:{}};const n={type:t,...e.data[r]};return{name:e.name,meta:e.meta,data:{fdc3:n}}}getContextWithFdc3Data(e){const{latest_fdc3_type:t,...r}=e,n={type:t.split("&").join("."),...r.data[`fdc3_${t}`]};delete r.data[`fdc3_${t}`];return{name:e.name,meta:e.meta,data:{...r.data,fdc3:n}}}current(){return this.storage.channels[0]}changed(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"):this.registry.add(CHANGED_KEY,e)}async add(e){const t=runDecoderWithIOError$1(channelDefinitionDecoder$2,e);return this.getAllChannelNames().includes(t.name)?ioError$1.raiseError("There's an already existing channel with such name"):(await this.bridge.send("channels",operations$5.addChannel,t),{name:t.name,meta:t.meta,data:t.data||{}})}async remove(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e);if(!this.getAllChannelNames().includes(e))return ioError$1.raiseError("There's no channel with such name");await this.bridge.send("channels",operations$5.removeChannel,{name:e},void 0,{includeOperationCheck:!0})}replaySubscribe=(e,t)=>{this.get(t).then(t=>{if(!t)return;const r=this.createContextName(t.name);return this.contexts.subscribe(r,(t,r,n,i,o)=>{e(t.data,t,r,o?.updaterId)})}).then(e=>e?.()).catch(e=>this.logger.trace(e))};async getMy(e){if(this.storage.channels.length)return e&&runDecoderWithIOError$1(fdc3OptionsDecoder,e),this.get(this.storage.channels[this.storage.channels.length-1],e)}async getWindowsOnChannel(e){const t=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(t),e);const{windowIds:r}=await this.bridge.send("channels",operations$5.getWindowIdsOnChannel,{channel:e},void 0,{includeOperationCheck:!0});return r.reduce((e,t)=>{const r=this.windowsController.findById(t);return r?[...e,r]:e},[])}async getWindowsWithChannels(e){const t=void 0!==e?{filter:runDecoderWithIOError$1(windowWithChannelFilterDecoder$1,e)}:{},{windowIdsWithChannels:r}=await this.bridge.send("channels",operations$5.getWindowIdsWithChannels,t,void 0,{includeOperationCheck:!0}),n=r.reduce((e,{application:t,channel:r,windowId:n})=>{const i=this.windowsController.findById(n);return i?[...e,{application:t,channel:r,window:i}]:e},[]);return n}async clearChannelData(e){await this.handleSetPaths("clearChannelData",[{path:"data",value:{}},{path:"latest_fdc3_type",value:null}],e)}async restrict(e){runDecoderWithIOError$1(channelRestrictionsDecoder$1,e);const t=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(t),e.name);const r={config:{...e,windowId:e.windowId??this.myWindowId}};await this.bridge.send("channels",operations$5.restrict,r,void 0,{includeOperationCheck:!0})}async handleRestrict({config:e}){const t=await this.getMy();if(!t)return this.updateRestriction(e);const r=this.isAllowedByRestrictions(t.name,"read");this.updateRestriction(e);e.name===t.name&&!r&&e.read&&this.replaySubscribeCallback(e.name)}updateRestriction(e){const t=this.storage.restrictions.some(t=>t.name===e.name);this.storage.restrictions=t?this.storage.restrictions.map(t=>t.name===e.name?e:t):this.storage.restrictions.concat(e)}updateAllRestrictions(e){const t=this.getAllChannelNames();this.storage.restrictions=t.map(t=>({name:t,...e}))}async getRestrictions(e){runDecoderWithIOError$1(optionalNonEmptyStringDecoder,e);const t=e&&e!==this.interop.instance.instance;return e&&t?this.bridge.send("channels",operations$5.getRestrictions,{windowId:e},void 0,{includeOperationCheck:!0}):{channels:this.storage.restrictions}}async restrictAll(e){runDecoderWithIOError$1(restrictionsConfigDecoder$1,e);const t={restrictions:{...e,windowId:e.windowId??this.myWindowId}};return this.bridge.send("channels",operations$5.restrictAll,t,void 0,{includeOperationCheck:!0})}async handleRestrictAll({restrictions:e}){const t=await this.getMy();if(!t)return this.updateAllRestrictions(e);const r=this.isAllowedByRestrictions(t.name,"read");this.updateAllRestrictions(e),!r&&e.read&&this.replaySubscribeCallback(t.name)}async setPath(e,t){const r=runDecoderWithIOError$1(pathValueDecoder,e),n=[{path:`data.${r.path}`,value:r.value}];await this.handleSetPaths("setPath",n,t)}async setPaths(e,t){const r=runDecoderWithIOError$1(pathsValueDecoder,e).map(({path:e,value:t})=>({path:`data.${e}`,value:t}));await this.handleSetPaths("setPaths",r,t)}async handleSetPaths(e,t,r){const n=r?[r]:this.storage.channels;if(!n.length)return ioError$1.raiseError(`Cannot complete ${e} operation, because channel is not specified. Either join one or pass a channel name as second argument!`);this.validateChannelNames(n);const{allowed:i,forbidden:o}=this.groupChannelsByPermission("write",n);if(n.length===o.length)return ioError$1.raiseError(`Cannot complete ${e} operation due to write restrictions to the following channels: ${n.join(", ")}`);o.length&&this.logger.warn(`Cannot set paths on channel${o.length>1?"s":""}: ${o.join(", ")} due to write restrictions`),await Promise.all(i.map(e=>{const r=this.createContextName(e);return this.contexts.setPaths(r,t)}))}validateChannelNames(e){const t=this.getAllChannelNames();e.forEach(e=>runDecoderWithIOError$1(channelNameDecoder(t),e))}groupChannelsByPermission(e,t){return t.reduce((t,r)=>(this.isAllowedByRestrictions(r,e)?t.allowed.push(r):t.forbidden.push(r),t),{allowed:[],forbidden:[]})}isAllowedByRestrictions(e,t){const r=this.storage.restrictions.find(t=>t.name===e);return!r||r[t]}replaySubscribeCallback(e){const t=this.createContextName(e);this.contexts.subscribe(t,(e,t,r,n,i)=>{this.registry.execute(SUBS_KEY,e.data,e,t,i?.updaterId)}).then(e=>{e&&"function"==typeof e&&e()}).catch(e=>this.logger.error(e))}async publishWithOptions(e,t){if(t.name){const e=this.getAllChannelNames();runDecoderWithIOError$1(channelNameDecoder(e),t.name)}if(!t.name&&this.storage.channels.length>1)return this.publishOnMultipleChannels(e,t.fdc3);const r=t.name||this.storage.channels[0];if(!r)return ioError$1.raiseError("Cannot publish to channel, because not joined to a channel!");return this.isAllowedByRestrictions(r,"write")?t.fdc3?this.publishFdc3Data(r,e):this.updateData(r,e):ioError$1.raiseError(`Cannot publish on channel ${r} due to restrictions`)}async publishOnMultipleChannels(e,t){const{allowed:r,forbidden:n}=this.groupChannelsByPermission("write",this.storage.channels);if(this.storage.channels.length===n.length)return ioError$1.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`);n.length&&this.logger.warn(`Data on channel${n.length>1?"s":""}: ${n.join(", ")} won't be published due to write restrictions`);const i=t?this.publishFdc3Data.bind(this):this.updateData.bind(this);await Promise.all(r.map(t=>i(t,e)))}async publishFdc3Data(e,t){runDecoderWithIOError$1(fdc3ContextDecoder,t);const{type:r,...n}=t,i=r.split(".").join("&"),o={[`fdc3_${i}`]:n};return this.updateData(e,o)}getWrappedSubscribeCallback(e){return(t,r,n,i)=>{if(!this.isAllowedByRestrictions(r.name,"read"))return;const{data:o,latest_fdc3_type:s}=r,a=`fdc3_${s}`;if(!s||n.data&&!n.data[a])return void e(t,r,i);const c={type:s.split("&").join("."),...o[a]},{[a]:l,...u}=t;e({...u,fdc3:c},r,i)}}getWrappedSubscribeCallbackWithFdc3Type(e,t){const r={replayed:!1};return(n,i,o,s)=>{if(!this.isAllowedByRestrictions(i.name,"read"))return;const{data:a,latest_fdc3_type:c}=i,l=`fdc3_${t.split(".").join("&")}`;if(!a[l]||o.data&&!o.data[l])return;if(r.replayed)return this.parseDataAndInvokeSubscribeCallback({latestFdc3TypeEncoded:c,searchedType:t,callback:e,context:i,updaterId:s});const u={type:t,...a[l]};e({fdc3:u},i,s),r.replayed=!0}}parseDataAndInvokeSubscribeCallback(e){const{latestFdc3TypeEncoded:t,searchedType:r,callback:n,context:i,updaterId:o}=e;if(t.split("&").join(".")!==r)return;n({fdc3:{type:r,...i.data[`fdc3_${t}`]}},i,o)}async requestChannelSelector(e){if(!e)return;const t=e.application,r=t.userProperties?.details;if(!r)return;if(!r?.channelSelector?.enabled)return;const n={windowId:e.id,channelsNames:this.storage.channels};await this.bridge.send("channels",operations$5.requestChannelSelector,n,void 0,{includeOperationCheck:!0})}async getPlatformChannelsMode(){try{return(await this.bridge.send("channels",operations$5.getMode,{},void 0,{includeOperationCheck:!0})).mode}catch(e){return this.logger.warn(e?.message||JSON.stringify(e)),DEFAULT_MODE}}onChannelsChanged(e){return"function"!=typeof e?ioError$1.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"):this.registry.add(CHANNELS_CHANGED,e)}async initialize(){if(!await this.checkIfAppHelloSupported())return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions");const{success:e,error:t}=await this.sendAppHello();if(t)return this.handleAppHelloFailure(t);this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(e)}`);const{mode:r,channels:n,restrictions:i}=e;this.storage.mode="inMemory",this._mode=r,this.storage.channels=n,this.storage.restrictions=i}async handleAppHelloFailure(e){this.logger.trace(e),this.storage.mode="sessionStorage",this._mode=await this.getPlatformChannelsMode()}async sendAppHello(){try{return{success:await this.bridge.send("channels",operations$5.appHello,{windowId:this.myWindowId},void 0,{includeOperationCheck:!0}),error:void 0}}catch(e){return{error:`Failed to get initial state from platform. Error: ${extractErrorMsg$2(e)}`,success:void 0}}}async checkIfAppHelloSupported(){try{const{isSupported:e}=await this.bridge.send("channels",operations$5.operationCheck,{operation:operations$5.appHello.name},void 0,{includeOperationCheck:!0});return e}catch(e){return this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${extractErrorMsg$2(e)}`),!1}}};const operations$4={getEnvironment:{name:"getEnvironment",resultDecoder:anyDecoder$1},getBase:{name:"getBase",resultDecoder:anyDecoder$1},platformShutdown:{name:"platformShutdown"},isFdc3DataWrappingSupported:{name:"isFdc3DataWrappingSupported"},clientError:{name:"clientError",dataDecoder:clientErrorDataDecoder$1},systemHello:{name:"systemHello",resultDecoder:systemHelloSuccessDecoder$1},operationCheck:{name:"operationCheck"}};let SystemController$1=class{supportedOperationsNames=[];bridge;ioc;logger;errorPort=errorChannel$1.port2;async start(e,t){this.logger=e.logger.subLogger("system.controller.web"),this.logger.trace("starting the web system controller"),this.bridge=t.bridge,this.ioc=t,this.addOperationsExecutors();let r=!1;try{const e=await this.bridge.send("system",operations$4.systemHello,void 0,void 0,{includeOperationCheck:!0});r=e.isClientErrorOperationSupported}catch(e){this.logger.warn("The platform of this client is outdated and does not support some system operations.")}this.errorPort.onmessage=async e=>{r&&await this.bridge.send("system",operations$4.clientError,{message:e.data},void 0,{includeOperationCheck:!0})},await this.setEnvironment()}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(systemOperationTypesDecoder$1,e.operation),r=operations$4[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async processPlatformShutdown(){Object.values(this.ioc.controllers).forEach(e=>e.handlePlatformShutdown?e.handlePlatformShutdown():null),this.ioc.preferredConnectionController.stop(),this.ioc.eventsDispatcher.stop(),await this.bridge.stop()}async setEnvironment(){const e=await this.bridge.send("system",operations$4.getEnvironment,void 0),t=await this.bridge.send("system",operations$4.getBase,void 0),r=window.glue42core||window.iobrowser,n=window.glue42core?"glue42core":"iobrowser",i=Object.assign({},r,t,{environment:e});window[n]=i}addOperationsExecutors(){operations$4.platformShutdown.execute=this.processPlatformShutdown.bind(this),operations$4.isFdc3DataWrappingSupported.execute=this.handleIsFdc3DataWrappingSupported.bind(this),operations$4.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$4)}async handleIsFdc3DataWrappingSupported(){return{isSupported:!0}}},Notification$1=class{onclick=()=>{};onshow=()=>{};id;title;badge;body;data;dir;icon;image;lang;renotify;requireInteraction;silent;tag;timestamp;vibrate;clickInterop;actions;focusPlatformOnDefaultClick;severity;showToast;showInPanel;state;constructor(e,t){this.id=t,this.badge=e.badge,this.body=e.body,this.data=e.data,this.dir=e.dir,this.icon=e.icon,this.image=e.image,this.lang=e.lang,this.renotify=e.renotify,this.requireInteraction=e.requireInteraction,this.silent=e.silent,this.tag=e.tag,this.timestamp=e.timestamp,this.vibrate=e.vibrate,this.title=e.title,this.clickInterop=e.clickInterop,this.actions=e.actions,this.focusPlatformOnDefaultClick=e.focusPlatformOnDefaultClick,this.severity=e.severity,this.showToast=e.showToast,this.showInPanel=e.showInPanel,this.state=e.state}};oneOf$1$1(constant$2$1("clientHello"));const extensionConfigDecoder=object$2$1({widget:object$2$1({inject:boolean$2$1()})}),operations$3={clientHello:{name:"clientHello",resultDecoder:extensionConfigDecoder}};class ExtController{windowId;logger;bridge;eventsDispatcher;channelsController;config;channels=[];unsubFuncs=[];contentCommands={widgetVisualizationPermission:{name:"widgetVisualizationPermission",handle:this.handleWidgetVisualizationPermission.bind(this)},changeChannel:{name:"changeChannel",handle:this.handleChangeChannel.bind(this)}};handlePlatformShutdown(){this.unsubFuncs.forEach(e=>e()),this.channels=[],this.unsubFuncs=[]}async start(e,t){this.logger=e.logger.subLogger("extension.controller.web"),this.windowId=t.publicWindowId,this.logger.trace("starting the extension web controller"),this.bridge=t.bridge,this.channelsController=t.channelsController,this.eventsDispatcher=t.eventsDispatcher;try{await this.registerWithPlatform()}catch(e){return}this.channels=await this.channelsController.list();const r=this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)),n=this.channelsController.onChanged(e=>{this.eventsDispatcher.sendContentMessage({command:"channelChange",newChannel:e})});this.unsubFuncs.push(r),this.unsubFuncs.push(n)}async handleBridgeMessage(e){}handleContentMessage(e){if(!e||"string"!=typeof e.command)return;const t=this.contentCommands[e.command];t&&t.handle(e)}async registerWithPlatform(){this.logger.trace("registering with the platform"),this.config=await this.bridge.send("extension",operations$3.clientHello,{windowId:this.windowId}),this.logger.trace("the platform responded to the hello message with a valid extension config")}async handleWidgetVisualizationPermission(){if(!this.config?.widget.inject)return this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!1});const e=this.channels.find(e=>e.name===this.channelsController.my());this.eventsDispatcher.sendContentMessage({command:"permissionResponse",allowed:!0,channels:this.channels,currentChannel:e})}async handleChangeChannel(e){"no-channel"!==e.name?await this.channelsController.join(e.name):await this.channelsController.leave()}}class EventsDispatcher{config;glue;registry=CallbackRegistryFactory$1$1();glue42EventName="Glue42";_handleMessage;_resolveWidgetReadyPromise;_resolveModalsUIFactoryReadyPromise;_resolveIntentResolverUIFactoryReadyPromise;constructor(e){this.config=e}events={notifyStarted:{name:"notifyStarted",handle:this.handleNotifyStarted.bind(this)},contentInc:{name:"contentInc",handle:this.handleContentInc.bind(this)},requestGlue:{name:"requestGlue",handle:this.handleRequestGlue.bind(this)},widgetFactoryReady:{name:"widgetFactoryReady",handle:this.handleWidgetReady.bind(this)},modalsUIFactoryReady:{name:"modalsUIFactoryReady",handle:this.handleModalsUIFactoryReady.bind(this)},intentResolverUIFactoryReady:{name:"intentResolverUIFactoryReady",handle:this.handleIntentResolverUIFactoryReady.bind(this)}};stop(){window.removeEventListener(this.glue42EventName,this._handleMessage)}start(e){this.glue=e,this.wireCustomEventListener(),this.announceStarted()}sendContentMessage(e){this.send("contentOut","glue42core",e)}onContentMessage(e){return this.registry.add("content-inc",e)}async widgetReady(){const e=new Promise(e=>{this._resolveWidgetReadyPromise=e});return this.requestWidgetReady(),e}async modalsUIFactoryReady(){const e=new Promise(e=>{this._resolveModalsUIFactoryReadyPromise=e});return this.requestModalsUIFactoryReady(),e}async intentResolverUIFactoryReady(){const e=new Promise(e=>{this._resolveIntentResolverUIFactoryReadyPromise=e});return this.requestIntentResolverUIFactoryReady(),e}wireCustomEventListener(){this._handleMessage=this.handleMessage.bind(this),window.addEventListener(this.glue42EventName,this._handleMessage)}handleMessage(e){const t=e.detail,r=t?.glue42??t?.glue42core;if(!r)return;const n=r.event,i=this.events[n];i&&i.handle(r.message)}announceStarted(){this.send("start","glue42")}handleRequestGlue(){this.config.exposeAPI?this.send("requestGlueResponse","glue42",{glue:this.glue}):this.send("requestGlueResponse","glue42",{error:"Will not give access to the underlying Glue API, because it was explicitly denied upon initialization."})}handleNotifyStarted(){this.announceStarted()}handleContentInc(e){this.registry.execute("content-inc",e)}requestWidgetReady(){this.send(REQUEST_WIDGET_READY,"glue42")}handleWidgetReady(){this._resolveWidgetReadyPromise?.()}requestModalsUIFactoryReady(){this.send(REQUEST_MODALS_UI_FACTORY_READY,"glue42")}handleModalsUIFactoryReady(){this._resolveModalsUIFactoryReadyPromise?.()}requestIntentResolverUIFactoryReady(){this.send(REQUEST_INTENT_RESOLVER_UI_FACTORY_READY,"glue42")}handleIntentResolverUIFactoryReady(){this._resolveIntentResolverUIFactoryReadyPromise?.()}send(e,t,r){const n={};n[t]={event:e,message:r};const i=new CustomEvent(this.glue42EventName,{detail:n});window.dispatchEvent(i)}}let PreferredConnectionController$1=class{coreGlue;transactionTimeout=15e3;transactionLocks={};webPlatformTransport;webPlatformMessagesUnsubscribe;reconnectCounter=0;logger;constructor(e){this.coreGlue=e,this.logger=this.coreGlue.logger.subLogger("web.preferred.connection.controller")}stop(){this.webPlatformMessagesUnsubscribe&&this.webPlatformMessagesUnsubscribe()}async start(e){if(e.isPlatformInternal)return void this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic.");if(!(this.coreGlue.connection.transport.name()===webPlatformTransportName$1))return ioError$1.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport.");if(!this.coreGlue.connection.transport.isPreferredActivated)return void this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization.");this.webPlatformTransport=this.coreGlue.connection.transport,this.webPlatformMessagesUnsubscribe=this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this));const t=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(t)}handleWebPlatformMessage(e){if("string"==typeof e)return;const t=this.coreGlue.connection.transport.name()===webPlatformTransportName$1,r=e.type,n=e.args,i=e.transactionId;return r===Glue42CoreMessageTypes$1.transportSwitchRequest.name?this.handleTransportSwitchRequest(n,i):r!==Glue42CoreMessageTypes$1.platformUnload.name||t?r===Glue42CoreMessageTypes$1.getCurrentTransportResponse.name?this.handleGetCurrentTransportResponse(n,i):r===Glue42CoreMessageTypes$1.checkPreferredLogic.name?this.handleCheckPreferredLogic(i):r===Glue42CoreMessageTypes$1.checkPreferredConnection.name?this.handleCheckPreferredConnection(n,i):void 0:this.handlePlatformUnload()}async reEstablishPlatformPort(){try{await this.webPlatformTransport.connect()}catch(e){if(this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(e)}`),--this.reconnectCounter,this.reconnectCounter>0)return this.reEstablishPlatformPort();this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform.")}this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."),this.reconnectCounter=0,this.webPlatformTransport.close();const e=await this.getCurrentPlatformTransportState();await this.checkSwitchTransport(e)}async checkSwitchTransport(e){const t=this.coreGlue.connection.transport.name();if(t===e.transportName)return void this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary");this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${t}, but it should reconnect to ${JSON.stringify(e)}`);const r=await this.coreGlue.connection.switchTransport(e);this.setConnected(),this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(r)}`)}async getCurrentPlatformTransportState(){this.logger.trace("Requesting the current transport state of the platform.");const e=this.setTransaction(Glue42CoreMessageTypes$1.getCurrentTransport.name);this.sendPlatformMessage(Glue42CoreMessageTypes$1.getCurrentTransport.name,e.id);const t=await e.lock;return this.logger.trace(`The platform responded with transport state: ${JSON.stringify(t)}`),t}setTransaction(e){const t={},r=nanoid$1$1(10),n=new Promise((n,i)=>{let o=!0;t.lift=e=>{o=!1,delete this.transactionLocks[r],n(e)},t.fail=e=>{o=!1,delete this.transactionLocks[r],i(e)},setTimeout(()=>{o&&(o=!1,this.logger.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[r],i(`Transaction for operation: ${e} timed out.`))},this.transactionTimeout)});return t.lock=n,t.id=r,this.transactionLocks[r]=t,t}sendPlatformMessage(e,t,r){this.logger.trace(`Sending a platform message of type: ${e}, id: ${t} and args: ${JSON.stringify(r)}`),this.webPlatformTransport.sendObject({glue42core:{type:e,args:r,transactionId:t}})}handleTransportSwitchRequest(e,t){this.logger.trace(`Received a transport switch request with id: ${t} and data: ${JSON.stringify(e)}`),this.coreGlue.connection.switchTransport(e.switchSettings).then(e=>{this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(e)}`),this.setConnected(),this.sendPlatformMessage(Glue42CoreMessageTypes$1.transportSwitchResponse.name,t,{success:e.success})}).catch(e=>{this.logger.error(e),this.sendPlatformMessage(Glue42CoreMessageTypes$1.transportSwitchResponse.name,t,{success:!1})})}handlePlatformUnload(){this.reconnectCounter=5,this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."),this.reEstablishPlatformPort()}handleGetCurrentTransportResponse(e,t){this.logger.trace(`Got a current transport response from the platform with id: ${t} and data: ${JSON.stringify(e)}`);const r=e.transportState,n=this.transactionLocks[t];n?.lift(r)}handleCheckPreferredLogic(e){setTimeout(()=>this.sendPlatformMessage(Glue42CoreMessageTypes$1.checkPreferredLogicResponse.name,e),0)}handleCheckPreferredConnection(e,t){const r=e.url;this.logger.trace(`Testing the possible connection to: ${r}`),this.checkPreferredConnection(r).then(e=>{this.logger.trace(`The connection to ${r} is possible`),this.sendPlatformMessage(Glue42CoreMessageTypes$1.checkPreferredConnectionResponse.name,t,e)}).catch(e=>{this.logger.trace(`The connection to ${r} is not possible`),this.sendPlatformMessage(Glue42CoreMessageTypes$1.checkPreferredConnectionResponse.name,t,{error:e})})}checkPreferredConnection(e){return new Promise(t=>{const r=new WebSocket(e);r.onerror=()=>t({live:!1}),r.onopen=()=>{r.close(),t({live:!0})}})}setConnected(){this.webPlatformTransport.manualSetReadyState()}};const operations$2={getCurrent:{name:"getCurrent",resultDecoder:simpleThemeResponseDecoder$1},list:{name:"list",resultDecoder:allThemesResponseDecoder$1},select:{name:"select",dataDecoder:selectThemeConfigDecoder$1}};let ThemesController$1=class{logger;bridge;registry=CallbackRegistryFactory$1$1();themesSubscription;activeThemeSubs=0;async start(e,t){this.logger=e.logger.subLogger("themes.controller.web"),this.logger.trace("starting the web themes controller"),this.bridge=t.bridge;const r=this.toApi();e.themes=r,this.logger.trace("themes are ready")}handlePlatformShutdown(){this.registry.clear(),this.activeThemeSubs=0,this.themesSubscription?.close(),delete this.themesSubscription}async handleBridgeMessage(){}toApi(){const e={getCurrent:this.getCurrent.bind(this),list:this.list.bind(this),select:this.select.bind(this),onChanged:this.onChanged.bind(this)};return Object.freeze(e)}async getCurrent(){return(await this.bridge.send("themes",operations$2.getCurrent,void 0,void 0,{includeOperationCheck:!0})).theme}async list(){return(await this.bridge.send("themes",operations$2.list,void 0,void 0,{includeOperationCheck:!0})).themes}async select(e){runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),await this.bridge.send("themes",operations$2.select,{name:e},void 0,{includeOperationCheck:!0})}async onChanged(e){if("function"!=typeof e)return ioError$1.raiseError("onChanged requires a callback of type function");const t=this.themesSubscription?Promise.resolve():this.configureThemeSubscription();await t,++this.activeThemeSubs;const r=this.registry.add("on-theme-change",e);return()=>this.themeUnsub(r)}async configureThemeSubscription(){this.themesSubscription||(this.themesSubscription=await this.bridge.createNotificationsSteam(),this.themesSubscription.onData(e=>{const t=e.data,r=simpleThemeResponseDecoder$1.run(t);if(!r.ok)return void this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(r.error)}`);const n=r.result;this.registry.execute("on-theme-change",n.theme)}),this.themesSubscription.onClosed(()=>{this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"),this.registry.clear(),this.activeThemeSubs=0,delete this.themesSubscription}))}themeUnsub(e){e(),--this.activeThemeSubs,this.activeThemeSubs||(this.themesSubscription?.close(),delete this.themesSubscription)}};class ChannelsStorage{sessionStorage=window.sessionStorage;_mode=DEFAULT_STORAGE_MODE;inMemoryChannels=[];inMemoryRestrictions=[];_unsubscribeDict={};clear(){this._mode=DEFAULT_STORAGE_MODE,this.inMemoryChannels=[],this.inMemoryRestrictions=[],this._unsubscribeDict={},this.sessionStorage.setItem(STORAGE_NAMESPACE,JSON.stringify([]))}get mode(){return this._mode}set mode(e){this._mode=e}get channels(){return"inMemory"===this.mode?this.inMemoryChannels.slice():this.getSessionStorageData()?.channels??[]}set channels(e){"inMemory"===this.mode&&(this.inMemoryChannels=e),this.setSessionStorageChannels(e)}get restrictions(){return"inMemory"===this.mode?this.inMemoryRestrictions.slice():this.getSessionStorageData()?.restrictions??[]}set restrictions(e){"inMemory"===this.mode&&(this.inMemoryRestrictions=e),this.setSessionStorageRestrictions(e)}getSessionStorageData(){return JSON.parse(this.sessionStorage.getItem(STORAGE_NAMESPACE)||"null")}addUnsubscribe(e,t){this._unsubscribeDict[e]=t}invokeUnsubscribes(e){if(e)return this._unsubscribeDict[e]?.(),void delete this._unsubscribeDict[e];Object.values(this._unsubscribeDict).forEach(e=>e()),this._unsubscribeDict={}}setSessionStorageChannels(e){const t=this.getSessionStorageData();if(t?.channels)return t.channels=e,this.setSessionStorageData(t);const r={channels:e,restrictions:t?.restrictions??[]};return this.setSessionStorageData(r)}setSessionStorageRestrictions(e){const t=this.getSessionStorageData();if(t?.restrictions)return t.restrictions=e,this.setSessionStorageData(t);const r={channels:t?.channels??[],restrictions:e};return this.setSessionStorageData(r)}setSessionStorageData(e){this.sessionStorage.setItem(STORAGE_NAMESPACE,JSON.stringify(e))}}const operations$1={clear:{name:"clear",dataDecoder:basePrefsConfigDecoder$1},clearAll:{name:"clearAll"},get:{name:"get",dataDecoder:basePrefsConfigDecoder$1,resultDecoder:getPrefsResultDecoder$1},getAll:{name:"getAll",resultDecoder:getAllPrefsResultDecoder$1},set:{name:"set",dataDecoder:changePrefsDataDecoder$1},update:{name:"update",dataDecoder:changePrefsDataDecoder$1},prefsChanged:{name:"prefsChanged",dataDecoder:getPrefsResultDecoder$1},prefsHello:{name:"prefsHello",resultDecoder:prefsHelloSuccessDecoder$1},operationCheck:{name:"operationCheck"},registerSubscriber:{name:"registerSubscriber",dataDecoder:subscriberRegisterConfigDecoder$1}};let PrefsController$1=class{supportedOperationsNames=[];bridge;config;logger;appManagerController;platformAppName;registry=CallbackRegistryFactory$1$1();validNonExistentApps;signaledSubscription=!1;interopId;handlePlatformShutdown(){this.registry.clear()}async start(e,t){this.logger=e.logger.subLogger("prefs.controller.web"),this.logger.trace("starting the web prefs controller"),this.addOperationsExecutors(),this.interopId=e.interop.instance.instance,this.bridge=t.bridge,this.config=t.config,this.appManagerController=t.appManagerController;try{const e=await this.bridge.send("prefs",operations$1.prefsHello,void 0,void 0,{includeOperationCheck:!0});this.platformAppName=e.platform.app,this.validNonExistentApps=e.validNonExistentApps??[]}catch(e){return void this.logger.warn("The platform of this client is outdated and does not support Prefs API.")}this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning");const r=this.toApi();e.prefs=r}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(prefsOperationTypesDecoder$1,e.operation),r=operations$1[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async get(e){const t=null==e?this.getMyAppName():runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),{prefs:r}=await this.bridge.send("prefs",operations$1.get,{app:t},void 0,{includeOperationCheck:!0});return r}async update(e,t){const r=runDecoderWithIOError$1(optional$2$1(basePrefsConfigDecoder$1),t),n=r?.app??this.getMyAppName();await this.updateFor(n,e)}addOperationsExecutors(){operations$1.prefsChanged.execute=this.handleOnChanged.bind(this),operations$1.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),this.supportedOperationsNames=getSupportedOperationsNames(operations$1)}toApi(){return{clear:this.clear.bind(this),clearAll:this.clearAll.bind(this),clearFor:this.clearFor.bind(this),get:this.get.bind(this),getAll:this.getAll.bind(this),set:this.set.bind(this),setFor:this.setFor.bind(this),subscribe:this.subscribe.bind(this),subscribeFor:this.subscribeFor.bind(this),update:this.update.bind(this),updateFor:this.updateFor.bind(this)}}async clear(){const e=this.getMyAppName();await this.clearFor(e)}async clearAll(){await this.bridge.send("prefs",operations$1.clearAll,void 0,void 0,{includeOperationCheck:!0})}async clearFor(e){const t=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e);await this.bridge.send("prefs",operations$1.clear,{app:t},void 0,{includeOperationCheck:!0})}async getAll(){return await this.bridge.send("prefs",operations$1.getAll,void 0,void 0,{includeOperationCheck:!0})}async set(e,t){const r=runDecoderWithIOError$1(optional$2$1(basePrefsConfigDecoder$1),t),n=r?.app??this.getMyAppName();await this.setFor(n,e)}async setFor(e,t){const r=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),n=runDecoderWithIOError$1(object$2$1(),t);await this.bridge.send("prefs",operations$1.set,{app:r,data:n},void 0,{includeOperationCheck:!0})}subscribe(e){const t=this.getMyAppName();return this.subscribeFor(t,e)}subscribeFor(e,t){const r=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),n=this.appManagerController.getApplications();if(!(r===this.platformAppName||n.some(e=>e.name===r)||this.validNonExistentApps.includes(r)))return ioError$1.raiseError(`The provided app name "${e}" is not valid.`);if("function"!=typeof t)return ioError$1.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!");this.signaledSubscription||(this.bridge.send("prefs",operations$1.registerSubscriber,{interopId:this.interopId,appName:r},void 0,{includeOperationCheck:!0}).catch(e=>{this.logger.warn("Failed to register subscriber for prefs"),this.logger.error(e)}),this.signaledSubscription=!0);const i=this.getSubscriptionKey(r);return this.get(r).then(t),this.registry.add(i,t)}async updateFor(e,t){const r=runDecoderWithIOError$1(nonEmptyStringDecoder$2$1,e),n=runDecoderWithIOError$1(object$2$1(),t);await this.bridge.send("prefs",operations$1.update,{app:r,data:n},void 0,{includeOperationCheck:!0})}getMyAppName(){const e=this.config.isPlatformInternal?this.platformAppName:this.appManagerController.me?.application.name;return e||ioError$1.raiseError("App Preferences operations can not be executed for windows that do not have app!")}getSubscriptionKey(e){return`prefs-changed-${e}`}async handleOnChanged({prefs:e}){const t=this.getSubscriptionKey(e.app);this.registry.execute(t,e)}};const operations={getResources:{name:"getResources",dataDecoder:getResourcesDataDecoder$1,resultDecoder:getResourcesResultDecoder$1},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder$1,resultDecoder:operationCheckResultDecoder$1},showAlert:{name:"showAlert",dataDecoder:uiAlertRequestMessageDecoder$1},showDialog:{name:"showDialog",dataDecoder:uiDialogRequestMessageDecoder$1},alertInteropAction:{name:"alertInteropAction",dataDecoder:alertInteropActionDataDecoder$1},showResolver:{name:"showResolver",dataDecoder:uiResolverRequestMessageDecoder,resultDecoder:uiResolverResponseMessageDecoder}},DEFAULT_ALERT_TTL=5e3,MODALS_SHADOW_HOST_ID="io-modals-shadow-host",MODALS_ROOT_ELEMENT_ID="io-modals-root",WIDGET_SHADOW_HOST_ID="io-widget-shadow-host",WIDGET_ROOT_ELEMENT_ID="io-widget-root",INTENT_RESOLVER_SHADOW_HOST_ID="io-intent-resolver-shadow-host",INTENT_RESOLVER_ROOT_ELEMENT_ID="io-intent-resolver-root",SHADOW_ROOT_ELEMENT_CLASSNAME="io-body io-variables";let UIController$1=class{ioc;supportedOperationsNames=[];logger;bridge;config;zIndexDictionary={[WIDGET_SHADOW_HOST_ID]:"100",[MODALS_SHADOW_HOST_ID]:"101",[INTENT_RESOLVER_SHADOW_HOST_ID]:"100"};widgetResources;modalsResources;intentResolverResources;modalsUiApi;isDialogOpen=!1;intentResolverUiApi;isIntentResolverOpen=!1;constructor(e){this.ioc=e}async start(e,t){this.logger=e.logger.subLogger("ui.controller.web"),this.logger.trace("starting the ui controller"),this.bridge=t.bridge,this.config=t.config,this.addOperationsExecutors();const r=await this.getResources();r?(this.logger.trace(`Received UI resources from platform: ${JSON.stringify(r)}`),this.setResources(r)):this.logger.trace("No UI elements to display - platform is not initialized with any UI resources")}async handleBridgeMessage(e){const t=runDecoderWithIOError$1(uiOperationTypesDecoder$1,e.operation),r=operations[t];if(!r.execute)return;let n=e.data;return r.dataDecoder&&(n=runDecoderWithIOError$1(r.dataDecoder,e.data)),await r.execute(n)}async showComponents(e){const t=this.widgetResources?this.initializeWidget(e,this.widgetResources):Promise.resolve(),r=this.modalsResources?this.initializeModalsUi(e,this.modalsResources):Promise.resolve(),n=this.intentResolverResources?this.initializeIntentResolverUI(e,this.intentResolverResources):Promise.resolve();await Promise.all([this.config.widget.awaitFactory?t:Promise.resolve(),this.config.modals.awaitFactory?r:Promise.resolve(),this.config.intentResolver.awaitFactory?n:Promise.resolve()])}isIntentResolverEnabled(){return!!this.intentResolverResources&&this.config.intentResolver.enable}addOperationsExecutors(){operations.operationCheck.execute=async e=>handleOperationCheck(this.supportedOperationsNames,e.operation),operations.showAlert.execute=this.handleShowAlert.bind(this),operations.showDialog.execute=this.handleShowDialog.bind(this),operations.showResolver.execute=this.handleShowResolver.bind(this),this.supportedOperationsNames=getSupportedOperationsNames(operations)}async handleShowAlert({config:e}){if(!this.config.modals.alerts.enabled)return ioError$1.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return ioError$1.raiseError("Unable to perform showAlert operation because modalsUiApi is missing.");const{promise:r,resolve:n}=wrapPromise(),i=e=>{const t=alertOnClickConfigDecoder.run(e);if(!t.ok)return void this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(t.error)}.`);const{interopAction:r}=t.result;this.bridge.send("ui",operations.alertInteropAction,{interopAction:r},void 0,{includeOperationCheck:!0}).catch(e=>this.logger.warn(extractErrorMsg$2(e)))};let o;try{this.logger.trace(`Open alert with config: ${JSON.stringify(e)}`),o=t.alerts.open({...e,onClick:i,onClose:n})}catch(e){return ioError$1.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${extractErrorMsg$2(e)}.`)}const s=openAlertResultDecoder.run(o);if(!s.ok)return ioError$1.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(s.error)}.`);const a=setTimeout(()=>{n()},getSafeTimeoutDelay$1(e.ttl??DEFAULT_ALERT_TTL));r.then(()=>{clearTimeout(a);try{t.alerts.close({id:s.result.id})}catch(e){this.logger.warn(`Failed to close alert with id ${s.result.id}. Reason: ${extractErrorMsg$2(e)}`)}})}async handleShowDialog({config:e}){if(!this.config.modals.dialogs.enabled)return ioError$1.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config.");const t=this.modalsUiApi;if(!t)return ioError$1.raiseError("Unable to perform showDialog operation because modalsUiApi is missing.");if(this.isDialogOpen)return ioError$1.raiseError("Cannot open a dialog because another one is already open.");const{promise:r,resolve:n}=wrapPromise();let i;try{this.logger.trace(`Open dialog with config: ${JSON.stringify(e)}`),i=t.dialogs.open({...e,onCompletion:n})}catch(e){return ioError$1.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${extractErrorMsg$2(e)}.`)}const o=openDialogResultDecoder.run(i);if(!o.ok)return ioError$1.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(o.error)}.`);let s;this.isDialogOpen=!0,e.timer&&(s=setTimeout(()=>{n({response:{isExpired:!0}})},getSafeTimeoutDelay$1(e.timer.duration)));const a=await r;clearTimeout(s),this.isDialogOpen=!1;try{t.dialogs.close({id:o.result.id})}catch(e){this.logger.warn(`Failed to close dialog with id ${o.result.id}. Reason: ${extractErrorMsg$2(e)}`)}const c=dialogOnCompletionConfigDecoder.run(a);return c.ok?{result:c.result.response}:ioError$1.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async handleShowResolver({config:e}){if(this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(e)}`),!this.config.intentResolver.enable)return ioError$1.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config.");const t=this.intentResolverUiApi;if(!t)return ioError$1.raiseError("Unable to perform showResolver operation because intentResolverApi is missing.");if(this.isIntentResolverOpen)return ioError$1.raiseError("Cannot open the intent resolver because another one is already open.");const{promise:r,resolve:n}=wrapPromise();let i;try{this.logger.trace(`Open intent resolver with config: ${JSON.stringify(e)}`),i=t.open({...e,onUserResponse:n})}catch(e){return ioError$1.raiseError(`intentResolverUI.open() failed. Reason: ${extractErrorMsg$2(e)}.`)}const o=openResolverResultDecoder.run(i);if(!o.ok)return ioError$1.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(o.error)}.`);const s=setTimeout(()=>n({response:{isExpired:!0}}),getSafeTimeoutDelay$1(e.timeout)),a=await r;clearTimeout(s),this.isIntentResolverOpen=!1;try{t.close({id:o.result.id})}catch(e){this.logger.warn(`Failed to close intent resolver with id ${o.result.id}. Reason: ${extractErrorMsg$2(e)}`)}const c=onUserResponseResponseDecoder.run(a);return c.ok?{result:c.result.response}:ioError$1.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(c.error)}.`)}async getResources(){const e={origin:window.origin};try{return(await this.bridge.send("ui",operations.getResources,e,void 0,{includeOperationCheck:!0})).resources}catch(e){this.logger.warn(e?.message||JSON.stringify(e))}}appendModalsResources(e){return this.logger.trace("Appending modals resources"),this.appendResources(MODALS_SHADOW_HOST_ID,MODALS_ROOT_ELEMENT_ID,e.sources)}appendWidgetResources(e){return this.logger.trace("Appending widget resources"),this.appendResources(WIDGET_SHADOW_HOST_ID,WIDGET_ROOT_ELEMENT_ID,e.sources)}appendIntentResolverResources(e){return this.logger.trace("Appending intent resolver resources"),this.appendResources(INTENT_RESOLVER_SHADOW_HOST_ID,INTENT_RESOLVER_ROOT_ELEMENT_ID,e.sources)}appendResources(e,t,r){const{bundle:n,fonts:i=[],styles:o}=r,s=document.createElement("div");s.id=e,s.style.position="fixed",s.style.zIndex=this.zIndexDictionary[e];const a=s.attachShadow({mode:"open"}),c=document.createElement("script");c.src=n,c.type="module",a.appendChild(c);const l=document.createElement("div");return l.id=t,l.className=SHADOW_ROOT_ELEMENT_CLASSNAME,a.appendChild(l),o.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,a.appendChild(t)}),i.forEach(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=e,document.head.insertBefore(t,document.head.firstChild)}),document.body.appendChild(s),{rootElement:l}}async initializeWidget(e,t){this.logger.trace("Initializing IOBrowserWidget.");const{rootElement:r}=this.appendWidgetResources(t);this.subscribeForThemeChanges(e,r);const n={...deepmerge$1$1(t.config,this.config.widget),rootElement:r};return PromiseWrap$1(async()=>{await this.ioc.eventsDispatcher.widgetReady(),this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(n)}`),await window.IOBrowserWidget(e,n),this.logger.trace("IOBrowserWidget was initialized successfully.")},n.timeout,`Timeout of ${n.timeout}ms hit waiting for IOBrowserWidget to initialize.`)}async initializeModalsUi(e,t){this.logger.trace("Initializing IOBrowserModalsUI.");const{rootElement:r}=this.appendModalsResources(t);this.subscribeForThemeChanges(e,r);const n={...this.config.modals,rootElement:r};return PromiseWrap$1(async()=>{await this.ioc.eventsDispatcher.modalsUIFactoryReady(),this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(n)}`),this.modalsUiApi=await window.IOBrowserModalsUI(e,n),this.logger.trace("IOBrowserModalsUI was initialized successfully.")},n.timeout,`Timeout of ${n.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`)}async initializeIntentResolverUI(e,t){this.logger.trace("Initializing IOBrowserIntentResolverUI.");const{rootElement:r}=this.appendIntentResolverResources(t);this.subscribeForThemeChanges(e,r);const n={...this.config.intentResolver,rootElement:r},i=n.timeout;return PromiseWrap$1(async()=>{await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(),this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(n)}`),this.intentResolverUiApi=await window.IOBrowserIntentResolverUI(e,n),this.logger.trace("IOBrowserIntentResolverUI initialized successfully.")},i,`Timeout of ${i}ms hit waiting for IOBrowserIntentResolverUI to initialize.`)}setResources(e){this.setWidgetResources(e.widget),this.setModalsUiResources(e.modals),this.setIntentResolverResources(e.intentResolver)}setWidgetResources(e){const t="Widget won't be displayed. Reason: ",r=widgetConfigDecoder$1.run(this.config.widget);r.ok?this.config.widget.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`):this.widgetResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'widget: { enable: false }' config`):this.logger.warn(`${t} invalid widget config. Error: ${r.error}`)}setModalsUiResources(e){const t="Modals won't be displayed. Reason: ",r=modalsConfigDecoder$1.run(this.config.modals);r.ok?this.config.modals.alerts.enabled||this.config.modals.dialogs.enabled?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`):this.modalsResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`):this.logger.warn(`${t} invalid modals config. Error: ${r.error}`)}setIntentResolverResources(e){const t="Intent Resolver UI won't be displayed. Reason: ",r=intentResolverConfigDecoder$1.run(this.config.intentResolver);r.ok?this.config.intentResolver.enable?e?e.blockedOrigin?this.logger.warn(`${t} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`):this.intentResolverResources=e:this.logger.trace(`${t} Platform did not provide resources`):this.logger.trace(`${t} Client initialized with 'intentResolver: { enable: false }' config`):this.logger.warn(`${t} invalid intent resolver config. Error: ${JSON.stringify(r.error)}`)}subscribeForThemeChanges(e,t){const r=e.themes;if(!r)return;const n=async e=>{if(t.classList.contains(e.name))return;const n=await r.list();t.classList.remove(...n.map(({name:e})=>e)),t.classList.add(e.name)};r.onChanged(n),r.getCurrent().then(n)}},IoC$3=class{_coreGlue;_communicationId;_publicWindowId;_webConfig;_windowsControllerInstance;_appManagerControllerInstance;_layoutsControllerInstance;_notificationsControllerInstance;_intentsControllerInstance;_channelsControllerInstance;_themesControllerInstance;_extensionController;_systemControllerInstance;_bridgeInstance;_eventsDispatcher;_preferredConnectionController;_channelsStorage;_prefsControllerInstance;_uiController;controllers={windows:this.windowsController,appManager:this.appManagerController,layouts:this.layoutsController,notifications:this.notificationsController,intents:this.intentsController,channels:this.channelsController,system:this.systemController,extension:this.extensionController,themes:this.themesController,prefs:this.prefsController,ui:this.uiController};get communicationId(){return this._communicationId}get publicWindowId(){return this._publicWindowId}get windowsController(){return this._windowsControllerInstance||(this._windowsControllerInstance=new WindowsController$1),this._windowsControllerInstance}get uiController(){return this._uiController||(this._uiController=new UIController$1(this)),this._uiController}get appManagerController(){return this._appManagerControllerInstance||(this._appManagerControllerInstance=new AppManagerController),this._appManagerControllerInstance}get layoutsController(){return this._layoutsControllerInstance||(this._layoutsControllerInstance=new LayoutsController$1),this._layoutsControllerInstance}get themesController(){return this._themesControllerInstance||(this._themesControllerInstance=new ThemesController$1),this._themesControllerInstance}get notificationsController(){return this._notificationsControllerInstance||(this._notificationsControllerInstance=new NotificationsController$1),this._notificationsControllerInstance}get intentsController(){return this._intentsControllerInstance||(this._intentsControllerInstance=new IntentsController$1),this._intentsControllerInstance}get systemController(){return this._systemControllerInstance||(this._systemControllerInstance=new SystemController$1),this._systemControllerInstance}get channelsController(){return this._channelsControllerInstance||(this._channelsControllerInstance=new ChannelsController$1),this._channelsControllerInstance}get prefsController(){return this._prefsControllerInstance||(this._prefsControllerInstance=new PrefsController$1),this._prefsControllerInstance}get extensionController(){return this._extensionController||(this._extensionController=new ExtController),this._extensionController}get eventsDispatcher(){return this._eventsDispatcher||(this._eventsDispatcher=new EventsDispatcher(this.config)),this._eventsDispatcher}get bridge(){return this._bridgeInstance||(this._bridgeInstance=new GlueBridge(this._coreGlue,this.communicationId)),this._bridgeInstance}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new PreferredConnectionController$1(this._coreGlue)),this._preferredConnectionController}get channelsStorage(){return this._channelsStorage||(this._channelsStorage=new ChannelsStorage),this._channelsStorage}get config(){return this._webConfig}defineGlue(e){this._coreGlue=e,this._publicWindowId=e.connection.transport.publicWindowId;const t=window.glue42core||window.iobrowser;this._communicationId=e.connection.transport.communicationId||t.communicationId}defineConfig(e){this._webConfig=e}async buildWebWindow(e,t,r){const n=new WebWindowModel(e,t,this.bridge,r),i=await n.toApi();return{id:e,model:n,api:i}}buildNotification(e,t){return new Notification$1(e,t)}async buildApplication(e,t){const r=new ApplicationModel(e,[],this.appManagerController).toApi(),n=t.map(e=>this.buildInstance(e,r));return r.instances.push(...n),r}buildInstance(e,t){return new InstanceModel(e,this.bridge,t).toApi()}};var version$1$1="4.2.4";const setupGlobalSystem=(e,t)=>({getContainerInfo:async()=>{if(window!==window.parent)return window.name.includes("#wsp")?{workspaceFrame:{id:"N/A"}}:window.parent===window.top?{top:{}}:{parent:{}}},getProfileData:async()=>{if(!t)throw new Error("Bridge is not available and cannot fetch the profile data");return await t.send("system",{name:"getProfileData"},void 0)}}),createFactoryFunction=e=>{let t;return r=>{if(window.glue42gd||window.iodesktop)return enterprise(r);const n=parseConfig(r);try{checkSingleton$1()}catch(e){return void 0===t?Promise.reject(new Error(e)):t}const i=(async t=>{const r=new IoC$3,n=await PromiseWrap$1(()=>e(t,{version:version$1$1}),3e4,"Glue Web initialization timed out, because core didn't resolve"),i=n.logger.subLogger("web.main.controller");r.defineGlue(n),await r.preferredConnectionController.start(t),await r.bridge.start(r.controllers),r.defineConfig(t),i.trace("the bridge has been started, initializing all controllers"),await Promise.all(Object.values(r.controllers).map(e=>e.start(n,r))),i.trace("all controllers reported started, starting all additional libraries");try{return await Promise.all(t.libraries.map(e=>e(n,t))),i.trace("all libraries were started"),r.eventsDispatcher.start(n),i.trace("start event dispatched, glue is ready, returning it"),await r.uiController.showComponents(n).catch(e=>i.warn(e?.message?e.message:JSON.stringify(e))),await Promise.all(Object.values(r.controllers).map(e=>e.postStart?e.postStart(n,r):Promise.resolve())),window.iobrowser.system=setupGlobalSystem(n,r.bridge),window.iobrowser=Object.freeze({...window.iobrowser}),n}catch(e){return ioError$1.raiseError(e,!0)}})(n);return t=r?.memoizeAPI?i:void 0,i}};var MetricTypes$1={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function getMetricTypeByValue$1(e){return e.type===MetricTypes$1.TIMESTAMP?"timestamp":e.type===MetricTypes$1.NUMBER?"number":e.type===MetricTypes$1.STRING?"string":e.type===MetricTypes$1.OBJECT?"object":"unknown"}function getTypeByValue$1(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function serializeMetric$1(e){const t={},r=getMetricTypeByValue$1(e);if("object"===r){const r=Object.keys(e.value).reduce((t,r)=>{const n=getTypeByValue$1(e.value[r]);if("object"===n){const n=defineNestedComposite$1(e.value[r]);t[r]={type:"object",description:"",context:{},composite:n}}else t[r]={type:n,description:"",context:{}};return t},{});t.composite=r}return t.name=normalizeMetricName$1(e.path.join("/")+"/"+e.name),t.type=r,t.description=e.description,t.context={},t}function defineNestedComposite$1(e){return Object.keys(e).reduce((t,r)=>{const n=getTypeByValue$1(e[r]);return t[r]="object"===n?{type:"object",description:"",context:{},composite:defineNestedComposite$1(e[r])}:{type:n,description:"",context:{}},t},{})}function normalizeMetricName$1(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function getMetricValueByType$1(e){return"timestamp"===getMetricTypeByValue$1(e)?Date.now():publishNestedComposite$1(e.value)}function publishNestedComposite$1(e){return"object"!=typeof e?e:Object.keys(e).reduce((t,r)=>{const n=e[r];return"object"==typeof n&&n.constructor!==Date?t[r]=publishNestedComposite$1(n):n.constructor===Date?t[r]=new Date(n).getTime():n.constructor===Boolean?t[r]=n.toString():t[r]=n,t},{})}function flatten$1(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?flatten$1(t):t),[])}function getHighestState$1(e){return e.sort((e,t)=>e.state?t.state?t.state-e.state:-1:1)[0]}function aggregateDescription$1(e){let t="";return e.forEach((e,r,n)=>{const i=e.path.join(".");r===n.length-1?t+=i+"."+e.name+": "+e.description:t+=i+"."+e.name+": "+e.description+","}),t.length>100?t.slice(0,100)+"...":t}function composeMsgForRootStateMetric$1(e){const t=flatten$1(e.root.getAggregateState()),r=getHighestState$1(t);return{description:aggregateDescription$1(t),value:r.state}}function gw3$1(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let r,n;const i=e=>{o(e.root)},o=e=>{s(e),e.metrics.forEach(e=>{a(e)}),e.subSystems.forEach(e=>{o(e)})},s=async e=>{if(void 0===e.parent)return;await r;const i={type:"define",metrics:[{name:normalizeMetricName$1(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};n.sendFireAndForget(i).catch(r=>{t.logger.warn(`Failed to send define for system state metric of ${e.name}: ${JSON.stringify(r)}`)})},a=async e=>{const i=l(e);await r;const o={type:"define",metrics:[serializeMetric$1(i)]};n.sendFireAndForget(o).catch(r=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(r)}`)}),void 0!==i.value&&c(i)},c=e=>{if(u()){const r=getMetricValueByType$1(e),i={type:"publish",values:[{name:normalizeMetricName$1(e.path.join("/")+"/"+e.name),value:r,timestamp:Date.now()}]};return n.sendFireAndForget(i).catch(r=>{t.logger.warn(`Failed to publish metric ${e.name}: ${JSON.stringify(r)}`)})}return Promise.resolve()},l=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},u=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:o=>{let s;r=new Promise(e=>{s=e}),n=e.domain("metrics"),n.onJoined(e=>{!e&&s&&(s(),s=void 0);const r={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};n.sendFireAndForget(r).catch(e=>{t.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(e)}`)}),e&&i(o)}),n.join({system:t.system,service:t.service,instance:t.instance})},createSystem:s,updateSystem:async(i,o)=>{await r;const s={type:"publish",values:[{name:normalizeMetricName$1(i.path.join("/")+"/"+i.name+"/State"),value:{Description:o.description,Value:o.state},timestamp:Date.now()}]};n.sendFireAndForget(s).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${i.name}: ${JSON.stringify(e)}`)});const a=composeMsgForRootStateMetric$1(i),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};n.sendFireAndForget(c).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${i.name}: ${JSON.stringify(e)}`)})},createMetric:a,updateMetric:async e=>{const t=l(e);await r,c(t)}}}var Helpers$1={validate:(e,t,r)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===r||"object"!=typeof r)throw new Error("Missing transport")}};let BaseMetric$1=class{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,r,n,i){this.definition=e,this.system=t,this.transport=r,this.value=n,this.type=i,Helpers$1.validate(e,t,r),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,r.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}},NumberMetric$1=class extends BaseMetric$1{constructor(e,t,r,n){super(e,t,r,n,MetricTypes$1.NUMBER)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}},ObjectMetric$1=class extends BaseMetric$1{constructor(e,t,r,n){super(e,t,r,n,MetricTypes$1.OBJECT)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach(t=>{void 0!==e[t]&&(this.value[t]=e[t])})}},StringMetric$1=class extends BaseMetric$1{constructor(e,t,r,n){super(e,t,r,n,MetricTypes$1.STRING)}},TimestampMetric$1=class extends BaseMetric$1{constructor(e,t,r,n){super(e,t,r,n,MetricTypes$1.TIMESTAMP)}now(){this.update(new Date)}};function system$1(e,t,r,n,i){if(!t)throw new Error("Repository is required");if(!r)throw new Error("Transport is required");const o=r,s=e,a=i||"",c=t,l=n,u=function e(t){if(!t||!t.parent)return[];const r=e(t.parent);return r.push(t.name),r}(n);let d={};const h=(g="/",((p=u)&&p.length>0?p.join(g):"")+e);var p,g;const m=t.root,f=[],y=[];function $(e,t,r,n){let i={name:""};i="string"==typeof e?{name:e}:e;const o=y.filter(e=>e.name===i.name);if(o.length>0){const e=o[0];if(e.type!==t)throw new Error(`A metric named ${i.name} is already defined with different type.`);return void 0!==r&&e.update(r).catch(()=>{}),e}const s=n(i);return y.push(s),s}const b={get name(){return s},get description(){return a},get repo(){return c},get parent(){return l},path:u,id:h,root:m,get subSystems(){return f},get metrics(){return y},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const r=f.filter(t=>t.name===e);if(r.length>0)return r[0];const n=system$1(e,c,o,b,t);return f.push(n),n},getState:()=>d,setState:function(e,t){d={state:e,description:t},o.updateSystem(b,d)},stringMetric:function(e,t){return $(e,MetricTypes$1.STRING,t,e=>new StringMetric$1(e,b,o,t))},timestampMetric:function(e,t){return $(e,MetricTypes$1.TIMESTAMP,t,e=>new TimestampMetric$1(e,b,o,t))},objectMetric:function(e,t){return $(e,MetricTypes$1.OBJECT,t,e=>new ObjectMetric$1(e,b,o,t))},numberMetric:function(e,t){return $(e,MetricTypes$1.NUMBER,t,e=>new NumberMetric$1(e,b,o,t))},getAggregateState:function(){const e=[];return Object.keys(d).length>0&&e.push({name:s,path:u,state:d.state,description:d.description}),f.forEach(t=>{const r=t.getAggregateState();r.length>0&&e.push(...r)}),e}};return o.createSystem(b),b}let Repository$1=class{root;constructor(e,t){t.init(this),this.root=system$1("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),r=e=>{if(!e.target)return;const r=e.target,n=r?r.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:n,id:r.id,type:"<"+r.tagName.toLowerCase()+">",href:r.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",r):document.attachEvent("onclick",r)}e.stringMetric("StartTime",(new Date).toString());const r=e.stringMetric("StartURL",""),n=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;r.update(e)}void 0!==window.glue42gd&&n.update(window.glue42gd.appName)}}},NullProtocol$1=class{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}},PerfTracker$1=class{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,r){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=r??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout(()=>{this.collect(),setInterval(()=>{this.collect()},this.publishInterval)},this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map(e=>e.toJSON());this.system.stringMetric("entries",JSON.stringify(t))}};var metrics$2=e=>{let t;t=e.connection&&"object"==typeof e.connection?gw3$1(e.connection,e):new NullProtocol$1;let r=new Repository$1(e,t).root;e.disableAutoAppSystem||(r=r.subSystem("App"));const n=addFAVSupport$1(r);return initPerf$1(n,e.pagePerformanceMetrics),n};function initPerf$1(e,t){if("undefined"==typeof window)return;const r=window?.glue42gd?.metrics?.pagePerformanceMetrics;r&&(t=r),t?.enabled&&new PerfTracker$1(e,t.initialPublishTimeout,t.publishInterval)}function addFAVSupport$1(e){const t=e.subSystem("reporting"),r={name:"features"};let n;return e.featureMetric=(e,i,o)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===i||""===i)throw new Error("action is mandatory");if(void 0===o||""===o)throw new Error("payload is mandatory");n?n.update({name:e,action:i,payload:o}):n=t.objectMetric(r,{name:e,action:i,payload:o})},e}var commonjsGlobal$2="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$3(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createRegistry$3(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;i{this.messageHandler(t)}).then(e=>{this.client=e})}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}},SharedWorkerTransport$1=class{logger;worker;registry=CallbackRegistryFactory$3();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}},Utils$1=class e{static isNode(){if(void 0!==e._isNode)return e._isNode;if("undefined"!=typeof window)return e._isNode=!1,!1;try{e._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(t){e._isNode=!1}return e._isNode}static _isNode},PromiseWrapper$2=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve;reject;promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};const timers$1={};function getAllTimers$1(){return timers$1}function timer$1(e){const t=timers$1[e];if(t)return t;const r=[];function n(){return(new Date).getTime()}const i=n();let o,s;function a(e,t){const i=t??n();let o=0;r.length>0&&(o=i-r[r.length-1].time),r.push({name:e,time:i,diff:o})}a("start",i);const c={get startTime(){return i},get endTime(){return o},get period(){return s},stop:function(){return o=n(),a("end",o),s=o-i,s},mark:a,marks:r};return timers$1[e]=c,c}const WebSocketConstructor$1=Utils$1.isNode()?null:window.WebSocket;let WS$1=class{ws;logger;settings;startupTimer=timer$1("connection");_running=!0;_registry=CallbackRegistryFactory$3();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise((t,r)=>{this.waitForSocketConnection(()=>{try{this.ws?.send(e),t()}catch(e){r(e)}},r)})}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise((e,t)=>{this.waitForSocketConnection(e,t)})}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new PromiseWrapper$2;return this.waitForSocketConnection(()=>{e.resolve()}),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout(()=>{const r=void 0===t?void 0:t-1;this.openSocket(e,r)},e)}}initiateSocket(){const e=new PromiseWrapper$2;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new WebSocketConstructor$1(this.settings.ws??"");let t=!1;return this.ws.onerror=r=>{let n;try{n=JSON.stringify(r)}catch(e){const t=new WeakSet,i=(e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r instanceof Error?{message:r.message,name:r.name,stack:r.stack}:r};n=JSON.stringify(r,i)}this.logger.info(`ws error - reason: ${n}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error")),this.notifyStatusChanged(!1,n)},this.ws.onclose=r=>{this.logger.info(`ws closed - code: ${r?.code} reason: ${r?.reason}`),e.reject("closed"),t&&(t=!1,this.notifyForSocketState("closed")),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),t=!0,this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach(t=>{e?t.failed&&t.failed(e):t.callback()}),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}},MessageReplayerImpl$1=class{specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const r of this.specs[t].types){let t=this.subsRefCount[r];if(t||(t=0),t+=1,this.subsRefCount[r]=t,t>1)continue;const n=e.on(r,e=>this.processMessage(r,e));this.subs[r]=n}}processMessage(e,t){if(!this.isDone&&t)for(const r of this.specsNames)if(-1!==this.specs[r].types.indexOf(e)){const e=this.messages[r]||[];this.messages[r]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}},urlAlphabet$4="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$6=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$4[64*Math.random()|0];return t};const PromisePlus$2=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});let WebPlatformTransport$1=class{settings;logger;identity;isPreferredActivated;_connectionProtocolVersion;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=CallbackRegistryFactory$3();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:()=>{}},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,r){this.settings=e,this.logger=t,this.identity=r,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId||"unknown"}, client connected: ${this.iAmConnected}`);const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=r=>{if(this.iAmConnected&&!r.data?.glue42core)return void this.registry.execute("onMessage",r.data);const n=r.data?.glue42core;n&&(n.type===this.messages.gatewayInternalConnect.name&&n.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),n.type===this.messages.gatewayInternalConnect.name&&n.error&&t(n.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))})}initiateRemoteConnection(e){return PromisePlus$2((t,r)=>{this.connectionResolve=t,this.connectionReject=r,this.myClientId=this.myClientId??nanoid$6(10);const n=this.getMyWindowId()||nanoid$6(10),i={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:n,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug(`sending connection request - clientId: ${this.myClientId}`),this.extContentConnecting)return i.glue42core.clientType="child",i.glue42core.bridgeInstanceId=this.myClientId,i.glue42core.parentWindowId=this.parentWindowId,window.postMessage(i,window.origin);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(i,this.defaultTargetString)},this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):(this.logger.debug("setting up window message listener"),window.addEventListener("message",e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const r=this.settings.allowedOrigins||[];if(r.length&&!r.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const n=t.type;this.logger.debug(`received valid glue42core message of type: ${n}`),this.messages[n].handle(e)}))}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):(this.logger.debug("setting up unload event listeners"),window.addEventListener("beforeunload",()=>{this._connectionProtocolVersion||this.signalClientDisappearing()}),window.addEventListener("pagehide",()=>{this._connectionProtocolVersion&&this.signalClientDisappearing()}))}signalClientDisappearing(){if(this.extContentConnected)return;this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`);const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent?.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId!==t.clientId?this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${t.clientId}`):this.handleAcceptanceOfMyRequest(t)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this._connectionProtocolVersion=e.connectionProtocolVersion,this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||nanoid$6(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",e=>{const t=e.data?.glue42ExtInc;if(!t)return;const r=this.settings.allowedOrigins||[];!r.length||r.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)}),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleConnectionRejected(e){if(this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"),!this.connectionReject)return;const t="string"==typeof e.data.glue42core?.error?`Connection was rejected. ${e.data.glue42core?.error}`:"The platform connection was rejected. Most likely because this window was not created by a glue API call";this.connectionReject(t),delete this.connectionReject}handleConnectionRequest(){this.extContentConnecting&&this.logger.debug("This connection request event is targeted at the extension content")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const r=e.source;this.logger.debug("responding to a parent ping with a ready message"),r.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.logger.debug("setting up platform unload listener"),this.onMessage(e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))})}handleManualUnload(){this.logger.debug("handling manual unload");const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);this.port?.postMessage(e)}handlePlatformPing(){}notifyStatusChanged(e,t){this.logger.debug(`status changed - connected: ${e}, reason: ${t||"none"}`),this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}requestConnectionPermissionFromExt(){return this.waitForContentScript().then(()=>PromisePlus$2((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},window.origin)},this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out"))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():PromisePlus$2(e=>{window.addEventListener("Glue42EXTReady",()=>{e()})},this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),r=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),n=new Set([...t,...r]);if(!n.size&&!this.extContentAvailable)throw new Error(e);if(!n.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(n)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e?.parent&&e!==e.parent?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=PromisePlus$2(t=>{this.parentPingResolve=t;const r={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval(()=>{e.forEach(e=>{e.postMessage(r,this.defaultTargetString)})},1e3)},this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch(()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)}),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${nanoid$6(10)}`,this.selfAssignedWindowId):void 0}};const waitForInvocations$1=(e,t)=>{let r=e;return()=>{r--,0===r&&t()}};let AsyncSequelizer$3=class{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}};function domainSession$1(e,t,r,n,i){null==e&&(e="global"),n=n??["success"],i=i??["error"];let o,s="global"===e,a=!1,c=!1;const l=CallbackRegistryFactory$3();t.disconnected(function(){r.debug("connection is down"),c=!1,s=!1,a=!0,Object.keys(u).forEach(e=>{const t=u[e];t&&(r.trace(`failing pending request ${e} due to connection lost`),t.error({err:"Connection lost - gateway connection was disconnected"}))}),l.execute("onLeft",{disconnected:!0})}),t.loggedIn(async function(){if(c=!0,a){r.debug("connection is now up - trying to reconnect...");try{await d(o)}catch{r.trace("failed to reconnect")}}}),t.on("success",e=>g(e)),t.on("error",e=>p(e)),t.on("result",e=>g(e)),n&&n.forEach(e=>{t.on(e,e=>g(e))}),i&&i.forEach(e=>{t.on(e,e=>p(e))});const u={};function d(t){return o=t,new Promise((n,i)=>{if(s)return void n({});let o;if("global"===e)o=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{r.debug(`joining domain ${e}`);o=y({type:"join",destination:e,domain:"global",options:t})}o.then(()=>{!function(){r.debug("did join "+e),s=!0;const t=a;a=!1,l.execute("onJoined",t)}(),n({})}).catch(t=>{r.debug("error joining "+e+" domain: "+JSON.stringify(t)),i(t)})})}function h(e){return s&&e(!1),l.add("onJoined",e)}function p(t){if(e!==t.domain)return;const r=t.request_id;if(!r)return;const n=u[r];n&&n.error(t)}function g(t){if(t.domain!==e)return;const r=t.request_id;if(!r)return;const n=u[r];n&&n.success(t)}function m(){return nanoid$6(10)}let f=[];function y(n,i,o){if(n.type&&-1===["hello","join"].indexOf(n.type)&&!s){console.warn(`trying to send a message (${n.domain} ${n.type}) but not connected, will queue`);const e=new PromiseWrapper$2;if(f.push({msg:n,tag:i,options:o,pw:e}),1===f.length){const e=h(()=>{r.info(`joined - will now send queued messages (${f.length} -> [${f.map(e=>e.msg.type)}])`),f.forEach(e=>{y(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),f=[],e()})}return e.promise}o=o??{},n.request_id=n.request_id??m(),n.domain=n.domain??e,o.skipPeerId||(n.peer_id=t.peerId);const a=n.request_id;return new Promise((e,r)=>{u[a]={success:t=>{delete u[a],t._tag=i,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete u[a],e._tag=i,r(e)}},t.send(n,o).catch(e=>{u[a]?.error({err:e})})})}return{join:d,leave:function(){return"global"===e?Promise.resolve():(r.debug("stopping session "+e+"..."),a=!1,y({type:"leave",destination:e,domain:"global"}).then(()=>{s=!1,l.execute("onLeft")}).catch(()=>{s=!1,l.execute("onLeft")}))},onJoined:h,onLeft:function(e){return s||e(),l.add("onLeft",e)},send:y,sendFireAndForget:function(r){return r.request_id=r.request_id?r.request_id:m(),r.domain=r.domain??e,r.peer_id=t.peerId,t.send(r)},on:(n,i)=>{t.on(n,t=>{if(t.domain===e)try{i(t)}catch(e){r.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}})},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}let Connection$1=class{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=CallbackRegistryFactory$3();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new AsyncSequelizer$3;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;loginRetryInProgress=!1;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new InProcTransport$1(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new SharedWorkerTransport$1(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new WebPlatformTransport$1(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new WS$1(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const r=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),n=this.transport.onMessage(this.handleTransportMessage.bind(this));this._transportSubscriptions.push(r),this._transportSubscriptions.push(n),this._defaultTransport=this.transport,this.ping()}async switchTransport(e){return this._sequelizer.enqueue(async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const r=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await r;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}})}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const r=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(r)}`),this.transport.sendObject(r,t)}{const r=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${r}`),this.transport.send(r,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const r=this.ids++;return this.messageHandlers[e][r]=t,{type:e,id:r}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn(()=>{const t=this.transport.name();e(t)})}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this.logger.debug(`Login initiated - reconnect: ${t}, transport: ${this.transport.name()}`),this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}try{await this.transport.open(),this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`),timer$1("connection").mark("transport-opened");const r=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(r)}`),timer$1("connection").mark("protocol-logged-in"),r}catch(e){throw this._switchInProgress&&(this.logger.debug("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,r){let n=this.sessions.find(t=>t.domain===e);return n||(n=domainSession$1(e,this,this.logger.subLogger(`domain=${e}`),t,r),this.sessions.push(n)),n}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then(e=>e.token):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&(this.initialLogin=!1,this.registry.execute("onLoggedIn"))}distributeMessage(e,t){const r=this.messageHandlers[t.toLowerCase()];void 0!==r&&Object.keys(r).forEach(t=>{const n=r[t];if(void 0!==n)try{n(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}})}handleConnectionChanged(e){this._connected!==e?(this.logger.info("connection state changed to "+(e?"connected":"disconnected")),this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new MessageReplayerImpl$1(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&this.attemptLoginWithRetry(),this.registry.execute("disconnected"))):this.logger.trace("connection state unchanged, skipping")}async attemptLoginWithRetry(){if(!this.loginConfig)throw new Error("no login info");if(this.loginRetryInProgress)this.logger.debug("login attempt already in progress, ignoring request...");else if(this._isLoggedIn)this.logger.debug("already logged in, ignoring request...");else{if(this.initialLogin){if(this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`),this.initialLoginAttempts<=0)return void this.logger.info("maximum initial login attempts reached, will not try to login again");this.initialLoginAttempts--}try{this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`),this.loginRetryInProgress=!0,await this.login(this.loginConfig,!0)}catch(e){this.logger.error(`error trying to login: ${e?.message}`,e),setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3)}finally{this.loginRetryInProgress=!1}}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return PromisePlus$2(e=>{let t;const r=waitForInvocations$1(2,()=>{t&&t(),e()});t=this.onLibReAnnounced(e=>"interop"===e.name||"contexts"===e.name?r():void 0)},1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new WS$1(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport.close().catch(e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`)),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,(e,t)=>{if("string"!=typeof t)return t;if(t.lengthe.leave());await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout(()=>{this.ping()},3e4))}};const order$1=["trace","debug","info","warn","error","off"];let Logger$2=class e{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,r){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!r,r&&(this.logFn=r,this.customLogFn=!0)}subLogger(t){const r=this.subLoggers.filter(e=>e.name===t)[0];if(void 0!==r)return r;Object.keys(this).forEach(e=>{if(e===t)throw new Error("This sub logger name is not allowed.")});const n=new e(t,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(n),n}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,r){this.publishMessage(t||"info",e,r)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error",t)}canPublish(e,t){return order$1.indexOf(e)>=order$1.indexOf(t||this.consoleLevel()||"trace")}publishMessage(t,r,n){const i=this.loggerFullName;if("error"===t&&!n){const e=new Error;e.stack&&(r=r+"\n"+e.stack.split("\n").slice(4).join("\n"))}if(this.canPublish(t,this.publishLevel())){const o=e.Interop;if(o)try{if(o.methods({name:e.InteropMethodName}).length>0){const s={msg:r,logger:i,level:t};n&&n instanceof Error&&(s.error={message:n.message,stack:n.stack??""}),o.invoke(e.InteropMethodName,s).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${e.message}`,e)})}}catch{}}if(this.canPublish(t)){let e="";if(this.includeTimeAndLevel){const r=new Date;e=`[${`${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}:${r.getMilliseconds()}`}] [${t}] `}const o=`${e}${i}: ${r}`;switch(t){case"trace":this.logFn.debug(o);break;case"debug":this.logFn.debug?this.logFn.debug(o):this.logFn.log(o);break;case"info":this.logFn.info(o);break;case"warn":this.logFn.warn(o);break;case"error":n?this.logFn.error(o,n):this.logFn.error(o)}}}};const GW_MESSAGE_CREATE_CONTEXT$1="create-context",GW_MESSAGE_ACTIVITY_CREATED$1="created",GW_MESSAGE_ACTIVITY_DESTROYED$1="destroyed",GW_MESSAGE_CONTEXT_CREATED$1="context-created",GW_MESSAGE_CONTEXT_ADDED$1="context-added",GW_MESSAGE_SUBSCRIBE_CONTEXT$1="subscribe-context",GW_MESSAGE_SUBSCRIBED_CONTEXT$1="subscribed-context",GW_MESSAGE_UNSUBSCRIBE_CONTEXT$1="unsubscribe-context",GW_MESSAGE_DESTROY_CONTEXT$1="destroy-context",GW_MESSAGE_CONTEXT_DESTROYED$1="context-destroyed",GW_MESSAGE_UPDATE_CONTEXT$1="update-context",GW_MESSAGE_CONTEXT_UPDATED$1="context-updated",GW_MESSAGE_JOINED_ACTIVITY$1="joined",ContextMessageReplaySpec$1={get name(){return"context"},get types(){return[GW_MESSAGE_CREATE_CONTEXT$1,GW_MESSAGE_ACTIVITY_CREATED$1,GW_MESSAGE_ACTIVITY_DESTROYED$1,GW_MESSAGE_CONTEXT_CREATED$1,GW_MESSAGE_CONTEXT_ADDED$1,GW_MESSAGE_SUBSCRIBE_CONTEXT$1,GW_MESSAGE_SUBSCRIBED_CONTEXT$1,GW_MESSAGE_UNSUBSCRIBE_CONTEXT$1,GW_MESSAGE_DESTROY_CONTEXT$1,GW_MESSAGE_CONTEXT_DESTROYED$1,GW_MESSAGE_UPDATE_CONTEXT$1,GW_MESSAGE_CONTEXT_UPDATED$1,GW_MESSAGE_JOINED_ACTIVITY$1]}};var version$4="6.8.1";function prepareConfig$1(e,t,r){let n;if(Utils$1.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{n=JSON.parse(e)}catch{}}function i(){if(e.application)return e.application;if(r)return r.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=nanoid$6(10);return Utils$1.isNode()?n?n.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const o=function(){const o=e.gateway,s=o?.protocolVersion??3,a=o?.reconnectInterval,c=o?.reconnectAttempts;let l=o?.ws;const u=o?.sharedWorker,d=o?.inproc,h=o?.webPlatform??void 0;let p,g,m,f,y;r&&(l=r.gwURL),Utils$1.isNode()&&n&&n.gwURL&&(l=n.gwURL),l||u||d||(l="ws://localhost:8385");const $=i();let b=$;void 0!==r?(g=r.windowId,m=r.pid,r.env&&(f=r.env.env,y=r.env.region),b=r.application??"glue-app",p=r.appInstanceId):Utils$1.isNode()?(m=process.pid,n&&(f=n.env,y=n.region,p=n.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,m=window?.glue42electron.pid,f=window?.glue42electron.env,y=window?.glue42electron.region,b=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const v=e.gateway?.replaySpecs??[];v.push(ContextMessageReplaySpec$1);let w={application:b,applicationName:$,windowId:g,instance:p,process:m,region:y,environment:f,api:t.version||version$4};return e.identity&&(w=Object.assign(w,e.identity)),{identity:w,reconnectInterval:a,ws:l,sharedWorker:u,webPlatform:h,inproc:d,protocolVersion:s,reconnectAttempts:c,replaySpecs:v}}();let s=i();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(s=t)}return{bus:e.bus??!1,application:s,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Utils$1.isNode()&&n&&n.gwToken?{gatewayToken:n.gwToken}:e.gateway?.webPlatform?{username:"glue42",password:""}:void 0,logger:function(){let t=e.logger;const n="warn";let i;return t||(t=n),r&&(i=r.consoleLogLevel),"string"==typeof t?{console:i??t,publish:n}:{console:i??t.console??n,publish:t.publish??n}}(),connection:o,metrics:e.metrics??!0,contexts:function(){const t={reAnnounceKnownContexts:!0,subscribeOnUpdate:!0,subscribeOnGet:!0,onlyReAnnounceSubscribedContexts:!0};return void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?t:"object"==typeof e.contexts&&{...t,...e.contexts}}(),version:t.version||version$4,libs:t.libs??[],customLogger:e.customLogger}}let GW3ContextData$1=class{name;contextId;context;isAnnounced;createdByUs;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;get hasReceivedSnapshot(){return this.snapshotPromiseWrapper.resolved}set hasReceivedSnapshot(e){e?this.snapshotPromiseWrapper.resolve():this.snapshotPromiseWrapper=new PromiseWrapper$2}get snapshotPromise(){return this.snapshotPromiseWrapper.promise}snapshotPromiseWrapper;constructor(e,t,r,n){this.contextId=e,this.name=t,this.isAnnounced=r,this.activityId=n,this.context={},this.snapshotPromiseWrapper=new PromiseWrapper$2}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}};var lodash_clonedeep$1={exports:{}};lodash_clonedeep$1.exports,function(e,t){var r="__lodash_hash_undefined__",n=9007199254740991,i="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",l="[object Map]",u="[object Number]",d="[object Object]",h="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",$="[object ArrayBuffer]",b="[object DataView]",v="[object Float32Array]",w="[object Float64Array]",S="[object Int8Array]",_="[object Int16Array]",E="[object Int32Array]",C="[object Uint8Array]",I="[object Uint8ClampedArray]",T="[object Uint16Array]",A="[object Uint32Array]",D=/\w*$/,x=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,O={};O[i]=O["[object Array]"]=O[$]=O[b]=O[o]=O[s]=O[v]=O[w]=O[S]=O[_]=O[E]=O[l]=O[u]=O[d]=O[p]=O[g]=O[m]=O[f]=O[C]=O[I]=O[T]=O[A]=!0,O["[object Error]"]=O[a]=O[y]=!1;var N="object"==typeof commonjsGlobal$2&&commonjsGlobal$2&&commonjsGlobal$2.Object===Object&&commonjsGlobal$2,P="object"==typeof self&&self&&self.Object===Object&&self,k=N||P||Function("return this")(),M=t&&!t.nodeType&&t,L=M&&e&&!e.nodeType&&e,F=L&&L.exports===M;function j(e,t){return e.set(t[0],t[1]),e}function U(e,t){return e.add(t),e}function B(e,t,r,n){for(var i=-1,o=e?e.length:0;++i-1},Ie.prototype.set=function(e,t){var r=this.__data__,n=Re(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new Ce,map:new(pe||Ie),string:new Ce}},Te.prototype.delete=function(e){return Me(this,e).delete(e)},Te.prototype.get=function(e){return Me(this,e).get(e)},Te.prototype.has=function(e){return Me(this,e).has(e)},Te.prototype.set=function(e,t){return Me(this,e).set(e,t),this},Ae.prototype.clear=function(){this.__data__=new Ie},Ae.prototype.delete=function(e){return this.__data__.delete(e)},Ae.prototype.get=function(e){return this.__data__.get(e)},Ae.prototype.has=function(e){return this.__data__.has(e)},Ae.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Ie){var n=r.__data__;if(!pe||n.length<199)return n.push([e,t]),this;r=this.__data__=new Te(n)}return r.set(e,t),this};var Fe=le?z(le,Object):function(){return[]},je=function(e){return ee.call(e)};function Ue(e,t){return!!(t=null==t?n:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=n}(e.length)&&!Je(e)}var Ge=ue||function(){return!1};function Je(e){var t=Ke(e)?ee.call(e):"";return t==a||t==c}function Ke(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ve(e){return We(e)?De(e):function(e){if(!Be(e))return de(e);var t=[];for(var r in Object(e))Q.call(e,r)&&"constructor"!=r&&t.push(r);return t}(e)}e.exports=function(e){return Oe(e,!0,!0)}}(lodash_clonedeep$1,lodash_clonedeep$1.exports);var lodash_clonedeepExports$1=lodash_clonedeep$1.exports,cloneDeep$1=getDefaultExportFromCjs$3(lodash_clonedeepExports$1);function applyContextDelta$1(e,t,r){try{if(r?.canPublish("trace")&&r?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=deepClone$1(e,void 0),t.commands){for(const r of t.commands)"remove"===r.type?deletePath$1(e,r.path):"set"===r.type&&setValueToPath$1(e,r.value,r.path);return e}const n=t.added,i=t.updated,o=t.removed;return n&&Object.keys(n).forEach(t=>{e[t]=n[t]}),i&&Object.keys(i).forEach(t=>{mergeObjectsProperties$1(t,e,i)}),o&&o.forEach(t=>{delete e[t]}),e}catch(n){return r?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,n),e}}function deepClone$1(e,t){return cloneDeep$1(e)}const mergeObjectsProperties$1=(e,t,r)=>{const n=r[e];if(void 0===n)return t;const i=t[e];return i&&n?"string"==typeof i||"number"==typeof i||"boolean"==typeof i||"string"==typeof n||"number"==typeof n||"boolean"==typeof n||Array.isArray(i)||Array.isArray(n)?(t[e]=n,t):(t[e]=Object.assign({},i,n),t):(t[e]=n,t)};function deepEqual$3(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const r in e)if(e.hasOwnProperty(r)){if(!t.hasOwnProperty(r))return!1;if(e[r]!==t[r]){if("object"!=typeof e[r])return!1;if(!deepEqual$3(e[r],t[r]))return!1}}for(const r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}function setValueToPath$1(e,t,r){const n=r.split("."),i=["__proto__","constructor","prototype"];let o;for(o=0;o"object"==typeof t[r]?isSubset$1(e?.[r]||{},t[r]||{}):t[r]===e?.[r])}function deletePath$1(e,t){const r=t.split(".");let n;for(n=0;n"context"===e.uri);this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._subscribeOnUpdate=e.subscribeOnUpdate??!0,this._subscribeOnGet=e.subscribeOnGet??!0,this._onlyReAnnounceSubscribedContexts=e.onlyReAnnounceSubscribedContexts??!0,this._gw3Session=this._connection.domain("global",[GW_MESSAGE_CONTEXT_CREATED$1,GW_MESSAGE_SUBSCRIBED_CONTEXT$1,GW_MESSAGE_CONTEXT_DESTROYED$1,GW_MESSAGE_CONTEXT_UPDATED$1]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined(e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then(()=>this._connection.setLibReAnnounced({name:"contexts"})).catch(e=>{this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(e)}`)}):(this._contextsTempCache={},this._connection.setLibReAnnounced({name:"contexts"}))}),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec$1.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED$1||t===GW_MESSAGE_CONTEXT_ADDED$1||t===GW_MESSAGE_ACTIVITY_CREATED$1?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT$1||t===GW_MESSAGE_CONTEXT_UPDATED$1||t===GW_MESSAGE_JOINED_ACTIVITY$1?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED$1&&t!==GW_MESSAGE_ACTIVITY_DESTROYED$1||this.handleContextDestroyedMessage(e))})}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:GW_MESSAGE_CREATE_CONTEXT$1,domain:"global",name:e,data:t,lifetime:"retained"}).then(r=>{this._contextNameToId[e]=r.context_id,this._contextIdToName[r.context_id]=e;const n=this._contextNameToData[e]||new GW3ContextData$1(r.context_id,e,!0,void 0);return n.isAnnounced=!0,n.name=e,n.contextId=r.context_id,n.context=r.data||deepClone$1(t),n.hasReceivedSnapshot=!0,this._contextNameToData[e]=n,delete this._creationPromises[e],n.sentExplicitSubscription=!0,n.createdByUs=!0,this.subscribe(e,()=>{}),r.context_id})),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter(e=>this._contextNameToData[e].isAnnounced)}async update(e,t){t&&(t=deepClone$1(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return void await this.createContext(e,t);const n=await this.get(r.name),i=this.setPathSupported?this.calculateContextDeltaV2(n,t):this.calculateContextDeltaV1(n,t);if(!(Object.keys(i.added).length||Object.keys(i.updated).length||i.removed.length||i.commands?.length))return Promise.resolve();const o=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT$1,domain:"global",context_id:r.contextId,delta:i},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&(await r.snapshotPromise,this.handleUpdated(r,i,{updaterId:o.peer_id}))}async set(e,t){t&&(t=deepClone$1(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return this.createContext(e,t);const n=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT$1,domain:"global",context_id:r.contextId,delta:{reset:t}},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&this.handleUpdated(r,{reset:t,added:{},removed:[],updated:{}},{updaterId:n.peer_id})}setPath(e,t,r){return this.setPathSupported?this.setPaths(e,[{path:t,value:r}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=deepClone$1(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced){const r={};for(const e of t)setValueToPath$1(r,e.value,e.path);return this.createContext(e,r)}const n=[];for(const e of t)null===e.value?n.push({type:"remove",path:e.path}):n.push({type:"set",path:e.path,value:e.value});const i=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT$1,domain:"global",context_id:r.contextId,delta:{commands:n}},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&(await r.snapshotPromise,this.handleUpdated(r,{added:{},removed:[],updated:{},commands:n},{updaterId:i.peer_id}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return!t&&this._subscribeOnGet&&this.subscribe(e,()=>{}),Promise.resolve({});if(t&&!t.sentExplicitSubscription)return new Promise((t,r)=>{this.subscribe(e,(e,r,n,i)=>{this._subscribeOnGet||this.unsubscribe(i),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):r(e)})});await t.snapshotPromise;const r=t?.context??{};return Promise.resolve(deepClone$1(r))}isInvalidContextError(e){return e.reason_uri===this.ERROR_URI_INVALID_CONTEXT||e.reason_uri===this.ERROR_URI_FAILURE&&e.reason?.startsWith("Unable to find context with id")}async subscribe(e,t,r){e in this._creationPromises&&await this._creationPromises[e];const n=void 0===r?this._nextCallbackSubscriptionNumber:r;void 0===r&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:n,callback:t}));let i=this._contextNameToData[e];if(!i||!i.isAnnounced)return i=i||new GW3ContextData$1(void 0,e,!1,void 0),this._contextNameToData[e]=i,i.updateCallbacks[n]=t,Promise.resolve(n);const o=i.hasCallbacks();if(i.updateCallbacks[n]=t,o){if(i.hasReceivedSnapshot&&!r){const e=deepClone$1(i.context);t(e,e,[],n)}return Promise.resolve(n)}if(i.joinedActivity||i.createdByUs){if(i.hasReceivedSnapshot&&!r){const e=deepClone$1(i.context);t(e,e,[],n)}return Promise.resolve(n)}if(i.context&&i.sentExplicitSubscription){if(i.hasReceivedSnapshot&&!r){const e=deepClone$1(i.context);t(e,e,[],n)}return Promise.resolve(n)}return this.sendSubscribe(i).then(()=>n,()=>(this.unsubscribe(n,!0),n))}unsubscribe(e,t){t||(this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter(t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const r=this._contextNameToData[t];if(!r)continue;const n=r.hasCallbacks();delete r.updateCallbacks[e],r.isAnnounced&&n&&!r.hasCallbacks()&&r.sentExplicitSubscription&&(r.hasReceivedSnapshot=!1,r.context={},this.sendUnsubscribe(r).catch(()=>{})),r.isAnnounced||r.hasCallbacks()||(delete this._contextNameToData[t],delete this._contextNameToId[t],r.contextId&&delete this._contextIdToName[r.contextId])}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e],r=t?.contextId;return t&&r?this._gw3Session.send({type:GW_MESSAGE_DESTROY_CONTEXT$1,domain:"global",context_id:t.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,r){const n=e.context;e.context=applyContextDelta$1(e.context,t,this._logger),this._contextNameToData[e.name]!==e||deepEqual$3(n,e.context)||this.invokeUpdateCallbacks(e,t,r)}subscribeToContextCreatedMessages(){const e=[GW_MESSAGE_CONTEXT_ADDED$1,GW_MESSAGE_CONTEXT_CREATED$1,GW_MESSAGE_ACTIVITY_CREATED$1];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===GW_MESSAGE_ACTIVITY_CREATED$1?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===GW_MESSAGE_CONTEXT_ADDED$1&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const r=this._contextIdToName[e.context_id];if(!r)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[r])throw new Error("Received created event for context with unknown id: "+e.context_id);let n=this._contextNameToData[r];if(n){if(n.isAnnounced)return;if(!n.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");n.isAnnounced=!0,n.contextId=e.context_id,n.activityId=e.activity_id,n.sentExplicitSubscription||this.sendSubscribe(n).catch(()=>{})}else this._contextNameToData[r]=n=new GW3ContextData$1(e.context_id,r,!0,e.activity_id),this._trackAllContexts&&this.subscribe(r,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[GW_MESSAGE_CONTEXT_UPDATED$1,GW_MESSAGE_SUBSCRIBED_CONTEXT$1,GW_MESSAGE_JOINED_ACTIVITY$1];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,r=e.context_id;let n=this._contextNameToData[this._contextIdToName[r]];const i=!n||!n.isAnnounced;if(t===GW_MESSAGE_JOINED_ACTIVITY$1)n||(n=this._contextNameToData[e.activity_id]||new GW3ContextData$1(r,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=n,this._contextIdToName[r]=e.activity_id,this._contextNameToId[e.activity_id]=r,n.contextId=r,n.isAnnounced=!0,n.activityId=e.activity_id,n.joinedActivity=!0;else if(!n||!n.isAnnounced)return void(t===GW_MESSAGE_SUBSCRIBED_CONTEXT$1?(n=n||new GW3ContextData$1(r,e.name,!0,void 0),n.sentExplicitSubscription=!0,this._contextNameToData[e.name]=n,this._contextIdToName[r]=e.name,this._contextNameToId[e.name]=r):this._logger.error(`Received 'update' for unknown context: ${r}`));const o=n.context;if(n.hasReceivedSnapshot=!0,t===GW_MESSAGE_SUBSCRIBED_CONTEXT$1)n.context=e.data??{};else if(t===GW_MESSAGE_JOINED_ACTIVITY$1)n.context=e.context_snapshot??{};else{if(t!==GW_MESSAGE_CONTEXT_UPDATED$1)throw new Error("Unrecognized context update message "+t);n.context=applyContextDelta$1(n.context,e.delta,this._logger)}!i&&deepEqual$3(n.context,o)&&t!==GW_MESSAGE_SUBSCRIBED_CONTEXT$1||this.invokeUpdateCallbacks(n,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,r){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),setValueToPath$1(t.updated,null,e.path)):"set"===e.type&&setValueToPath$1(t.updated,e.value,e.path)}for(const n in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(n))try{(0,e.updateCallbacks[n])(deepClone$1(e.context),deepClone$1(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(n,10),r)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[GW_MESSAGE_CONTEXT_DESTROYED$1,GW_MESSAGE_ACTIVITY_DESTROYED$1];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,r;if(e.type===GW_MESSAGE_ACTIVITY_DESTROYED$1){if(r=e.activity_id,t=this._contextNameToId[r],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,r=this._contextIdToName[t],!r)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[r];const n=this._contextNameToData[r];delete this._contextNameToData[r],n&&n.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}async sendSubscribe(e){e.sentExplicitSubscription=!0;try{return void await this._gw3Session.send({type:GW_MESSAGE_SUBSCRIBE_CONTEXT$1,domain:"global",context_id:e.contextId})}catch(t){throw e.sentExplicitSubscription=!1,t}}async sendUnsubscribe(e){const t=e.sentExplicitSubscription;e.sentExplicitSubscription=!1;try{return void await this._gw3Session.send({type:GW_MESSAGE_UNSUBSCRIBE_CONTEXT$1,domain:"global",context_id:e.contextId})}catch(r){throw e.sentExplicitSubscription=t,r}}calculateContextDeltaV1(e,t){const r={added:{},updated:{},removed:[],reset:void 0};if(e)for(const n of Object.keys(e))-1===Object.keys(t).indexOf(n)||null===t[n]||deepEqual$3(e[n],t[n])||(r.updated[n]=t[n]);for(const n of Object.keys(t))e&&-1!==Object.keys(e).indexOf(n)?null===t[n]&&r.removed.push(n):null!==t[n]&&(r.added[n]=t[n]);return r}calculateContextDeltaV2(e,t){const r={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const n of Object.keys(t))if(null!==t[n]){deepEqual$3(e?e[n]:null,t[n])||r.commands?.push({type:"set",path:n,value:t[n]})}else r.commands?.push({type:"remove",path:n});return r}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey,!0),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((e,t)=>{const r=this._contextNameToData[t];return(!this._onlyReAnnounceSubscribedContexts||r.hasReceivedSnapshot)&&(e[t]=this._contextNameToData[t].context),e},{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec$1.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED$1||t===GW_MESSAGE_CONTEXT_ADDED$1||t===GW_MESSAGE_ACTIVITY_CREATED$1?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT$1||t===GW_MESSAGE_CONTEXT_UPDATED$1||t===GW_MESSAGE_JOINED_ACTIVITY$1?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED$1&&t!==GW_MESSAGE_ACTIVITY_DESTROYED$1||this.handleContextDestroyedMessage(e))}),await Promise.all(this._contextsSubscriptionsCache.map(e=>this.subscribe(e.contextName,e.callback,e.subKey))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise(e=>setTimeout(()=>e(),0))}},ContextsModule$1=class{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new GW3Bridge$1(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,r){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(r),this.set(e,r)):this._bridge.setPath(e,t,r)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:r}of t){this.checkPath(e);""===e&&this.checkData(r)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(e,r,n,i,o)=>t(e,r,n,()=>this._bridge.unsubscribe(i),o)).then(e=>()=>{this._bridge.unsubscribe(e)})}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}};function promisify$1(e,t,r){return"function"!=typeof t&&"function"!=typeof r?e:("function"!=typeof t?t=()=>{}:"function"!=typeof r&&(r=()=>{}),e.then(t,r))}function rejectAfter$1(e=0,t,r){let n;const i=()=>{n&&clearTimeout(n)};return t.then(()=>{i()}).catch(()=>{i()}),new Promise((t,i)=>{n=setTimeout(()=>i(r),e)})}var ok$4=function(e){return{ok:!0,result:e}},err$4=function(e){return{ok:!1,error:e}},asPromise$4=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$4=function(e,t){return!0===t.ok?t.result:e},withException$4=function(e){if(!0===e.ok)return e.result;throw e.error},map$5=function(e,t){return!0===t.ok?ok$4(e(t.result)):t},map2$4=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$4(e(t.result,r.result))},mapError$4=function(e,t){return!0===t.ok?t:err$4(e(t.error))},andThen$4=function(e,t){return!0===t.ok?e(t.result):t},__assign$4=function(){return __assign$4=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{const r=typeof e;return"function"===r?anyJson$4():fail$1$1(`The provided argument as ${t} should be of type function, provided: ${typeof r}`)},nonEmptyStringDecoder$5=string$7().where(e=>e.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$4=number$7().where(e=>e>=0,"Expected a non-negative number or 0"),methodDefinitionDecoder$1=object$5({name:nonEmptyStringDecoder$5,objectTypes:optional$5(array$5(nonEmptyStringDecoder$5)),displayName:optional$5(nonEmptyStringDecoder$5),accepts:optional$5(nonEmptyStringDecoder$5),returns:optional$5(nonEmptyStringDecoder$5),description:optional$5(nonEmptyStringDecoder$5),version:optional$5(nonNegativeNumberDecoder$4),supportsStreaming:optional$5(boolean$6()),flags:optional$5(object$5()),getServers:optional$5(anyJson$4().andThen(e=>functionCheck$2(e,"method definition getServers")))}),methodFilterDecoder$1=union$3(nonEmptyStringDecoder$5,methodDefinitionDecoder$1),instanceDecoder$1=object$5({application:optional$5(nonEmptyStringDecoder$5),applicationName:optional$5(nonEmptyStringDecoder$5),pid:optional$5(nonNegativeNumberDecoder$4),machine:optional$5(nonEmptyStringDecoder$5),user:optional$5(nonEmptyStringDecoder$5),environment:optional$5(nonEmptyStringDecoder$5),region:optional$5(nonEmptyStringDecoder$5),service:optional$5(nonEmptyStringDecoder$5),instance:optional$5(nonEmptyStringDecoder$5),windowId:optional$5(nonEmptyStringDecoder$5),peerId:optional$5(nonEmptyStringDecoder$5),isLocal:optional$5(boolean$6()),api:optional$5(nonEmptyStringDecoder$5),getMethods:optional$5(anyJson$4().andThen(e=>functionCheck$2(e,"instance getMethods"))),getStreams:optional$5(anyJson$4().andThen(e=>functionCheck$2(e,"instance getStreams")))}),targetDecoder$1=union$3(constant$4("best"),constant$4("all"),constant$4("skipMine"),instanceDecoder$1,array$5(instanceDecoder$1)),invokeOptionsDecoder$1=object$5({waitTimeoutMs:optional$5(nonNegativeNumberDecoder$4),methodResponseTimeoutMs:optional$5(nonNegativeNumberDecoder$4)});var InvokeStatus$1;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(InvokeStatus$1||(InvokeStatus$1={}));let Client$1=class{protocol;repo;instance;configuration;constructor(e,t,r,n){this.protocol=e,this.repo=t,this.instance=r,this.configuration=n}subscribe(e,t,r,n,i){const o=(e,r,n,o)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(r,t,e,n,o,i)},s=new Promise((r,n)=>{const i=e=>{r(e)},s=e=>{n(e)};if(!e)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void n(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let l=0,u=this.getServerMethodsByFilterAndTarget(a,c);if(u.length>0)o(u,u[0].methods[0],i,s);else{const r=()=>{if(c&&t.waitTimeoutMs)if(l+=500,u=this.getServerMethodsByFilterAndTarget(a,c),u.length>0){const e=u[0].methods[0];o(u,e,i,s)}else if(l>=t.waitTimeoutMs){o(u,"string"==typeof e?{name:e}:e,i,s)}else setTimeout(r,500)};setTimeout(r,500)}});return promisify$1(s,r,n)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map(e=>e.server.instance)}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved((t,r)=>{e(t,r)})}serverMethodAdded(e){return this.repo.onServerMethodAdded((t,r)=>{e({server:t,method:r})})}serverMethodRemoved(e){return this.repo.onServerMethodRemoved((t,r)=>{e({server:t,method:r})})}async invoke(e,t,r,n,i,o){return promisify$1((async()=>{const s="string"==typeof e?{name:e}:{...e};t||(t={}),r||(r="best"),n||(n={});const a=methodFilterDecoder$1.run(s);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if("object"!=typeof t){const e="The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const c=targetDecoder$1.run(r);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const l=invokeOptionsDecoder$1.run(n);if(!l.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(l.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(i&&"function"!=typeof i){const e="The provided 'success' function is invalid. Error: The success should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(o&&"function"!=typeof o){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=n.method_response_timeout,void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=n.wait_for_method_timeout,void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=this.configuration.waitTimeoutMs));let u=this.getServerMethodsByFilterAndTarget(s,r);if(0===u.length)try{u=await this.tryToAwaitForMethods(s,r,n)}catch(n){const i=`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(r)}`;return Promise.reject(this.generateInvalidInputInvocationResult(i,s,t))}const d=n.methodResponseTimeoutMs,h=n,p=u.map(e=>{const r=nanoid$6(10),n=e.methods[0],i=e.server,o=this.protocol.client.invoke(r,n,t,i,h);return Promise.race([o,rejectAfter$1(d,o,{invocationId:r,message:`Invocation timeout (${d} ms) reached for method name: ${n?.name}, target instance: ${JSON.stringify(i.instance)}, options: ${JSON.stringify(h)}`,status:InvokeStatus$1.Error})])}),g=await Promise.all(p),m=this.getInvocationResultObj(g,s,t);return g.every(e=>e.status===InvokeStatus$1.Error)?Promise.reject(m):m})(),i,o)}generateInvalidInputInvocationResult(e,t,r){const n={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},i={invocationId:nanoid$6(10),status:InvokeStatus$1.Error,message:e};return this.getInvocationResultObj([i],n,r)}getInvocationResultObj(e,t,r){const n=e.filter(e=>e.status===InvokeStatus$1.Success).reduce((e,n)=>e=[...e,{executed_by:n.instance,returned:n.result,called_with:r,method:t,message:n.message,status:n.status}],[]),i=e.filter(e=>e.status===InvokeStatus$1.Error).reduce((e,n)=>e=[...e,{executed_by:n.instance,called_with:r,name:t.name,message:n.message}],[]),o=e[0];return{method:t,called_with:r,returned:o.result,executed_by:o.instance,all_return_values:n,all_errors:i,message:o.message,status:o.status}}tryToAwaitForMethods(e,t,r){return new Promise((n,i)=>{if(0===r.waitTimeoutMs)return void i();let o=0;const s=setInterval(()=>{o+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(s),n(a);else if(o>=(r.waitTimeoutMs||1e4))return clearInterval(s),void i()},500)})}filterByTarget(e,t){if("string"!=typeof e){let r;r=Array.isArray(e)?e:[e];const n=r.reduce((e,r)=>{const n=t.filter(e=>this.instanceMatch(r,e.server.instance));return e.concat(n)},[]);return n}if("all"===e)return[...t];if("best"===e){const e=t.find(e=>e.server.instance.isLocal);if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter(({server:e})=>e.instance.peerId!==this.instance.peerId);return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter(t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0]).every(r=>{let n;const i=e[r],o=t[r];switch(r){case"objectTypes":n=(i||[]).every(e=>(o||[]).includes(e));break;case"flags":n=isSubset$1(o||{},i||{});break;default:n=String(i).toLowerCase()===String(o).toLowerCase()}return n})}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter(t=>this.methodMatch(e,t))}getMethodsForInstance(e){const t=this.repo.getServers().filter(t=>this.instanceMatch(e,t.instance));if(0===t.length)return[];let r={};return 1===t.length?r=t[0].methods:t.forEach(e=>{Object.keys(e.methods).forEach(t=>{const n=e.methods[t];r[n.identifier]=n})}),Object.keys(r).map(e=>r[e])}getServers(e){const t=this.repo.getServers();return void 0===e?t.map(e=>({server:e,methods:[]})):t.reduce((t,r)=>{const n=Object.values(r.methods).filter(t=>this.methodMatch(e,t));return n.length>0&&t.push({server:r,methods:n}),t},[])}getServerMethodsByFilterAndTarget(e,t){const r=this.getServers(e);return this.filterByTarget(t,r)}},ServerSubscription$1=class{protocol;repoMethod;subscription;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.subscription=r}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}},Request$2=class{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.requestContext=r,this.arguments=r.arguments,this.instance=r.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}},ServerStreaming$1$1=class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest((e,t)=>this.handleSubRequest(e,t)),e.server.onSubAdded((e,t)=>this.handleSubAdded(e,t)),e.server.onSubRemoved((e,t)=>this.handleSubRemoved(e,t))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const r=new Request$2(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(r)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const r=new ServerSubscription$1(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(r)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const r=new ServerSubscription$1(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(r)}},ServerBranch$1=class{key;protocol;repoMethod;constructor(e,t,r){this.key=e,this.protocol=t,this.repoMethod=r}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map(e=>new ServerSubscription$1(this.protocol,this.repoMethod,e))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}},ServerStream$1=class{_protocol;_repoMethod;_server;name;constructor(e,t,r){this._protocol=e,this._repoMethod=t,this._server=r,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new ServerBranch$1(e,this._protocol,this._repoMethod):void 0:t.map(e=>new ServerBranch$1(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new ServerSubscription$1(this._protocol,this._repoMethod,e))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}close(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}},Server$1=class{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new ServerStreaming$1$1(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,r,n,i){const o=new Promise((r,n)=>{if(!e)return void n("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let o;if(o="string"==typeof e?{name:""+e}:{...e},!o.name)return n(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(o)}`);if(this.serverRepository.getList().some(e=>e.definition.name===o.name))return n(`A stream with the name "${o.name}" already exists! Please, provide a unique name for the stream.`);o.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const s=this.serverRepository.add({definition:o,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(s).then(()=>{let e;i?(e=i,i.updateRepoMethod(s)):e=new ServerStream$1(this.protocol,s,this),s.stream=e,r(e)}).catch(e=>{s.repoId&&this.serverRepository.remove(s.repoId),n(e)})});return promisify$1(o,r,n)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const r=async(e,r)=>{try{const n=t(e.args,e.instance);if(n&&"function"==typeof n.then){r(void 0,await n)}else r(void 0,n)}catch(e){r(e??"",e??"")}};return r.userCallback=t,this.registerCore(e,r)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const r=async(e,r)=>{try{let n=!1;const i=e=>{n||r(void 0,e),n=!0},o=e=>{n||(e||(e=""),r(e,e)),n=!0},s=t(e.args,e.instance,i,o);s&&"function"==typeof s.then&&s.then(i).catch(o)}catch(e){r(e,void 0)}};return r.userCallbackAsync=t,this.registerCore(e,r)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let r;if(r="string"==typeof e?{name:e}:e,void 0===r.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const n=this.serverRepository.getList().find(e=>e.definition.name===r.name&&(e.definition.supportsStreaming||!1)===t);if(!n)return Promise.reject(`Method with a name "${r.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([n])}async unregisterWithPredicate(e,t){const r=this.serverRepository.getList().filter(t=>e(t.definition)).filter(e=>(e.definition.supportsStreaming||!1)===t);if(!r||0===r.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(r)}removeMethodsOrStreams(e){const t=[];return e.forEach(e=>{const r=this.protocol.server.unregister(e).then(()=>{e.repoId&&this.serverRepository.remove(e.repoId)});t.push(r),this.addAsCurrentlyUnregistering(e.definition.name,r)}),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const r=new Promise(e=>setTimeout(e,5e3));this.currentlyUnregistering[e]=Promise.race([t,r]).then(()=>{delete this.currentlyUnregistering[e]})}async registerCore(e,t){let r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const n=this.currentlyUnregistering[r.name];void 0!==n&&await n;if(this.serverRepository.getList().some(e=>e.definition.name===r.name))return Promise.reject(`A method with the name "${r.name}" already exists! Please, provide a unique name for the method.`);if(r.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${r.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const i=this.serverRepository.add({definition:r,theFunction:t,protocolState:{}});return this.protocol.server.register(i).catch(e=>{throw i?.repoId&&this.serverRepository.remove(i.repoId),e})}onMethodInvoked(e,t,r){e&&e.theFunction&&e.theFunction(r,(r,n)=>{if(null!=r)if(r.message&&"string"==typeof r.message)r=r.message;else if("string"!=typeof r)try{r=JSON.stringify(r)}catch(e){r=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(r)}`}n?("object"!=typeof n||Array.isArray(n))&&(n={_value:n}):n={},this.protocol.server.methodInvocationResult(e,t,r,n)})}},InstanceWrapper$1=class{wrapped={};constructor(e,t,r){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter(e=>e.supportsStreaming)},t&&this.refreshWrappedObject(t),r&&(r.loggedIn(()=>{this.refresh(r)}),this.refresh(r))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,r=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(r)}refreshWrappedObject(e){Object.keys(e).forEach(t=>{this.wrapped[t]=e[t]}),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??nanoid$6(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}};const hideMethodSystemFlags$1=e=>({...e,flags:e.flags.metadata||{}});let ClientRepository$1=class{logger;API;servers={};myServer;methodsCount={};callbacks=CallbackRegistryFactory$3();constructor(e,t){this.logger=e,this.API=t;const r=this.API.instance.peerId;this.myServer={id:r,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[r]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const r=this.servers[t];if(r)return r.id;const n=new InstanceWrapper$1(this.API,e),i={id:t,methods:{},instance:n.unwrap(),wrapper:n};return this.servers[t]=i,this.callbacks.execute("onServerAdded",i.instance),t}removeServerById(e,t){const r=this.servers[e];r?(this.logger.debug(`removing server ${e}`),Object.keys(r.methods).forEach(t=>{this.removeServerMethod(e,t)}),delete this.servers[e],this.callbacks.execute("onServerRemoved",r.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");if(r.methods[t.id])return;const n=this.createMethodIdentifier(t),i=this,o={identifier:n,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>i.getServersByMethod(n)};o.object_types=o.objectTypes,o.display_name=o.displayName,o.version=o.version,r.methods[t.id]=o;const s=hideMethodSystemFlags$1(o);return this.methodsCount[n]||(this.methodsCount[n]=0,this.callbacks.execute("onMethodAdded",s)),this.methodsCount[n]=this.methodsCount[n]+1,this.callbacks.execute("onServerMethodAdded",r.instance,s),o}removeServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");const n=r.methods[t];delete r.methods[t];const i=hideMethodSystemFlags$1(n);this.methodsCount[n.identifier]=this.methodsCount[n.identifier]-1,0===this.methodsCount[n.identifier]&&this.callbacks.execute("onMethodRemoved",i),this.callbacks.execute("onServerMethodRemoved",r.instance,i)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags$1)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),r=this.getServers().map(e=>e.instance);return this.returnUnsubWithDelayedReplay(t,r,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),r=this.getMethods();return this.returnUnsubWithDelayedReplay(t,r,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let r=!1;const n=this.getServers();return setTimeout(()=>{n.forEach(t=>{const n=t.methods;Object.keys(n).forEach(i=>{r||e(t.instance,n[i])})})},0),()=>{r=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach(e=>{this.removeServerById(e,"reset")}),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",r=e.result_signature??"";return(e.name+t+r).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach(r=>{Object.values(r.methods).forEach(n=>{n.identifier===e&&t.push(r.instance)})}),t}returnUnsubWithDelayedReplay(e,t,r){let n=!1;return setTimeout(()=>{t.forEach(e=>{n||r(e)})},0),()=>{n=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach(([e,r])=>{t[e]=hideMethodSystemFlags$1(r)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}},ServerRepository$1=class{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter(t=>t.repoId!==e)}getById(e){if("string"==typeof e)return this.methods.find(t=>t.repoId===e)}getList(){return this.methods.map(e=>e)}length(){return this.methods.length}reset(){this.methods=[]}};const SUBSCRIPTION_REQUEST$1="onSubscriptionRequest",SUBSCRIPTION_ADDED$1="onSubscriptionAdded",SUBSCRIPTION_REMOVED$1="onSubscriptionRemoved";let ServerStreaming$2=class{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=CallbackRegistryFactory$3();nextStreamId=0;constructor(e,t,r,n){this.session=e,this.repository=t,this.serverRepository=r,this.logger=n,e.on("add-interest",e=>{this.handleAddInterest(e)}),e.on("remove-interest",e=>{this.handleRemoveInterest(e)})}acceptRequestOnBranch(e,t,r){if("string"!=typeof r&&(r=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const n=this.getStreamId(t,r),i=e.msg.subscription_id,o={id:i,arguments:e.arguments,instance:e.instance,branchKey:r,streamId:n,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[i]=o,this.session.sendFireAndForget({type:"accepted",subscription_id:i,stream_id:n}).catch(e=>{this.logger.warn(`Failed to send accepted message for subscription ${i}: ${JSON.stringify(e)}`)}),this.callbacks.execute(SUBSCRIPTION_ADDED$1,o,t)}rejectRequest(e,t,r){"string"!=typeof r&&(r=""),this.sendSubscriptionFailed("Subscription rejected by user. "+r,e.msg.subscription_id)}pushData(e,t,r){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof r?r=[r]:(!Array.isArray(r)||r.length<=0)&&(r=[]);const n=e.protocolState.branchKeyToStreamIdMap.filter(e=>!r||0===r.length||r.indexOf(e.key)>=0).map(e=>e.streamId);n.forEach(e=>{const r={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(r).catch(t=>{this.logger.warn(`Failed to send publish message for stream ${e}: ${JSON.stringify(t)}`)})})}pushDataToSingle(e,t,r){if("object"!=typeof r)throw new Error("Invalid arguments. Data must be an object.");const n={type:"post",subscription_id:t.id,data:r};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send post message for subscription ${t.id}: ${JSON.stringify(e)}`)})}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const r={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${t.id}: ${JSON.stringify(e)}`)}),t.instance,this.callbacks.execute(SUBSCRIPTION_REMOVED$1,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const r=e.protocolState.subscriptionsMap;let n=Object.keys(r).map(e=>r[e]);"string"==typeof t&&(n=n.filter(e=>e.branchKey===t)),n.forEach(e=>{delete r[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t).catch(t=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${e.id}: ${JSON.stringify(t)}`)})})}getSubscriptionList(e,t){if("object"!=typeof e)return[];let r=[];if(!e.protocolState.subscriptionsMap)return[];const n=e.protocolState.subscriptionsMap,i=Object.keys(n).map(e=>n[e]);return r="string"!=typeof t?i:i.filter(e=>e.branchKey===t),r}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,r=Object.keys(t).map(e=>t[e]),n=[];return r.forEach(e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===n.indexOf(t)&&n.push(t)}),n}onSubAdded(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED$1,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST$1,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED$1,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const r=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(SUBSCRIPTION_REMOVED$1,r,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),r=t?.instance??{},n={msg:e,arguments:e.arguments_kv||{},instance:r},i=this.serverRepository.getById(e.method_id);if(void 0===i){const t="No method with id "+e.method_id+" on this server.";return void this.sendSubscriptionFailed(t,e.subscription_id)}i.protocolState.subscriptionsMap&&i.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(SUBSCRIPTION_REQUEST$1,n,i)}sendSubscriptionFailed(e,t){const r={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send subscription failed message for subscription ${t}: ${JSON.stringify(e)}`)})}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const r=e.protocolState.branchKeyToStreamIdMap.filter(e=>e.key===t)[0];let n=r?r.streamId:void 0;return"string"==typeof n&&""!==n||(n=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:n})),n}},ServerProtocol$1=class{session;clientRepository;serverRepository;logger;callbacks=CallbackRegistryFactory$3();streaming;constructor(e,t,r,n){this.session=e,this.clientRepository=t,this.serverRepository=r,this.logger=n,this.streaming=new ServerStreaming$2(e,t,r,n.subLogger("streaming")),this.session.on("invoke",e=>this.handleInvokeMessage(e))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const r=e.definition,n=Object.assign({},{metadata:r.flags??{}},{streaming:t||!1}),i={type:"register",methods:[{id:e.repoId,name:r.name,display_name:r.displayName,description:r.description,version:r.version,flags:n,object_types:r.objectTypes||r.object_types,input_signature:r.accepts,result_signature:r.returns,restrictions:void 0}]};return this.session.send(i,{methodId:e.repoId}).then(()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)}).catch(t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t})}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,r,n){let i;i=r||""===r?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:r,context:n,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:n,request_id:void 0},this.session.sendFireAndForget(i).catch(r=>{this.logger.warn(`Failed to send method invocation result for method ${e.definition.name} invocation ${t} - ${JSON.stringify(r)}`)})}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,r){this.streaming.pushData(e,t,r)}pushDataToSingle(e,t,r){this.streaming.pushDataToSingle(e,t,r)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,r){this.streaming.acceptRequestOnBranch(e,t,r)}rejectRequest(e,t,r){this.streaming.rejectRequest(e,t,r)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,r=e.caller_id,n=e.method_id,i=e.arguments_kv,o=this.serverRepository.getList().filter(e=>e.repoId===n)[0];if(void 0===o)return;const s=this.clientRepository.getServerById(r)?.instance,a={args:i,instance:s};this.callbacks.execute("onInvoked",o,t,a)}},UserSubscription$1=class{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce((e,t)=>{if(t.subscriptionId){const r=this.repository.getServerById(t.serverId)?.instance;r&&e.push(r)}return e},[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach(t=>{e(t)})}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}},TimedCache$1=class{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=nanoid$6(10);this.cache.push({id:t,element:e});const r=setTimeout(()=>{const e=this.cache.findIndex(e=>e.id===t);e<0||this.cache.splice(e,1)},this.config.ELEMENT_TTL_MS);this.timeoutIds.push(r)}flush(){const e=this.cache.map(e=>e.element);return this.timeoutIds.forEach(e=>clearInterval(e)),this.cache=[],this.timeoutIds=[],e}};const STATUS_AWAITING_ACCEPT$1="awaitingAccept",STATUS_SUBSCRIBED$1="subscribed",ERR_MSG_SUB_FAILED$1="Subscription failed.",ERR_MSG_SUB_REJECTED$1="Subscription rejected.",ON_CLOSE_MSG_SERVER_INIT$1="ServerInitiated",ON_CLOSE_MSG_CLIENT_INIT$1="ClientInitiated";let ClientStreaming$1=class{session;repository;logger;subscriptionsList={};timedCache=new TimedCache$1({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,r,n,i,o){if(0===r.length)return void i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED$1+" No available servers matched the target params."});const s=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(s,e,t,n,i,t.methodResponseTimeout||1e4,o);"object"==typeof a?r.forEach(r=>{const n=r.server.id,i=r.methods.find(t=>t.name===e.name);if(!i)return void this.logger.error(`can not find method ${e.name} for target ${r.server.id}`);a.trackedServers.push({serverId:n,subscriptionId:void 0});const o={type:"subscribe",server_id:n,method_id:i.gatewayId,arguments_kv:t.arguments};this.session.send(o,{serverId:n,subLocalKey:s}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED$1+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,r,n,i,o,s){const a={localKey:e,status:STATUS_AWAITING_ACCEPT$1,method:t,params:r,success:n,error:i,trackedServers:[],handlers:{onData:s?.handlers.onData||[],onClosed:s?.handlers.onClosed||[],onConnected:s?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:s?.subscription};return s||(r.onData&&a.handlers.onData.push(r.onData),r.onClosed&&a.handlers.onClosed.push(r.onClosed),r.onConnected&&a.handlers.onConnected.push(r.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout(()=>{if(void 0===this.subscriptionsList[e])return;const n=this.subscriptionsList[e];n.status===STATUS_AWAITING_ACCEPT$1?(i({method:t,called_with:r.arguments,message:ERR_MSG_SUB_FAILED$1+" Subscription attempt timed out after "+o+" ms."}),delete this.subscriptionsList[e]):n.status===STATUS_SUBSCRIBED$1&&n.trackedServers.length>0&&(n.trackedServers=n.trackedServers.filter(e=>void 0!==e.subscriptionId),delete n.timeoutId,n.trackedServers.length<=0&&(this.callOnClosedHandlers(n),delete this.subscriptionsList[e]))},o),a}handleErrorSubscribing=e=>{const t=e._tag,r=t.subLocalKey,n=this.subscriptionsList[r];if("object"==typeof n&&(n.trackedServers=n.trackedServers.filter(e=>e.serverId!==t.serverId),n.trackedServers.length<=0)){if(clearTimeout(n.timeoutId),n.status===STATUS_AWAITING_ACCEPT$1){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",r="object"==typeof n.params.arguments?JSON.stringify(n.params.arguments):"{}";n.error({message:ERR_MSG_SUB_REJECTED$1+t+" Called with:"+r,called_with:n.params.arguments,method:n.method})}else n.status===STATUS_SUBSCRIBED$1&&this.callOnClosedHandlers(n);delete this.subscriptionsList[r]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=e._tag.serverId,i=r.trackedServers.filter(e=>e.serverId===n)[0];if("object"!=typeof i)return;i.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const o=r.status===STATUS_AWAITING_ACCEPT$1;if(r.status=STATUS_SUBSCRIBED$1,o){let e=!1,t=r.subscription;t?(t.setNewSubscription(r),r.success(t),e=!0):(t=new UserSubscription$1(this.repository,r),r.subscription=t,r.success(t));for(const n of r.handlers.onConnected)try{n(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.filter(t=>t.subscriptionId===e.subscription_id);if(1!==n.length)return;const i=e.oob,o=n[0].serverId,s=this.repository.getServerById(o),a=()=>({data:e.data,server:s?.instance??{},requestArguments:r.params.arguments,message:void 0,private:i}),c=r.handlers.onData,l=r.queued.data;c.length>0?c.forEach(e=>{"function"==typeof e&&e(a())}):l.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.length-1;r.trackedServers=r.trackedServers.filter(t=>t.subscriptionId!==e.subscription_id||(r.queued.closers.push(t.serverId),!1)),r.trackedServers.length===n&&(r.trackedServers.length<=0&&(this.timedCache.add(r),clearTimeout(r.timeoutId),this.callOnClosedHandlers(r),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const r=e.queued.closers.length,n=r>0?e.queued.closers[r-1]:null;let i;void 0!==n&&"string"==typeof n&&(i=this.repository.getServerById(n)?.instance??{}),e.handlers.onClosed.forEach(r=>{"function"==typeof r&&r({message:t||ON_CLOSE_MSG_SERVER_INIT$1,requestArguments:e.params.arguments||{},server:i,stream:e.method})})}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach(e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:ON_CLOSE_MSG_CLIENT_INIT$1}).catch(t=>{this.logger.warn(`Error sending unsubscribe for subscription id ${e.subscriptionId}: ${JSON.stringify(t)}`)}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])}),t.trackedServers=[],this.callOnClosedHandlers(t,ON_CLOSE_MSG_CLIENT_INIT$1),delete this.subscriptionsList[e])}},ClientProtocol$1=class{session;repository;logger;streaming;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("peer-added",e=>this.handlePeerAdded(e)),e.on("peer-removed",e=>this.handlePeerRemoved(e)),e.on("methods-added",e=>this.handleMethodsAddedMessage(e)),e.on("methods-removed",e=>this.handleMethodsRemovedMessage(e)),this.streaming=new ClientStreaming$1(e,t,r)}subscribe(e,t,r,n,i,o){this.streaming.subscribe(e,t,r,n,i,o)}invoke(e,t,r,n){const i=n.id,o={type:"call",server_id:i,method_id:t.gatewayId,arguments_kv:r};return this.session.send(o,{invocationId:e,serverId:i}).then(e=>this.handleResultMessage(e)).catch(e=>this.handleInvocationError(e))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,r=e.identity,n=!e.meta||e.meta.local,i=Number(r.process),o={machine:r.machine,pid:isNaN(i)?r.process:i,instance:r.instance,application:r.application,applicationName:r.applicationName,environment:r.environment,region:r.region,user:r.user,windowId:r.windowId,peerId:t,api:r.api,isLocal:n};this.repository.addServer(o,t)}handlePeerRemoved(e){const t=e.removed_id,r=e.reason;this.repository.removeServerById(t,r)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach(e=>{this.repository.addServerMethod(t,e)})}handleMethodsRemovedMessage(e){const t=e.server_id,r=e.methods,n=this.repository.getServerById(t);if(n){Object.keys(n.methods).forEach(e=>{const i=n.methods[e];r.indexOf(i.gatewayId)>-1&&this.repository.removeServerMethod(t,e)})}}handleResultMessage(e){const t=e._tag.invocationId,r=e.result,n=e._tag.serverId,i=this.repository.getServerById(n);return{invocationId:t,result:r,instance:i?.instance,status:InvokeStatus$1.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,r=e._tag.serverId,n=this.repository.getServerById(r),i=e.reason;return{invocationId:t,result:e.context,instance:n?.instance,status:InvokeStatus$1.Error,message:i}}return{invocationId:"",message:e.message,status:InvokeStatus$1.Error,error:e}}};function gW3ProtocolFactory$1(e,t,r,n,i,o){const s=i.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),l=t.domain("agm",["subscribed"]),u=new ServerProtocol$1(l,r,n,s.subLogger("server")),d=new ClientProtocol$1(l,r,s.subLogger("client"));return l.onJoined(i=>{r.addServer(e,t.peerId),i?async function(){s.info("reconnected - will replay registered methods and subscriptions"),d.drainSubscriptionsCache().forEach(e=>{const t=e.method,r=Object.assign({},e.params);s.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(r)}`),o.client.subscribe(t,r,void 0,void 0,e).then(()=>s.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>s.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=d.drainSubscriptions();for(const r of t){const t=r.method,n=Object.assign({},r.params);s.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),e.push(o.client.subscribe(t,n,void 0,void 0,r).then(()=>s.info(`subscribing to method ${t.name} DONE`)))}const r=n.getList();n.reset();for(const t of r){const r=t.definition;t.stream?e.push(o.server.createStream(r,t.streamCallbacks,void 0,void 0,t.stream).then(()=>s.info(`subscribing to method ${r.name} DONE`)).catch(()=>s.warn(`subscribing to method ${r.name} FAILED`))):t?.theFunction?.userCallback?e.push(o.register(r,t.theFunction.userCallback).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(o.registerAsync(r,t.theFunction.userCallbackAsync).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`)))}await Promise.all(e),s.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>s.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:d,server:u}),a=void 0)}),l.onLeft(()=>{r.reset()}),l.join(),c}let Interop$1=class{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let r;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new InstanceWrapper$1(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new ClientRepository$1(e.logger.subLogger("cRep"),this),this.serverRepository=new ServerRepository$1,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);r=gW3ProtocolFactory$1(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=r.then(t=>(this.protocol=t,this.client=new Client$1(this.protocol,this.clientRepository,this.instance,e),this.server=new Server$1(this.protocol,this.serverRepository),this))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,r,n){return this.client.subscribe(e,t,r,n)}createStream(e,t,r,n){return this.server.createStream(e,t,r,n)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,r,n,i,o){return this.client.invoke(e,t,r,n,i,o)}waitForMethod(e){const t=new PromiseWrapper$2,r=this.client.methodAdded(n=>{n.name===e&&(r(),t.resolve(n))});return t.promise}};const successMessages$1=["subscribed","success"];let MessageBus$1=class{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",successMessages$1),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()})}ready(){return this.readyPromise}publish=(e,t,r)=>{const{routingKey:n,target:i}=r||{},o=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:n,target_identity:i});this.session.send(o).catch(t=>{this.logger.error(`Failed to publish message to topic ${e} with routing key ${n} for ${JSON.stringify(i)}: ${JSON.stringify(t)}`)})};subscribe=(e,t,r)=>new Promise((n,i)=>{const{routingKey:o,target:s}=r||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:o,source:s});this.session.send(a).then(r=>{const{subscription_id:i}=r;this.subscriptions.push({subscription_id:i,topic:e,callback:t,source:s}),n({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:i,peer_id:this.peerId}).then(()=>{this.subscriptions=this.subscriptions.filter(e=>e.subscription_id!==i)}).catch(e=>{this.logger.warn(`Failed to send unsubscribe request for ${i}: ${JSON.stringify(e)}`)}),Promise.resolve())})}).catch(e=>i(e))});watchOnEvent=()=>{this.session.on("event",e=>{const{data:t,subscription_id:r}=e,n=e["publisher-identity"],i=this.subscriptions.find(e=>e.subscription_id===r);i&&(i.source?this.keysMatch(i.source,n)&&i.callback(t,i.topic,n):i.callback(t,i.topic,n))})};removeEmptyValues(e){const t={};return Object.keys(e).forEach(r=>{void 0!==e[r]&&null!==e[r]&&(t[r]=e[r])}),t}keysMatch(e,t){const r=Object.keys(e);let n=!0;return r.forEach(r=>{e[r]!==t[r]&&(n=!1)}),n}};const IOConnectCoreFactory$1=(e,t)=>{const r="object"==typeof window?window.iodesktop??window.glue42gd:void 0,n="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),i=timer$1("glue"),o=prepareConfig$1(e=e||{},t=t||{},r);let s,a,c,l,u,d,h;const p={};function g(e,t,r){h=c.canPublish("trace"),h&&c.trace(`registering ${e} module`);const n=n=>{if(t.initTime=r.stop(),t.initEndTime=r.endTime,t.marks=r.marks,!h)return;const i=n?`${e} failed - ${n.message}`:`${e} is ready - ${r.endTime-r.startTime}`;c.trace(i)};t.initStartTime=r.startTime,t.ready?t.ready().then(()=>{n()}).catch(e=>{const t="string"==typeof e?new Error(e):e;n(t)}):n(),Array.isArray(e)||(e=[e]),e.forEach(e=>{p[e]=t,IOConnectCoreFactory$1[e]=t})}function m(){const e=timer$1("metrics"),t=o.metrics,n=r?.getMetricsPublishingEnabled,i=o.connection.identity,a=n||(()=>!0),u=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return l=metrics$2({connection:t?s:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:i?.service??r?.applicationName??o.application,instance:i?.instance??i?.windowId??nanoid$6(10),disableAutoAppSystem:u,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",l,e),Promise.resolve()}function f(){const e=timer$1("interop"),t={connection:s,logger:c.subLogger("interop")};return a=new Interop$1(t),Logger$2.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function y(){const e=o.activities&&3===s.protocolVersion;if(o.contexts||e){const e=timer$1("contexts");u=new ContextsModule$1({connection:s,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof o.contexts&&o.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof o.contexts&&o.contexts.reAnnounceKnownContexts,subscribeOnGet:"object"!=typeof o.contexts||o.contexts.subscribeOnGet,subscribeOnUpdate:"object"!=typeof o.contexts||o.contexts.subscribeOnUpdate,onlyReAnnounceSubscribedContexts:"object"!=typeof o.contexts||o.contexts.onlyReAnnounceSubscribedContexts}),g("contexts",u,e)}else{const e=s.replayer;e&&e.drain(ContextMessageReplaySpec$1.name)}return Promise.resolve()}async function $(){if(!o.bus)return Promise.resolve();const e=timer$1("bus");return d=new MessageBus$1(s,c.subLogger("bus")),g("bus",d,e),Promise.resolve()}function b(e){try{return e.forEach(e=>{!function(e,t){const r=timer$1(e),n=t(p);n&&g(e,n,r)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return n.then(function(){const e=timer$1("logger");return c=new Logger$2(`${o.connection.identity?.application}`,void 0,o.customLogger),c.consoleLevel(o.logger.console),c.publishLevel(o.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)}).then(function(){const e=timer$1("connection");s=new Connection$1(o.connection,c.subLogger("connection"));let t=Promise.resolve(o.auth);return o.connection&&!o.auth&&(r?t=r.getGWToken().then(e=>({gatewayToken:e})):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then(t=>{let r;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return r=t,s.login(r)}).then(()=>(g("connection",s,e),o)).catch(e=>{throw s&&s.logout(),e})}).then(()=>Promise.all([m(),f(),y(),$()])).then(()=>a.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(Utils$1.isNode()&&"undefined"==="undefined".env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>b(o.libs||[])).then(function(){const e=Object.keys(p).map(e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const n={coreVersion:version$4,version:o.version};i.stop();const h={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:c,interop:a,agm:a,connection:s,metrics:l,contexts:u,bus:d,version:o.version,userConfig:e,done:()=>(c?.info("done called by user..."),s.logout())};if(h.performance={get glueVer(){return o.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=getAllTimers$1();return Object.keys(e).map(t=>{const r=e[t];return{name:t,duration:r.endTime-r.startTime,marks:r.marks,startTime:r.startTime,endTime:r.endTime}})}},Object.keys(p).forEach(e=>{const t=p[e];h[e]=t}),h.config={},Object.keys(o).forEach(e=>{h.config[e]=o[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{h.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(h),r&&r.updatePerfData&&r.updatePerfData(h.performance),h.agm){const e=(e,t,r)=>function(){return h.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${r}' instead.`),e.apply(h.agm,arguments)},t=h.agm;t.method_added=e(h.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(h.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(h.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(h.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(h.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return h}).catch(e=>Promise.reject({err:e,libs:p}))};"undefined"!=typeof window&&(window.IOConnectCore=IOConnectCoreFactory$1),IOConnectCoreFactory$1.version=version$4,IOConnectCoreFactory$1.default=IOConnectCoreFactory$1;const iOConnectBrowserFactory=createFactoryFunction(IOConnectCoreFactory$1);if("undefined"!=typeof window){const e=window;e.IOBrowser=iOConnectBrowserFactory,delete e.GlueCore,delete e.IOConnectCore}const legacyGlobal$1=window.glue42gd||window.glue42core,ioGlobal$1=window.iodesktop||window.iobrowser;legacyGlobal$1||ioGlobal$1||(window.iobrowser={webStarted:!1}),window.iodesktop||window.iobrowser.system||(window.iobrowser.system=setupGlobalSystem()),iOConnectBrowserFactory.version=version$1$1;const Glue42CoreMessageTypes={connectionRequest:{name:"connectionRequest"},connectionRejected:{name:"connectionRejected"},connectionAccepted:{name:"connectionAccepted"},platformPing:{name:"platformPing"},platformReady:{name:"platformReady"},platformUnload:{name:"platformUnload"},clientUnload:{name:"clientUnload"},parentPing:{name:"parentPing"},parentReady:{name:"parentReady"},gatewayDisconnect:{name:"gatewayDisconnect"},gatewayInternalConnect:{name:"gatewayInternalConnect"},transportSwitchRequest:{name:"transportSwitchRequest"},transportSwitchResponse:{name:"transportSwitchResponse"},getCurrentTransport:{name:"getCurrentTransport"},getCurrentTransportResponse:{name:"getCurrentTransportResponse"},checkPreferredLogic:{name:"checkPreferredLogic"},checkPreferredConnection:{name:"checkPreferredConnection"},checkPreferredLogicResponse:{name:"checkPreferredLogicResponse"},checkPreferredConnectionResponse:{name:"checkPreferredConnectionResponse"}},GlueWebPlatformControlName="T42.Web.Platform.Control",GlueWebPlatformStreamName="T42.Web.Platform.Stream",GlueClientControlName="T42.Web.Client.Control",GlueWebPlatformWorkspacesStreamName="T42.Web.Platform.WSP.Stream",GlueWorkspaceFrameClientControlName="T42.Workspaces.Control",GlueWorkspacesEventsReceiverName="T42.Workspaces.Events",GlueWebIntentsPrefix="Tick42.FDC3.Intents.",ChannelContextPrefix="___channel___",serviceWorkerBroadcastChannelName="glue42-core-worker",webPlatformTransportName="web-platform",defaultNoAppWindowComponentAppName$1="no-app-window",errorChannel=new MessageChannel,FDC3HelloRequestType="WCP1Hello",FDC3HelloResponseType="WCP2LoadUrl",FDC3ProxyUrl="https://fdc3-web-proxy.interop.io",publicLicKey="-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxY2hhPdsQVno6NwsKm0+\nnhfhHvFsapevdtPt78jZRWgSAv9nbNtcAHyAOqisL0T2FaWPwZZcMs1qQEyyyQIU\nbase/s7oVGj5jLU32kYuAf3rA7uIdCpxT8UhJtj740KFUgT946a7hTXHL2DejxV0\niJhhDKIl/2UFWfYdIygz4ECCperhBnDw4JrdbTs6BnMZNGaBmQFT/HjkFUxkKkjI\nccwQdahc+yB2azG8vVwjsvhag9lo/zfhEEEKNX7BVFDBiPK/2RswNf0yaSTBs0Cd\njo+gwFr69/gap7xWwxobAuwIGyuGZx3RfVphryB9CKPebDZE0N47FakMSS+cOrpk\nejTNzNjhGybjVxNvpHtYaP5hwRWbDeptZ+cu+nafXH8p0HiVkeIy1RqiSstiGZ3v\nOa31j0oDT4mIe7r0BuleqkCkCIDe8EB2n+xJieWJmFzooswrYMQ6ry2m0moPwYEQ\nib6v4DLw7LTsnz/kK7yWeWlv1LsPF09CEBlfJLXvT+tXWHzf/bbWxH7SU5vgil0L\nwhbe4UJwBW4Cf3QDCoFCqwnGXUbzF8EbDKxPVWeCZa0zxT2L44JwMyVz3U1z7cOp\nAzI43TpwU/6hD0LMim14XfUKhtdV7bp8ulRHxgkZoZHpz+7CuYZLT0dG5xOiwUsE\nAfLTMnm30gbSGK3vtNeXbq8CAwEAAQ==\n-----END PUBLIC KEY-----\n",noop$1=async()=>{},MAX_SET_TIMEOUT_DELAY=2147483647,DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1=3e4,DEFAULT_WAIT_TIMEOUT_MS=3e4,systemPrefsAppName="io-connect-platform",notificationsPrefsKey="_ioCB_notifications",connectionProtocolVersion="2.0.0",globalTickIntervalMSForScheduler=3e3,maxConcurrentRequestsForScheduler=4,defaultCacheDBName="io-connect-rest-cache",defaultPlatformConfig={windows:{windowResponseTimeoutMs:1e4,defaultWindowOpenBounds:{top:0,left:0,width:800,height:600}},applications:{local:[]},layouts:{mode:"idb",local:[]},channels:{definitions:[],mode:"single"},plugins:{definitions:[]},licenseKey:"",gateway:{logging:{level:"info"}},themes:{defaultTheme:"dark"},connection:{},browser:{},environment:{},workspacesFrameCache:!0},defaultNotificationsConfig={enable:!0,enableToasts:!0,sourceFilter:{allowed:["*"],blocked:[]},showNotificationBadge:!0,clearNotificationOnClick:!0},defaultManagerFeatures={applicationsStore:!0,layoutsStore:!0,preferencesStore:!0},defaultTargetString="*",defaultFetchTimeoutMs=3e3,defaultOpenerTimeoutMs=1e3,defaultPreferredDiscoveryIntervalMS=15e3,defaultClientPortRequestTimeoutMS=15e3,defaultClientPreferredLogicTestTimeoutMS=5e3,checkIsOpenerIOConnect=e=>{if(!window.opener)return Promise.resolve(!1);if(window.name.includes("g42-"))return Promise.resolve(!0);const t=e?.allowedClientFallbackOrigin||defaultTargetString;return new Promise(e=>{const r=t=>{const n=t.data?.glue42core;n&&n.type===Glue42CoreMessageTypes.platformReady.name&&(window.removeEventListener("message",r),e(!0))};window.addEventListener("message",r);const n={glue42core:{type:Glue42CoreMessageTypes.platformPing.name}};window.opener.postMessage(n,t),setTimeout(()=>e(!1),defaultOpenerTimeoutMs)})},checkIfPlacedInWorkspace=()=>-1!==window.name.indexOf("#wsp"),fallbackToEnterprise=async e=>{const t=e?.browserFactory?await(e?.browserFactory(e?.browser)):await iOConnectBrowserFactory(e?.browser);return e?.applications?.local?.length&&await t.appManager.inMemory.import(e.applications.local,"merge"),e?.layouts?.local?.length&&await t.layouts.import(e.layouts.local,"merge"),{io:t}};var commonjsGlobal$1="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var uaParser={exports:{}};!function(e,t){!function(r,n){var i="function",o="undefined",s="object",a="string",c="major",l="model",u="name",d="type",h="vendor",p="version",g="architecture",m="console",f="mobile",y="tablet",$="smarttv",b="wearable",v="embedded",w="Amazon",S="Apple",_="ASUS",E="BlackBerry",C="Browser",I="Chrome",T="Firefox",A="Google",D="Huawei",x="LG",R="Microsoft",O="Motorola",N="Opera",P="Samsung",k="Sharp",M="Sony",L="Xiaomi",F="Zebra",j="Facebook",U="Chromium OS",B="Mac OS",H=" Browser",q=function(e){for(var t={},r=0;r0?2===c.length?typeof c[1]==i?this[c[0]]=c[1].call(this,u):this[c[0]]=c[1]:3===c.length?typeof c[1]!==i||c[1].exec&&c[1].test?this[c[0]]=u?u.replace(c[1],c[2]):n:this[c[0]]=u?c[1].call(this,u,c[2]):n:4===c.length&&(this[c[0]]=u?c[3].call(this,u.replace(c[1],c[2])):n):this[c]=u||n;d+=2}},K=function(e,t){for(var r in t)if(typeof t[r]===s&&t[r].length>0){for(var i=0;i2&&(e[l]="iPad",e[d]=y),e},this.getEngine=function(){var e={};return e[u]=n,e[p]=n,J.call(e,$,v.engine),e},this.getOS=function(){var e={};return e[u]=n,e[p]=n,J.call(e,$,v.os),w&&!e[u]&&b&&b.platform&&"Unknown"!=b.platform&&(e[u]=b.platform.replace(/chrome os/i,U).replace(/macos/i,B)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return $},this.setUA=function(e){return $=typeof e===a&&e.length>500?G(e,500):e,this},this.setUA($),this};X.VERSION="1.0.40",X.BROWSER=q([u,p,c]),X.CPU=q([g]),X.DEVICE=q([l,h,d,m,f,$,y,b,v]),X.ENGINE=X.OS=q([u,p]),e.exports&&(t=e.exports=X),t.UAParser=X;var Y=typeof r!==o&&(r.jQuery||r.Zepto);if(Y&&!Y.ua){var Q=new X;Y.ua=Q.getResult(),Y.ua.get=function(){return Q.getUA()},Y.ua.set=function(e){Q.setUA(e);var t=Q.getResult();for(var r in t)Y.ua[r]=t[r]}}}("object"==typeof window?window:commonjsGlobal$1)}(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,dist={},builder$7={},_globalThis$7="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},VERSION$7="1.9.0",re$2=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function _makeCompatibilityCheck(e){var t=new Set([e]),r=new Set,n=e.match(re$2);if(!n)return function(){return!1};var i=+n[1],o=+n[2],s=+n[3];if(null!=n[4])return function(t){return t===e};function a(e){return r.add(e),!1}function c(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;var n=e.match(re$2);if(!n)return a(e);var l=+n[1],u=+n[2],d=+n[3];return null!=n[4]||i!==l?a(e):0===i?o===u&&s<=d?c(e):a(e):o<=u?c(e):a(e)}}var isCompatible=_makeCompatibilityCheck(VERSION$7),major=VERSION$7.split(".")[0],GLOBAL_OPENTELEMETRY_API_KEY=Symbol.for("opentelemetry.js.api."+major),_global$6=_globalThis$7;function registerGlobal(e,t,r,n){var i;void 0===n&&(n=!1);var o=_global$6[GLOBAL_OPENTELEMETRY_API_KEY]=null!==(i=_global$6[GLOBAL_OPENTELEMETRY_API_KEY])&&void 0!==i?i:{version:VERSION$7};if(!n&&o[e]){var s=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(s.stack||s.message),!1}if(o.version!==VERSION$7){s=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+e+" does not match previously registered API v"+VERSION$7);return r.error(s.stack||s.message),!1}return o[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+VERSION$7+"."),!0}function getGlobal(e){var t,r,n=null===(t=_global$6[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===t?void 0:t.version;if(n&&isCompatible(n))return null===(r=_global$6[GLOBAL_OPENTELEMETRY_API_KEY])||void 0===r?void 0:r[e]}function unregisterGlobal(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+VERSION$7+".");var r=_global$6[GLOBAL_OPENTELEMETRY_API_KEY];r&&delete r[e]}var __read$4=function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__spreadArray$3=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i=n?i.bind(t):function(){}}return eDiagLogLevel.ALL&&(e=DiagLogLevel.ALL),t=t||{},{error:r("error",DiagLogLevel.ERROR),warn:r("warn",DiagLogLevel.WARN),info:r("info",DiagLogLevel.INFO),debug:r("debug",DiagLogLevel.DEBUG),verbose:r("verbose",DiagLogLevel.VERBOSE)}}!function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(DiagLogLevel||(DiagLogLevel={}));var __read$3=function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__spreadArray$2=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i";a.warn("Current logger will be overwritten from "+l),c.warn("Current logger will overwrite one already registered from "+l)}return registerGlobal("diag",c,t,!0)},t.disable=function(){unregisterGlobal(API_NAME$4,t)},t.createComponentLogger=function(e){return new DiagComponentLogger(e)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e}(),__read$2=function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__values=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},BaggageImpl=function(){function e(e){this._entries=e?new Map(e):new Map}return e.prototype.getEntry=function(e){var t=this._entries.get(e);if(t)return Object.assign({},t)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var t=__read$2(e,2);return[t[0],t[1]]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],i=0;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__spreadArray$1=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},__spreadArray=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;iMAX_TRACE_STATE_LEN$1||(this._internalState=e.split(LIST_MEMBERS_SEPARATOR$1).reverse().reduce(function(e,t){var r=t.trim(),n=r.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER$1);if(-1!==n){var i=r.slice(0,n),o=r.slice(n+1,t.length);validateKey$1(i)&&validateValue$1(o)&&e.set(i,o)}return e},new Map),this._internalState.size>MAX_TRACE_STATE_ITEMS$1&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS$1))))},e.prototype._keys=function(){return Array.from(this._internalState.keys()).reverse()},e.prototype._clone=function(){var t=new e;return t._internalState=new Map(this._internalState),t},e}();function createTraceState(e){return new TraceStateImpl(e)}var context=ContextAPI.getInstance(),diag=DiagAPI.instance(),NoopMeterProvider=function(){function e(){}return e.prototype.getMeter=function(e,t,r){return NOOP_METER},e}(),NOOP_METER_PROVIDER=new NoopMeterProvider,API_NAME$2="metrics",MetricsAPI=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(e){return registerGlobal(API_NAME$2,e,DiagAPI.instance())},e.prototype.getMeterProvider=function(){return getGlobal(API_NAME$2)||NOOP_METER_PROVIDER},e.prototype.getMeter=function(e,t,r){return this.getMeterProvider().getMeter(e,t,r)},e.prototype.disable=function(){unregisterGlobal(API_NAME$2,DiagAPI.instance())},e}(),metrics$1=MetricsAPI.getInstance(),NoopTextMapPropagator=function(){function e(){}return e.prototype.inject=function(e,t){},e.prototype.extract=function(e,t){return e},e.prototype.fields=function(){return[]},e}(),BAGGAGE_KEY=createContextKey("OpenTelemetry Baggage Key");function getBaggage(e){return e.getValue(BAGGAGE_KEY)||void 0}function getActiveBaggage(){return getBaggage(ContextAPI.getInstance().active())}function setBaggage(e,t){return e.setValue(BAGGAGE_KEY,t)}function deleteBaggage(e){return e.deleteValue(BAGGAGE_KEY)}var API_NAME$1="propagation",NOOP_TEXT_MAP_PROPAGATOR=new NoopTextMapPropagator,PropagationAPI=function(){function e(){this.createBaggage=createBaggage,this.getBaggage=getBaggage,this.getActiveBaggage=getActiveBaggage,this.setBaggage=setBaggage,this.deleteBaggage=deleteBaggage}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(e){return registerGlobal(API_NAME$1,e,DiagAPI.instance())},e.prototype.inject=function(e,t,r){return void 0===r&&(r=defaultTextMapSetter),this._getGlobalPropagator().inject(e,t,r)},e.prototype.extract=function(e,t,r){return void 0===r&&(r=defaultTextMapGetter),this._getGlobalPropagator().extract(e,t,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){unregisterGlobal(API_NAME$1,DiagAPI.instance())},e.prototype._getGlobalPropagator=function(){return getGlobal(API_NAME$1)||NOOP_TEXT_MAP_PROPAGATOR},e}(),propagation=PropagationAPI.getInstance(),API_NAME="trace",TraceAPI=function(){function e(){this._proxyTracerProvider=new ProxyTracerProvider,this.wrapSpanContext=wrapSpanContext,this.isSpanContextValid=isSpanContextValid,this.deleteSpan=deleteSpan,this.getSpan=getSpan,this.getActiveSpan=getActiveSpan,this.getSpanContext=getSpanContext,this.setSpan=setSpan,this.setSpanContext=setSpanContext}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(e){var t=registerGlobal(API_NAME,this._proxyTracerProvider,DiagAPI.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},e.prototype.getTracerProvider=function(){return getGlobal(API_NAME)||this._proxyTracerProvider},e.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},e.prototype.disable=function(){unregisterGlobal(API_NAME,DiagAPI.instance()),this._proxyTracerProvider=new ProxyTracerProvider},e}(),trace=TraceAPI.getInstance(),index$2={context:context,diag:diag,metrics:metrics$1,propagation:propagation,trace:trace},esm$d=Object.freeze({__proto__:null,DiagConsoleLogger:DiagConsoleLogger,get DiagLogLevel(){return DiagLogLevel},INVALID_SPANID:INVALID_SPANID,INVALID_SPAN_CONTEXT:INVALID_SPAN_CONTEXT,INVALID_TRACEID:INVALID_TRACEID,ProxyTracer:ProxyTracer,ProxyTracerProvider:ProxyTracerProvider,ROOT_CONTEXT:ROOT_CONTEXT,get SamplingDecision(){return SamplingDecision$1},get SpanKind(){return SpanKind},get SpanStatusCode(){return SpanStatusCode},get TraceFlags(){return TraceFlags},get ValueType(){return ValueType},baggageEntryMetadataFromString:baggageEntryMetadataFromString,context:context,createContextKey:createContextKey,createNoopMeter:createNoopMeter,createTraceState:createTraceState,default:index$2,defaultTextMapGetter:defaultTextMapGetter,defaultTextMapSetter:defaultTextMapSetter,diag:diag,isSpanContextValid:isSpanContextValid,isValidSpanId:isValidSpanId,isValidTraceId:isValidTraceId,metrics:metrics$1,propagation:propagation,trace:trace}),require$$13$1=getAugmentedNamespace(esm$d),builder$6={},builder$5={},factoryBuilder={},validator$1={};Object.defineProperty(validator$1,"__esModule",{value:!0}),validator$1.Validator=void 0;class Validator{static isNullOrUndefined(e){return null==e}static throwIfNullOrUndefined(e,t,r){if(this.isNullOrUndefined(e))throw new Error(r||`${t} must be defined`)}}validator$1.Validator=Validator,Object.defineProperty(factoryBuilder,"__esModule",{value:!0}),factoryBuilder.MetricsFactoryBuilderValidator=void 0;const validator_1$s=validator$1;class MetricsFactoryBuilderValidator{validate(e){validator_1$s.Validator.throwIfNullOrUndefined(e,"builder"),validator_1$s.Validator.throwIfNullOrUndefined(e.logger,"logger")}validateDependencies(e){validator_1$s.Validator.throwIfNullOrUndefined(e,"dependencyContainer"),validator_1$s.Validator.throwIfNullOrUndefined(e.instanceFocusedHandler,"instanceFocusedHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.instanceReadyHandler,"instanceReadyHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.layoutRestoredHandler,"layoutRestoredHandler"),validator_1$s.Validator.throwIfNullOrUndefined(e.performanceProvider,"performanceProvider"),validator_1$s.Validator.throwIfNullOrUndefined(e.platformStartedHandler,"platformStartedHandler")}}factoryBuilder.MetricsFactoryBuilderValidator=MetricsFactoryBuilderValidator;var factory$2={},factory$1={};Object.defineProperty(factory$1,"__esModule",{value:!0}),factory$1.MetricsFactoryValidator=void 0;const validator_1$r=validator$1;class MetricsFactoryValidator{validate(e){validator_1$r.Validator.throwIfNullOrUndefined(e,"factory"),validator_1$r.Validator.throwIfNullOrUndefined(e.metricsFactories,"metricsFactories"),validator_1$r.Validator.throwIfNullOrUndefined(e.logger,"logger")}}factory$1.MetricsFactoryValidator=MetricsFactoryValidator;var _null$4={};Object.defineProperty(_null$4,"__esModule",{value:!0}),_null$4.NullMetric=void 0;class NullMetric{constructor(e,t){this.settings=e,this.logger=t,this.started=!1}start(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been started instead of ${this.settings.type} one`),this.started=!0,Promise.resolve()}stop(){var e;return null===(e=this.logger)||void 0===e||e.debug(`null metric has been stopped instead of ${this.settings.type} one`),this.started=!1,Promise.resolve()}add(){}record(){}}_null$4.NullMetric=NullMetric;var customCounter={},base$1={},base={};Object.defineProperty(base,"__esModule",{value:!0}),base.MetricBaseValidator=void 0;const validator_1$q=validator$1;class MetricBaseValidator{validate(e){validator_1$q.Validator.throwIfNullOrUndefined(e,"base"),validator_1$q.Validator.throwIfNullOrUndefined(e.logger,"logger"),this.validateSettings(e.settings)}validateSettings(e){validator_1$q.Validator.throwIfNullOrUndefined(e,"settings"),validator_1$q.Validator.throwIfNullOrUndefined(e.enabled,"enabled"),validator_1$q.Validator.throwIfNullOrUndefined(e.name,"name"),validator_1$q.Validator.throwIfNullOrUndefined(e.type,"type"),validator_1$q.Validator.throwIfNullOrUndefined(e.description,"description"),validator_1$q.Validator.throwIfNullOrUndefined(e.platformVersion,"platformVersion")}}base.MetricBaseValidator=MetricBaseValidator;var container$1={},container={};Object.defineProperty(container,"__esModule",{value:!0}),container.ContainerValidator=void 0;const validator_1$p=validator$1;class ContainerValidator{validate(e){validator_1$p.Validator.throwIfNullOrUndefined(e,"container"),validator_1$p.Validator.throwIfNullOrUndefined(e.settings,"metrics"),validator_1$p.Validator.throwIfNullOrUndefined(e.traces,"traces"),validator_1$p.Validator.throwIfNullOrUndefined(e.logs,"logs")}}container.ContainerValidator=ContainerValidator;var safeStringify$1={},isPlainObject$6={}; -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ -function isObject$5(e){return"[object Object]"===Object.prototype.toString.call(e)}function isPlainObject$5(e){let t,r;return!1!==isObject$5(e)&&(t=e.constructor,void 0===t||(r=t.prototype,!1!==isObject$5(r)&&!1!==r.hasOwnProperty("isPrototypeOf")))}Object.defineProperty(isPlainObject$6,"__esModule",{value:!0}),isPlainObject$6.isPlainObject=void 0,isPlainObject$6.isPlainObject=isPlainObject$5,Object.defineProperty(safeStringify$1,"__esModule",{value:!0}),safeStringify$1.safeStringify=void 0;const is_plain_object_1=isPlainObject$6;function safeStringify(e){return e?JSON.stringify(e,(e,t)=>t&&"object"==typeof t?(0,is_plain_object_1.isPlainObject)(t)?t:Object.prototype.toString.call(t):t):JSON.stringify(e)}safeStringify$1.safeStringify=safeStringify;var __awaiter$b=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(container$1,"__esModule",{value:!0}),container$1.Container=void 0;const container_1$r=container,safe_stringify_1$6=safeStringify$1;class Container{static get instance(){return Container._instance}static errorless(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return Container.handleErrorlessMode(e,t)}}static errorlessDefined(e,t){try{if("function"!=typeof e)return e;return e()}catch(e){return Container.handleErrorlessMode(e,t)}}static errorlessAsync(e,t){return __awaiter$b(this,void 0,void 0,function*(){try{if("function"!=typeof e)return e;return(yield e)()}catch(e){return Container.handleErrorlessMode(e,t)}})}static handleErrorlessMode(e,t){var r,n,i,o,s;let a;try{if((null==e?void 0:e.message)&&(a=(null==e?void 0:e.message)+" "+(null!==(r=null==e?void 0:e.stack)&&void 0!==r?r:(new Error).stack)),!a)try{a=(0,safe_stringify_1$6.safeStringify)(e)+" "+(new Error).stack}catch(e){}if(!a)try{a=(null==e?void 0:e.toString())+" "+(new Error).stack}catch(e){}}catch(e){}a||(a="unknown "+(new Error).stack);try{if(!(null===(i=null===(n=Container.instance)||void 0===n?void 0:n.settings)||void 0===i?void 0:i.errorlessMode))throw null===(o=Container.instance.logger)||void 0===o||o.error("Observed error "+a),e}catch(t){throw e}try{return null===(s=Container.instance.logger)||void 0===s||s.warn("Caught error "+a),t}catch(e){return t}}constructor(e,t,r,n,i){this._settings=e,this.traces=t,this.metrics=r,this.logs=n,this.logger=i,this.started=!1;(new container_1$r.ContainerValidator).validate(this),Container._instance=this}waitForFinalExport(e){var t,r,n;return Promise.all([null===(t=this.traces)||void 0===t?void 0:t.waitForFinalExport(e),null===(r=this.metrics)||void 0===r?void 0:r.waitForFinalExport(e),null===(n=this.logs)||void 0===n?void 0:n.waitForFinalExport(e)])}get settings(){return this._settings}start(){return __awaiter$b(this,void 0,void 0,function*(){const e=this.metrics.settings.enabled?this.metrics.start():Promise.resolve(),t=this.traces.settings.enabled?this.traces.start():Promise.resolve(),r=this.logs.settings.enabled?this.logs.start():Promise.resolve();yield Promise.all([e,t,r]),this.started=!0})}stop(){return __awaiter$b(this,void 0,void 0,function*(){const e=this.metrics.started?this.metrics.stop():Promise.resolve(),t=this.traces.started?this.traces.stop():Promise.resolve(),r=this.logs.started?this.logs.stop():Promise.resolve();yield Promise.all([e,t,r]),this.started=!1})}}container$1.Container=Container;var __awaiter$a=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(base$1,"__esModule",{value:!0}),base$1.MetricBase=void 0;const base_1$h=base,container_1$q=container$1;class MetricBase{constructor(e,t,r){this.settings=e,this.meter=t,this.logger=r,this.started=!1;(new base_1$h.MetricBaseValidator).validate(this)}start(){return __awaiter$a(this,void 0,void 0,function*(){try{yield this.createMetric(),this.logger.debug(`metric ${this.settings.name} has been created`),yield this.subscribe(),this.logger.debug(`metric ${this.settings.name} has subscribed`),this.started=!0}catch(e){const t=`error while starting and subscribing for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}return Promise.resolve()})}stop(){return __awaiter$a(this,void 0,void 0,function*(){try{yield this.unsubscribe(),this.logger.debug(`metric ${this.settings.name} has unsubscribed`),yield this.destroyMetric(),this.logger.debug(`metric ${this.settings.name} has been destroyed`),this.started=!1}catch(e){const t=`error while stopping and unsubscribing for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}return Promise.resolve()})}createMetric(){const e=this.settings.name||this.settings.type+"-"+this.createUniqueName(10),t=this.settings.description,r=this.settings.unit;return this.metricAny=this.createMetricCore(e,{description:t,unit:r}),Promise.resolve()}subscribe(){return Promise.resolve()}unsubscribe(){return Promise.resolve()}destroyMetric(){return Promise.resolve()}getData(){return Object.assign({platformVersion:this.settings.platformVersion,user:this.settings.user},container_1$q.Container.errorless(this.settings.additionalAttributes))}getApplicationData(e){return Object.assign(Object.assign({},this.getData()),{application:e})}getLayoutData(e){return Object.assign(Object.assign({},this.getData()),{layout:e})}createUniqueName(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";let r="";const n=new Uint8Array(e);return crypto.getRandomValues(n),n.forEach(e=>{r+=t[e%52]}),r}}base$1.MetricBase=MetricBase,Object.defineProperty(customCounter,"__esModule",{value:!0}),customCounter.CustomCounterMetric=void 0;const base_1$g=base$1;class CustomCounterMetric extends base_1$g.MetricBase{constructor(e,t,r){super(e,t,r),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createCounter(e,t)}add(e,t){var r;null===(r=this.metric)||void 0===r||r.add(e,Object.assign(Object.assign({},this.getData()),t))}}customCounter.CustomCounterMetric=CustomCounterMetric;var customHistogram={};Object.defineProperty(customHistogram,"__esModule",{value:!0}),customHistogram.CustomHistogramMetric=void 0;const base_1$f=base$1;class CustomHistogramMetric extends base_1$f.MetricBase{constructor(e,t,r){super(e,t,r),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createHistogram(e,t)}record(e,t){var r;null===(r=this.metric)||void 0===r||r.record(e,Object.assign(Object.assign({},this.getData()),t))}}customHistogram.CustomHistogramMetric=CustomHistogramMetric;var customUpDownCounter={};Object.defineProperty(customUpDownCounter,"__esModule",{value:!0}),customUpDownCounter.CustomUpDownCounterMetric=void 0;const base_1$e=base$1;class CustomUpDownCounterMetric extends base_1$e.MetricBase{constructor(e,t,r){super(e,t,r),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createUpDownCounter(e,t)}add(e,t){var r;null===(r=this.metric)||void 0===r||r.add(e,Object.assign(Object.assign({},this.getData()),t))}}customUpDownCounter.CustomUpDownCounterMetric=CustomUpDownCounterMetric;var customObservableGauge={},observable={},__awaiter$9=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(observable,"__esModule",{value:!0}),observable.ObservableMetricBase=void 0;const base_1$d=base$1,container_1$p=container$1;class ObservableMetricBase extends base_1$d.MetricBase{constructor(e,t,r,n,i,o){super(e,t,r),this.observeCallback=n,this.subscribeCallback=i,this.unsubcribeCallback=o}createMetric(){const e=Object.create(null,{createMetric:{get:()=>super.createMetric}});return __awaiter$9(this,void 0,void 0,function*(){yield e.createMetric.call(this),this.metric=this.metricAny})}subscribeCore(){return container_1$p.Container.errorlessAsync(()=>{var e,t;return null!==(t=null===(e=this.subscribeCallback)||void 0===e?void 0:e.call(this))&&void 0!==t?t:Promise.resolve()})}unsubscribeCore(){return container_1$p.Container.errorlessAsync(()=>{var e,t;return null!==(t=null===(e=this.unsubcribeCallback)||void 0===e?void 0:e.call(this))&&void 0!==t?t:Promise.resolve()})}observeCore(e){return container_1$p.Container.errorlessAsync(()=>{var t,r;return null!==(r=null===(t=this.observeCallback)||void 0===t?void 0:t.call(this,e))&&void 0!==r?r:Promise.resolve()})}subscribe(){return __awaiter$9(this,void 0,void 0,function*(){this.observableCallback=this.observe.bind(this),this.metric.addCallback(this.observableCallback),yield this.subscribeCore()})}destroyMetric(){return this.metric.removeCallback(this.observableCallback),Promise.resolve()}unsubscribe(){return this.unsubscribeCore()}observe(e){return __awaiter$9(this,void 0,void 0,function*(){try{this.logger.debug(`observe is being invoked for metric ${this.settings.name}`),yield this.observeCore(e),this.logger.debug(`gauge metric ${this.settings.name} has been observed`)}catch(e){const t=`error while executing observe for metric ${this.settings.name} from type: ${this.settings.type}`;this.logger.warn(t,e)}})}}observable.ObservableMetricBase=ObservableMetricBase,Object.defineProperty(customObservableGauge,"__esModule",{value:!0}),customObservableGauge.CustomObservableGaugeMetric=void 0;const observable_1$5=observable;class CustomObservableGaugeMetric extends observable_1$5.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableGauge(e,t)}}customObservableGauge.CustomObservableGaugeMetric=CustomObservableGaugeMetric;var customObservableCounter={};Object.defineProperty(customObservableCounter,"__esModule",{value:!0}),customObservableCounter.CustomObservableCounterMetric=void 0;const observable_1$4=observable;class CustomObservableCounterMetric extends observable_1$4.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableCounter(e,t)}}customObservableCounter.CustomObservableCounterMetric=CustomObservableCounterMetric;var customObservableUpDownCounter={};Object.defineProperty(customObservableUpDownCounter,"__esModule",{value:!0}),customObservableUpDownCounter.CustomObservableUpDownCounterMetric=void 0;const observable_1$3=observable;class CustomObservableUpDownCounterMetric extends observable_1$3.ObservableMetricBase{createMetricCore(e,t){var r;return null===(r=this.meter)||void 0===r?void 0:r.createObservableUpDownCounter(e,t)}}customObservableUpDownCounter.CustomObservableUpDownCounterMetric=CustomObservableUpDownCounterMetric;var customGauge={};Object.defineProperty(customGauge,"__esModule",{value:!0}),customGauge.CustomGaugeMetric=void 0;const base_1$c=base$1;class CustomGaugeMetric extends base_1$c.MetricBase{constructor(e,t,r){super(e,t,r),this.meter=t}createMetricCore(e,t){return this.metric=this.meter.createGauge(e,t)}record(e,t){var r;null===(r=this.metric)||void 0===r||r.record(e,Object.assign(Object.assign({},this.getData()),t))}}customGauge.CustomGaugeMetric=CustomGaugeMetric,Object.defineProperty(factory$2,"__esModule",{value:!0}),factory$2.MetricsFactory=void 0;const factory_1$1=factory$1,null_1$2=_null$4,customCounter_1=customCounter,customHistogram_1=customHistogram,customUpDownCounter_1=customUpDownCounter,customObservableGauge_1=customObservableGauge,customObservableCounter_1=customObservableCounter,customObservableUpDownCounter_1=customObservableUpDownCounter,customGauge_1=customGauge;class MetricsFactory{constructor(e,t,r){this.logger=e,this.metricsFactories=t,this.meter=r;(new factory_1$1.MetricsFactoryValidator).validate(this)}create(e,t,r,n){const i=e.type;if(~i.indexOf("observable")&&!t)throw new Error(`Metric type ${i} requires observeCallback argument to be provided.`);if(this.metricsFactories.has(i)){return this.metricsFactories.get(i)(e)}if("custom_observable_gauge"===i)return new customObservableGauge_1.CustomObservableGaugeMetric(e,this.meter,this.logger,t,r,n);if("custom_observable_counter"===i)return new customObservableCounter_1.CustomObservableCounterMetric(e,this.meter,this.logger,t,r,n);if("custom_observable_up_down_counter"===i)return new customObservableUpDownCounter_1.CustomObservableUpDownCounterMetric(e,this.meter,this.logger,t,r,n);if("custom_counter"===i)return new customCounter_1.CustomCounterMetric(e,this.meter,this.logger);if("custom_gauge"===i)return new customGauge_1.CustomGaugeMetric(e,this.meter,this.logger);if("custom_up_down_counter"===i)return new customUpDownCounter_1.CustomUpDownCounterMetric(e,this.meter,this.logger);if("custom_histogram"===i)return new customHistogram_1.CustomHistogramMetric(e,this.meter,this.logger);return this.createNullMetric(e,"not supported")}createNullMetric(e,t){this.logger.debug(`cannot create ${e.name} metric, reason: ${t}`);return new null_1$2.NullMetric(e,this.logger)}}factory$2.MetricsFactory=MetricsFactory;var count$3={},count$2={};Object.defineProperty(count$2,"__esModule",{value:!0}),count$2.ApplicationCountMetricValidator=void 0;const validator_1$o=validator$1;class ApplicationCountMetricValidator{validate(e){validator_1$o.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$o.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler"),validator_1$o.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler")}validateInstanceStarted(e){validator_1$o.Validator.throwIfNullOrUndefined(e,"args"),validator_1$o.Validator.throwIfNullOrUndefined(e.application,"application")}validateInstanceStopped(e){validator_1$o.Validator.throwIfNullOrUndefined(e,"args"),validator_1$o.Validator.throwIfNullOrUndefined(e.application,"application")}}count$2.ApplicationCountMetricValidator=ApplicationCountMetricValidator,Object.defineProperty(count$3,"__esModule",{value:!0}),count$3.ApplicationCountMetric=void 0;const base_1$b=base$1,count_1$2=count$2,container_1$o=container$1;class ApplicationCountMetric extends base_1$b.MetricBase{constructor(e,t,r,n,i){super(e,t,r),this.meter=t,this.instanceStartedHandler=n,this.instanceStoppedHandler=i,this.validator=new count_1$2.ApplicationCountMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appCountMetric=this.meter.createUpDownCounter(e,t)}subscribe(){return this.instanceStartedUn=container_1$o.Container.errorless(()=>this.instanceStartedHandler(this.handleInstanceStarted.bind(this))),this.instanceStoppedUn=container_1$o.Container.errorless(()=>this.instanceStoppedHandler(this.handleInstanceStopped.bind(this))),Promise.resolve()}unsubscribe(){return container_1$o.Container.errorless(()=>this.instanceStartedUn),container_1$o.Container.errorless(()=>this.instanceStoppedUn),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceStarted(e){try{this.validator.validateInstanceStarted(e),this.logger.debug(`instance started for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appCountMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleInstanceStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}handleInstanceStopped(e){try{this.validator.validateInstanceStopped(e),this.logger.debug(`instance stopped for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appCountMetric.add(-1,t),this.logger.debug(`metric ${this.settings.name} sent 1 less for app ${t.application}`)}catch(e){const t=`error while executing handleInstanceStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}count$3.ApplicationCountMetric=ApplicationCountMetric;var cpu$1={},perf={};Object.defineProperty(perf,"__esModule",{value:!0}),perf.PerformanceProviderValidator=void 0;const validator_1$n=validator$1;class PerformanceProviderValidator{validate(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"performanceProvider")}validateAppsCPU(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"data"),e.forEach(e=>{validator_1$n.Validator.throwIfNullOrUndefined(e,"item"),validator_1$n.Validator.throwIfNullOrUndefined(e.app,"app"),validator_1$n.Validator.throwIfNullOrUndefined(e.instance,"instance"),validator_1$n.Validator.throwIfNullOrUndefined(e.cpu,"cpu")})}validateAppsMemory(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"data"),e.forEach(e=>{validator_1$n.Validator.throwIfNullOrUndefined(e,"item"),validator_1$n.Validator.throwIfNullOrUndefined(e.app,"app"),validator_1$n.Validator.throwIfNullOrUndefined(e.instance,"instance"),validator_1$n.Validator.throwIfNullOrUndefined(e.memory,"memory")})}validateSystemCPU(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"data"),validator_1$n.Validator.throwIfNullOrUndefined(e.current,"current"),validator_1$n.Validator.throwIfNullOrUndefined(e.average,"average"),validator_1$n.Validator.throwIfNullOrUndefined(e.platform,"platform")}validateSystemMemory(e){validator_1$n.Validator.throwIfNullOrUndefined(e,"data"),validator_1$n.Validator.throwIfNullOrUndefined(e.platformTotal,"platformTotal"),validator_1$n.Validator.throwIfNullOrUndefined(e.systemFree,"systemFree"),validator_1$n.Validator.throwIfNullOrUndefined(e.systemTotal,"systemTotal")}}perf.PerformanceProviderValidator=PerformanceProviderValidator;var zeroOutClosedAppGaugeMetricBase={},__awaiter$8=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(zeroOutClosedAppGaugeMetricBase,"__esModule",{value:!0}),zeroOutClosedAppGaugeMetricBase.ZeroOutClosedAppGaugeMetricBase=void 0;const observable_1$2=observable;class ZeroOutClosedAppGaugeMetricBase extends observable_1$2.ObservableMetricBase{observeCore(e){return __awaiter$8(this,void 0,void 0,function*(){const t=yield this.observeCoreCore(e);if(this.reported)for(const r of this.reported.filter(e=>!t.some(t=>e.instance===t.instance))){const t=Object.assign({applicationInstance:r.instance},this.getApplicationData(r.app));e.observe(0,t),this.logger.debug(`metric ${this.settings.name} sent 0 for closed app ${t.application} and instance ${t.applicationInstance}`)}this.reported=t})}createMetricCore(e,t){return this.meter.createObservableGauge(e,t)}}zeroOutClosedAppGaugeMetricBase.ZeroOutClosedAppGaugeMetricBase=ZeroOutClosedAppGaugeMetricBase;var __awaiter$7=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(cpu$1,"__esModule",{value:!0}),cpu$1.ApplicationCPUMetric=void 0;const perf_1$3=perf,validator_1$m=validator$1,zeroOutClosedAppGaugeMetricBase_1$1=zeroOutClosedAppGaugeMetricBase,container_1$n=container$1;class ApplicationCPUMetric extends zeroOutClosedAppGaugeMetricBase_1$1.ZeroOutClosedAppGaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.perfProvider=n}subscribeCore(){return Promise.resolve()}observeCoreCore(e){return __awaiter$7(this,void 0,void 0,function*(){const t=new perf_1$3.PerformanceProviderValidator;t.validate(this.perfProvider);const r=yield container_1$n.Container.errorlessAsync(()=>this.perfProvider.getAppsCPU());return validator_1$m.Validator.isNullOrUndefined(r)?[]:(t.validateAppsCPU(r),r.forEach(t=>{const r=Object.assign({applicationInstance:t.instance},this.getApplicationData(t.app));e.observe(t.cpu,r),this.logger.debug(`metric ${this.settings.name} sent cpu ${t.cpu} for app ${r.application} and instance ${r.applicationInstance}`)}),r)})}unsubscribeCore(){return Promise.resolve()}}cpu$1.ApplicationCPUMetric=ApplicationCPUMetric;var crash$1={},crash={};Object.defineProperty(crash,"__esModule",{value:!0}),crash.PlatformCrashMetricValidator=void 0;const validator_1$l=validator$1;class PlatformCrashMetricValidator{validate(e){validator_1$l.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$l.Validator.throwIfNullOrUndefined(e.instanceCrashHandler,"applicationCrashHandler")}validateApplicationCrash(e){validator_1$l.Validator.throwIfNullOrUndefined(e,"args"),validator_1$l.Validator.throwIfNullOrUndefined(e.application,"application")}}crash.PlatformCrashMetricValidator=PlatformCrashMetricValidator,Object.defineProperty(crash$1,"__esModule",{value:!0}),crash$1.ApplicationCrashMetric=void 0;const base_1$a=base$1,crash_1$1=crash,container_1$m=container$1;class ApplicationCrashMetric extends base_1$a.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceCrashHandler=n,this.validator=new crash_1$1.PlatformCrashMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.applicationCrashMetric=this.meter.createCounter(e,t)}subscribe(){return this.applicationCrashUn=container_1$m.Container.errorless(()=>this.instanceCrashHandler(this.handleInstanceCrash.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return container_1$m.Container.errorless(()=>{var e;return null===(e=this.applicationCrashUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleInstanceCrash(e){try{this.validator.validateApplicationCrash(e),this.logger.debug(`crash for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=Object.assign({reason:e.reason},this.getApplicationData(e.application));this.applicationCrashMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleApplicationCrash for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}crash$1.ApplicationCrashMetric=ApplicationCrashMetric;var duration$3={},duration$2={};Object.defineProperty(duration$2,"__esModule",{value:!0}),duration$2.ApplicationDurationMetricValidator=void 0;const validator_1$k=validator$1;class ApplicationDurationMetricValidator{validate(e){validator_1$k.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$k.Validator.throwIfNullOrUndefined(e.instanceFocusHandler,"instanceFocusHandler")}validateFocusChanged(e){validator_1$k.Validator.throwIfNullOrUndefined(e,"args"),validator_1$k.Validator.throwIfNullOrUndefined(e.application,"application"),validator_1$k.Validator.throwIfNullOrUndefined(e.focused,"focused")}}duration$2.ApplicationDurationMetricValidator=ApplicationDurationMetricValidator,Object.defineProperty(duration$3,"__esModule",{value:!0}),duration$3.ApplicationDurationMetric=void 0;const validator_1$j=validator$1,duration_1$2=duration$2,observable_1$1=observable,container_1$l=container$1;class ApplicationDurationMetric extends observable_1$1.ObservableMetricBase{constructor(e,t,r,n){super(e,t,r),this.instanceFocusHandler=n,this.focusedTimes=new Map,this.validator=new duration_1$2.ApplicationDurationMetricValidator,this.validator.validate(this)}createMetricCore(){const e={explicitBucketBoundaries:this.settings.buckets};return this.appDurationMetric=this.meter.createHistogram(this.settings.name,{description:this.settings.description,unit:this.settings.unit,advice:e}),this.meter.createObservableGauge(this.createUniqueName(10))}sendMetric(e,t){e.forEach(e=>{this.appDurationMetric.record(e,t),this.logger.debug(`metric ${this.settings.name} sent focused time ${e} for app ${t.application}`)})}observeCore(){return this.focusedTimes.forEach((e,t)=>{const r=this.getApplicationData(t);this.sendMetric(e,r),e.splice(0)}),Promise.resolve()}subscribeCore(){return this.unInstanceFocusHandler=container_1$l.Container.errorless(()=>this.instanceFocusHandler(this.handleFocusChanged.bind(this))),Promise.resolve()}unsubscribeCore(){return container_1$l.Container.errorless(()=>{var e;return null===(e=this.unInstanceFocusHandler)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleFocusChanged(e){try{return this.validator.validateFocusChanged(e),this.logger.debug(`focused changed is being invoked for metric ${this.settings.name} with ${JSON.stringify(e)}`),this.handleFocusChangedCore(e)}catch(e){const t=`error while executing handleFocusChanges for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}handleFocusChangedCore(e){const t=e.focused,r=e.application;if(t)this.handleGotFocus(r);else try{this.handleLostFocus(r)}finally{this.currentFocusedApp=void 0}}handleGotFocus(e){const t=(new Date).getTime();this.currentFocusedApp={name:e,gotFocusTime:t},this.focusedTimes.has(this.currentFocusedApp.name)||this.focusedTimes.set(this.currentFocusedApp.name,[]),this.logger.debug(`got focus event has been added for metric ${this.settings.name}`)}handleLostFocus(e){if(validator_1$j.Validator.isNullOrUndefined(this.currentFocusedApp))throw new Error(`cannot handle focus lost for application ${e} since there is no previous got focus event`);const t=this.currentFocusedApp.name,r=this.currentFocusedApp.gotFocusTime;if(e!==t)throw new Error(`cannot handle focus lost for application ${e} since the previous got focus event had come from application ${t}`);if(!this.focusedTimes.has(e))throw new Error(`there is no got focus event for ${e}`);this.addFocusLostEventCore(t,r),this.logger.debug(`lost focus event has been added for metric ${this.settings.name}`)}addFocusLostEventCore(e,t){const r=(new Date).getTime()-t;this.focusedTimes.get(e).push(r)}}duration$3.ApplicationDurationMetric=ApplicationDurationMetric;var durationSoft={},__awaiter$6=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(durationSoft,"__esModule",{value:!0}),durationSoft.ApplicationDurationSoftMetric=void 0;const duration_1$1=duration$3;class ApplicationDurationSoftMetric extends duration_1$1.ApplicationDurationMetric{observeCore(){const e=Object.create(null,{observeCore:{get:()=>super.observeCore}});return __awaiter$6(this,void 0,void 0,function*(){const t=void 0!==this.currentFocusedApp,r=t?this.currentFocusedApp.name:void 0;return t&&this.handleFocusChanged({application:r,focused:!1}),yield e.observeCore.call(this),t&&this.handleFocusChanged({application:r,focused:!0}),Promise.resolve()})}}durationSoft.ApplicationDurationSoftMetric=ApplicationDurationSoftMetric;var error$J={},error$I={};Object.defineProperty(error$I,"__esModule",{value:!0}),error$I.ApplicationErrorMetricValidator=void 0;const validator_1$i=validator$1;class ApplicationErrorMetricValidator{validate(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$i.Validator.throwIfNullOrUndefined(e.instanceErrorHandler,"appErrorHandler")}validateApplicationError(e){validator_1$i.Validator.throwIfNullOrUndefined(e,"args"),validator_1$i.Validator.throwIfNullOrUndefined(e.application,"application")}}error$I.ApplicationErrorMetricValidator=ApplicationErrorMetricValidator,Object.defineProperty(error$J,"__esModule",{value:!0}),error$J.ApplicationErrorMetric=void 0;const base_1$9=base$1,error_1$2=error$I,container_1$k=container$1;class ApplicationErrorMetric extends base_1$9.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceErrorHandler=n,this.validator=new error_1$2.ApplicationErrorMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appErrorMetric=this.meter.createCounter(e,t)}subscribe(){return this.appErrorUn=container_1$k.Container.errorless(()=>this.instanceErrorHandler(this.instanceApplicationError.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return container_1$k.Container.errorless(()=>{var e;return null===(e=this.appErrorUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}instanceApplicationError(e){try{this.validator.validateApplicationError(e),this.logger.debug(`app error for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appErrorMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleAppError for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}error$J.ApplicationErrorMetric=ApplicationErrorMetric;var memory$1={},__awaiter$5=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(memory$1,"__esModule",{value:!0}),memory$1.ApplicationMemoryMetric=void 0;const perf_1$2=perf,validator_1$h=validator$1,zeroOutClosedAppGaugeMetricBase_1=zeroOutClosedAppGaugeMetricBase,container_1$j=container$1;class ApplicationMemoryMetric extends zeroOutClosedAppGaugeMetricBase_1.ZeroOutClosedAppGaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.perfProvider=n,this.validator=new perf_1$2.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}subscribeCore(){return Promise.resolve()}observeCoreCore(e){return __awaiter$5(this,void 0,void 0,function*(){const t=yield container_1$j.Container.errorlessAsync(()=>this.perfProvider.getAppsMemory());return validator_1$h.Validator.isNullOrUndefined(t)?[]:(this.validator.validateAppsMemory(t),t.forEach(t=>{var r;const n=Object.assign({applicationInstance:t.instance},this.getApplicationData(t.app));e.observe(null!==(r=t.memory)&&void 0!==r?r:0,n),this.logger.debug(`metric ${this.settings.name} sent memory ${t.memory} for app ${n.application} and instance ${n.applicationInstance}`)}),t)})}unsubscribeCore(){return Promise.resolve()}}memory$1.ApplicationMemoryMetric=ApplicationMemoryMetric;var started$2={},started$1={};Object.defineProperty(started$1,"__esModule",{value:!0}),started$1.ApplicationStartedMetricValidator=void 0;const validator_1$g=validator$1;class ApplicationStartedMetricValidator{validate(e){validator_1$g.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$g.Validator.throwIfNullOrUndefined(e.instanceStartedHandler,"instanceStartedHandler")}validateInstanceStarted(e){validator_1$g.Validator.throwIfNullOrUndefined(e,"args"),validator_1$g.Validator.throwIfNullOrUndefined(e.application,"application")}}started$1.ApplicationStartedMetricValidator=ApplicationStartedMetricValidator,Object.defineProperty(started$2,"__esModule",{value:!0}),started$2.ApplicationStartedMetric=void 0;const base_1$8=base$1,started_1$1=started$1,container_1$i=container$1;class ApplicationStartedMetric extends base_1$8.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceStartedHandler=n,this.validator=new started_1$1.ApplicationStartedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStartedMetric=this.meter.createCounter(e,t)}subscribe(){return this.instanceStartedUn=container_1$i.Container.errorless(()=>this.instanceStartedHandler(this.handleInstanceStarted.bind(this))),Promise.resolve()}destroyMetric(){return Promise.resolve()}unsubscribe(){return container_1$i.Container.errorless(()=>{var e;return null===(e=this.instanceStartedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleInstanceStarted(e){try{this.validator.validateInstanceStarted(e),this.logger.debug(`instance started for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appStartedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleInstanceStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}started$2.ApplicationStartedMetric=ApplicationStartedMetric;var startup$4={},startupHistogram$1={};Object.defineProperty(startupHistogram$1,"__esModule",{value:!0}),startupHistogram$1.ApplicationStartupHistogramMetricValidator=void 0;const validator_1$f=validator$1;class ApplicationStartupHistogramMetricValidator{validate(e){validator_1$f.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$f.Validator.throwIfNullOrUndefined(e.instanceReadyHandler,"instanceReadyHandler")}validateInstanceReady(e){validator_1$f.Validator.throwIfNullOrUndefined(e,"args"),validator_1$f.Validator.throwIfNullOrUndefined(e.application,"application"),validator_1$f.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$f.Validator.throwIfNullOrUndefined(e.endTime,"endTime")}}startupHistogram$1.ApplicationStartupHistogramMetricValidator=ApplicationStartupHistogramMetricValidator,Object.defineProperty(startup$4,"__esModule",{value:!0}),startup$4.ApplicationStartupMetric=void 0;const startupHistogram_1$1=startupHistogram$1,base_1$7=base$1,container_1$h=container$1;class ApplicationStartupMetric extends base_1$7.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceReadyHandler=n,this.validator=new startupHistogram_1$1.ApplicationStartupHistogramMetricValidator,this.validator.validate(this)}createMetricCore(e,t){const r={explicitBucketBoundaries:this.settings.buckets};return this.appStartupMetric=this.meter.createHistogram(e,Object.assign(Object.assign({},t),{advice:r}))}subscribe(){return this.instanceReadyUn=container_1$h.Container.errorless(()=>this.instanceReadyHandler(this.handleInstanceReady.bind(this))),Promise.resolve()}unsubscribe(){return container_1$h.Container.errorless(()=>{var e;return null===(e=this.instanceReadyUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceReady(e){try{this.validator.validateInstanceReady(e),this.logger.debug(`instance ready for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=e.endTime.getTime()-e.startTime.getTime(),r=Object.assign({api:e.api},this.getApplicationData(e.application));this.appStartupMetric.record(t,r),this.logger.debug(`start up time ${t} has been added for metric ${this.settings.name}`)}catch(e){const t=`error while executing handleInstanceReady for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}startup$4.ApplicationStartupMetric=ApplicationStartupMetric;var stopped$2={},stopped$1={};Object.defineProperty(stopped$1,"__esModule",{value:!0}),stopped$1.ApplicationStoppedMetricValidator=void 0;const validator_1$e=validator$1;class ApplicationStoppedMetricValidator{validate(e){validator_1$e.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$e.Validator.throwIfNullOrUndefined(e.instanceStoppedHandler,"instanceStoppedHandler")}validateInstanceStopped(e){validator_1$e.Validator.throwIfNullOrUndefined(e,"args"),validator_1$e.Validator.throwIfNullOrUndefined(e.application,"application")}}stopped$1.ApplicationStoppedMetricValidator=ApplicationStoppedMetricValidator,Object.defineProperty(stopped$2,"__esModule",{value:!0}),stopped$2.ApplicationStoppedMetric=void 0;const base_1$6=base$1,stopped_1$1=stopped$1,container_1$g=container$1;class ApplicationStoppedMetric extends base_1$6.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.instanceStoppedHandler=n,this.validator=new stopped_1$1.ApplicationStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.appStoppedMetric=this.meter.createCounter(e,t)}subscribe(){return this.instanceStoppedUn=container_1$g.Container.errorless(()=>this.instanceStoppedHandler(this.handleInstanceStopped.bind(this))),Promise.resolve()}unsubscribe(){return container_1$g.Container.errorless(()=>{var e;return null===(e=this.instanceStoppedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}destroyMetric(){return Promise.resolve()}handleInstanceStopped(e){try{this.validator.validateInstanceStopped(e),this.logger.debug(`instance stopped for application ${e.application} and metric ${this.settings.name} is being invoked`);const t=this.getApplicationData(e.application);this.appStoppedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleInstanceStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}stopped$2.ApplicationStoppedMetric=ApplicationStoppedMetric;var startup$3={},startupHistogram={};Object.defineProperty(startupHistogram,"__esModule",{value:!0}),startupHistogram.LayoutStartupMetricHistogramValidator=void 0;const validator_1$d=validator$1;class LayoutStartupMetricHistogramValidator{validate(e){validator_1$d.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$d.Validator.throwIfNullOrUndefined(e.layoutRestoredHandler,"layoutRestoredHandler")}validateLayoutRestored(e){validator_1$d.Validator.throwIfNullOrUndefined(e,"args"),validator_1$d.Validator.throwIfNullOrUndefined(e.layout,"layout"),validator_1$d.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$d.Validator.throwIfNullOrUndefined(e.endTime,"endTime")}}startupHistogram.LayoutStartupMetricHistogramValidator=LayoutStartupMetricHistogramValidator,Object.defineProperty(startup$3,"__esModule",{value:!0}),startup$3.LayoutStartupMetric=void 0;const startupHistogram_1=startupHistogram,base_1$5=base$1,container_1$f=container$1;class LayoutStartupMetric extends base_1$5.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.layoutRestoredHandler=n,this.validator=new startupHistogram_1.LayoutStartupMetricHistogramValidator,this.validator.validate(this)}createMetricCore(e,t){const r={explicitBucketBoundaries:this.settings.buckets};return this.layoutStartupMetric=this.meter.createHistogram(e,Object.assign(Object.assign({},t),{advice:r}))}subscribe(){return this.layoutRestoredUn=container_1$f.Container.errorless(()=>this.layoutRestoredHandler(this.handleLayoutRestored.bind(this))),Promise.resolve()}unsubscribe(){return container_1$f.Container.errorless(()=>{var e;return null===(e=this.layoutRestoredUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleLayoutRestored(e){try{this.validator.validateLayoutRestored(e),this.logger.debug(`layout restored is being invoked for metric ${this.settings.name}`);const t=e.endTime.getTime()-e.startTime.getTime(),r=this.getLayoutData(e.layout);this.layoutStartupMetric.record(t,r),this.logger.debug(`metric ${this.settings.name} sent startup time ${t} for layout ${r.layout}`)}catch(e){const t=`error while executing handleLayoutRestored for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}startup$3.LayoutStartupMetric=LayoutStartupMetric;var error$H={},error$G={};Object.defineProperty(error$G,"__esModule",{value:!0}),error$G.PlatformErrorMetricValidator=void 0;const validator_1$c=validator$1;class PlatformErrorMetricValidator{validate(e){validator_1$c.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$c.Validator.throwIfNullOrUndefined(e.platformErrorHandler,"platformErrorHandler")}validatePlatformError(e){validator_1$c.Validator.throwIfNullOrUndefined(e,"args")}}error$G.PlatformErrorMetricValidator=PlatformErrorMetricValidator,Object.defineProperty(error$H,"__esModule",{value:!0}),error$H.PlatformErrorMetric=void 0;const base_1$4=base$1,error_1$1=error$G,container_1$e=container$1;class PlatformErrorMetric extends base_1$4.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.platformErrorHandler=n,this.validator=new error_1$1.PlatformErrorMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.platformErrorMetric=this.meter.createCounter(e,t)}subscribe(){return this.platformErrorUn=container_1$e.Container.errorless(()=>this.platformErrorHandler(this.handlePlatformError.bind(this))),Promise.resolve()}unsubscribe(){var e;return null===(e=this.platformErrorUn)||void 0===e||e.call(this),Promise.resolve()}handlePlatformError(e){try{this.validator.validatePlatformError(e),this.logger.debug(`platform error for metric ${this.settings.name} is being invoked`);const t=this.getData();this.platformErrorMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handlePlatformError for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}error$H.PlatformErrorMetric=PlatformErrorMetric;var startup$2={},gauge={};Object.defineProperty(gauge,"__esModule",{value:!0}),gauge.GaugeMetricBase=void 0;const observable_1=observable;class GaugeMetricBase extends observable_1.ObservableMetricBase{createMetricCore(e,t){return this.meter.createObservableGauge(e,t)}}gauge.GaugeMetricBase=GaugeMetricBase;var startup$1={};Object.defineProperty(startup$1,"__esModule",{value:!0}),startup$1.PlatformStartupMetricValidator=void 0;const validator_1$b=validator$1;class PlatformStartupMetricValidator{validate(e){validator_1$b.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$b.Validator.throwIfNullOrUndefined(e.platformStartedHandler,"platformStartedHandler")}validatePlatformStarted(e){validator_1$b.Validator.throwIfNullOrUndefined(e,"args"),validator_1$b.Validator.throwIfNullOrUndefined(e.startTime,"startTime"),validator_1$b.Validator.throwIfNullOrUndefined(e.endTime,"endTime"),validator_1$b.Validator.throwIfNullOrUndefined(e.api,"api")}}startup$1.PlatformStartupMetricValidator=PlatformStartupMetricValidator;var __awaiter$4=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(startup$2,"__esModule",{value:!0}),startup$2.PlatformStartupMetric=void 0;const gauge_1$2=gauge,validator_1$a=validator$1,startup_1$2=startup$1,container_1$d=container$1;class PlatformStartupMetric extends gauge_1$2.GaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.platformStartedHandler=n,this.validator=new startup_1$2.PlatformStartupMetricValidator,this.validator.validate(this)}subscribeCore(){return this.platformStartedUn=container_1$d.Container.errorless(()=>this.platformStartedHandler(this.handlePlatformStarted.bind(this))),Promise.resolve()}observeCore(e){return __awaiter$4(this,void 0,void 0,function*(){if(!validator_1$a.Validator.isNullOrUndefined(this.startupTime)){const t=Object.assign({api:this.apiVersion},this.getData());this.sendMetric(this.startupTime,t,e)}})}unsubscribeCore(){return container_1$d.Container.errorless(()=>{var e;return null===(e=this.platformStartedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}sendMetric(e,t,r){r.observe(e,t),this.logger.debug(`metric ${this.settings.name} sent startup time ${e}`)}handlePlatformStarted(e){try{this.validator.validatePlatformStarted(e),this.logger.debug(`platform started is being invoked for metric ${this.settings.name}`),this.startupTime=e.endTime.getTime()-e.startTime.getTime(),this.apiVersion=e.api,this.logger.debug(`start up time ${this.startupTime} has been added for metric ${this.settings.name}`)}catch(e){const t=`error while executing handlePlatformStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}startup$2.PlatformStartupMetric=PlatformStartupMetric;var cpu={},__awaiter$3=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(cpu,"__esModule",{value:!0}),cpu.SystemCPUMetric=void 0;const gauge_1$1=gauge,perf_1$1=perf,validator_1$9=validator$1,container_1$c=container$1;class SystemCPUMetric extends gauge_1$1.GaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.perfProvider=n,this.validator=new perf_1$1.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}observeCore(e){return __awaiter$3(this,void 0,void 0,function*(){const t=yield container_1$c.Container.errorlessAsync(()=>this.perfProvider.getSystemCPU());validator_1$9.Validator.isNullOrUndefined(t)||(this.validator.validateSystemCPU(t),this.sendMetrics(t,e))})}sendMetrics(e,t){const r=this.getData(),n=this.settings.name;t.observe(e.current,Object.assign({type:"current_system_cpu"},r)),this.logger.debug(`metric ${n} sent current system cpu ${e.current}`),t.observe(e.average,Object.assign({type:"average_system_cpu"},r)),this.logger.debug(`metric ${n} sent average system cpu ${e.average}`),t.observe(e.platform,Object.assign({type:"average_platform_cpu"},r)),this.logger.debug(`metric ${n} sent average platform cpu ${e.platform}`)}}cpu.SystemCPUMetric=SystemCPUMetric;var memory={},__awaiter$2=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(memory,"__esModule",{value:!0}),memory.SystemMemoryMetric=void 0;const gauge_1=gauge,perf_1=perf,validator_1$8=validator$1,container_1$b=container$1;class SystemMemoryMetric extends gauge_1.GaugeMetricBase{constructor(e,t,r,n){super(e,t,r),this.perfProvider=n,this.validator=new perf_1.PerformanceProviderValidator,this.validator.validate(this.perfProvider)}observeCore(e){return __awaiter$2(this,void 0,void 0,function*(){const t=yield container_1$b.Container.errorlessAsync(()=>this.perfProvider.getSystemMemory());validator_1$8.Validator.isNullOrUndefined(t)||(this.validator.validateSystemMemory(t),this.sendMetrics(t,e))})}sendMetrics(e,t){const r=this.getData(),n=this.settings.name;t.observe(e.platformTotal,Object.assign({type:"used_platform_memory"},r)),this.logger.debug(`metric ${n} sent used platform memory ${e.platformTotal}`);const i=e.systemTotal-e.systemFree;t.observe(i,Object.assign({type:"used_system_memory"},r)),this.logger.debug(`metric ${n} sent used system memory ${i}`),t.observe(e.systemFree,Object.assign({type:"free_system_memory"},r)),this.logger.debug(`metric ${n} sent free system memory ${e.systemFree}`)}}memory.SystemMemoryMetric=SystemMemoryMetric;var count$1={},count={};Object.defineProperty(count,"__esModule",{value:!0}),count.WorkspaceCountMetricValidator=void 0;const validator_1$7=validator$1;class WorkspaceCountMetricValidator{validate(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$7.Validator.throwIfNullOrUndefined(e.workspaceStartedHandler,"workspaceStartedHandler"),validator_1$7.Validator.throwIfNullOrUndefined(e.workspaceStoppedHandler,"workspaceStoppedHandler")}validateWorkspaceSaved(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"args"),validator_1$7.Validator.throwIfNullOrUndefined(e.layout,"layout")}validateWorkspaceStarted(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"args"),validator_1$7.Validator.throwIfNullOrUndefined(e.layout,"layout")}validateWorkspaceStopped(e){validator_1$7.Validator.throwIfNullOrUndefined(e,"args"),validator_1$7.Validator.throwIfNullOrUndefined(e.layout,"layout")}}count.WorkspaceCountMetricValidator=WorkspaceCountMetricValidator,Object.defineProperty(count$1,"__esModule",{value:!0}),count$1.WorkspaceCountMetric=void 0;const base_1$3=base$1,count_1$1=count,container_1$a=container$1;class WorkspaceCountMetric extends base_1$3.MetricBase{constructor(e,t,r,n,i,o,s){super(e,t,r),this.meter=t,this.workspaceSavedHandler=n,this.workspaceStartedHandler=i,this.workspaceRestoredHandler=o,this.workspaceStoppedHandler=s,this.validator=new count_1$1.WorkspaceCountMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceCountMetric=this.meter.createUpDownCounter(e,t)}subscribe(){return this.workspaceStartedUn=container_1$a.Container.errorless(()=>this.workspaceStartedHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceRestoredUn=container_1$a.Container.errorless(()=>this.workspaceRestoredHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceStoppedUn=container_1$a.Container.errorless(()=>this.workspaceStoppedHandler(this.handleWorkspaceStopped.bind(this))),this.workspaceSavedUn=container_1$a.Container.errorless(()=>this.workspaceSavedHandler(this.handleWorkspaceSaved.bind(this))),Promise.resolve()}unsubscribe(){return container_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceStartedUn)||void 0===e?void 0:e.call(this)}),container_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceRestoredUn)||void 0===e?void 0:e.call(this)}),container_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceStoppedUn)||void 0===e?void 0:e.call(this)}),container_1$a.Container.errorless(()=>{var e;return null===(e=this.workspaceSavedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceSaved(e){try{if(this.validator.validateWorkspaceSaved(e),this.logger.debug(`workspace saved for layout ${e.layout}, old layout ${e.oldLayout} and metric ${this.settings.name} is being invoked`),e.oldLayout){const t=this.getLayoutData(e.oldLayout);this.workspaceCountMetric.add(-1,t),this.logger.debug(`metric ${this.settings.name} sent 1 less for app ${t.application}`)}const t=this.getLayoutData(e.layout);this.workspaceCountMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleWorkspaceSaved for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}handleWorkspaceStarted(e){try{this.validator.validateWorkspaceStarted(e),this.logger.debug(`workspace started for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceCountMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for app ${t.application}`)}catch(e){const t=`error while executing handleWorkspaceStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}handleWorkspaceStopped(e){try{this.validator.validateWorkspaceStopped(e),this.logger.debug(`workspace stopped for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceCountMetric.add(-1,t),this.logger.debug(`metric ${this.settings.name} sent 1 less for app ${t.application}`)}catch(e){const t=`error while executing handleWorkspaceStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}count$1.WorkspaceCountMetric=WorkspaceCountMetric;var started={},startedOrStoppedMetric={};Object.defineProperty(startedOrStoppedMetric,"__esModule",{value:!0}),startedOrStoppedMetric.WorkspaceStartedOrStoppedMetricValidator=void 0;const validator_1$6=validator$1;class WorkspaceStartedOrStoppedMetricValidator{validate(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"metric"),validator_1$6.Validator.throwIfNullOrUndefined(e.workspaceActionHandler,"workspaceActionHandler")}validateWorkspaceStarted(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"args")}validateWorkspaceStopped(e){validator_1$6.Validator.throwIfNullOrUndefined(e,"args"),validator_1$6.Validator.throwIfNullOrUndefined(e.layout,"layout")}}startedOrStoppedMetric.WorkspaceStartedOrStoppedMetricValidator=WorkspaceStartedOrStoppedMetricValidator,Object.defineProperty(started,"__esModule",{value:!0}),started.WorkspaceStartedMetric=void 0;const base_1$2=base$1,startedOrStoppedMetric_1$1=startedOrStoppedMetric,container_1$9=container$1;class WorkspaceStartedMetric extends base_1$2.MetricBase{constructor(e,t,r,n,i){super(e,t,r),this.meter=t,this.workspaceActionHandler=n,this.workspaceRestoredHandler=i,this.validator=new startedOrStoppedMetric_1$1.WorkspaceStartedOrStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceStartedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceStartedUn=container_1$9.Container.errorless(()=>this.workspaceActionHandler(this.handleWorkspaceStarted.bind(this))),this.workspaceRestoredUn=container_1$9.Container.errorless(()=>this.workspaceRestoredHandler(this.handleWorkspaceStarted.bind(this))),Promise.resolve()}unsubscribe(){return container_1$9.Container.errorless(()=>{var e;return null===(e=this.workspaceStartedUn)||void 0===e?void 0:e.call(this)}),container_1$9.Container.errorless(()=>{var e;return null===(e=this.workspaceRestoredUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceStarted(e){try{this.validator.validateWorkspaceStarted(e),this.logger.debug(`workspace Started for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceStartedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for workspace layout ${t.layout}`)}catch(e){const t=`error while executing handleWorkspaceStarted for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}started.WorkspaceStartedMetric=WorkspaceStartedMetric;var startup={};Object.defineProperty(startup,"__esModule",{value:!0}),startup.WorkspaceStartupHistogramMetric=void 0;const startup_1$1=startup$3;class WorkspaceStartupHistogramMetric extends startup_1$1.LayoutStartupMetric{constructor(e,t,r,n,i){super(e,t,r,e=>{const t=this.workspaceLoadedHandler(e),r=this.workspaceRestoredHandler(e);return()=>{t(),r()}}),this.workspaceLoadedHandler=n,this.workspaceRestoredHandler=i}}startup.WorkspaceStartupHistogramMetric=WorkspaceStartupHistogramMetric;var stopped={};Object.defineProperty(stopped,"__esModule",{value:!0}),stopped.WorkspaceStoppedMetric=void 0;const base_1$1=base$1,startedOrStoppedMetric_1=startedOrStoppedMetric,container_1$8=container$1;class WorkspaceStoppedMetric extends base_1$1.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.workspaceActionHandler=n,this.validator=new startedOrStoppedMetric_1.WorkspaceStartedOrStoppedMetricValidator,this.validator.validate(this)}createMetricCore(e,t){return this.workspaceStoppedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceStoppedUn=container_1$8.Container.errorless(()=>this.workspaceActionHandler(this.handleWorkspaceStopped.bind(this))),Promise.resolve()}unsubscribe(){return container_1$8.Container.errorless(()=>{var e;return null===(e=this.workspaceStoppedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleWorkspaceStopped(e){try{this.validator.validateWorkspaceStopped(e),this.logger.debug(`workspace stopped for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceStoppedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for workspace layout ${t.layout}`)}catch(e){const t=`error while executing handleWorkspaceStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}stopped.WorkspaceStoppedMetric=WorkspaceStoppedMetric;var selected={};Object.defineProperty(selected,"__esModule",{value:!0}),selected.WorkspaceSelectedMetric=void 0;const base_1=base$1,container_1$7=container$1;class WorkspaceSelectedMetric extends base_1.MetricBase{constructor(e,t,r,n){super(e,t,r),this.meter=t,this.workspaceActionHandler=n}createMetricCore(e,t){return this.workspaceSelectedMetric=this.meter.createCounter(e,t)}subscribe(){return this.workspaceSelectedUn=container_1$7.Container.errorless(()=>this.workspaceActionHandler(this.handleSelectedStopped.bind(this))),Promise.resolve()}unsubscribe(){return container_1$7.Container.errorless(()=>{var e;return null===(e=this.workspaceSelectedUn)||void 0===e?void 0:e.call(this)}),Promise.resolve()}handleSelectedStopped(e){try{this.logger.debug(`workspace selected for layout ${e.layout} and metric ${this.settings.name} is being invoked`);const t=this.getLayoutData(e.layout);this.workspaceSelectedMetric.add(1,t),this.logger.debug(`metric ${this.settings.name} sent 1 more for workspace layout ${t.layout}`)}catch(e){const t=`error while executing handleSelectedStopped for metric from type: ${this.settings.type}`;this.logger.warn(t,e)}}}selected.WorkspaceSelectedMetric=WorkspaceSelectedMetric,Object.defineProperty(builder$5,"__esModule",{value:!0}),builder$5.MetricsFactoryBuilder=void 0;const factoryBuilder_1=factoryBuilder,factory_1=factory$2,count_1=count$3,cpu_1=cpu$1,crash_1=crash$1,duration_1=duration$3,durationSoft_1=durationSoft,error_1=error$J,memory_1=memory$1,started_1=started$2,startup_1=startup$4,stopped_1=stopped$2,startup_2=startup$3,error_2=error$H,startup_3=startup$2,cpu_2=cpu,memory_2=memory,count_2=count$1,started_2=started,startup_4=startup,stopped_2=stopped,selected_1=selected;class MetricsFactoryBuilder{constructor(e,t,r){this.lazyMeterProvider=e,this.dependencyContainer=t,this.logger=r,this.metricsFactories=new Map,this.metricsFactories=new Map}get meter(){return this.lazyMeterProvider.getMeter()}build(){(new factoryBuilder_1.MetricsFactoryBuilderValidator).validate(this);return new factory_1.MetricsFactory(this.logger,this.metricsFactories,this.meter)}withDefaults(){return this.withAppStarted().withAppStopped().withAppStartupHistogram().withAppCount().withAppDurationHistogram().withAppDurationSoftHistogram().withAppMemory().withAppCPU().withSystemMemory().withSystemCPU().withAppError().withAppCrash().withLayoutStartupHistogram().withWorkspaceStartupHistogram().withWorkspaceStarted().withWorkspaceStopped().withWorkspaceSelected().withWorkspaceCount().withPlatformStartup().withPlatformError()}withAppStarted(){return this.metricsFactories.set("app_started",(e=>new started_1.ApplicationStartedMetric(e,this.meter,this.logger,this.dependencyContainer.instanceStartedHandler)).bind(this)),this}withAppStopped(){return this.metricsFactories.set("app_stopped",(e=>new stopped_1.ApplicationStoppedMetric(e,this.meter,this.logger,this.dependencyContainer.instanceStoppedHandler)).bind(this)),this}withAppStartupHistogram(){return this.metricsFactories.set("app_startup",(e=>new startup_1.ApplicationStartupMetric(e,this.meter,this.logger,this.dependencyContainer.instanceReadyHandler)).bind(this)),this}withAppCount(){return this.metricsFactories.set("app_count",(e=>new count_1.ApplicationCountMetric(e,this.meter,this.logger,this.dependencyContainer.instanceStartedHandler,this.dependencyContainer.instanceStoppedHandler)).bind(this)),this}withAppDurationHistogram(){return this.metricsFactories.set("app_duration",(e=>new duration_1.ApplicationDurationMetric(e,this.meter,this.logger,this.dependencyContainer.instanceFocusedHandler)).bind(this)),this}withAppDurationSoftHistogram(){return this.metricsFactories.set("app_duration_soft",(e=>new durationSoft_1.ApplicationDurationSoftMetric(e,this.meter,this.logger,this.dependencyContainer.instanceFocusedHandler)).bind(this)),this}withAppMemory(){return this.metricsFactories.set("app_memory",(e=>new memory_1.ApplicationMemoryMetric(e,this.meter,this.logger,this.dependencyContainer.performanceProvider)).bind(this)),this}withAppCPU(){return this.metricsFactories.set("app_cpu",(e=>new cpu_1.ApplicationCPUMetric(e,this.meter,this.logger,this.dependencyContainer.performanceProvider)).bind(this)),this}withAppError(){return this.metricsFactories.set("app_error",(e=>new error_1.ApplicationErrorMetric(e,this.meter,this.logger,this.dependencyContainer.instanceErrorHandler)).bind(this)),this}withAppCrash(){return this.metricsFactories.set("app_crash",(e=>new crash_1.ApplicationCrashMetric(e,this.meter,this.logger,this.dependencyContainer.instanceCrashHandler)).bind(this)),this}withSystemMemory(){return this.metricsFactories.set("system_memory",(e=>new memory_2.SystemMemoryMetric(e,this.meter,this.logger,this.dependencyContainer.performanceProvider)).bind(this)),this}withSystemCPU(){return this.metricsFactories.set("system_cpu",(e=>new cpu_2.SystemCPUMetric(e,this.meter,this.logger,this.dependencyContainer.performanceProvider)).bind(this)),this}withLayoutStartupHistogram(){return this.metricsFactories.set("layout_startup",(e=>new startup_2.LayoutStartupMetric(e,this.meter,this.logger,this.dependencyContainer.layoutRestoredHandler)).bind(this)),this}withWorkspaceStartupHistogram(){return this.metricsFactories.set("workspace_startup",(e=>new startup_4.WorkspaceStartupHistogramMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceLoadedHandler,this.dependencyContainer.workspaceRestoredHandler)).bind(this)),this}withWorkspaceStarted(){return this.metricsFactories.set("workspace_started",(e=>new started_2.WorkspaceStartedMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceStartedHandler,this.dependencyContainer.workspaceRestoredHandler)).bind(this)),this}withWorkspaceStopped(){return this.metricsFactories.set("workspace_stopped",(e=>new stopped_2.WorkspaceStoppedMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceStoppedHandler)).bind(this)),this}withWorkspaceSelected(){return this.metricsFactories.set("workspace_selected",(e=>new selected_1.WorkspaceSelectedMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceSelectedHandler)).bind(this)),this}withWorkspaceCount(){return this.metricsFactories.set("workspace_count",(e=>new count_2.WorkspaceCountMetric(e,this.meter,this.logger,this.dependencyContainer.workspaceSavedHandler,this.dependencyContainer.workspaceStartedHandler,this.dependencyContainer.workspaceRestoredHandler,this.dependencyContainer.workspaceStoppedHandler)).bind(this)),this}withPlatformStartup(){return this.metricsFactories.set("platform_startup",(e=>new startup_3.PlatformStartupMetric(e,this.meter,this.logger,this.dependencyContainer.platformStartedHandler)).bind(this)),this}withPlatformError(){return this.metricsFactories.set("platform_error",(e=>new error_2.PlatformErrorMetric(e,this.meter,this.logger,this.dependencyContainer.platformErrorHandler)).bind(this)),this}}builder$5.MetricsFactoryBuilder=MetricsFactoryBuilder;var manager$4={},manager$3={};Object.defineProperty(manager$3,"__esModule",{value:!0}),manager$3.MetricsManagerValidator=void 0;const validator_1$5=validator$1;class MetricsManagerValidator{validate(e){validator_1$5.Validator.throwIfNullOrUndefined(e,"manager"),validator_1$5.Validator.throwIfNullOrUndefined(e.settings,"settings"),validator_1$5.Validator.throwIfNullOrUndefined(e.metricsFactory,"metricsFactory"),validator_1$5.Validator.throwIfNullOrUndefined(e.meterProvider,"meterProvider"),validator_1$5.Validator.throwIfNullOrUndefined(e.logger,"logger")}}manager$3.MetricsManagerValidator=MetricsManagerValidator;var constants$3={};Object.defineProperty(constants$3,"__esModule",{value:!0}),constants$3.Defaults=void 0,constants$3.Defaults={TRACE_VERSION:"00",DEFAULT_USER:"unknown-user",DEFAULT_SERVICE_NAME:"unknown-service-name",DEFAULT_SERVICE_ID:"unknown-service-id",DEFAULT_SERVICE_VERSION:"unknown-service-version",DEFAULT_PLATFORM_VERSION:"unknown-platform-version",DEFAULT_METRIC_DESCRIPTION:"unknown-metric",stopPropagationIfSpanIsDisabled:!1,countMetric:!1,durationMetric:!1,resultMetric:!1,countMetricOnDisabledSpans:!1,durationMetricOnDisabledSpans:!1,resultMetricOnDisabledSpans:!1,maxAttributeDepth:5,otelSpanOptions:{},disablePropagation:!1,addContextToTrace:!0,level:"INFO",forceChildTracing:!1,canBeRoot:!0,currentTracingStateGetterContextName:"interopio.insights.currentTracingStateGetter",minDurationMs:0,log:!1,logOnDisabledSpans:!1};var __awaiter$1=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(manager$4,"__esModule",{value:!0}),manager$4.MetricsManager=void 0;const manager_1$4=manager$3,safe_stringify_1$5=safeStringify$1,container_1$6=container$1,constants_1$3=constants$3;class MetricsManager{constructor(e,t,r,n,i){this.otelSettings=e,this.settings=t,this.metricsFactory=r,this.meterProvider=n,this.logger=i,this.metrics=new Map,this.started=!1,!1!==(null==e?void 0:e.logSettingsOnStartup)&&(null==i||i.info(`Starting MetricsManager with settings ${(0,safe_stringify_1$5.safeStringify)(t)}`));(new manager_1$4.MetricsManagerValidator).validate(this)}get(e){return this.getOrCreateMetric(e)}getFromSettings(e){return this.getOrCreateMetricFromSettings(e)}getObservable(e,t,r,n){return this.getOrCreateMetric(e,t,r,n)}getObservableFromSettings(e,t,r,n){return this.getOrCreateMetricFromSettings(e,t,r,n)}start(){var e;return __awaiter$1(this,void 0,void 0,function*(){try{this.createEnabledMetrics(null!==(e=this.settings.metrics)&&void 0!==e?e:[]);for(const e of this.metrics){const t=e[1];yield this.startMetric(t)}this.started=!0,this.logger.debug("metrics manager has been started")}catch(e){const t="error while starting metrics manager";this.logger.warn(t,e)}})}stop(){return __awaiter$1(this,void 0,void 0,function*(){try{for(const e of this.metrics){const t=e[1];yield this.stopMetric(t)}yield this.meterProvider.forceFlush(),this.started=!1,this.logger.debug("metrics manager has been stopped")}catch(e){const t="error while stopping metrics manager";this.logger.warn(t,e)}})}waitForFinalExport(e){return __awaiter$1(this,void 0,void 0,function*(){const t=new Date;this.meterProvider.metricReader.collect({timeoutMillis:e});const r=e?e-((new Date).getTime()-t.getTime()):void 0;this.meterProvider.metricReader.forceFlush({timeoutMillis:r})})}createEnabledMetrics(e){const t=e.filter(e=>!this.metrics.has(e.name)),r=t.filter(e=>e.enabled);r.forEach(e=>this.createMetric(e))}getOrCreateMetric(e,t,r,n){var i;if(this.metrics.has(e))return this.metrics.get(e);{let o;const s=null===(i=this.settings.metrics)||void 0===i?void 0:i.find(t=>t.name===e);return s&&(o=this.createMetric(s,t,r,n)),o}}getOrCreateMetricFromSettings(e,t,r,n){var i;if(!e.name)throw new Error("settings.name not defined");return this.metrics.has(e.name)?this.metrics.get(e.name):this.createMetric(Object.assign(Object.assign({},e),{enabled:null===(i=e.enabled)||void 0===i||i}),t,r,n)}createMetric(e,t,r,n){try{const i=e.additionalAttributes;e=Object.assign(Object.assign({},e),{description:e.description||constants_1$3.Defaults.DEFAULT_METRIC_DESCRIPTION,platformVersion:e.platformVersion||this.otelSettings.platformVersion||"unknown",user:e.user||this.otelSettings.userId||constants_1$3.Defaults.DEFAULT_USER,additionalAttributes:()=>Object.assign(Object.assign(Object.assign({},container_1$6.Container.errorless(this.otelSettings.additionalAttributes)),container_1$6.Container.errorless(this.settings.additionalAttributes)),container_1$6.Container.errorless(i))});const o=this.metricsFactory.create(e,t,r,n);return o&&this.metrics.set(e.name,o),o}catch(t){const r=`error while creating metric from type: ${e.type}`;return void this.logger.warn(r,t)}}startMetric(e){return __awaiter$1(this,void 0,void 0,function*(){try{yield e.start()}catch(t){const r=`error while starting metric from type: ${e.settings.type}`;this.logger.warn(r,t)}})}stopMetric(e){return __awaiter$1(this,void 0,void 0,function*(){try{yield e.stop()}catch(t){const r=`error while stopping metric from type: ${e.settings.type}`;this.logger.warn(r,t)}})}}manager$4.MetricsManager=MetricsManager;var builder$4={},settingsBuilder={};Object.defineProperty(settingsBuilder,"__esModule",{value:!0}),settingsBuilder.MetricsSettingsBuilderValidator=void 0;const validator_1$4=validator$1;class MetricsSettingsBuilderValidator{validate(e){validator_1$4.Validator.throwIfNullOrUndefined(e,"builder"),validator_1$4.Validator.throwIfNullOrUndefined(e.enabled,"enabled"),validator_1$4.Validator.throwIfNullOrUndefined(e.metrics,"metrics")}}settingsBuilder.MetricsSettingsBuilderValidator=MetricsSettingsBuilderValidator;var _default$2={};Object.defineProperty(_default$2,"__esModule",{value:!0}),_default$2.DefaultMetricsSettings=void 0;class DefaultMetricsSettings{constructor(){this.unknown="unknown"}get enabled(){return!0}get platformMetricsEnabled(){return!0}get userId(){return this.unknown}get platformVersion(){return this.unknown}get additionalAttributes(){return{}}get metrics(){return[this.getAppCount(),this.getAppCPU(),this.getAppCrash(),this.getAppDuration(),this.getAppDurationSoft(),this.getAppError(),this.getAppMemory(),this.getAppStarted(),this.getAppStartup(),this.getAppStopped(),this.getLayoutStartup(),this.getPlatformError(),this.getPlatformStartup(),this.getSystemCPU(),this.getSystemMemory(),this.getWorkspaceCount(),this.getWorkspaceSelected(),this.getWorkspaceStarted(),this.getWorkspaceStartup(),this.getWorkspaceStopped()]}getAppStarted(){return this.getSettings("app_started","Number of times an application has been started during each platform session","app_started")}getAppStopped(){return this.getSettings("app_stopped","Number of times an application has been stopped during each platform session","app_stopped")}getAppCount(){return this.getSettings("app_count","Number of application instances running in the platform during each platform session","app_count")}getAppStartup(){return this.getSettings("app_startup","Time to load an application","app_startup","ms",[100,1e3,1e4,3e4,6e4])}getAppDuration(){return this.getSettings("app_duration","How long an application has been focused during each platform session","app_duration","ms",[1e3,1e4,3e4,6e4,6e5])}getAppDurationSoft(){return this.getSettings("app_duration_soft","How long an application has been focused during each platform session (without the currently focused application)","app_duration_soft","ms",[1e3,1e4,3e4,6e4,6e5])}getAppMemory(){return this.getSettings("app_memory","Current app memory usage","app_memory","kb")}getAppCPU(){return this.getSettings("app_cpu","Percentage of CPU used for the last interval.","app_cpu","%")}getAppError(){return this.getSettings("app_error","Number of times app error was received during each platform session","app_error")}getAppCrash(){return this.getSettings("app_crash","Number of times an application crashed during each platform session","app_crash")}getLayoutStartup(){return this.getSettings("layout_startup","Time to load a layout","layout_startup","ms",[100,1e3,1e4,3e4,6e4])}getWorkspaceStartup(){return this.getSettings("workspace_startup","Time to load the workspace layout","workspace_startup","ms",[100,1e3,1e4,3e4,6e4])}getWorkspaceStarted(){return this.getSettings("workspace_started","Number of times a workspace has been stopped during each platform session","workspace_started")}getWorkspaceStopped(){return this.getSettings("workspace_stopped","Number of times a workspace has been stopped during each platform session","workspace_stopped")}getWorkspaceSelected(){return this.getSettings("workspace_selected","TBD","workspace_selected")}getWorkspaceCount(){return this.getSettings("workspace_count","Number of workspace running in the platform during each platform session","workspace_count")}getPlatformStartup(){return this.getSettings("platform_startup","Time to load the platform","platform_startup","ms")}getPlatformError(){return this.getSettings("platform_error","Number of times platform error was received during each platform session","platform_error")}getSystemMemory(){return this.getSettings("system_memory","Free system memory, used system memory and used platform memory","system_memory","gb")}getSystemCPU(){return this.getSettings("system_cpu","Current and average system CPU and average platform CPU","system_cpu","%")}getSettings(e,t,r,n,i){return{enabled:!0,name:e,description:t,user:this.unknown,platformVersion:this.unknown,type:r,unit:n,buckets:i}}}_default$2.DefaultMetricsSettings=DefaultMetricsSettings,Object.defineProperty(builder$4,"__esModule",{value:!0}),builder$4.MetricsSettingsBuilder=void 0;const settingsBuilder_1=settingsBuilder,default_1=_default$2,container_1$5=container$1,constants_1$2=constants$3;class MetricsSettingsBuilder{constructor(){this.metrics=new Map,this.defaultSettings=new default_1.DefaultMetricsSettings,this.withSettings({enabled:!1,platformVersion:constants_1$2.Defaults.DEFAULT_PLATFORM_VERSION,serviceId:constants_1$2.Defaults.DEFAULT_SERVICE_ID,serviceName:constants_1$2.Defaults.DEFAULT_SERVICE_NAME,userId:constants_1$2.Defaults.DEFAULT_USER,serviceVersion:constants_1$2.Defaults.DEFAULT_SERVICE_VERSION,metrics:this.defaultSettings})}build(){var e,t,r,n,i,o,s,a,c,l,u,d,h,p,g,m,f,y,$,b;if(!this.platformMetricsEnabled)for(const e of this.defaultSettings.metrics)this.metrics.delete(e.name);this.metrics.forEach(e=>{this.metrics.set(e.name,this.convert(e))});const v=null!==(t=null===(e=this.meter)||void 0===e?void 0:e.headers)&&void 0!==t?t:Object.assign(Object.assign({},container_1$5.Container.errorless(null===(r=this.otelSettings)||void 0===r?void 0:r.headers)),container_1$5.Container.errorless(null===(n=this.settings)||void 0===n?void 0:n.headers)),w=Object.assign(Object.assign({},this.settings),{enabled:this.enabled,platformMetricsEnabled:this.platformMetricsEnabled,url:null!==(s=null!==(i=this.meter.url)&&void 0!==i?i:null===(o=this.settings)||void 0===o?void 0:o.url)&&void 0!==s?s:"http://localhost:4318/v1/metrics",publishInterval:null!==(l=null!==(a=this.meter.publishInterval)&&void 0!==a?a:null===(c=this.settings)||void 0===c?void 0:c.publishInterval)&&void 0!==l?l:3e4,compression:null!==(u=this.meter.compression)&&void 0!==u?u:null===(d=this.settings)||void 0===d?void 0:d.compression,headers:v,hostname:null!==(h=this.meter.hostname)&&void 0!==h?h:null===(p=this.settings)||void 0===p?void 0:p.hostname,keepAlive:null!==(g=this.meter.keepAlive)&&void 0!==g?g:null===(m=this.settings)||void 0===m?void 0:m.keepAlive,concurrencyLimit:null!==(f=this.meter.concurrencyLimit)&&void 0!==f?f:null===(y=this.settings)||void 0===y?void 0:y.concurrencyLimit,timeoutMillis:null!==($=this.meter.concurrencyLimit)&&void 0!==$?$:null===(b=this.settings)||void 0===b?void 0:b.timeoutMillis,metrics:[...this.metrics.values()],additionalAttributes:()=>{var e,t;return Object.assign(Object.assign({},container_1$5.Container.errorless(null===(e=this.otelSettings)||void 0===e?void 0:e.additionalAttributes)),container_1$5.Container.errorless(null===(t=this.settings)||void 0===t?void 0:t.additionalAttributes))}});return(new settingsBuilder_1.MetricsSettingsBuilderValidator).validate(w),w}withSettings(e){var t,r,n,i,o,s,a,c,l,u,d,h;const p=this.otelSettings;this.otelSettings=e;const g=this.settings;return this.settings=null==e?void 0:e.metrics,this.withEnabled(null!==(r=null===(t=this.settings)||void 0===t?void 0:t.enabled)&&void 0!==r?r:null==g?void 0:g.enabled).withPlatformMetricsEnabled(null!==(i=null===(n=this.settings)||void 0===n?void 0:n.platformMetricsEnabled)&&void 0!==i?i:null==g?void 0:g.platformMetricsEnabled).withUser(null!==(s=null===(o=this.otelSettings)||void 0===o?void 0:o.userId)&&void 0!==s?s:null==p?void 0:p.userId).withPlatformVersion(null!==(c=null===(a=this.otelSettings)||void 0===a?void 0:a.platformVersion)&&void 0!==c?c:null==p?void 0:p.platformVersion).withAdditionalAttributes(null===(l=this.settings)||void 0===l?void 0:l.additionalAttributes).withCustomMetrics(null===(u=this.settings)||void 0===u?void 0:u.metrics).withMeter(null!==(h=null===(d=this.settings)||void 0===d?void 0:d.meter)&&void 0!==h?h:this.meter)}withEnabled(e){return this.enabled=null!=e?e:this.enabled,this}withUser(e){return this.userId=null!=e?e:this.userId,this.metrics.forEach(e=>{e.user=this.userId,this.metrics.set(e.name,e)}),this}withAdditionalAttributes(e){return this.additionalAttributes=null!=e?e:this.additionalAttributes,this.metrics.forEach(e=>{e.additionalAttributes=this.additionalAttributes,this.metrics.set(e.type,e)}),this}withPlatformVersion(e){return this.platformVersion=null!=e?e:this.platformVersion,this.metrics.forEach(e=>{e.platformVersion=this.platformVersion,this.metrics.set(e.name,e)}),this}withPlatformMetricsEnabled(e){return this.platformMetricsEnabled=null!=e?e:this.platformMetricsEnabled,this}withMeter(e){var t,r,n,i,o,s,a,c,l,u;const d=this.meter;return this.meter=Object.assign(Object.assign(Object.assign({},d),null!=e?e:{}),{url:null!==(t=null==e?void 0:e.url)&&void 0!==t?t:null==d?void 0:d.url,publishInterval:null!==(r=null==e?void 0:e.publishInterval)&&void 0!==r?r:null==d?void 0:d.publishInterval,compression:null!==(o=null!==(n=null==e?void 0:e.compression)&&void 0!==n?n:null===(i=this.settings)||void 0===i?void 0:i.compression)&&void 0!==o?o:null==d?void 0:d.compression,headers:null!==(s=null==e?void 0:e.headers)&&void 0!==s?s:null==d?void 0:d.headers,hostname:null!==(a=null==e?void 0:e.hostname)&&void 0!==a?a:null==d?void 0:d.hostname,keepAlive:null!==(c=null==e?void 0:e.keepAlive)&&void 0!==c?c:null==d?void 0:d.keepAlive,concurrencyLimit:null!==(l=null==e?void 0:e.concurrencyLimit)&&void 0!==l?l:null==d?void 0:d.concurrencyLimit,timeoutMillis:null!==(u=null==e?void 0:e.timeoutMillis)&&void 0!==u?u:null==d?void 0:d.timeoutMillis}),this}withCustomMetrics(e){return(null!=e?e:[]).forEach(e=>this.withCustomMetric(e)),this}withCustomMetric(e){if(!e.name)throw new Error("settings.name is not defined");if(this.metrics.has(e.name)){const t=this.metrics.get(e.type),r=this.mergeSettings(e,t);this.metrics.set(r.name,r)}else{const t=this.convert(e);this.metrics.set(e.name,t)}return this}convert(e){var t,r,n,i;return Object.assign(Object.assign(Object.assign({},this.settings),e),{type:e.type,user:this.userId,enabled:null===(t=e.enabled)||void 0===t||t,name:null!==(r=e.name)&&void 0!==r?r:e.type,description:null!==(n=e.description)&&void 0!==n?n:null!==(i=e.name)&&void 0!==i?i:e.type,platformVersion:this.platformVersion,unit:e.unit,buckets:e.buckets,additionalAttributes:e.additionalAttributes})}mergeSettings(e,t){var r,n,i,o,s;return Object.assign(Object.assign(Object.assign({},t),this.settings),{type:e.type,user:this.userId,enabled:null!==(r=e.enabled)&&void 0!==r?r:t.enabled,name:null!==(n=e.name)&&void 0!==n?n:t.name,description:null!==(i=e.description)&&void 0!==i?i:t.description,platformVersion:this.platformVersion,unit:t.unit,buckets:null!==(o=e.buckets)&&void 0!==o?o:t.buckets,additionalAttributes:null!==(s=e.additionalAttributes)&&void 0!==s?s:t.additionalAttributes})}}builder$4.MetricsSettingsBuilder=MetricsSettingsBuilder;var builder$3={};Object.defineProperty(builder$3,"__esModule",{value:!0}),builder$3.MetricsBuilderValidator=void 0;const validator_1$3=validator$1;class MetricsBuilderValidator{validate(e){var t,r;validator_1$3.Validator.throwIfNullOrUndefined(e,"builder"),validator_1$3.Validator.throwIfNullOrUndefined(e.logger,"logger"),(null===(r=null===(t=e.settings)||void 0===t?void 0:t.metrics)||void 0===r?void 0:r.platformMetricsEnabled)&&validator_1$3.Validator.throwIfNullOrUndefined(e.dependencyContainer,"dependencyContainer",".withDependencyContainer() must be called to initialize metrics")}}builder$3.MetricsBuilderValidator=MetricsBuilderValidator;var providerFactory={};const VERSION$6="2.0.1",TMP_HTTP_URL="http.url",TMP_HTTP_USER_AGENT="http.user_agent",SEMATTRS_HTTP_URL=TMP_HTTP_URL,SEMATTRS_HTTP_USER_AGENT=TMP_HTTP_USER_AGENT,TMP_PROCESS_RUNTIME_NAME="process.runtime.name",TMP_TELEMETRY_SDK_NAME="telemetry.sdk.name",TMP_TELEMETRY_SDK_LANGUAGE="telemetry.sdk.language",TMP_TELEMETRY_SDK_VERSION="telemetry.sdk.version",SEMRESATTRS_PROCESS_RUNTIME_NAME=TMP_PROCESS_RUNTIME_NAME,SEMRESATTRS_TELEMETRY_SDK_NAME=TMP_TELEMETRY_SDK_NAME,SEMRESATTRS_TELEMETRY_SDK_LANGUAGE=TMP_TELEMETRY_SDK_LANGUAGE,SEMRESATTRS_TELEMETRY_SDK_VERSION=TMP_TELEMETRY_SDK_VERSION,TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS="webjs",TELEMETRYSDKLANGUAGEVALUES_WEBJS=TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS,ATTR_ERROR_TYPE="error.type",ATTR_EXCEPTION_MESSAGE="exception.message",ATTR_EXCEPTION_STACKTRACE="exception.stacktrace",ATTR_EXCEPTION_TYPE="exception.type",ATTR_HTTP_REQUEST_METHOD="http.request.method",ATTR_HTTP_REQUEST_METHOD_ORIGINAL="http.request.method_original",ATTR_HTTP_RESPONSE_STATUS_CODE="http.response.status_code",ATTR_SERVER_ADDRESS="server.address",ATTR_SERVER_PORT="server.port",ATTR_SERVICE_NAME="service.name",ATTR_TELEMETRY_SDK_LANGUAGE="telemetry.sdk.language",TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS="webjs",ATTR_TELEMETRY_SDK_NAME="telemetry.sdk.name",ATTR_TELEMETRY_SDK_VERSION="telemetry.sdk.version",ATTR_URL_FULL="url.full",ATTR_PROCESS_RUNTIME_NAME="process.runtime.name",SDK_INFO$1={[ATTR_TELEMETRY_SDK_NAME]:"opentelemetry",[ATTR_PROCESS_RUNTIME_NAME]:"browser",[ATTR_TELEMETRY_SDK_LANGUAGE]:TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS,[ATTR_TELEMETRY_SDK_VERSION]:VERSION$6};function defaultServiceName$1(){return"unknown_service"}const isPromiseLike$1=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;let ResourceImpl$1=class e{_rawAttributes;_asyncAttributesPending=!1;_memoizedAttributes;static FromAttributeList(t){const r=new e({});return r._rawAttributes=guardedRawAttributes(t),r._asyncAttributesPending=t.filter(([e,t])=>isPromiseLike$1(t)).length>0,r}constructor(e){const t=e.attributes??{};this._rawAttributes=Object.entries(t).map(([e,t])=>(isPromiseLike$1(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=guardedRawAttributes(this._rawAttributes)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;eisPromiseLike$1(t)?[e,t.catch(t=>{diag.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}const detectResources=(e={})=>{const t=(e.detectors||[]).map(t=>{try{const r=resourceFromDetectedResource(t.detect(e));return diag.debug(`${t.constructor.name} found resource.`,r),r}catch(e){return diag.debug(`${t.constructor.name} failed: ${e.message}`),emptyResource()}});return t.reduce((e,t)=>e.merge(t),emptyResource())};class EnvDetector{_MAX_LENGTH=255;_COMMA_SEPARATOR=",";_LABEL_KEY_VALUE_SPLITTER="=";_ERROR_MESSAGE_INVALID_CHARS="should be a ASCII string with a length greater than 0 and not exceed "+this._MAX_LENGTH+" characters.";_ERROR_MESSAGE_INVALID_VALUE="should be a ASCII string with a length not exceed "+this._MAX_LENGTH+" characters.";detect(e){return{attributes:{}}}_parseResourceAttributes(e){if(!e)return{};const t={},r=e.split(this._COMMA_SEPARATOR,-1);for(const e of r){const r=e.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(2!==r.length)continue;let[n,i]=r;if(n=n.trim(),i=i.trim().split(/^"|"$/).join(""),!this._isValidAndNotEmpty(n))throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(i))throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);t[n]=decodeURIComponent(i)}return t}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let t=0;t126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}}const envDetector=new EnvDetector;class NoopDetector{detect(){return{attributes:{}}}}const noopDetector=new NoopDetector,hostDetector=noopDetector,osDetector=noopDetector,processDetector=noopDetector,serviceInstanceIdDetector=noopDetector;var esm$c=Object.freeze({__proto__:null,defaultResource:defaultResource$1,defaultServiceName:defaultServiceName$1,detectResources:detectResources,emptyResource:emptyResource,envDetector:envDetector,hostDetector:hostDetector,osDetector:osDetector,processDetector:processDetector,resourceFromAttributes:resourceFromAttributes$1,serviceInstanceIdDetector:serviceInstanceIdDetector}),require$$2=getAugmentedNamespace(esm$c);const SUPPRESS_TRACING_KEY$2=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing$2(e){return e.setValue(SUPPRESS_TRACING_KEY$2,!0)}function unsuppressTracing(e){return e.deleteValue(SUPPRESS_TRACING_KEY$2)}function isTracingSuppressed$1(e){return!0===e.getValue(SUPPRESS_TRACING_KEY$2)}const BAGGAGE_KEY_PAIR_SEPARATOR="=",BAGGAGE_PROPERTIES_SEPARATOR=";",BAGGAGE_ITEMS_SEPARATOR=",",BAGGAGE_HEADER="baggage",BAGGAGE_MAX_NAME_VALUE_PAIRS=180,BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,BAGGAGE_MAX_TOTAL_LENGTH=8192;function serializeKeyPairs(e){return e.reduce((e,t)=>{const r=`${e}${""!==e?BAGGAGE_ITEMS_SEPARATOR:""}${t}`;return r.length>BAGGAGE_MAX_TOTAL_LENGTH?e:r},"")}function getKeyPairs(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return void 0!==t.metadata&&(r+=BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),r})}function parsePairKeyValue(e){const t=e.split(BAGGAGE_PROPERTIES_SEPARATOR);if(t.length<=0)return;const r=t.shift();if(!r)return;const n=r.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);if(n<=0)return;const i=decodeURIComponent(r.substring(0,n).trim()),o=decodeURIComponent(r.substring(n+1).trim());let s;return t.length>0&&(s=baggageEntryMetadataFromString(t.join(BAGGAGE_PROPERTIES_SEPARATOR))),{key:i,value:o,metadata:s}}function parseKeyPairsIntoRecord(e){return"string"!=typeof e||0===e.length?{}:e.split(BAGGAGE_ITEMS_SEPARATOR).map(e=>parsePairKeyValue(e)).filter(e=>void 0!==e&&e.value.length>0).reduce((e,t)=>(e[t.key]=t.value,e),{})}class W3CBaggagePropagator{inject(e,t,r){const n=propagation.getBaggage(e);if(!n||isTracingSuppressed$1(e))return;const i=serializeKeyPairs(getKeyPairs(n).filter(e=>e.length<=BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,BAGGAGE_MAX_NAME_VALUE_PAIRS));i.length>0&&r.set(t,BAGGAGE_HEADER,i)}extract(e,t,r){const n=r.get(t,BAGGAGE_HEADER),i=Array.isArray(n)?n.join(BAGGAGE_ITEMS_SEPARATOR):n;if(!i)return e;const o={};if(0===i.length)return e;return i.split(BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{const t=parsePairKeyValue(e);if(t){const e={value:t.value};t.metadata&&(e.metadata=t.metadata),o[t.key]=e}}),0===Object.entries(o).length?e:propagation.setBaggage(e,propagation.createBaggage(o))}fields(){return[BAGGAGE_HEADER]}}class AnchoredClock{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){const e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}function sanitizeAttributes$1(e){const t={};if("object"!=typeof e||null==e)return t;for(const[r,n]of Object.entries(e))isAttributeKey$1(r)?isAttributeValue$1(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:diag.warn(`Invalid attribute value set for key: ${r}`):diag.warn(`Invalid attribute key: ${r}`);return t}function isAttributeKey$1(e){return"string"==typeof e&&e.length>0}function isAttributeValue$1(e){return null==e||(Array.isArray(e)?isHomogeneousAttributeValueArray$1(e):isValidPrimitiveAttributeValue$1(e))}function isHomogeneousAttributeValueArray$1(e){let t;for(const r of e)if(null!=r){if(!t){if(isValidPrimitiveAttributeValue$1(r)){t=typeof r;continue}return!1}if(typeof r!==t)return!1}return!0}function isValidPrimitiveAttributeValue$1(e){switch(typeof e){case"number":case"boolean":case"string":return!0}return!1}function loggingErrorHandler$2(){return e=>{diag.error(stringifyException$2(e))}}function stringifyException$2(e){return"string"==typeof e?e:JSON.stringify(flattenException$2(e))}function flattenException$2(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler$2=loggingErrorHandler$2();function setGlobalErrorHandler(e){delegateHandler$2=e}function globalErrorHandler$2(e){try{delegateHandler$2(e)}catch{}}function getStringFromEnv(e){}function getBooleanFromEnv(e){}function getNumberFromEnv$1(e){}function getStringListFromEnv(e){}const _globalThis$6="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},otperformance$4=performance,VERSION$5="2.0.0",SDK_INFO={[SEMRESATTRS_TELEMETRY_SDK_NAME]:"opentelemetry",[SEMRESATTRS_PROCESS_RUNTIME_NAME]:"browser",[SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]:TELEMETRYSDKLANGUAGEVALUES_WEBJS,[SEMRESATTRS_TELEMETRY_SDK_VERSION]:VERSION$5};function unrefTimer$2(e){}const NANOSECOND_DIGITS$4=9,NANOSECOND_DIGITS_IN_MILLIS$5=6,MILLISECONDS_TO_NANOSECONDS$5=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$5),SECOND_TO_NANOSECONDS$4=Math.pow(10,NANOSECOND_DIGITS$4);function millisToHrTime$5(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$5)]}function getTimeOrigin$4(){let e=otperformance$4.timeOrigin;if("number"!=typeof e){const t=otperformance$4;e=t.timing&&t.timing.fetchStart}return e}function hrTime$4(e){return addHrTimes$4(millisToHrTime$5(getTimeOrigin$4()),millisToHrTime$5("number"==typeof e?e:otperformance$4.now()))}function timeInputToHrTime$1(e){if(isTimeInputHrTime$2(e))return e;if("number"==typeof e)return e=SECOND_TO_NANOSECONDS$4&&(r[1]-=SECOND_TO_NANOSECONDS$4,r[0]+=1),r}var ExportResultCode$2;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode$2||(ExportResultCode$2={}));class CompositePropagator{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>"function"==typeof e.fields?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,t,r){for(const n of this._propagators)try{n.inject(e,t,r)}catch(e){diag.warn(`Failed to inject with ${n.constructor.name}. Err: ${e.message}`)}}extract(e,t,r){return this._propagators.reduce((e,n)=>{try{return n.extract(e,t,r)}catch(e){diag.warn(`Failed to extract with ${n.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}const VALID_KEY_CHAR_RANGE="[_0-9a-z-*/]",VALID_KEY=`[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`,VALID_VENDOR_KEY=`[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`,VALID_KEY_REGEX=new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`),VALID_VALUE_BASE_REGEX=/^[ -~]{0,255}[!-~]$/,INVALID_VALUE_COMMA_EQUAL_REGEX=/,|=/;function validateKey(e){return VALID_KEY_REGEX.test(e)}function validateValue(e){return VALID_VALUE_BASE_REGEX.test(e)&&!INVALID_VALUE_COMMA_EQUAL_REGEX.test(e)}const MAX_TRACE_STATE_ITEMS=32,MAX_TRACE_STATE_LEN=512,LIST_MEMBERS_SEPARATOR=",",LIST_MEMBER_KEY_VALUE_SPLITTER="=";class TraceState{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){const r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+LIST_MEMBER_KEY_VALUE_SPLITTER+this.get(t)),e),[]).join(LIST_MEMBERS_SEPARATOR)}_parse(e){e.length>MAX_TRACE_STATE_LEN||(this._internalState=e.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((e,t)=>{const r=t.trim(),n=r.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);if(-1!==n){const i=r.slice(0,n),o=r.slice(n+1,t.length);validateKey(i)&&validateValue(o)&&e.set(i,o)}return e},new Map),this._internalState.size>MAX_TRACE_STATE_ITEMS&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,MAX_TRACE_STATE_ITEMS))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new TraceState;return e._internalState=new Map(this._internalState),e}}const TRACE_PARENT_HEADER="traceparent",TRACE_STATE_HEADER="tracestate",VERSION$4="00",VERSION_PART="(?!ff)[\\da-f]{2}",TRACE_ID_PART="(?![0]{32})[\\da-f]{32}",PARENT_ID_PART="(?![0]{16})[\\da-f]{16}",FLAGS_PART="[\\da-f]{2}",TRACE_PARENT_REGEX=new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`);function parseTraceParent(e){const t=TRACE_PARENT_REGEX.exec(e);return t?"00"===t[1]&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}:null}class W3CTraceContextPropagator{inject(e,t,r){const n=trace.getSpanContext(e);if(!n||isTracingSuppressed$1(e)||!isSpanContextValid(n))return;const i=`${VERSION$4}-${n.traceId}-${n.spanId}-0${Number(n.traceFlags||TraceFlags.NONE).toString(16)}`;r.set(t,TRACE_PARENT_HEADER,i),n.traceState&&r.set(t,TRACE_STATE_HEADER,n.traceState.serialize())}extract(e,t,r){const n=r.get(t,TRACE_PARENT_HEADER);if(!n)return e;const i=Array.isArray(n)?n[0]:n;if("string"!=typeof i)return e;const o=parseTraceParent(i);if(!o)return e;o.isRemote=!0;const s=r.get(t,TRACE_STATE_HEADER);if(s){const e=Array.isArray(s)?s.join(","):s;o.traceState=new TraceState("string"==typeof e?e:void 0)}return trace.setSpanContext(e,o)}fields(){return[TRACE_PARENT_HEADER,TRACE_STATE_HEADER]}}const RPC_METADATA_KEY=createContextKey("OpenTelemetry SDK Context Key RPC_METADATA");var RPCType;function setRPCMetadata(e,t){return e.setValue(RPC_METADATA_KEY,t)}function deleteRPCMetadata(e){return e.deleteValue(RPC_METADATA_KEY)}function getRPCMetadata(e){return e.getValue(RPC_METADATA_KEY)}!function(e){e.HTTP="http"}(RPCType||(RPCType={}));const objectTag$1="[object Object]",nullTag$1="[object Null]",undefinedTag$1="[object Undefined]",funcProto$1=Function.prototype,funcToString$1=funcProto$1.toString,objectCtorString$2=funcToString$1.call(Object),getPrototypeOf$3=Object.getPrototypeOf,objectProto$1=Object.prototype,hasOwnProperty$3=objectProto$1.hasOwnProperty,symToStringTag$1=Symbol?Symbol.toStringTag:void 0,nativeObjectToString$1=objectProto$1.toString;function isPlainObject$4(e){if(!isObjectLike$1(e)||baseGetTag$1(e)!==objectTag$1)return!1;const t=getPrototypeOf$3(e);if(null===t)return!0;const r=hasOwnProperty$3.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString$1.call(r)===objectCtorString$2}function isObjectLike$1(e){return null!=e&&"object"==typeof e}function baseGetTag$1(e){return null==e?void 0===e?undefinedTag$1:nullTag$1:symToStringTag$1&&symToStringTag$1 in Object(e)?getRawTag$1(e):objectToString$2(e)}function getRawTag$1(e){const t=hasOwnProperty$3.call(e,symToStringTag$1),r=e[symToStringTag$1];let n=!1;try{e[symToStringTag$1]=void 0,n=!0}catch(e){}const i=nativeObjectToString$1.call(e);return n&&(t?e[symToStringTag$1]=r:delete e[symToStringTag$1]),i}function objectToString$2(e){return nativeObjectToString$1.call(e)}const MAX_LEVEL$1=20;function merge$3(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=mergeTwoObjects$1(t,e.shift(),0,r);return t}function takeValue$1(e){return isArray$7(e)?e.slice():e}function mergeTwoObjects$1(e,t,r=0,n){let i;if(!(r>MAX_LEVEL$1)){if(r++,isPrimitive$1(e)||isPrimitive$1(t)||isFunction$5(t))i=takeValue$1(t);else if(isArray$7(e)){if(i=e.slice(),isArray$7(t))for(let e=0,r=t.length;e(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}function urlMatches$3(e,t){return"string"==typeof t?e===t:!!e.match(t)}function isUrlIgnored$2(e,t){if(!t)return!1;for(const r of t)if(urlMatches$3(e,r))return!0;return!1}let Deferred$1=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}},BindOnceFuture$1=class{_callback;_that;_isCalled=!1;_deferred=new Deferred$1;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}};const logLevelMap={ALL:DiagLogLevel.ALL,VERBOSE:DiagLogLevel.VERBOSE,DEBUG:DiagLogLevel.DEBUG,INFO:DiagLogLevel.INFO,WARN:DiagLogLevel.WARN,ERROR:DiagLogLevel.ERROR,NONE:DiagLogLevel.NONE};function diagLogLevelFromString(e){if(null==e)return;const t=logLevelMap[e.toUpperCase()];return null==t?(diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(logLevelMap)}, using default`),DiagLogLevel.INFO):t}function _export$2(e,t){return new Promise(r=>{context.with(suppressTracing$2(context.active()),()=>{e.export(t,e=>{r(e)})})})}const internal$2={_export:_export$2};var esm$b=Object.freeze({__proto__:null,AnchoredClock:AnchoredClock,BindOnceFuture:BindOnceFuture$1,CompositePropagator:CompositePropagator,get ExportResultCode(){return ExportResultCode$2},get RPCType(){return RPCType},SDK_INFO:SDK_INFO,TRACE_PARENT_HEADER:TRACE_PARENT_HEADER,TRACE_STATE_HEADER:TRACE_STATE_HEADER,TimeoutError:TimeoutError$1,TraceState:TraceState,W3CBaggagePropagator:W3CBaggagePropagator,W3CTraceContextPropagator:W3CTraceContextPropagator,_globalThis:_globalThis$6,addHrTimes:addHrTimes$4,callWithTimeout:callWithTimeout$1,deleteRPCMetadata:deleteRPCMetadata,diagLogLevelFromString:diagLogLevelFromString,getBooleanFromEnv:getBooleanFromEnv,getNumberFromEnv:getNumberFromEnv$1,getRPCMetadata:getRPCMetadata,getStringFromEnv:getStringFromEnv,getStringListFromEnv:getStringListFromEnv,getTimeOrigin:getTimeOrigin$4,globalErrorHandler:globalErrorHandler$2,hrTime:hrTime$4,hrTimeDuration:hrTimeDuration$1,hrTimeToMicroseconds:hrTimeToMicroseconds$2,hrTimeToMilliseconds:hrTimeToMilliseconds,hrTimeToNanoseconds:hrTimeToNanoseconds$1,hrTimeToTimeStamp:hrTimeToTimeStamp,internal:internal$2,isAttributeValue:isAttributeValue$1,isTimeInput:isTimeInput$1,isTimeInputHrTime:isTimeInputHrTime$2,isTracingSuppressed:isTracingSuppressed$1,isUrlIgnored:isUrlIgnored$2,loggingErrorHandler:loggingErrorHandler$2,merge:merge$3,millisToHrTime:millisToHrTime$5,otperformance:otperformance$4,parseKeyPairsIntoRecord:parseKeyPairsIntoRecord,parseTraceParent:parseTraceParent,sanitizeAttributes:sanitizeAttributes$1,setGlobalErrorHandler:setGlobalErrorHandler,setRPCMetadata:setRPCMetadata,suppressTracing:suppressTracing$2,timeInputToHrTime:timeInputToHrTime$1,unrefTimer:unrefTimer$2,unsuppressTracing:unsuppressTracing,urlMatches:urlMatches$3}),AggregationTemporality$2,InstrumentType$2,DataPointType$2,AggregationType$1,AggregationTemporalityPreference;!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality$2||(AggregationTemporality$2={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType$2||(InstrumentType$2={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType$2||(DataPointType$2={})),function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(AggregationType$1||(AggregationType$1={})),function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE",e[e.LOWMEMORY=2]="LOWMEMORY"}(AggregationTemporalityPreference||(AggregationTemporalityPreference={}));class OTLPExporterBase{_delegate;constructor(e){this._delegate=e}export(e,t){this._delegate.export(e,t)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class OTLPExporterError extends Error{code;name="OTLPExporterError";data;constructor(e,t,r){super(e),this.data=r,this.code=t}}function validateTimeoutMillis(e){if(Number.isFinite(e)&&e>0)return e;throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${e}')`)}function wrapStaticHeadersInFunction(e){if(null!=e)return()=>e}function mergeOtlpSharedConfigurationWithDefaults(e,t,r){return{timeoutMillis:validateTimeoutMillis(e.timeoutMillis??t.timeoutMillis??r.timeoutMillis),concurrencyLimit:e.concurrencyLimit??t.concurrencyLimit??r.concurrencyLimit,compression:e.compression??t.compression??r.compression}}function getSharedConfigurationDefaults(){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none"}}class BoundedQueueExportPromiseHandler{_concurrencyLimit;_sendingPromises=[];constructor(e){this._concurrencyLimit=e}pushPromise(e){if(this.hasReachedLimit())throw new Error("Concurrency Limit reached");this._sendingPromises.push(e);const t=()=>{const t=this._sendingPromises.indexOf(e);this._sendingPromises.splice(t,1)};e.then(t,t)}hasReachedLimit(){return this._sendingPromises.length>=this._concurrencyLimit}async awaitAll(){await Promise.all(this._sendingPromises)}}function createBoundedQueueExportPromiseHandler(e){return new BoundedQueueExportPromiseHandler(e.concurrencyLimit)}function isPartialSuccessResponse(e){return Object.prototype.hasOwnProperty.call(e,"partialSuccess")}function createLoggingPartialSuccessResponseHandler(){return{handleResponse(e){null!=e&&isPartialSuccessResponse(e)&&null!=e.partialSuccess&&0!==Object.keys(e.partialSuccess).length&&diag.warn("Received Partial Success response:",JSON.stringify(e.partialSuccess))}}}class OTLPExportDelegate{_transport;_serializer;_responseHandler;_promiseQueue;_timeout;_diagLogger;constructor(e,t,r,n,i){this._transport=e,this._serializer=t,this._responseHandler=r,this._promiseQueue=n,this._timeout=i,this._diagLogger=diag.createComponentLogger({namespace:"OTLPExportDelegate"})}export(e,t){if(this._diagLogger.debug("items to be sent",e),this._promiseQueue.hasReachedLimit())return void t({code:ExportResultCode$2.FAILED,error:new Error("Concurrent export limit reached")});const r=this._serializer.serializeRequest(e);null!=r?this._promiseQueue.pushPromise(this._transport.send(r,this._timeout).then(e=>{if("success"!==e.status)"failure"===e.status&&e.error?t({code:ExportResultCode$2.FAILED,error:e.error}):"retryable"===e.status?t({code:ExportResultCode$2.FAILED,error:new OTLPExporterError("Export failed with retryable status")}):t({code:ExportResultCode$2.FAILED,error:new OTLPExporterError("Export failed with unknown error")});else{if(null!=e.data)try{this._responseHandler.handleResponse(this._serializer.deserializeResponse(e.data))}catch(t){this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?",t,e.data)}t({code:ExportResultCode$2.SUCCESS})}},e=>t({code:ExportResultCode$2.FAILED,error:e}))):t({code:ExportResultCode$2.FAILED,error:new Error("Nothing to send")})}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started"),await this.forceFlush(),this._transport.shutdown()}}function createOtlpExportDelegate(e,t){return new OTLPExportDelegate(e.transport,e.serializer,createLoggingPartialSuccessResponseHandler(),e.promiseHandler,t.timeout)}function createOtlpNetworkExportDelegate(e,t,r){return createOtlpExportDelegate({transport:r,serializer:t,promiseHandler:createBoundedQueueExportPromiseHandler(e)},{timeout:e.timeoutMillis})}const CumulativeTemporalitySelector=()=>AggregationTemporality$2.CUMULATIVE,DeltaTemporalitySelector=e=>{switch(e){case InstrumentType$2.COUNTER:case InstrumentType$2.OBSERVABLE_COUNTER:case InstrumentType$2.GAUGE:case InstrumentType$2.HISTOGRAM:case InstrumentType$2.OBSERVABLE_GAUGE:return AggregationTemporality$2.DELTA;case InstrumentType$2.UP_DOWN_COUNTER:case InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER:return AggregationTemporality$2.CUMULATIVE}},LowMemoryTemporalitySelector=e=>{switch(e){case InstrumentType$2.COUNTER:case InstrumentType$2.HISTOGRAM:return AggregationTemporality$2.DELTA;case InstrumentType$2.GAUGE:case InstrumentType$2.UP_DOWN_COUNTER:case InstrumentType$2.OBSERVABLE_UP_DOWN_COUNTER:case InstrumentType$2.OBSERVABLE_COUNTER:case InstrumentType$2.OBSERVABLE_GAUGE:return AggregationTemporality$2.CUMULATIVE}};function chooseTemporalitySelectorFromEnvironment(){const e="cumulative".toLowerCase();return"cumulative"===e?CumulativeTemporalitySelector:"delta"===e?DeltaTemporalitySelector:"lowmemory"===e?LowMemoryTemporalitySelector:(diag.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),CumulativeTemporalitySelector)}function chooseTemporalitySelector(e){return null!=e?e===AggregationTemporalityPreference.DELTA?DeltaTemporalitySelector:e===AggregationTemporalityPreference.LOWMEMORY?LowMemoryTemporalitySelector:CumulativeTemporalitySelector:chooseTemporalitySelectorFromEnvironment()}const DEFAULT_AGGREGATION$1=Object.freeze({type:AggregationType$1.DEFAULT});function chooseAggregationSelector(e){return e?.aggregationPreference??(()=>DEFAULT_AGGREGATION$1)}class OTLPMetricExporterBase extends OTLPExporterBase{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=chooseAggregationSelector(t),this._aggregationTemporalitySelector=chooseTemporalitySelector(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}}function intValue(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-87:e-55}function hexToBinary(e){const t=new Uint8Array(e.length/2);let r=0;for(let n=0;n>BigInt(32)))}}function encodeAsLongBits(e){return toLongBits(hrTimeToNanos(e))}function encodeAsString(e){return hrTimeToNanos(e).toString()}const encodeTimestamp="undefined"!=typeof BigInt?encodeAsString:hrTimeToNanoseconds$1;function identity(e){return e}function optionalHexToBinary(e){if(void 0!==e)return hexToBinary(e)}const DEFAULT_ENCODER={encodeHrTime:encodeAsLongBits,encodeSpanContext:hexToBinary,encodeOptionalSpanContext:optionalHexToBinary};function getOtlpEncoder(e){if(void 0===e)return DEFAULT_ENCODER;const t=e.useLongBits??!0,r=e.useHex??!1;return{encodeHrTime:t?encodeAsLongBits:encodeTimestamp,encodeSpanContext:r?identity:hexToBinary,encodeOptionalSpanContext:r?identity:optionalHexToBinary}}function createResource(e){return{attributes:toAttributes(e.attributes),droppedAttributesCount:0}}function createInstrumentationScope(e){return{name:e.name,version:e.version}}function toAttributes(e){return Object.keys(e).map(t=>toKeyValue(t,e[t]))}function toKeyValue(e,t){return{key:e,value:toAnyValue(t)}}function toAnyValue(e){const t=typeof e;return"string"===t?{stringValue:e}:"number"===t?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:"boolean"===t?{boolValue:e}:e instanceof Uint8Array?{bytesValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(toAnyValue)}}:"object"===t&&null!=e?{kvlistValue:{values:Object.entries(e).map(([e,t])=>toKeyValue(e,t))}}:{}}function createExportLogsServiceRequest(e,t){return{resourceLogs:logRecordsToResourceLogs(e,getOtlpEncoder(t))}}function createResourceMap$1(e){const t=new Map;for(const r of e){const{resource:e,instrumentationScope:{name:n,version:i="",schemaUrl:o=""}}=r;let s=t.get(e);s||(s=new Map,t.set(e,s));const a=`${n}@${i}:${o}`;let c=s.get(a);c||(c=[],s.set(a,c)),c.push(r)}return t}function logRecordsToResourceLogs(e,t){const r=createResourceMap$1(e);return Array.from(r,([e,r])=>({resource:createResource(e),scopeLogs:Array.from(r,([,e])=>({scope:createInstrumentationScope(e[0].instrumentationScope),logRecords:e.map(e=>toLogRecord(e,t)),schemaUrl:e[0].instrumentationScope.schemaUrl})),schemaUrl:void 0}))}function toLogRecord(e,t){return{timeUnixNano:t.encodeHrTime(e.hrTime),observedTimeUnixNano:t.encodeHrTime(e.hrTimeObserved),severityNumber:toSeverityNumber(e.severityNumber),severityText:e.severityText,body:toAnyValue(e.body),attributes:toLogAttributes(e.attributes),droppedAttributesCount:e.droppedAttributesCount,flags:e.spanContext?.traceFlags,traceId:t.encodeOptionalSpanContext(e.spanContext?.traceId),spanId:t.encodeOptionalSpanContext(e.spanContext?.spanId)}}function toSeverityNumber(e){return e}function toLogAttributes(e){return Object.keys(e).map(t=>toKeyValue(t,e[t]))}var AggregationTemporality$1,InstrumentType$1,DataPointType$1;function toResourceMetrics(e,t){const r=getOtlpEncoder(t);return{resource:createResource(e.resource),schemaUrl:void 0,scopeMetrics:toScopeMetrics(e.scopeMetrics,r)}}function toScopeMetrics(e,t){return Array.from(e.map(e=>({scope:createInstrumentationScope(e.scope),metrics:e.metrics.map(e=>toMetric(e,t)),schemaUrl:e.scope.schemaUrl})))}function toMetric(e,t){const r={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},n=toAggregationTemporality(e.aggregationTemporality);switch(e.dataPointType){case DataPointType$1.SUM:r.sum={aggregationTemporality:n,isMonotonic:e.isMonotonic,dataPoints:toSingularDataPoints(e,t)};break;case DataPointType$1.GAUGE:r.gauge={dataPoints:toSingularDataPoints(e,t)};break;case DataPointType$1.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:toHistogramDataPoints(e,t)};break;case DataPointType$1.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:toExponentialHistogramDataPoints(e,t)}}return r}function toSingularDataPoint(e,t,r){const n={attributes:toAttributes(e.attributes),startTimeUnixNano:r.encodeHrTime(e.startTime),timeUnixNano:r.encodeHrTime(e.endTime)};switch(t){case ValueType.INT:n.asInt=e.value;break;case ValueType.DOUBLE:n.asDouble=e.value}return n}function toSingularDataPoints(e,t){return e.dataPoints.map(r=>toSingularDataPoint(r,e.descriptor.valueType,t))}function toHistogramDataPoints(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:toAttributes(e.attributes),bucketCounts:r.buckets.counts,explicitBounds:r.buckets.boundaries,count:r.count,sum:r.sum,min:r.min,max:r.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function toExponentialHistogramDataPoints(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:toAttributes(e.attributes),count:r.count,min:r.min,max:r.max,sum:r.sum,positive:{offset:r.positive.offset,bucketCounts:r.positive.bucketCounts},negative:{offset:r.negative.offset,bucketCounts:r.negative.bucketCounts},scale:r.scale,zeroCount:r.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function toAggregationTemporality(e){switch(e){case AggregationTemporality$1.DELTA:return 1;case AggregationTemporality$1.CUMULATIVE:return 2}}function createExportMetricsServiceRequest(e,t){return{resourceMetrics:e.map(e=>toResourceMetrics(e,t))}}function sdkSpanToOtlpSpan(e,t){const r=e.spanContext(),n=e.status,i=e.parentSpanContext?.spanId?t.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:t.encodeSpanContext(r.traceId),spanId:t.encodeSpanContext(r.spanId),parentSpanId:i,traceState:r.traceState?.serialize(),name:e.name,kind:null==e.kind?0:e.kind+1,startTimeUnixNano:t.encodeHrTime(e.startTime),endTimeUnixNano:t.encodeHrTime(e.endTime),attributes:toAttributes(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>toOtlpSpanEvent(e,t)),droppedEventsCount:e.droppedEventsCount,status:{code:n.code,message:n.message},links:e.links.map(e=>toOtlpLink(e,t)),droppedLinksCount:e.droppedLinksCount}}function toOtlpLink(e,t){return{attributes:e.attributes?toAttributes(e.attributes):[],spanId:t.encodeSpanContext(e.context.spanId),traceId:t.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}function toOtlpSpanEvent(e,t){return{attributes:e.attributes?toAttributes(e.attributes):[],name:e.name,timeUnixNano:t.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}function createExportTraceServiceRequest(e,t){return{resourceSpans:spanRecordsToResourceSpans(e,getOtlpEncoder(t))}}function createResourceMap(e){const t=new Map;for(const r of e){let e=t.get(r.resource);e||(e=new Map,t.set(r.resource,e));const n=`${r.instrumentationScope.name}@${r.instrumentationScope.version||""}:${r.instrumentationScope.schemaUrl||""}`;let i=e.get(n);i||(i=[],e.set(n,i)),i.push(r)}return t}function spanRecordsToResourceSpans(e,t){const r=[],n=createResourceMap(e).entries();let i=n.next();for(;!i.done;){const[e,o]=i.value,s=[],a=o.values();let c=a.next();for(;!c.done;){const e=c.value;if(e.length>0){const r=e.map(e=>sdkSpanToOtlpSpan(e,t));s.push({scope:createInstrumentationScope(e[0].instrumentationScope),spans:r,schemaUrl:e[0].instrumentationScope.schemaUrl})}c=a.next()}const l={resource:createResource(e),scopeSpans:s,schemaUrl:void 0};r.push(l),i=n.next()}return r}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality$1||(AggregationTemporality$1={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType$1||(InstrumentType$1={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType$1||(DataPointType$1={}));const JsonLogsSerializer={serializeRequest:e=>{const t=createExportLogsServiceRequest(e,{useHex:!0,useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},JsonMetricsSerializer={serializeRequest:e=>{const t=createExportMetricsServiceRequest([e],{useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},JsonTraceSerializer={serializeRequest:e=>{const t=createExportTraceServiceRequest(e,{useHex:!0,useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{const t=new TextDecoder;return JSON.parse(t.decode(e))}},MAX_ATTEMPTS=5,INITIAL_BACKOFF=1e3,MAX_BACKOFF=5e3,BACKOFF_MULTIPLIER=1.5,JITTER=.2;function getJitter(){return Math.random()*(2*JITTER)-JITTER}class RetryingTransport{_transport;constructor(e){this._transport=e}retry(e,t,r){return new Promise((n,i)=>{setTimeout(()=>{this._transport.send(e,t).then(n,i)},r)})}async send(e,t){const r=Date.now()+t;let n=await this._transport.send(e,t),i=MAX_ATTEMPTS,o=INITIAL_BACKOFF;for(;"retryable"===n.status&&i>0;){i--;const t=Math.max(Math.min(o,MAX_BACKOFF)+getJitter(),0);o*=BACKOFF_MULTIPLIER;const s=n.retryInMillis??t,a=r-Date.now();if(s>a)return n;n=await this.retry(e,a,s)}return n}shutdown(){return this._transport.shutdown()}}function createRetryingTransport(e){return new RetryingTransport(e.transport)}function isExportRetryable(e){return[429,502,503,504].includes(e)}function parseRetryAfterToMills(e){if(null==e)return;const t=Number.parseInt(e,10);if(Number.isInteger(t))return t>0?1e3*t:-1;const r=new Date(e).getTime()-Date.now();return r>=0?r:0}class XhrTransport{_parameters;constructor(e){this._parameters=e}send(e,t){return new Promise(r=>{const n=new XMLHttpRequest;n.timeout=t,n.open("POST",this._parameters.url);const i=this._parameters.headers();Object.entries(i).forEach(([e,t])=>{n.setRequestHeader(e,t)}),n.ontimeout=e=>{r({status:"failure",error:new Error("XHR request timed out")})},n.onreadystatechange=()=>{n.status>=200&&n.status<=299?(diag.debug("XHR success"),r({status:"success"})):n.status&&isExportRetryable(n.status)?r({status:"retryable",retryInMillis:parseRetryAfterToMills(n.getResponseHeader("Retry-After"))}):0!==n.status&&r({status:"failure",error:new Error("XHR request failed with non-retryable status")})},n.onabort=()=>{r({status:"failure",error:new Error("XHR request aborted")})},n.onerror=()=>{r({status:"failure",error:new Error("XHR request errored")})},n.send(e)})}shutdown(){}}function createXhrTransport(e){return new XhrTransport(e)}class SendBeaconTransport{_params;constructor(e){this._params=e}send(e){return new Promise(t=>{navigator.sendBeacon(this._params.url,new Blob([e],{type:this._params.blobType}))?(diag.debug("SendBeacon success"),t({status:"success"})):t({status:"failure",error:new Error("SendBeacon failed")})})}shutdown(){}}function createSendBeaconTransport(e){return new SendBeaconTransport(e)}function createOtlpXhrExportDelegate(e,t){return createOtlpNetworkExportDelegate(e,t,createRetryingTransport({transport:createXhrTransport(e)}))}function createOtlpSendBeaconExportDelegate(e,t){return createOtlpNetworkExportDelegate(e,t,createRetryingTransport({transport:createSendBeaconTransport({url:e.url,blobType:e.headers()["Content-Type"]})}))}function validateAndNormalizeHeaders(e){return()=>{const t={};return Object.entries(e?.()??{}).forEach(([e,r])=>{void 0!==r?t[e]=String(r):diag.warn(`Header "${e}" has invalid value (${r}) and will be ignored`)}),t}}function mergeHeaders(e,t,r){const n={...r()},i={};return()=>(null!=t&&Object.assign(i,t()),null!=e&&Object.assign(i,e()),Object.assign(i,n))}function validateUserProvidedUrl(e){if(null!=e)try{return new URL(e),e}catch(t){throw new Error(`Configuration: Could not parse user-provided export URL: '${e}'`)}}function mergeOtlpHttpConfigurationWithDefaults(e,t,r){return{...mergeOtlpSharedConfigurationWithDefaults(e,t,r),headers:mergeHeaders(validateAndNormalizeHeaders(e.headers),t.headers,r.headers),url:validateUserProvidedUrl(e.url)??t.url??r.url,agentOptions:e.agentOptions??t.agentOptions??r.agentOptions}}function getHttpConfigurationDefaults(e,t){return{...getSharedConfigurationDefaults(),headers:()=>e,url:"http://localhost:4318/"+t,agentOptions:{keepAlive:!0}}}function convertLegacyBrowserHttpOptions(e,t,r){return mergeOtlpHttpConfigurationWithDefaults({url:e.url,timeoutMillis:e.timeoutMillis,headers:wrapStaticHeadersInFunction(e.headers),concurrencyLimit:e.concurrencyLimit},{},getHttpConfigurationDefaults(r,t))}function createLegacyOtlpBrowserExportDelegate(e,t,r,n){const i=!!e.headers||"function"!=typeof navigator.sendBeacon,o=convertLegacyBrowserHttpOptions(e,r,n);return i?createOtlpXhrExportDelegate(o,t):createOtlpSendBeaconExportDelegate(o,t)}class OTLPMetricExporter extends OTLPMetricExporterBase{constructor(e){super(createLegacyOtlpBrowserExportDelegate(e??{},JsonMetricsSerializer,"v1/metrics",{"Content-Type":"application/json"}),e)}}var esm$a=Object.freeze({__proto__:null,get AggregationTemporalityPreference(){return AggregationTemporalityPreference},CumulativeTemporalitySelector:CumulativeTemporalitySelector,DeltaTemporalitySelector:DeltaTemporalitySelector,LowMemoryTemporalitySelector:LowMemoryTemporalitySelector,OTLPMetricExporter:OTLPMetricExporter,OTLPMetricExporterBase:OTLPMetricExporterBase}),require$$5=getAugmentedNamespace(esm$a),AggregationTemporality,InstrumentType,DataPointType,AggregatorKind;function isNotNullish(e){return null!=e}function hashAttributes(e){let t=Object.keys(e);return 0===t.length?"":(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}function instrumentationScopeId(e){return`${e.name}:${e.version??""}:${e.schemaUrl??""}`}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(AggregationTemporality||(AggregationTemporality={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(InstrumentType||(InstrumentType={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(DataPointType||(DataPointType={}));class TimeoutError extends Error{constructor(e){super(e),Object.setPrototypeOf(this,TimeoutError.prototype)}}function callWithTimeout(e,t){let r;const n=new Promise(function(e,n){r=setTimeout(function(){n(new TimeoutError("Operation timed out."))},t)});return Promise.race([e,n]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}async function PromiseAllSettled(e){return Promise.all(e.map(async e=>{try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}))}function isPromiseAllSettledRejectionResult(e){return"rejected"===e.status}function FlatMap(e,t){const r=[];return e.forEach(e=>{r.push(...t(e))}),r}function setEquals(e,t){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}function binarySearchUB(e,t){let r=0,n=e.length-1,i=e.length;for(;n>=r;){const o=r+Math.trunc((n-r)/2);e[o]0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}class HistogramAccumulation{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,r=!0,n=createNewEmptyCheckpoint(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=r,this._current=n}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);const t=binarySearchUB(this._boundaries,e);this._current.buckets.counts[t]+=1}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class HistogramAggregator{_boundaries;_recordMinMax;kind=AggregatorKind.HISTOGRAM;constructor(e,t){this._boundaries=e,this._recordMinMax=t}createAccumulation(e){return new HistogramAccumulation(e,this._boundaries,this._recordMinMax)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue(),i=r.buckets.counts,o=n.buckets.counts,s=new Array(i.length);for(let e=0;e{const i=r.toPointValue(),o=e.type===InstrumentType.GAUGE||e.type===InstrumentType.UP_DOWN_COUNTER||e.type===InstrumentType.OBSERVABLE_GAUGE||e.type===InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:o?void 0:i.sum,buckets:i.buckets,count:i.count}}})}}}class Buckets{backing;indexBase;indexStart;indexEnd;constructor(e=new BucketsBacking,t=0,r=0,n=0){this.backing=e,this.indexBase=t,this.indexStart=r,this.indexEnd=n}get offset(){return this.indexStart}get length(){return 0===this.backing.length||this.indexEnd===this.indexStart&&0===this.at(0)?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){const t=this.indexBase-this.indexStart;return e=0;e--)if(0!==this.at(e)){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();const t=1+this.indexEnd-this.indexStart,r=1<>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new Buckets(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const e=this.indexBase-this.indexStart;0!==e&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}}class BucketsBacking{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,r){const n=new Array(e).fill(0);n.splice(r,this._counts.length-t,...this._counts.slice(t)),n.splice(0,t,...this._counts.slice(0,t)),this._counts=n}reverse(e,t){const r=Math.floor((e+t)/2)-e;for(let n=0;n=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new BucketsBacking([...this._counts])}}const SIGNIFICAND_WIDTH=52,EXPONENT_MASK=2146435072,SIGNIFICAND_MASK=1048575,EXPONENT_BIAS=1023,MIN_NORMAL_EXPONENT=1-EXPONENT_BIAS,MAX_NORMAL_EXPONENT=EXPONENT_BIAS,MIN_VALUE=Math.pow(2,-1022);function getNormalBase2(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);return((t.getUint32(0)&EXPONENT_MASK)>>20)-EXPONENT_BIAS}function getSignificand(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);const r=t.getUint32(0),n=t.getUint32(4);return(r&SIGNIFICAND_MASK)*Math.pow(2,32)+n}function ldexp(e,t){return 0===e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY||Number.isNaN(e)?e:e*Math.pow(2,t)}function nextGreaterSquare(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}class MappingError extends Error{}class ExponentMapping{_shift;constructor(e){this._shift=-e}mapToIndex(e){if(e>this._shift}lowerBoundary(e){const t=this._minNormalLowerBoundaryIndex();if(er)throw new MappingError(`overflow: ${e} is > maximum lower boundary: ${r}`);return ldexp(1,e<>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return MAX_NORMAL_EXPONENT>>this._shift}_rightShift(e,t){return Math.floor(e*Math.pow(2,-t))}}class LogarithmMapping{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=ldexp(Math.LOG2E,e),this._inverseFactor=ldexp(Math.LN2,-e)}mapToIndex(e){if(e<=MIN_VALUE)return this._minNormalLowerBoundaryIndex()-1;if(0===getSignificand(e)){return(getNormalBase2(e)<=r?r:t}lowerBoundary(e){const t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1< maximum lower boundary: ${t}`)}const r=this._minNormalLowerBoundaryIndex();if(e<=r){if(e===r)return MIN_VALUE;if(e===r-1)return Math.exp((e+(1<t>10?new LogarithmMapping(t-10):new ExponentMapping(t-10));function getMapping(e){if(e>MAX_SCALE$1||e= ${MIN_SCALE} && <= ${MAX_SCALE$1}, got: ${e}`);return PREBUILT_MAPPINGS[e+10]}class HighLow{low;high;static combine(e,t){return new HighLow(Math.min(e.low,t.low),Math.max(e.high,t.high))}constructor(e,t){this.low=e,this.high=t}}const MAX_SCALE=20,DEFAULT_MAX_SIZE=160,MIN_MAX_SIZE=2;class ExponentialHistogramAccumulation{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e=e,t=DEFAULT_MAX_SIZE,r=!0,n=0,i=0,o=0,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,c=new Buckets,l=new Buckets,u=getMapping(MAX_SCALE)){this.startTime=e,this._maxSize=t,this._recordMinMax=r,this._sum=n,this._count=i,this._zeroCount=o,this._min=s,this._max=a,this._positive=c,this._negative=l,this._mapping=u,this._maxSizethis._max&&(this._max=e),e0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)):this._zeroCount+=t)}merge(e){0===this._count?(this._min=e.min,this._max=e.max):0!==e.count&&(e.minthis.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new ExponentialHistogramAccumulation(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,r){let n=this._mapping.mapToIndex(t),i=!1,o=0,s=0;if(0===e.length?(e.indexStart=n,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):n=this._maxSize?(i=!0,s=n,o=e.indexEnd):n>e.indexEnd&&n-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,o=n),i){const e=this._changeScale(o,s);this._downscale(e),n=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,n,r)}_incrementIndexBy(e,t,r){if(0===r)return;if(0===e.length&&(e.indexStart=e.indexEnd=e.indexBase=t),t=e.backing.length&&this._grow(e,r+1),e.indexStart=t}else if(t>e.indexEnd){const r=t-e.indexStart;r>=e.backing.length&&this._grow(e,r+1),e.indexEnd=t}let n=t-e.indexBase;n<0&&(n+=e.backing.length),e.incrementBucket(n,r)}_grow(e,t){const r=e.backing.length,n=e.indexBase-e.indexStart,i=r-n;let o=nextGreaterSquare(t);o>this._maxSize&&(o=this._maxSize);const s=o-n;e.backing.growTo(o,i,s)}_changeScale(e,t){let r=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,r++;return r}_downscale(e){if(0===e)return;if(e<0)throw new Error(`impossible change of scale: ${this.scale}`);const t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=getMapping(t)}_minScale(e){const t=Math.min(this.scale,e.scale),r=HighLow.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),n=HighLow.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(r.high,r.low),t-this._changeScale(n.high,n.low))}_highLowAtScale(e,t,r){if(0===e.length)return new HighLow(0,-1);const n=t-r;return new HighLow(e.indexStart>>n,e.indexEnd>>n)}_mergeBuckets(e,t,r,n){const i=r.offset,o=t.scale-n;for(let t=0;t>o,r.at(t))}_diffBuckets(e,t,r,n){const i=r.offset,o=t.scale-n;for(let t=0;t>o)-e.indexBase;n<0&&(n+=e.backing.length),e.decrementBucket(n,r.at(t))}e.trim()}}class ExponentialHistogramAggregator{_maxSize;_recordMinMax;kind=AggregatorKind.EXPONENTIAL_HISTOGRAM;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new ExponentialHistogramAccumulation(e,this._maxSize,this._recordMinMax)}merge(e,t){const r=t.clone();return r.merge(e),r}diff(e,t){const r=t.clone();return r.diff(e),r}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType.EXPONENTIAL_HISTOGRAM,dataPoints:r.map(([t,r])=>{const i=r.toPointValue(),o=e.type===InstrumentType.GAUGE||e.type===InstrumentType.UP_DOWN_COUNTER||e.type===InstrumentType.OBSERVABLE_GAUGE||e.type===InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:i.hasMinMax?i.min:void 0,max:i.hasMinMax?i.max:void 0,sum:o?void 0:i.sum,positive:{offset:i.positive.offset,bucketCounts:i.positive.bucketCounts},negative:{offset:i.negative.offset,bucketCounts:i.negative.bucketCounts},count:i.count,scale:i.scale,zeroCount:i.zeroCount}}})}}}const SUPPRESS_TRACING_KEY$1=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing$1(e){return e.setValue(SUPPRESS_TRACING_KEY$1,!0)}function loggingErrorHandler$1(){return e=>{diag.error(stringifyException$1(e))}}function stringifyException$1(e){return"string"==typeof e?e:JSON.stringify(flattenException$1(e))}function flattenException$1(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler$1=loggingErrorHandler$1();function globalErrorHandler$1(e){try{delegateHandler$1(e)}catch{}}function unrefTimer$1(e){}const NANOSECOND_DIGITS_IN_MILLIS$4=6,MILLISECONDS_TO_NANOSECONDS$4=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$4);function millisToHrTime$4(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$4)]}function hrTimeToMicroseconds$1(e){return 1e6*e[0]+e[1]/1e3}var ExportResultCode$1;function _export$1(e,t){return new Promise(r=>{context.with(suppressTracing$1(context.active()),()=>{e.export(t,e=>{r(e)})})})}!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode$1||(ExportResultCode$1={}));const internal$1={_export:_export$1};class LastValueAccumulation{startTime;_current;sampleTime;constructor(e,t=0,r=[0,0]){this.startTime=e,this._current=t,this.sampleTime=r}record(e){this._current=e,this.sampleTime=millisToHrTime$4(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class LastValueAggregator{kind=AggregatorKind.LAST_VALUE;createAccumulation(e){return new LastValueAccumulation(e)}merge(e,t){const r=hrTimeToMicroseconds$1(t.sampleTime)>=hrTimeToMicroseconds$1(e.sampleTime)?t:e;return new LastValueAccumulation(e.startTime,r.toPointValue(),r.sampleTime)}diff(e,t){const r=hrTimeToMicroseconds$1(t.sampleTime)>=hrTimeToMicroseconds$1(e.sampleTime)?t:e;return new LastValueAccumulation(t.startTime,r.toPointValue(),r.sampleTime)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType.GAUGE,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()}))}}}class SumAccumulation{startTime;monotonic;_current;reset;constructor(e,t,r=0,n=!1){this.startTime=e,this.monotonic=t,this._current=r,this.reset=n}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class SumAggregator{monotonic;kind=AggregatorKind.SUM;constructor(e){this.monotonic=e}createAccumulation(e){return new SumAccumulation(e,this.monotonic)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue();return t.reset?new SumAccumulation(t.startTime,this.monotonic,n,t.reset):new SumAccumulation(e.startTime,this.monotonic,r+n)}diff(e,t){const r=e.toPointValue(),n=t.toPointValue();return this.monotonic&&r>n?new SumAccumulation(t.startTime,this.monotonic,n,!0):new SumAccumulation(t.startTime,this.monotonic,n-r)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:DataPointType.SUM,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()})),isMonotonic:this.monotonic}}}class DropAggregation{static DEFAULT_INSTANCE=new DropAggregator;createAggregator(e){return DropAggregation.DEFAULT_INSTANCE}}class SumAggregation{static MONOTONIC_INSTANCE=new SumAggregator(!0);static NON_MONOTONIC_INSTANCE=new SumAggregator(!1);createAggregator(e){switch(e.type){case InstrumentType.COUNTER:case InstrumentType.OBSERVABLE_COUNTER:case InstrumentType.HISTOGRAM:return SumAggregation.MONOTONIC_INSTANCE;default:return SumAggregation.NON_MONOTONIC_INSTANCE}}}class LastValueAggregation{static DEFAULT_INSTANCE=new LastValueAggregator;createAggregator(e){return LastValueAggregation.DEFAULT_INSTANCE}}class HistogramAggregation{static DEFAULT_INSTANCE=new HistogramAggregator([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(e){return HistogramAggregation.DEFAULT_INSTANCE}}class ExplicitBucketHistogramAggregation{_recordMinMax;_boundaries;constructor(e,t=!0){if(this._recordMinMax=t,null==e)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");e=(e=e.concat()).sort((e,t)=>e-t);const r=e.lastIndexOf(-1/0);let n=e.indexOf(1/0);-1===n&&(n=void 0),this._boundaries=e.slice(r+1,n)}createAggregator(e){return new HistogramAggregator(this._boundaries,this._recordMinMax)}}class ExponentialHistogramAggregation{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new ExponentialHistogramAggregator(this._maxSize,this._recordMinMax)}}class DefaultAggregation{_resolve(e){switch(e.type){case InstrumentType.COUNTER:case InstrumentType.UP_DOWN_COUNTER:case InstrumentType.OBSERVABLE_COUNTER:case InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:return SUM_AGGREGATION;case InstrumentType.GAUGE:case InstrumentType.OBSERVABLE_GAUGE:return LAST_VALUE_AGGREGATION;case InstrumentType.HISTOGRAM:return e.advice.explicitBucketBoundaries?new ExplicitBucketHistogramAggregation(e.advice.explicitBucketBoundaries):HISTOGRAM_AGGREGATION}return diag.warn(`Unable to recognize instrument type: ${e.type}`),DROP_AGGREGATION}createAggregator(e){return this._resolve(e).createAggregator(e)}}const DROP_AGGREGATION=new DropAggregation,SUM_AGGREGATION=new SumAggregation,LAST_VALUE_AGGREGATION=new LastValueAggregation,HISTOGRAM_AGGREGATION=new HistogramAggregation,DEFAULT_AGGREGATION=new DefaultAggregation;var AggregationType;function toAggregation(e){switch(e.type){case AggregationType.DEFAULT:return DEFAULT_AGGREGATION;case AggregationType.DROP:return DROP_AGGREGATION;case AggregationType.SUM:return SUM_AGGREGATION;case AggregationType.LAST_VALUE:return LAST_VALUE_AGGREGATION;case AggregationType.EXPONENTIAL_HISTOGRAM:{const t=e;return new ExponentialHistogramAggregation(t.options?.maxSize,t.options?.recordMinMax)}case AggregationType.EXPLICIT_BUCKET_HISTOGRAM:{const t=e;return null==t.options?HISTOGRAM_AGGREGATION:new ExplicitBucketHistogramAggregation(t.options?.boundaries,t.options?.recordMinMax)}default:throw new Error("Unsupported Aggregation")}}!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(AggregationType||(AggregationType={}));const DEFAULT_AGGREGATION_SELECTOR=e=>({type:AggregationType.DEFAULT}),DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR=e=>AggregationTemporality.CUMULATIVE;class MetricReader{_shutdown=!1;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(e){this._aggregationSelector=e?.aggregationSelector??DEFAULT_AGGREGATION_SELECTOR,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(void 0===this._sdkMetricProducer)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");const[t,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),n=t.errors.concat(FlatMap(r,e=>e.errors));return{resourceMetrics:{resource:t.resourceMetrics.resource,scopeMetrics:t.resourceMetrics.scopeMetrics.concat(FlatMap(r,e=>e.resourceMetrics.scopeMetrics))},errors:n}}async shutdown(e){this._shutdown?diag.error("Cannot call shutdown twice."):(null==e?.timeoutMillis?await this.onShutdown():await callWithTimeout(this.onShutdown(),e.timeoutMillis),this._shutdown=!0)}async forceFlush(e){this._shutdown?diag.warn("Cannot forceFlush on already shutdown MetricReader."):null!=e?.timeoutMillis?await callWithTimeout(this.onForceFlush(),e.timeoutMillis):await this.onForceFlush()}}class PeriodicExportingMetricReader extends MetricReader{_interval;_exporter;_exportInterval;_exportTimeout;constructor(e){if(super({aggregationSelector:e.exporter.selectAggregation?.bind(e.exporter),aggregationTemporalitySelector:e.exporter.selectAggregationTemporality?.bind(e.exporter),metricProducers:e.metricProducers}),void 0!==e.exportIntervalMillis&&e.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(void 0!==e.exportTimeoutMillis&&e.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(void 0!==e.exportTimeoutMillis&&void 0!==e.exportIntervalMillis&&e.exportIntervalMillis0&&diag.error("PeriodicExportingMetricReader: metrics collection errors",...t),e.resource.asyncAttributesPending)try{await(e.resource.waitForAsyncAttributes?.())}catch(e){diag.debug("Error while resolving async portion of resource: ",e),globalErrorHandler$1(e)}if(0===e.scopeMetrics.length)return;const r=await internal$1._export(this._exporter,e);if(r.code!==ExportResultCode$1.SUCCESS)throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${r.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),unrefTimer$1(this._interval)}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}class InMemoryMetricExporter{_shutdown=!1;_aggregationTemporality;_metrics=[];constructor(e){this._aggregationTemporality=e}export(e,t){this._shutdown?setTimeout(()=>t({code:ExportResultCode$1.FAILED}),0):(this._metrics.push(e),setTimeout(()=>t({code:ExportResultCode$1.SUCCESS}),0))}getMetrics(){return this._metrics}forceFlush(){return Promise.resolve()}reset(){this._metrics=[]}selectAggregationTemporality(e){return this._aggregationTemporality}shutdown(){return this._shutdown=!0,Promise.resolve()}}class ConsoleMetricExporter{_shutdown=!1;_temporalitySelector;constructor(e){this._temporalitySelector=e?.temporalitySelector??DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR}export(e,t){if(!this._shutdown)return ConsoleMetricExporter._sendMetrics(e,t);setImmediate(t,{code:ExportResultCode$1.FAILED})}forceFlush(){return Promise.resolve()}selectAggregationTemporality(e){return this._temporalitySelector(e)}shutdown(){return this._shutdown=!0,Promise.resolve()}static _sendMetrics(e,t){for(const t of e.scopeMetrics)for(const e of t.metrics)console.dir({descriptor:e.descriptor,dataPointType:e.dataPointType,dataPoints:e.dataPoints},{depth:null});t({code:ExportResultCode$1.SUCCESS})}}class ViewRegistry{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(r=>this._matchInstrument(r.instrumentSelector,e)&&this._matchMeter(r.meterSelector,t))}_matchInstrument(e,t){return(void 0===e.getType()||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(void 0===t.version||e.getVersionFilter().match(t.version))&&(void 0===t.schemaUrl||e.getSchemaUrlFilter().match(t.schemaUrl))}}function createInstrumentDescriptor(e,t,r){return isValidName(e)||diag.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:t,description:r?.description??"",unit:r?.unit??"",valueType:r?.valueType??ValueType.DOUBLE,advice:r?.advice??{}}}function createInstrumentDescriptorWithView(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}function isDescriptorCompatibleWith(e,t){return equalsCaseInsensitive(e.name,t.name)&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType}const NAME_REGEXP=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function isValidName(e){return null!=e.match(NAME_REGEXP)}class SyncInstrument{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},r=context.active()){"number"==typeof e?(this._descriptor.valueType!==ValueType.INT||Number.isInteger(e)||(diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._writableMetricStorage.record(e,t,r,millisToHrTime$4(Date.now())):diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`)}}class UpDownCounterInstrument extends SyncInstrument{add(e,t,r){this._record(e,t,r)}}class CounterInstrument extends SyncInstrument{add(e,t,r){e<0?diag.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class GaugeInstrument extends SyncInstrument{record(e,t,r){this._record(e,t,r)}}class HistogramInstrument extends SyncInstrument{record(e,t,r){e<0?diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class ObservableInstrument{_observableRegistry;_metricStorages;_descriptor;constructor(e,t,r){this._observableRegistry=r,this._descriptor=e,this._metricStorages=t}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}}class ObservableCounterInstrument extends ObservableInstrument{}class ObservableGaugeInstrument extends ObservableInstrument{}class ObservableUpDownCounterInstrument extends ObservableInstrument{}function isObservableInstrument(e){return e instanceof ObservableInstrument}class Meter{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){const r=createInstrumentDescriptor(e,InstrumentType.GAUGE,t),n=this._meterSharedState.registerMetricStorage(r);return new GaugeInstrument(n,r)}createHistogram(e,t){const r=createInstrumentDescriptor(e,InstrumentType.HISTOGRAM,t),n=this._meterSharedState.registerMetricStorage(r);return new HistogramInstrument(n,r)}createCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType.COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new CounterInstrument(n,r)}createUpDownCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType.UP_DOWN_COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new UpDownCounterInstrument(n,r)}createObservableGauge(e,t){const r=createInstrumentDescriptor(e,InstrumentType.OBSERVABLE_GAUGE,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableGaugeInstrument(r,n,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType.OBSERVABLE_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableCounterInstrument(r,n,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){const r=createInstrumentDescriptor(e,InstrumentType.OBSERVABLE_UP_DOWN_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new ObservableUpDownCounterInstrument(r,n,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}class MetricStorage{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=createInstrumentDescriptor(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class HashMap{_hash;_valueMap=new Map;_keyMap=new Map;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){const r=this._hash(e);if(this._valueMap.has(r))return this._valueMap.get(r);const n=t();return this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,n),n}set(e,t,r){r??=this._hash(e),this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){const e=this._keyMap.entries();let t=e.next();for(;!0!==t.done;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){const e=this._valueMap.entries();let t=e.next();for(;!0!==t.done;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}}class AttributeHashMap extends HashMap{constructor(){super(hashAttributes)}}class DeltaMetricProcessor{_aggregator;_activeCollectionStorage=new AttributeHashMap;_cumulativeMemoStorage=new AttributeHashMap;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=hashAttributes(this._overflowAttributes)}record(e,t,r,n){let i=this._activeCollectionStorage.get(t);if(!i){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const t=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(n));return void t?.record(e)}i=this._aggregator.createAccumulation(n),this._activeCollectionStorage.set(t,i)}i?.record(e)}batchCumulate(e,t){Array.from(e.entries()).forEach(([e,r,n])=>{const i=this._aggregator.createAccumulation(t);i?.record(r);let o=i;if(this._cumulativeMemoStorage.has(e,n)){const t=this._cumulativeMemoStorage.get(e,n);o=this._aggregator.diff(t,i)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,n=this._overflowHashCode,this._cumulativeMemoStorage.has(e,n))){const t=this._cumulativeMemoStorage.get(e,n);o=this._aggregator.diff(t,i)}if(this._activeCollectionStorage.has(e,n)){const t=this._activeCollectionStorage.get(e,n);o=this._aggregator.merge(t,o)}this._cumulativeMemoStorage.set(e,i,n),this._activeCollectionStorage.set(e,o,n)})}collect(){const e=this._activeCollectionStorage;return this._activeCollectionStorage=new AttributeHashMap,e}}class TemporalMetricProcessor{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(e,t,r,n){this._stashAccumulations(r);const i=this._getMergedUnreportedAccumulations(e);let o,s=i;if(this._reportHistory.has(e)){const t=this._reportHistory.get(e),r=t.collectionTime;o=t.aggregationTemporality,s=o===AggregationTemporality.CUMULATIVE?TemporalMetricProcessor.merge(t.accumulations,i,this._aggregator):TemporalMetricProcessor.calibrateStartTime(t.accumulations,i,r)}else o=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:s,collectionTime:n,aggregationTemporality:o});const a=AttributesMapToAccumulationRecords(s);if(0!==a.length)return this._aggregator.toMetricData(t,o,a,n)}_stashAccumulations(e){const t=this._unreportedAccumulations.keys();for(const r of t){let t=this._unreportedAccumulations.get(r);void 0===t&&(t=[],this._unreportedAccumulations.set(r,t)),t.push(e)}}_getMergedUnreportedAccumulations(e){let t=new AttributeHashMap;const r=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),void 0===r)return t;for(const e of r)t=TemporalMetricProcessor.merge(t,e,this._aggregator);return t}static merge(e,t,r){const n=e,i=t.entries();let o=i.next();for(;!0!==o.done;){const[t,s,a]=o.value;if(e.has(t,a)){const i=e.get(t,a),o=r.merge(i,s);n.set(t,o,a)}else n.set(t,s,a);o=i.next()}return n}static calibrateStartTime(e,t,r){for(const[n,i]of e.keys()){const e=t.get(n,i);e?.setStartTime(r)}return t}}function AttributesMapToAccumulationRecords(e){return Array.from(e.entries())}class AsyncMetricStorage extends MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,r,n,i){super(e),this._attributesProcessor=r,this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new TemporalMetricProcessor(t,n)}record(e,t){const r=new AttributeHashMap;Array.from(e.entries()).forEach(([e,t])=>{r.set(this._attributesProcessor.process(e),t)}),this._deltaMetricStorage.batchCumulate(r,t)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}function getIncompatibilityDetails(e,t){let r="";return e.unit!==t.unit&&(r+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(r+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(r+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(r+=`\t- Description '${e.description}' does not match '${t.description}'\n`),r}function getValueTypeConflictResolutionRecipe(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}function getUnitConflictResolutionRecipe(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}function getTypeConflictResolutionRecipe(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'`}function getDescriptionResolutionRecipe(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'\n \t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${n}\n \t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${n}`}function getConflictResolutionRecipe(e,t){return e.valueType!==t.valueType?getValueTypeConflictResolutionRecipe(e,t):e.unit!==t.unit?getUnitConflictResolutionRecipe(e,t):e.type!==t.type?getTypeConflictResolutionRecipe(e,t):e.description!==t.description?getDescriptionResolutionRecipe(e,t):""}class MetricStorageRegistry{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new MetricStorageRegistry}getStorages(e){let t=[];for(const e of this._sharedRegistry.values())t=t.concat(e);const r=this._perCollectorRegistry.get(e);if(null!=r)for(const e of r.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let r=this._perCollectorRegistry.get(e);null==r&&(r=new Map,this._perCollectorRegistry.set(e,r)),this._registerStorage(t,r)}findOrUpdateCompatibleStorage(e){const t=this._sharedRegistry.get(e.name);return void 0===t?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){const r=this._perCollectorRegistry.get(e);if(void 0===r)return null;const n=r.get(t.name);return void 0===n?null:this._findOrUpdateCompatibleStorage(t,n)}_registerStorage(e,t){const r=e.getInstrumentDescriptor(),n=t.get(r.name);void 0!==n?n.push(e):t.set(r.name,[e])}_findOrUpdateCompatibleStorage(e,t){let r=null;for(const n of t){const t=n.getInstrumentDescriptor();isDescriptorCompatibleWith(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&n.updateDescription(e.description),diag.warn("A view or instrument with the name ",e.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",getIncompatibilityDetails(t,e),"The longer description will be used.\nTo resolve the conflict:",getConflictResolutionRecipe(t,e))),r=n):diag.warn("A view or instrument with the name ",e.name," has already been registered and is incompatible with another registered view.\n","Details:\n",getIncompatibilityDetails(t,e),"To resolve the conflict:\n",getConflictResolutionRecipe(t,e))}return r}}class MultiMetricStorage{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,r,n){this._backingStorages.forEach(i=>{i.record(e,t,r,n)})}}class ObservableResultImpl{_instrumentName;_valueType;_buffer=new AttributeHashMap;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){"number"==typeof e?(this._valueType!==ValueType.INT||Number.isInteger(e)||(diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._buffer.set(t,e):diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`)}}class BatchObservableResultImpl{_buffer=new Map;observe(e,t,r={}){if(!isObservableInstrument(e))return;let n=this._buffer.get(e);null==n&&(n=new AttributeHashMap,this._buffer.set(e,n)),"number"==typeof t?(e._descriptor.valueType!==ValueType.INT||Number.isInteger(t)||(diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),Number.isInteger(t)))&&n.set(r,t):diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`)}}class ObservableRegistry{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){const r=this._findCallback(e,t);r<0||this._callbacks.splice(r,1)}addBatchCallback(e,t){const r=new Set(t.filter(isObservableInstrument));if(0===r.size)return void diag.error("BatchObservableCallback is not associated with valid instruments",t);this._findBatchCallback(e,r)>=0||this._batchCallbacks.push({callback:e,instruments:r})}removeBatchCallback(e,t){const r=new Set(t.filter(isObservableInstrument)),n=this._findBatchCallback(e,r);n<0||this._batchCallbacks.splice(n,1)}async observe(e,t){const r=this._observeCallbacks(e,t),n=this._observeBatchCallbacks(e,t),i=(await PromiseAllSettled([...r,...n])).filter(isPromiseAllSettledRejectionResult).map(e=>e.reason);return i}_observeCallbacks(e,t){return this._callbacks.map(async({callback:r,instrument:n})=>{const i=new ObservableResultImpl(n._descriptor.name,n._descriptor.valueType);let o=Promise.resolve(r(i));null!=t&&(o=callWithTimeout(o,t)),await o,n._metricStorages.forEach(t=>{t.record(i._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:r,instruments:n})=>{const i=new BatchObservableResultImpl;let o=Promise.resolve(r(i));null!=t&&(o=callWithTimeout(o,t)),await o,n.forEach(t=>{const r=i._buffer.get(t);null!=r&&t._metricStorages.forEach(t=>{t.record(r,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(r=>r.callback===e&&r.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(r=>r.callback===e&&setEquals(r.instruments,t))}}class SyncMetricStorage extends MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,r,n,i){super(e),this._attributesProcessor=r,this._aggregationCardinalityLimit=i,this._deltaMetricStorage=new DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new TemporalMetricProcessor(t,n)}record(e,t,r,n){t=this._attributesProcessor.process(t,r),this._deltaMetricStorage.record(e,t,r,n)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}class NoopAttributesProcessor{process(e,t){return e}}class MultiAttributesProcessor{_processors;constructor(e){this._processors=e}process(e,t){let r=e;for(const e of this._processors)r=e.process(r,t);return r}}class AllowListProcessor{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){const r={};return Object.keys(e).filter(e=>this._allowedAttributeNames.includes(e)).forEach(t=>r[t]=e[t]),r}}class DenyListProcessor{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){const r={};return Object.keys(e).filter(e=>!this._deniedAttributeNames.includes(e)).forEach(t=>r[t]=e[t]),r}}function createNoopAttributesProcessor(){return NOOP}function createMultiAttributesProcessor(e){return new MultiAttributesProcessor(e)}function createAllowListAttributesProcessor(e){return new AllowListProcessor(e)}function createDenyListAttributesProcessor(e){return new DenyListProcessor(e)}const NOOP=new NoopAttributesProcessor;class MeterSharedState{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new MetricStorageRegistry;observableRegistry=new ObservableRegistry;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new Meter(this)}registerMetricStorage(e){const t=this._registerMetricStorage(e,SyncMetricStorage);return 1===t.length?t[0]:new MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,AsyncMetricStorage)}async collect(e,t,r){const n=await this.observableRegistry.observe(t,r?.timeoutMillis),i=this.metricStorageRegistry.getStorages(e);if(0===i.length)return null;const o=i.map(r=>r.collect(e,t)).filter(isNotNullish);return 0===o.length?{errors:n}:{scopeMetrics:{scope:this._instrumentationScope,metrics:o},errors:n}}_registerMetricStorage(e,t){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{const n=createInstrumentDescriptorWithView(r,e),i=this.metricStorageRegistry.findOrUpdateCompatibleStorage(n);if(null!=i)return i;const o=r.aggregation.createAggregator(n),s=new t(n,o,r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(s),s});if(0===r.length){const n=this._meterProviderSharedState.selectAggregations(e.type).map(([r,n])=>{const i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(r,e);if(null!=i)return i;const o=n.createAggregator(e),s=r.selectCardinalityLimit(e.type),a=new t(e,o,createNoopAttributesProcessor(),[r],s);return this.metricStorageRegistry.registerForCollector(r,a),a});r=r.concat(n)}return r}}class MeterProviderSharedState{resource;viewRegistry=new ViewRegistry;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){const t=instrumentationScopeId(e);let r=this.meterSharedStates.get(t);return null==r&&(r=new MeterSharedState(this,e),this.meterSharedStates.set(t,r)),r}selectAggregations(e){const t=[];for(const r of this.metricCollectors)t.push([r,toAggregation(r.selectAggregation(e))]);return t}}class MetricCollector{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){const t=millisToHrTime$4(Date.now()),r=[],n=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{const o=await i.collect(this,t,e);null!=o?.scopeMetrics&&r.push(o.scopeMetrics),null!=o?.errors&&n.push(...o.errors)});return await Promise.all(i),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:n}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}const ESCAPE=/[\^$\\.+?()[\]{}|]/g;class PatternPredicate{_matchAll;_regexp;constructor(e){"*"===e?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(PatternPredicate.escapePattern(e)))}match(e){return!!this._matchAll||this._regexp.test(e)}static escapePattern(e){return`^${e.replace(ESCAPE,"\\$&").replace("*",".*")}$`}static hasWildcard(e){return e.includes("*")}}class ExactPredicate{_matchAll;_pattern;constructor(e){this._matchAll=void 0===e,this._pattern=e}match(e){return!!this._matchAll||e===this._pattern}}class InstrumentSelector{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new PatternPredicate(e?.name??"*"),this._type=e?.type,this._unitFilter=new ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class MeterSelector{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new ExactPredicate(e?.name),this._versionFilter=new ExactPredicate(e?.version),this._schemaUrlFilter=new ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}function isSelectorNotProvided(e){return null==e.instrumentName&&null==e.instrumentType&&null==e.instrumentUnit&&null==e.meterName&&null==e.meterVersion&&null==e.meterSchemaUrl}function validateViewOptions(e){if(isSelectorNotProvided(e))throw new Error("Cannot create view with no selector arguments supplied");if(null!=e.name&&(null==e?.instrumentName||PatternPredicate.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}class View{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){validateViewOptions(e),null!=e.attributesProcessors?this.attributesProcessor=createMultiAttributesProcessor(e.attributesProcessors):this.attributesProcessor=createNoopAttributesProcessor(),this.name=e.name,this.description=e.description,this.aggregation=toAggregation(e.aggregation??{type:AggregationType.DEFAULT}),this.instrumentSelector=new InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}class MeterProvider{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new MeterProviderSharedState(e?.resource??defaultResource$1()),null!=e?.views&&e.views.length>0)for(const t of e.views)this._sharedState.viewRegistry.addView(new View(t));if(null!=e?.readers&&e.readers.length>0)for(const t of e.readers){const e=new MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,t="",r={}){return this._shutdown?(diag.warn("A shutdown MeterProvider cannot provide a Meter"),createNoopMeter()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:r.schemaUrl}).meter}async shutdown(e){this._shutdown?diag.warn("shutdown may only be called once per MeterProvider"):(this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e))))}async forceFlush(e){this._shutdown?diag.warn("invalid attempt to force flush after MeterProvider shutdown"):await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}var esm$9=Object.freeze({__proto__:null,get AggregationTemporality(){return AggregationTemporality},get AggregationType(){return AggregationType},ConsoleMetricExporter:ConsoleMetricExporter,get DataPointType(){return DataPointType},InMemoryMetricExporter:InMemoryMetricExporter,get InstrumentType(){return InstrumentType},MeterProvider:MeterProvider,MetricReader:MetricReader,PeriodicExportingMetricReader:PeriodicExportingMetricReader,TimeoutError:TimeoutError,createAllowListAttributesProcessor:createAllowListAttributesProcessor,createDenyListAttributesProcessor:createDenyListAttributesProcessor}),require$$4=getAugmentedNamespace(esm$9),meterFactory={};Object.defineProperty(meterFactory,"__esModule",{value:!0}),meterFactory.MetricsMeterFactoryValidator=void 0;class MetricsMeterFactoryValidator{}meterFactory.MetricsMeterFactoryValidator=MetricsMeterFactoryValidator,Object.defineProperty(providerFactory,"__esModule",{value:!0}),providerFactory.MetricsMeterProviderFactory=void 0;const resources_1$1=require$$2,exporter_metrics_otlp_http_1=require$$5,sdk_metrics_1=require$$4,meterFactory_1=meterFactory,container_1$4=container$1;class MetricsMeterProviderFactory{create(e,t){let r;new meterFactory_1.MetricsMeterFactoryValidator,r=e.metricExporter?e.metricExporter:new exporter_metrics_otlp_http_1.OTLPMetricExporter(Object.assign(Object.assign({},e),{headers:Object.assign(Object.assign({},container_1$4.Container.errorless(t.headers)),container_1$4.Container.errorless(e.headers))}));const n=new sdk_metrics_1.PeriodicExportingMetricReader({exporter:r,exportIntervalMillis:e.publishInterval});return{meterProvider:this.createMeterProvider(e,t,n),metricReader:n}}createMeterProvider(e,t,r){var n;return new sdk_metrics_1.MeterProvider({resource:(0,resources_1$1.resourceFromAttributes)(null!==(n=container_1$4.Container.errorless(e.additionalResourceAttributes))&&void 0!==n?n:{}),readers:[r]})}}providerFactory.MetricsMeterProviderFactory=MetricsMeterProviderFactory;var lazyProvider={};Object.defineProperty(lazyProvider,"__esModule",{value:!0}),lazyProvider.LazyMetricsMeterProvider=void 0;class LazyMetricsMeterProvider{get metricReader(){return this._metricReader||this.buildMeterProvider(),this._metricReader}constructor(e,t){this.meterProviderCreateFunc=e,this.serviceName=t}getMeter(){return this.getMeterProvider().getMeter(this.serviceName)}forceFlush(){return this.getMeterProvider().forceFlush()}getMeterProvider(){return this.meterProvider||this.buildMeterProvider(),this.meterProvider}buildMeterProvider(){const e=this.meterProviderCreateFunc();this.meterProvider=e.meterProvider,this._metricReader=e.metricReader}}lazyProvider.LazyMetricsMeterProvider=LazyMetricsMeterProvider;var nullMetricsManager={},nullManager$1={};Object.defineProperty(nullManager$1,"__esModule",{value:!0}),nullManager$1.NullManager=void 0;class NullManager{constructor(){this.started=!1}waitForFinalExport(e){return Promise.resolve()}get settings(){return{}}start(){return this.started=!0,Promise.resolve()}stop(){return this.started=!1,Promise.resolve()}}nullManager$1.NullManager=NullManager,Object.defineProperty(nullMetricsManager,"__esModule",{value:!0}),nullMetricsManager.NullMetricsManager=void 0;const nullManager_1$3=nullManager$1,null_1$1=_null$4,safe_stringify_1$4=safeStringify$1;class NullMetricsManager extends nullManager_1$3.NullManager{constructor(e,t,r){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==r||r.info(`Starting NullMetrcsManager with settings ${(0,safe_stringify_1$4.safeStringify)(e)}`)),super()}waitForFinalExport(e){return Promise.resolve()}getFromSettings(e){return new null_1$1.NullMetric(e)}get(e){return new null_1$1.NullMetric({name:e,type:e,enabled:!1,description:e})}}nullMetricsManager.NullMetricsManager=NullMetricsManager,Object.defineProperty(builder$6,"__esModule",{value:!0}),builder$6.MetricsManagerBuilder=void 0;const builder_1$1=builder$5,manager_1$3=manager$4,builder_2$1=builder$4,builder_3$1=builder$3,providerFactory_1=providerFactory,lazyProvider_1=lazyProvider,nullMetricsManager_1$1=nullMetricsManager;class MetricsManagerBuilder{withLogger(e){return this.logger=e,this}withSettings(e){return this.settings=e,this}withMeterProvider(e){return this.meterProviderCreateFunc=e,this}withDependencyContainer(e){return this.dependencyContainer=e,this}build(){return(new builder_3$1.MetricsBuilderValidator).validate(this),this.buildCore()}buildCore(){var e,t,r,n;const i=this.createMetricsSettings();if(!0!==(null===(e=this.settings)||void 0===e?void 0:e.enabled)||!0!==(null==i?void 0:i.enabled))return new nullMetricsManager_1$1.NullMetricsManager(i,this.settings,this.logger);this.dependencyContainer=null!==(r=null===(t=this.settings.metrics)||void 0===t?void 0:t.dependencyContainerOverride)&&void 0!==r?r:this.dependencyContainer;const o=null!==(n=this.meterProviderCreateFunc)&&void 0!==n?n:this.createMeterProviderCreateFunc(i,this.settings),s=new lazyProvider_1.LazyMetricsMeterProvider(o,this.settings.serviceName||"io.Insights"),a=this.createMetricsFactory(s);return new manager_1$3.MetricsManager(this.settings,i,a,s,this.logger)}createMetricsSettings(){return(new builder_2$1.MetricsSettingsBuilder).withSettings(this.settings).build()}createMetricsFactory(e){return new builder_1$1.MetricsFactoryBuilder(e,this.dependencyContainer,this.logger).withDefaults().build()}createMeterProviderCreateFunc(e,t){return()=>(new providerFactory_1.MetricsMeterProviderFactory).create(e,t)}}builder$6.MetricsManagerBuilder=MetricsManagerBuilder;var builder$2={},manager$2={},utils$7={};class OTLPTraceExporter extends OTLPExporterBase{constructor(e={}){super(createLegacyOtlpBrowserExportDelegate(e,JsonTraceSerializer,"v1/traces",{"Content-Type":"application/json"}))}}var esm$8=Object.freeze({__proto__:null,OTLPTraceExporter:OTLPTraceExporter}),require$$15=getAugmentedNamespace(esm$8);const SUPPRESS_TRACING_KEY=createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function suppressTracing(e){return e.setValue(SUPPRESS_TRACING_KEY,!0)}function isTracingSuppressed(e){return!0===e.getValue(SUPPRESS_TRACING_KEY)}function sanitizeAttributes(e){const t={};if("object"!=typeof e||null==e)return t;for(const[r,n]of Object.entries(e))isAttributeKey(r)?isAttributeValue(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:diag.warn(`Invalid attribute value set for key: ${r}`):diag.warn(`Invalid attribute key: ${r}`);return t}function isAttributeKey(e){return"string"==typeof e&&e.length>0}function isAttributeValue(e){return null==e||(Array.isArray(e)?isHomogeneousAttributeValueArray(e):isValidPrimitiveAttributeValue(e))}function isHomogeneousAttributeValueArray(e){let t;for(const r of e)if(null!=r){if(!t){if(isValidPrimitiveAttributeValue(r)){t=typeof r;continue}return!1}if(typeof r!==t)return!1}return!0}function isValidPrimitiveAttributeValue(e){switch(typeof e){case"number":case"boolean":case"string":return!0}return!1}function loggingErrorHandler(){return e=>{diag.error(stringifyException(e))}}function stringifyException(e){return"string"==typeof e?e:JSON.stringify(flattenException(e))}function flattenException(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}let delegateHandler=loggingErrorHandler();function globalErrorHandler(e){try{delegateHandler(e)}catch{}}function getNumberFromEnv(e){}const otperformance$3=performance;function unrefTimer(e){}const NANOSECOND_DIGITS$3=9,NANOSECOND_DIGITS_IN_MILLIS$3=6,MILLISECONDS_TO_NANOSECONDS$3=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$3),SECOND_TO_NANOSECONDS$3=Math.pow(10,NANOSECOND_DIGITS$3);function millisToHrTime$3(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$3)]}function getTimeOrigin$3(){let e=otperformance$3.timeOrigin;if("number"!=typeof e){const t=otperformance$3;e=t.timing&&t.timing.fetchStart}return e}function hrTime$3(e){return addHrTimes$3(millisToHrTime$3(getTimeOrigin$3()),millisToHrTime$3("number"==typeof e?e:otperformance$3.now()))}function hrTimeDuration(e,t){let r=t[0]-e[0],n=t[1]-e[1];return n<0&&(r-=1,n+=SECOND_TO_NANOSECONDS$3),[r,n]}function hrTimeToMicroseconds(e){return 1e6*e[0]+e[1]/1e3}function isTimeInputHrTime$1(e){return Array.isArray(e)&&2===e.length&&"number"==typeof e[0]&&"number"==typeof e[1]}function isTimeInput(e){return isTimeInputHrTime$1(e)||"number"==typeof e||e instanceof Date}function addHrTimes$3(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS$3&&(r[1]-=SECOND_TO_NANOSECONDS$3,r[0]+=1),r}var ExportResultCode;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ExportResultCode||(ExportResultCode={}));const objectTag="[object Object]",nullTag="[object Null]",undefinedTag="[object Undefined]",funcProto=Function.prototype,funcToString=funcProto.toString,objectCtorString$1=funcToString.call(Object),getPrototypeOf$2=Object.getPrototypeOf,objectProto=Object.prototype,hasOwnProperty$2=objectProto.hasOwnProperty,symToStringTag=Symbol?Symbol.toStringTag:void 0,nativeObjectToString=objectProto.toString;function isPlainObject$3(e){if(!isObjectLike(e)||baseGetTag(e)!==objectTag)return!1;const t=getPrototypeOf$2(e);if(null===t)return!0;const r=hasOwnProperty$2.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&funcToString.call(r)===objectCtorString$1}function isObjectLike(e){return null!=e&&"object"==typeof e}function baseGetTag(e){return null==e?void 0===e?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(e)?getRawTag(e):objectToString$1(e)}function getRawTag(e){const t=hasOwnProperty$2.call(e,symToStringTag),r=e[symToStringTag];let n=!1;try{e[symToStringTag]=void 0,n=!0}catch(e){}const i=nativeObjectToString.call(e);return n&&(t?e[symToStringTag]=r:delete e[symToStringTag]),i}function objectToString$1(e){return nativeObjectToString.call(e)}const MAX_LEVEL=20;function merge$2(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=mergeTwoObjects(t,e.shift(),0,r);return t}function takeValue(e){return isArray$6(e)?e.slice():e}function mergeTwoObjects(e,t,r=0,n){let i;if(!(r>MAX_LEVEL)){if(r++,isPrimitive(e)||isPrimitive(t)||isFunction$4(t))i=takeValue(t);else if(isArray$6(e)){if(i=e.slice(),isArray$6(t))for(let e=0,r=t.length;e{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}class BindOnceFuture{_callback;_that;_isCalled=!1;_deferred=new Deferred;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}function _export(e,t){return new Promise(r=>{context.with(suppressTracing(context.active()),()=>{e.export(t,e=>{r(e)})})})}const internal={_export:_export},ExceptionEventName="exception";class SpanImpl{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;name;status={code:SpanStatusCode.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){const t=Date.now();this._spanContext=e.spanContext,this._performanceStartTime=otperformance$3.now(),this._performanceOffset=t-(this._performanceStartTime+getTimeOrigin$3()),this._startTimeProvided=null!=e.startTime,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit||0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,this.links=e.links||[],this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,null!=e.attributes&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,t){if(null==t||this._isSpanEnded())return this;if(0===e.length)return diag.warn(`Invalid attribute key: ${e}`),this;if(!isAttributeValue(t))return diag.warn(`Invalid attribute value set for key: ${e}`),this;const{attributeCountLimit:r}=this._spanLimits;return void 0!==r&&Object.keys(this.attributes).length>=r&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(t),this)}setAttributes(e){for(const[t,r]of Object.entries(e))this.setAttribute(t,r);return this}addEvent(e,t,r){if(this._isSpanEnded())return this;const{eventCountLimit:n}=this._spanLimits;if(0===n)return diag.warn("No events allowed."),this._droppedEventsCount++,this;void 0!==n&&this.events.length>=n&&(0===this._droppedEventsCount&&diag.debug("Dropping extra events."),this.events.shift(),this._droppedEventsCount++),isTimeInput(t)&&(isTimeInput(r)||(r=t),t=void 0);const i=sanitizeAttributes(t);return this.events.push({name:e,attributes:i,time:this._getTime(r),droppedAttributesCount:0}),this}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}setStatus(e){return this._isSpanEnded()||(this.status={...e},null!=this.status.message&&"string"!=typeof e.message&&(diag.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`),delete this.status.message)),this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){this._isSpanEnded()?diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`):(this._ended=!0,this.endTime=this._getTime(e),this._duration=hrTimeDuration(this.startTime,this.endTime),this._duration[0]<0&&(diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._spanProcessor.onEnd(this))}_getTime(e){if("number"==typeof e&&e<=otperformance$3.now())return hrTime$3(e+this._performanceOffset);if("number"==typeof e)return millisToHrTime$3(e);if(e instanceof Date)return millisToHrTime$3(e.getTime());if(isTimeInputHrTime$1(e))return e;if(this._startTimeProvided)return millisToHrTime$3(Date.now());const t=otperformance$3.now()-this._performanceStartTime;return addHrTimes$3(this.startTime,millisToHrTime$3(t))}isRecording(){return!1===this._ended}recordException(e,t){const r={};"string"==typeof e?r[ATTR_EXCEPTION_MESSAGE]=e:e&&(e.code?r[ATTR_EXCEPTION_TYPE]=e.code.toString():e.name&&(r[ATTR_EXCEPTION_TYPE]=e.name),e.message&&(r[ATTR_EXCEPTION_MESSAGE]=e.message),e.stack&&(r[ATTR_EXCEPTION_STACKTRACE]=e.stack)),r[ATTR_EXCEPTION_TYPE]||r[ATTR_EXCEPTION_MESSAGE]?this.addEvent(ExceptionEventName,r,t):diag.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){const e=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){const t=this._attributeValueLengthLimit;return t<=0?(diag.warn(`Attribute value limit must be positive, got ${t}`),e):"string"==typeof e?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>"string"==typeof e?this._truncateToLimitUtil(e,t):e):e}}var SamplingDecision;!function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(SamplingDecision||(SamplingDecision={}));class AlwaysOffSampler{shouldSample(){return{decision:SamplingDecision.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class AlwaysOnSampler{shouldSample(){return{decision:SamplingDecision.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class ParentBasedSampler{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||(globalErrorHandler(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new AlwaysOnSampler),this._remoteParentSampled=e.remoteParentSampled??new AlwaysOnSampler,this._remoteParentNotSampled=e.remoteParentNotSampled??new AlwaysOffSampler,this._localParentSampled=e.localParentSampled??new AlwaysOnSampler,this._localParentNotSampled=e.localParentNotSampled??new AlwaysOffSampler}shouldSample(e,t,r,n,i,o){const s=trace.getSpanContext(e);return s&&isSpanContextValid(s)?s.isRemote?s.traceFlags&TraceFlags.SAMPLED?this._remoteParentSampled.shouldSample(e,t,r,n,i,o):this._remoteParentNotSampled.shouldSample(e,t,r,n,i,o):s.traceFlags&TraceFlags.SAMPLED?this._localParentSampled.shouldSample(e,t,r,n,i,o):this._localParentNotSampled.shouldSample(e,t,r,n,i,o):this._root.shouldSample(e,t,r,n,i,o)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}class TraceIdRatioBasedSampler{_ratio;_upperBound;constructor(e=0){this._ratio=e,this._ratio=this._normalize(e),this._upperBound=Math.floor(4294967295*this._ratio)}shouldSample(e,t){return{decision:isValidTraceId(t)&&this._accumulate(t)=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let r=0;r>>0}return t}}const DEFAULT_RATIO=1;function loadDefaultConfig$1(){return{sampler:buildSamplerFromEnv(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function buildSamplerFromEnv(){const e="parentbased_always_on";switch(e){case"always_on":return new AlwaysOnSampler;case"always_off":return new AlwaysOffSampler;case"parentbased_always_on":return new ParentBasedSampler({root:new AlwaysOnSampler});case"parentbased_always_off":return new ParentBasedSampler({root:new AlwaysOffSampler});case"traceidratio":return new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv());case"parentbased_traceidratio":return new ParentBasedSampler({root:new TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv())});default:return diag.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "parentbased_always_on".`),new ParentBasedSampler({root:new AlwaysOnSampler})}}function getSamplerProbabilityFromEnv(){return diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`),DEFAULT_RATIO}const DEFAULT_ATTRIBUTE_COUNT_LIMIT=128,DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT=1/0;function mergeConfig$2(e){const t={sampler:buildSamplerFromEnv()},r=loadDefaultConfig$1(),n=Object.assign({},r,t,e);return n.generalLimits=Object.assign({},r.generalLimits,e.generalLimits||{}),n.spanLimits=Object.assign({},r.spanLimits,e.spanLimits||{}),n}function reconfigureLimits$1(e){const t=Object.assign({},e.spanLimits);return t.attributeCountLimit=e.spanLimits?.attributeCountLimit??e.generalLimits?.attributeCountLimit??getNumberFromEnv()??getNumberFromEnv()??DEFAULT_ATTRIBUTE_COUNT_LIMIT,t.attributeValueLengthLimit=e.spanLimits?.attributeValueLengthLimit??e.generalLimits?.attributeValueLengthLimit??getNumberFromEnv()??getNumberFromEnv()??DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,Object.assign({},e,{spanLimits:t})}class BatchSpanProcessorBase{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,t){this._exporter=e,this._maxExportBatchSize="number"==typeof t?.maxExportBatchSize?t.maxExportBatchSize:512,this._maxQueueSize="number"==typeof t?.maxQueueSize?t.maxQueueSize:2048,this._scheduledDelayMillis="number"==typeof t?.scheduledDelayMillis?t.scheduledDelayMillis:5e3,this._exportTimeoutMillis="number"==typeof t?.exportTimeoutMillis?t.exportTimeoutMillis:3e4,this._shutdownOnce=new BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||0!==(e.spanContext().traceFlags&TraceFlags.SAMPLED)&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize)return 0===this._droppedSpansCount&&diag.debug("maxQueueSize reached, dropping spans"),void this._droppedSpansCount++;this._droppedSpansCount>0&&(diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{const r=[];for(let e=0,t=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);e{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),0===this._finishedSpans.length?Promise.resolve():new Promise((e,t)=>{const r=setTimeout(()=>{t(new Error("Timeout"))},this._exportTimeoutMillis);context.with(suppressTracing(context.active()),()=>{let n;this._finishedSpans.length<=this._maxExportBatchSize?(n=this._finishedSpans,this._finishedSpans=[]):n=this._finishedSpans.splice(0,this._maxExportBatchSize);const i=()=>this._exporter.export(n,n=>{clearTimeout(r),n.code===ExportResultCode.SUCCESS?e():t(n.error??new Error("BatchSpanProcessor: span export failed"))});let o=null;for(let e=0,t=n.length;e{globalErrorHandler(e),t(e)})})})}_maybeStartTimer(){if(this._isExporting)return;const e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,globalErrorHandler(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();void 0===this._timer&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),unrefTimer(this._timer))}_clearTimer(){void 0!==this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}class BatchSpanProcessor extends BatchSpanProcessorBase{_visibilityChangeListener;_pageHideListener;constructor(e,t){super(e,t),this.onInit(t)}onInit(e){!0!==e?.disableAutoFlushOnDocumentHide&&"undefined"!=typeof document&&(this._visibilityChangeListener=()=>{"hidden"===document.visibilityState&&this.forceFlush().catch(e=>{globalErrorHandler(e)})},this._pageHideListener=()=>{this.forceFlush().catch(e=>{globalErrorHandler(e)})},document.addEventListener("visibilitychange",this._visibilityChangeListener),document.addEventListener("pagehide",this._pageHideListener))}onShutdown(){"undefined"!=typeof document&&(this._visibilityChangeListener&&document.removeEventListener("visibilitychange",this._visibilityChangeListener),this._pageHideListener&&document.removeEventListener("pagehide",this._pageHideListener))}}const SPAN_ID_BYTES=8,TRACE_ID_BYTES=16;class RandomIdGenerator{generateTraceId=getIdGenerator(TRACE_ID_BYTES);generateSpanId=getIdGenerator(SPAN_ID_BYTES)}const SHARED_CHAR_CODES_ARRAY=Array(32);function getIdGenerator(e){return function(){for(let t=0;t<2*e;t++)SHARED_CHAR_CODES_ARRAY[t]=Math.floor(16*Math.random())+48,SHARED_CHAR_CODES_ARRAY[t]>=58&&(SHARED_CHAR_CODES_ARRAY[t]+=39);return String.fromCharCode.apply(null,SHARED_CHAR_CODES_ARRAY.slice(0,2*e))}}class Tracer{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;constructor(e,t,r,n){const i=mergeConfig$2(t);this._sampler=i.sampler,this._generalLimits=i.generalLimits,this._spanLimits=i.spanLimits,this._idGenerator=t.idGenerator||new RandomIdGenerator,this._resource=r,this._spanProcessor=n,this.instrumentationScope=e}startSpan(e,t={},r=context.active()){t.root&&(r=trace.deleteSpan(r));const n=trace.getSpan(r);if(isTracingSuppressed(r)){diag.debug("Instrumentation suppressed, returning Noop Span");return trace.wrapSpanContext(INVALID_SPAN_CONTEXT)}const i=n?.spanContext(),o=this._idGenerator.generateSpanId();let s,a,c;i&&trace.isSpanContextValid(i)?(a=i.traceId,c=i.traceState,s=i):a=this._idGenerator.generateTraceId();const l=t.kind??SpanKind.INTERNAL,u=(t.links??[]).map(e=>({context:e.context,attributes:sanitizeAttributes(e.attributes)})),d=sanitizeAttributes(t.attributes),h=this._sampler.shouldSample(r,a,e,l,d,u);c=h.traceState??c;const p={traceId:a,spanId:o,traceFlags:h.decision===SamplingDecision$1.RECORD_AND_SAMPLED?TraceFlags.SAMPLED:TraceFlags.NONE,traceState:c};if(h.decision===SamplingDecision$1.NOT_RECORD){diag.debug("Recording is off, propagating context in a non-recording span");return trace.wrapSpanContext(p)}const g=sanitizeAttributes(Object.assign(d,h.attributes));return new SpanImpl({resource:this._resource,scope:this.instrumentationScope,context:r,spanContext:p,name:e,kind:l,links:u,parentSpanContext:s,attributes:g,startTime:t.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits})}startActiveSpan(e,t,r,n){let i,o,s;if(arguments.length<2)return;2===arguments.length?s=t:3===arguments.length?(i=t,s=r):(i=t,o=r,s=n);const a=o??context.active(),c=this.startSpan(e,i,a),l=trace.setSpan(a,c);return context.with(l,s,void 0,c)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class MultiSpanProcessor{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){const e=[];for(const t of this._spanProcessors)e.push(t.forceFlush());return new Promise(t=>{Promise.all(e).then(()=>{t()}).catch(e=>{globalErrorHandler(e||new Error("MultiSpanProcessor: forceFlush failed")),t()})})}onStart(e,t){for(const r of this._spanProcessors)r.onStart(e,t)}onEnd(e){for(const t of this._spanProcessors)t.onEnd(e)}shutdown(){const e=[];for(const t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,r)=>{Promise.all(e).then(()=>{t()},r)})}}var ForceFlushState;!function(e){e[e.resolved=0]="resolved",e[e.timeout=1]="timeout",e[e.error=2]="error",e[e.unresolved=3]="unresolved"}(ForceFlushState||(ForceFlushState={}));class BasicTracerProvider{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){const t=merge$2({},loadDefaultConfig$1(),reconfigureLimits$1(e));this._resource=t.resource??defaultResource$1(),this._config=Object.assign({},t,{resource:this._resource});const r=[];e.spanProcessors?.length&&r.push(...e.spanProcessors),this._activeSpanProcessor=new MultiSpanProcessor(r)}getTracer(e,t,r){const n=`${e}@${t||""}:${r?.schemaUrl||""}`;return this._tracers.has(n)||this._tracers.set(n,new Tracer({name:e,version:t,schemaUrl:r?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(n)}forceFlush(){const e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(r=>{let n;const i=setTimeout(()=>{r(new Error(`Span processor did not completed within timeout period of ${e} ms`)),n=ForceFlushState.timeout},e);t.forceFlush().then(()=>{clearTimeout(i),n!==ForceFlushState.timeout&&(n=ForceFlushState.resolved,r(n))}).catch(e=>{clearTimeout(i),n=ForceFlushState.error,r(e)})}));return new Promise((e,r)=>{Promise.all(t).then(t=>{const n=t.filter(e=>e!==ForceFlushState.resolved);n.length>0?r(n):e()}).catch(e=>r([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}class ConsoleSpanExporter{export(e,t){return this._sendSpans(e,t)}shutdown(){return this._sendSpans([]),this.forceFlush()}forceFlush(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,traceId:e.spanContext().traceId,parentSpanContext:e.parentSpanContext,traceState:e.spanContext().traceState?.serialize(),name:e.name,id:e.spanContext().spanId,kind:e.kind,timestamp:hrTimeToMicroseconds(e.startTime),duration:hrTimeToMicroseconds(e.duration),attributes:e.attributes,status:e.status,events:e.events,links:e.links}}_sendSpans(e,t){for(const t of e)console.dir(this._exportInfo(t),{depth:3});if(t)return t({code:ExportResultCode.SUCCESS})}}class InMemorySpanExporter{_finishedSpans=[];_stopped=!1;export(e,t){if(this._stopped)return t({code:ExportResultCode.FAILED,error:new Error("Exporter has been stopped")});this._finishedSpans.push(...e),setTimeout(()=>t({code:ExportResultCode.SUCCESS}),0)}shutdown(){return this._stopped=!0,this._finishedSpans=[],this.forceFlush()}forceFlush(){return Promise.resolve()}reset(){this._finishedSpans=[]}getFinishedSpans(){return this._finishedSpans}}class SimpleSpanProcessor{_exporter;_shutdownOnce;_pendingExports;constructor(e){this._exporter=e,this._shutdownOnce=new BindOnceFuture(this._shutdown,this),this._pendingExports=new Set}async forceFlush(){await Promise.all(Array.from(this._pendingExports)),this._exporter.forceFlush&&await this._exporter.forceFlush()}onStart(e,t){}onEnd(e){if(this._shutdownOnce.isCalled)return;if(0===(e.spanContext().traceFlags&TraceFlags.SAMPLED))return;const t=this._doExport(e).catch(e=>globalErrorHandler(e));this._pendingExports.add(t),t.finally(()=>this._pendingExports.delete(t))}async _doExport(e){e.resource.asyncAttributesPending&&await(e.resource.waitForAsyncAttributes?.());const t=await internal._export(this._exporter,[e]);if(t.code!==ExportResultCode.SUCCESS)throw t.error??new Error(`SimpleSpanProcessor: span export failed (status ${t})`)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}class NoopSpanProcessor{onStart(e,t){}onEnd(e){}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}}var esm$7=Object.freeze({__proto__:null,AlwaysOffSampler:AlwaysOffSampler,AlwaysOnSampler:AlwaysOnSampler,BasicTracerProvider:BasicTracerProvider,BatchSpanProcessor:BatchSpanProcessor,ConsoleSpanExporter:ConsoleSpanExporter,InMemorySpanExporter:InMemorySpanExporter,NoopSpanProcessor:NoopSpanProcessor,ParentBasedSampler:ParentBasedSampler,RandomIdGenerator:RandomIdGenerator,get SamplingDecision(){return SamplingDecision},SimpleSpanProcessor:SimpleSpanProcessor,TraceIdRatioBasedSampler:TraceIdRatioBasedSampler}),require$$14$1=getAugmentedNamespace(esm$7),filter={};Object.defineProperty(filter,"__esModule",{value:!0}),filter.TracesFilterValidator=void 0;class TracesFilterValidator{validate(e){if(!(e.source||e.context&&Object.keys(e.context).length))throw new Error("At least one of source / context need to be specified.")}}filter.TracesFilterValidator=TracesFilterValidator;var attributeData={};Object.defineProperty(attributeData,"__esModule",{value:!0}),attributeData.TracesAttributeDataValidator=void 0;const validator_1$2=validator$1;class TracesAttributeDataValidator{validate(e){if(validator_1$2.Validator.throwIfNullOrUndefined(e,"data"),"object"!=typeof e)throw new Error("'data' must be an object")}}attributeData.TracesAttributeDataValidator=TracesAttributeDataValidator;var ioInsightsSampler={},hasRequiredIoInsightsSampler;function requireIoInsightsSampler(){if(hasRequiredIoInsightsSampler)return ioInsightsSampler;hasRequiredIoInsightsSampler=1,Object.defineProperty(ioInsightsSampler,"__esModule",{value:!0}),ioInsightsSampler.ioInsightsSampler=void 0;const e=require$$14$1,t=requireUtils();return ioInsightsSampler.ioInsightsSampler=class{constructor(e,t,r,n){this.settings=e,this.defaults=t,this.filteringContextGetter=r,this.logger=n}shouldSample(t,r,n,i,o,s){var a,c,l,u,d,h,p,g,m,f,y,$,b;const v=(null===(a=this.filteringContextGetter)||void 0===a?void 0:a.call(null))||{};for(const e of this.settings||[]){let t=!0;if(t&&e.name&&(this.matchObjects("name",{name:e.name},{name:n})||(t=!1)),t&&e.attributes&&(this.matchObjects("attributes",e.attributes,o)||(t=!1)),t&&e.context&&(this.matchObjects("context",e.context,v,!0)||(t=!1)),t)return(null===(d=this.logger)||void 0===d?void 0:d.level)&&(null===(h=this.logger)||void 0===h?void 0:h.level)>=80&&(null===(p=this.logger)||void 0===p||p.verbose("sampling rule matched: "+JSON.stringify(e))),this.maybeSample(r,e.sample);(null===(c=this.logger)||void 0===c?void 0:c.level)&&(null===(l=this.logger)||void 0===l?void 0:l.level)>=80&&(null===(u=this.logger)||void 0===u||u.verbose("sampling rule didn't match: "+JSON.stringify(e)))}return(null===(g=this.logger)||void 0===g?void 0:g.level)&&(null===(m=this.logger)||void 0===m?void 0:m.level)>=80&&(null===(f=this.logger)||void 0===f||f.verbose("no sampling rule matched, will fall back to defaults "+JSON.stringify(this.defaults||{}))),this.defaults?this.maybeSample(r,this.defaults.sample||!0):((null===(y=this.logger)||void 0===y?void 0:y.level)&&(null===($=this.logger)||void 0===$?void 0:$.level)>=80&&(null===(b=this.logger)||void 0===b||b.verbose("no sampling rule matched, no defaults - will sample")),{decision:e.SamplingDecision.RECORD_AND_SAMPLED})}toString(){try{return"ioInsightsSampler: "+JSON.stringify({settings:this.settings,defaults:this.defaults})}catch(e){return"ioInsightsSampler: (error) "+e.message}}matchObjects(e,r,n,i){var o,s,a,c,l,u;for(const[d,h]of Object.entries(r)){const r=i?(0,t.deep_value)(n,d):n[d];if("string"==typeof h&&"#"===h[0]&&(null==r||!new RegExp(h.substring(1),"i").test(r+"")))return(null===(o=this.logger)||void 0===o?void 0:o.level)&&(null===(s=this.logger)||void 0===s?void 0:s.level)>=80&&(null===(a=this.logger)||void 0===a||a.verbose(`matching ${e}: regex ${h} doesn't match ${r}`)),!1;if(h!==r)return(null===(c=this.logger)||void 0===c?void 0:c.level)&&(null===(l=this.logger)||void 0===l?void 0:l.level)>=80&&(null===(u=this.logger)||void 0===u||u.verbose(`matching ${e}: ${h} doesn't match ${r}`)),!1}return!0}maybeSample(t,r){var n,i,o;let s;if(!0===r||"number"==typeof r&&r>=1)s={decision:e.SamplingDecision.RECORD_AND_SAMPLED};else if(!1===r||"number"==typeof r&&r<=0)s={decision:e.SamplingDecision.NOT_RECORD};else{const n=((e,t=0)=>{let r=3735928559^t,n=1103547991^t;for(let t,i=0;i>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&n)+(r>>>0)})(t);s={decision:n/1e3-Math.floor(n/1e3)<=r?e.SamplingDecision.RECORD_AND_SAMPLED:e.SamplingDecision.NOT_RECORD}}return(null===(n=this.logger)||void 0===n?void 0:n.level)&&(null===(i=this.logger)||void 0===i?void 0:i.level)>=80&&(null===(o=this.logger)||void 0===o||o.verbose(`sampling decision with value ${r}: ${JSON.stringify(s)}`)),s}},ioInsightsSampler}var otelUtils={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getOTELData=e.flattenOtelAtributes=void 0;e.flattenOtelAtributes=(t,r)=>{if(null==t)return{};"object"!=typeof t&&(t={unknownAttribute:t});const n={};for(const[i,o]of Object.entries(t)){const t=(0,e.getOTELData)(i,o,0,r);for(const[e,r]of t)n[e]=r}return n};e.getOTELData=(e,n,i,o)=>{if((i+=1)>o)return[[e,""]];const s=Boolean(n&&"object"==typeof n);return"number"==typeof n||"string"==typeof n||"boolean"==typeof n?[[e,n]]:r(n)?[[e,n]].concat(t(e,n,i,o)):s?t(e,n,i,o):"function"==typeof n?[]:n?[[e,n+""]]:[]};const t=(t,r,n,i)=>{const o=[];for(const[s,a]of Object.entries(r))for(const[r,c]of(0,e.getOTELData)(s,a,n,i))o.push([t+"."+r,c]);return o},r=e=>!!Array.isArray(e)&&e.every(e=>null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)}(otelUtils);var require$$8=getAugmentedNamespace(esm$b),durationFilterProcessor={},hasRequiredUtils;Object.defineProperty(durationFilterProcessor,"__esModule",{value:!0}),durationFilterProcessor.DurationFilterProcessor=void 0;class DurationFilterProcessor{constructor(e){this._innerProcessor=e}onStart(e,t){this._innerProcessor.onStart(e,t)}onEnd(e){const t=e.attributes.insightsMinDurationMs&&parseInt(e.attributes.insightsMinDurationMs+"",10);if(t){1e9*e.endTime[0]+e.endTime[1]-(1e9*e.startTime[0]+e.startTime[1])>=1e6*t&&this._innerProcessor.onEnd(e)}else this._innerProcessor.onEnd(e)}shutdown(){return this._innerProcessor.shutdown()}forceFlush(){return this._innerProcessor.forceFlush()}}function requireUtils(){return hasRequiredUtils||(hasRequiredUtils=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extractFilteringContextFromArgs=e.deep_value=e.saveDataInAttribute=e.isFunctionType=e.setTracerProvider=e.isFilterMatch=e.findMatchingFilters=e.isSpanEnabled=void 0;const t=require$$15,r=require$$14$1,n=require$$13$1,i=require$$2,o=filter,s=attributeData,a=requireIoInsightsSampler(),c=otelUtils,l=require$$8,u=durationFilterProcessor,d=container$1;e.isSpanEnabled=(e,t,r)=>{var n,i;let o;return o=e?void 0===e.enabled||e.enabled:null===(i=null!==(n=null==t?void 0:t.enabled)&&void 0!==n?n:null==r?void 0:r.enabled)||void 0===i||i,o};e.findMatchingFilters=(t,r,n)=>{let i=!1;const o={},s={source:"",context:{},enabled:!1,stopPropagationIfSpanIsDisabled:!1,level:"INFO",addContextToTrace:!1,autoSetSuccessStatus:!1,sample:0,disablePropagation:!1,disableNesting:!1,countMetric:!1,countMetricOnDisabledSpans:!1,resultMetric:!1,resultMetricOnDisabledSpans:!1,durationMetric:!1,durationMetricOnDisabledSpans:!1,canBeRoot:!1,maxAttributeDepth:0,forceChildTracing:!1,otelSpanOptions:{},minDurationMs:0,log:!1,logOnDisabledSpans:!1};for(const a of t)if((0,e.isFilterMatch)(a,r,n)){i=!0;for(const e of Object.keys(s))void 0===o[e]&&(o[e]=a[e])}return i?o:void 0};e.isFilterMatch=(t,r,n)=>{let i=!0;if(t){(new o.TracesFilterValidator).validate(t)}if(t.source&&t.source.startsWith("#")){if(!new RegExp(t.source.substring(1),"i").test(n))return 0}else if(t.source&&n!==t.source&&!n.startsWith(t.source+".")&&n+"."!==t.source)return 0;if(!t.context)return 1;for(const n of Object.keys(t.context)){const o=t.context[n],s=(0,e.deep_value)(r,n);if("string"!=typeof o||"#"!==o[0]){o!==s&&(i=!1);break}if(null==s||!new RegExp(o.substring(1),"i").test(s+"")){i=!1;break}}return i?2:0};e.setTracerProvider=(e,o,s,c,h,p,g,m,f)=>{var y;if(!s&&!f)throw new Error("Required arguments not provided");const $=null==f?void 0:f.traces;if(!s){const e=new r.ParentBasedSampler({root:new a.ioInsightsSampler((null==$?void 0:$.sampling)||[],null==$?void 0:$.defaults,()=>Object.assign(Object.assign({},d.Container.errorless(null==$?void 0:$.additionalResourceAttributes)),d.Container.errorless(null==$?void 0:$.additionalAttributes)),m)}),n=[];if(h)for(const e of h)n.push(new u.DurationFilterProcessor(e));if(p)for(const e of p)n.push(new u.DurationFilterProcessor(new r.BatchSpanProcessor(e)));(null==$?void 0:$.url)&&n.push(new u.DurationFilterProcessor(new r.BatchSpanProcessor(new t.OTLPTraceExporter(Object.assign(Object.assign({},$.otlpExporterConfig),{url:$.url,headers:Object.assign(Object.assign({},d.Container.errorless(null==f?void 0:f.headers)),d.Container.errorless($.headers))}))))),(null==$?void 0:$.console)&&n.push(new u.DurationFilterProcessor(new r.BatchSpanProcessor(new r.ConsoleSpanExporter))),s=new r.BasicTracerProvider(Object.assign({sampler:"function"==typeof c?c(e):e,resource:(0,i.resourceFromAttributes)(null!==(y=d.Container.errorless(null==$?void 0:$.additionalResourceAttributes))&&void 0!==y?y:{}),spanProcessors:n},null==$?void 0:$.tracerProviderConfig))}n.trace.setGlobalTracerProvider(s),e&&n.context.setGlobalContextManager(null!=e?e:null==g?void 0:g.contextManager),o?n.propagation.setGlobalPropagator(null!=o?o:null==g?void 0:g.propagator):n.propagation.setGlobalPropagator(new l.W3CTraceContextPropagator),"function"==typeof s.register&&s.register(g||{})};e.isFunctionType=e=>"function"==typeof e;e.saveDataInAttribute=(e,t,r)=>{if(null==e)return;"object"!=typeof e&&(e={unknownAttribute:e});(new s.TracesAttributeDataValidator).validate(e);for(const[n,i]of Object.entries(e)){const e=(0,c.getOTELData)(n,i,0,r);for(const[r,n]of e)t.setAttribute(r,n)}};e.deep_value=function(e,t){if(!t)return null;for(var r=0,n=(t=t.split(".")).length;r{let i={};return"function"==typeof t.thisMapping?i=Object.assign(Object.assign({},i),t.thisMapping.apply(n,[n])):Object.keys(t.thisMapping||{}).forEach(r=>{if(!r||!t.thisMapping)return;const o=t.thisMapping[r];i[o]=(0,e.deep_value)(n,r)}),"function"==typeof t.argMapping?i=Object.assign(Object.assign({},i),t.argMapping.apply(n,r)):Object.keys(t.argMapping||{}).forEach(n=>{if(!n||!t.argMapping)return;const o=t.argMapping[n],s=(0,e.deep_value)(r,n);"string"!=typeof s&&"number"!=typeof s||(i[o]=s)}),i}}(utils$7)),utils$7}durationFilterProcessor.DurationFilterProcessor=DurationFilterProcessor;var manager$1={};Object.defineProperty(manager$1,"__esModule",{value:!0}),manager$1.TracesManagerValidator=void 0;const validator_1$1=validator$1;class TracesManagerValidator{validate(e){validator_1$1.Validator.throwIfNullOrUndefined(e,"manager"),validator_1$1.Validator.throwIfNullOrUndefined(e.settings,"settings")}}manager$1.TracesManagerValidator=TracesManagerValidator;var tracingState={},types$1={};!function(e){var t;Object.defineProperty(e,"__esModule",{value:!0}),e.SpanVerbosity=void 0,(t=e.SpanVerbosity||(e.SpanVerbosity={}))[t.OFF=0]="OFF",t[t.LOWEST=1]="LOWEST",t[t.DIAGNOSTIC=2]="DIAGNOSTIC",t[t.DEBUG=3]="DEBUG",t[t.INFO=4]="INFO",t[t.WARN=5]="WARN",t[t.HIGHEST=6]="HIGHEST"}(types$1),Object.defineProperty(tracingState,"__esModule",{value:!0}),tracingState.TracingState=void 0;const types_1=types$1,api_1$3=require$$13$1,utils_1$2=requireUtils();class TracingState{constructor(e,t,r,n,i,o,s,a,c){this.source=e,this.level=t,this.span=r,this.logger=n,this.version=i,this.disablePropagation=o,this.forceChildTracing=s,this.maxAttributeDepth=a,this.context=c,this.currentSpanStatus={code:api_1$3.SpanStatusCode.UNSET},this.hasEnded=!1,this.spanContextField=r.spanContext()}endSpan(){var e;return this.hasEnded?null===(e=this.logger)||void 0===e||e.debug(`Span ended more than once: ${this.source}`):(this.hasEnded=!0,this.span.end()),Promise.resolve()}get enabled(){return!0}get id(){return this.spanContextField.spanId}get traceId(){return this.spanContextField.traceId}set status(e){this.currentSpanStatus=Object.assign({},e),this.span.setStatus.call(this.span,e)}get status(){return this.currentSpanStatus}addEvent(e,t,r){return this.span.addEvent.call(this.span,e,t,r),this}recordException(e,t){this.span.recordException.call(this.span,e,t)}isRecording(){return this.span.isRecording.call(this.span)}updateName(e){return this.span.updateName.call(this.span,e),this}spanContext(){return this.span.spanContext.call(this.span)}addData(e,t){var r;"string"==typeof e&&(e=types_1.SpanVerbosity[e]),e>=types_1.SpanVerbosity[this.level]&&(0,utils_1$2.saveDataInAttribute)(t,this.span,null!==(r=this.maxAttributeDepth)&&void 0!==r?r:5)}end(){this.span.end()}getPropagationInfo(){const e={traceparent:`${this.version}-${this.spanContextField.traceId}-${this.spanContextField.spanId}-0${this.spanContextField.traceFlags}`,tracestate:this.spanContextField.traceState&&String(this.spanContextField.traceState)};return this.forceChildTracing&&(e.forceTracing=!0),e}injectPropagationInfo(e){if(this.disablePropagation)return;const t=this.getPropagationInfo();t&&(e.__interopIOTracePropagationInfo=t)}}tracingState.TracingState=TracingState;var withSpan={};Object.defineProperty(withSpan,"__esModule",{value:!0}),withSpan.TracesWithSpanValidator=void 0;const utils_1$1=requireUtils();class TracesWithSpanValidator{validate(e,t,r,n,i){if(!e)throw new Error("Missing required argument 'source' in withSpan(). Expected a string.");if(!(i||(0,utils_1$1.isFunctionType)(t)||(0,utils_1$1.isFunctionType)(r)||(0,utils_1$1.isFunctionType)(n)))throw new Error("Missing required argument 'callback' in withSpan(). Expected a function.")}}withSpan.TracesWithSpanValidator=TracesWithSpanValidator;var nullTracingState={};Object.defineProperty(nullTracingState,"__esModule",{value:!0});const api_1$2=require$$13$1;class NullTracingState{constructor(e,t,r){this.source=e,this.propagationInfo=t,this.disablePropagation=r,this.currentSpanStatus={code:api_1$2.SpanStatusCode.UNSET},this.level="OFF"}endSpan(){return Promise.resolve()}get enabled(){return!1}get id(){}get traceId(){}set status(e){this.currentSpanStatus=Object.assign({},e)}get status(){return this.currentSpanStatus}addEvent(e,t,r){return this}recordException(e,t){}isRecording(){return!1}updateName(e){return this}spanContext(){}addData(e,t){}end(){}getPropagationInfo(){return this.propagationInfo?this.propagationInfo:null}injectPropagationInfo(e){this.propagationInfo&&!this.disablePropagation&&(e.__interopIOTracePropagationInfo=this.propagationInfo)}}nullTracingState.default=NullTracingState;var traces={},nullTracesManager={},hasRequiredNullTracesManager,hasRequiredTraces;function requireNullTracesManager(){if(hasRequiredNullTracesManager)return nullTracesManager;hasRequiredNullTracesManager=1;var e=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nullTracesManager,"__esModule",{value:!0}),nullTracesManager.NullTracesManager=void 0;const t=nullManager$1,r=safeStringify$1,n=e(nullTracingState),i=e(requireTraces());class o extends t.NullManager{get settings(){return this._settings||{}}set settings(e){this._settings=e}constructor(e,t,n){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==n||n.info(`Starting NullTracesManager with settings ${(0,r.safeStringify)(e)}`)),super(),this._settings=e,this.logger=n}get currentTracingState(){return new n.default("nullTracingState",null,!0)}set currentTracingState(e){}waitForFinalExport(e){return Promise.resolve()}withSpan(e,t,r,o,s){var a;const c="function"==typeof t?t:"function"==typeof r?r:"function"==typeof o?o:s;if(!c)throw new Error("callback must be provided");null===(a=this.logger)||void 0===a||a.debug("nullTracesManager.withSpan: "+e);const l=new n.default(e,null,!0);i.default.currentTracingState=l;try{return c(l)}finally{i.default.currentTracingState=null}}}return nullTracesManager.NullTracesManager=o,nullTracesManager}function requireTraces(){if(hasRequiredTraces)return traces;hasRequiredTraces=1;var e=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(traces,"__esModule",{value:!0}),traces.withSpan=traces.getCurrentTracingStateInternal=void 0;const t=requireNullTracesManager(),r=e(nullTracingState),n=requireUtils();let i;traces.getCurrentTracingStateInternal=()=>i;class o{static get instance(){return o._instance}static set instance(e){o._instance=e}static get currentTracingState(){var e;return(null===(e=o._instance)||void 0===e?void 0:e.currentTracingState)||new r.default("unknown",null,!0)}static set currentTracingState(e){i=e}static removePropagationInfo(e){return o.extractPropagationInfo(e,!0),e}static extractPropagationInfo(e,t){if(null==e?void 0:e.traceparent)return e;const r=null==e?void 0:e.__interopIOTracePropagationInfo;return r?(!0===t&&delete e.__interopIOTracePropagationInfo,r):null}static withSpan(e,t,r,i,s){return t instanceof Function||t&&!t.argMapping&&!t.thisMapping&&!t.defaults||r||i||s?o.instance.withSpan(e,t,r,i,s):function(r,i,s){let a;a=s?s.value:r;const c=function(...r){return o.withSpan(e,t?(0,n.extractFilteringContextFromArgs)(t,r,this):{},null,t,()=>a.apply(this,r))};if(!s)return c;s.value=c}}static withSpans(e,t){for(const r in e)if("function"==typeof t[r]){const n=t[r],i=e[r];if(!i)continue;let s;s="string"==typeof i?o.withSpan(i):o.withSpan(i.source,i.decoratorOptions),t[r]=s(n)}return t}}return traces.default=o,o._instance=new t.NullTracesManager(void 0,void 0,void 0),traces.withSpan=o.withSpan,traces}const otperformance$2=performance,NANOSECOND_DIGITS$2=9,NANOSECOND_DIGITS_IN_MILLIS$2=6,MILLISECONDS_TO_NANOSECONDS$2=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$2),SECOND_TO_NANOSECONDS$2=Math.pow(10,NANOSECOND_DIGITS$2);function millisToHrTime$2(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$2)]}function getTimeOrigin$2(){let e=otperformance$2.timeOrigin;if("number"!=typeof e){const t=otperformance$2;e=t.timing&&t.timing.fetchStart}return e}function hrTime$2(e){return addHrTimes$2(millisToHrTime$2(getTimeOrigin$2()),millisToHrTime$2("number"==typeof e?e:otperformance$2.now()))}function timeInputToHrTime(e){if(isTimeInputHrTime(e))return e;if("number"==typeof e)return e=SECOND_TO_NANOSECONDS$2&&(r[1]-=SECOND_TO_NANOSECONDS$2,r[0]+=1),r}function urlMatches$2(e,t){return"string"==typeof t?e===t:!!e.match(t)}var PerformanceTimingNames;!function(e){e.CONNECT_END="connectEnd",e.CONNECT_START="connectStart",e.DECODED_BODY_SIZE="decodedBodySize",e.DOM_COMPLETE="domComplete",e.DOM_CONTENT_LOADED_EVENT_END="domContentLoadedEventEnd",e.DOM_CONTENT_LOADED_EVENT_START="domContentLoadedEventStart",e.DOM_INTERACTIVE="domInteractive",e.DOMAIN_LOOKUP_END="domainLookupEnd",e.DOMAIN_LOOKUP_START="domainLookupStart",e.ENCODED_BODY_SIZE="encodedBodySize",e.FETCH_START="fetchStart",e.LOAD_EVENT_END="loadEventEnd",e.LOAD_EVENT_START="loadEventStart",e.NAVIGATION_START="navigationStart",e.REDIRECT_END="redirectEnd",e.REDIRECT_START="redirectStart",e.REQUEST_START="requestStart",e.RESPONSE_END="responseEnd",e.RESPONSE_START="responseStart",e.SECURE_CONNECTION_START="secureConnectionStart",e.START_TIME="startTime",e.UNLOAD_EVENT_END="unloadEventEnd",e.UNLOAD_EVENT_START="unloadEventStart"}(PerformanceTimingNames||(PerformanceTimingNames={}));const ATTR_HTTP_RESPONSE_CONTENT_LENGTH="http.response_content_length",ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED="http.response_content_length_uncompressed";let urlNormalizingAnchor;function getUrlNormalizingAnchor(){return urlNormalizingAnchor||(urlNormalizingAnchor=document.createElement("a")),urlNormalizingAnchor}function hasKey(e,t){return t in e}function addSpanNetworkEvent(e,t,r,n=!0){if(hasKey(r,t)&&"number"==typeof r[t]&&(!n||0!==r[t]))return e.addEvent(t,r[t])}function addSpanNetworkEvents(e,t,r=!1,n,i){if(void 0===n&&(n=0!==t[PerformanceTimingNames.START_TIME]),r||(addSpanNetworkEvent(e,PerformanceTimingNames.FETCH_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.DOMAIN_LOOKUP_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.DOMAIN_LOOKUP_END,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.CONNECT_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.SECURE_CONNECTION_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.CONNECT_END,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.REQUEST_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.RESPONSE_START,t,n),addSpanNetworkEvent(e,PerformanceTimingNames.RESPONSE_END,t,n)),!i){const r=t[PerformanceTimingNames.ENCODED_BODY_SIZE];void 0!==r&&e.setAttribute(ATTR_HTTP_RESPONSE_CONTENT_LENGTH,r);const n=t[PerformanceTimingNames.DECODED_BODY_SIZE];void 0!==n&&r!==n&&e.setAttribute(ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,n)}}function sortResources(e){return e.slice().sort((e,t)=>{const r=e[PerformanceTimingNames.FETCH_START],n=t[PerformanceTimingNames.FETCH_START];return r>n?1:r1){let e=c[0],t=findMainRequest(c,e[PerformanceTimingNames.RESPONSE_END],r);const n=e[PerformanceTimingNames.RESPONSE_END];return t[PerformanceTimingNames.FETCH_START]=i&&(!o||c{const r=hrTimeToNanoseconds(timeInputToHrTime(t[PerformanceTimingNames.FETCH_START])),n=hrTimeToNanoseconds(timeInputToHrTime(t[PerformanceTimingNames.RESPONSE_END]));return t.initiatorType.toLowerCase()===(o||"xmlhttprequest")&&t.name===e&&r>=s&&n<=a});return c.length>0&&(c=c.filter(e=>!i.has(e))),c}function parseUrl(e){if("function"==typeof URL)return new URL(e,"undefined"!=typeof document?document.baseURI:"undefined"!=typeof location?location.href:void 0);const t=getUrlNormalizingAnchor();return t.href=e,t}function getElementXPath(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return"/";const r=getNodeValue(e,t);if(t&&r.indexOf("@id")>0)return r;let n="";return e.parentNode&&(n+=getElementXPath(e.parentNode,!1)),n+=r,n}function getNodeIndex(e){if(!e.parentNode)return 0;const t=[e.nodeType];e.nodeType===Node.CDATA_SECTION_NODE&&t.push(Node.TEXT_NODE);let r=Array.from(e.parentNode.childNodes);return r=r.filter(r=>{const n=r.localName;return t.indexOf(r.nodeType)>=0&&n===e.localName}),r.length>=1?r.indexOf(e)+1:0}function getNodeValue(e,t){const r=e.nodeType,n=getNodeIndex(e);let i="";if(r===Node.ELEMENT_NODE){const r=e.getAttribute("id");if(t&&r)return`//*[@id="${r}"]`;i=e.localName}else if(r===Node.TEXT_NODE||r===Node.CDATA_SECTION_NODE)i="text()";else{if(r!==Node.COMMENT_NODE)return"";i="comment()"}return i&&n>1?`/${i}[${n}]`:`/${i}`}function shouldPropagateTraceHeaders(e,t){let r=t||[];("string"==typeof r||r instanceof RegExp)&&(r=[r]);return parseUrl(e).origin===getOrigin()||r.some(t=>urlMatches$2(e,t))}let NoopLogger$5=class{emit(e){}};const NOOP_LOGGER$5=new NoopLogger$5;let NoopLoggerProvider$4=class{getLogger(e,t,r){return new NoopLogger$5}};const NOOP_LOGGER_PROVIDER$4=new NoopLoggerProvider$4;let ProxyLogger$4=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$5}},ProxyLoggerProvider$4=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger$4(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER$4}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const _globalThis$5="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY$4=Symbol.for("io.opentelemetry.js.api.logs"),_global$5=_globalThis$5;function makeGetter$4(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION$4=1;let LogsAPI$4=class e{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider$4}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return _global$5[GLOBAL_LOGS_API_KEY$4]?this.getLoggerProvider():(_global$5[GLOBAL_LOGS_API_KEY$4]=makeGetter$4(API_BACKWARDS_COMPATIBILITY_VERSION$4,e,NOOP_LOGGER_PROVIDER$4),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$5[GLOBAL_LOGS_API_KEY$4])||void 0===e?void 0:e.call(_global$5,API_BACKWARDS_COMPATIBILITY_VERSION$4))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$5[GLOBAL_LOGS_API_KEY$4],this._proxyLoggerProvider=new ProxyLoggerProvider$4}};const logs$5=LogsAPI$4.getInstance();let logger$5=console.error.bind(console);function defineProperty$6(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$5=(e,t,r)=>{if(!e||!e[t])return void logger$5("no original function "+String(t)+" to wrap");if(!r)return logger$5("no wrapper function"),void logger$5((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$5("original object and wrapper must be functions");const i=r(n,t);return defineProperty$6(i,"__original",n),defineProperty$6(i,"__unwrap",()=>{e[t]===i&&defineProperty$6(e,t,n)}),defineProperty$6(i,"__wrapped",!0),defineProperty$6(e,t,i),i},massWrap$4=(e,t,r)=>{if(!e)return logger$5("must provide one or more modules to patch"),void logger$5((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$5(e,t,r)})}):logger$5("must provide one or more functions to wrap on modules")},unwrap$5=(e,t)=>{if(!e||!e[t])return logger$5("no function to unwrap."),void logger$5((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$5("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap$4=(e,t)=>{if(!e)return logger$5("must provide one or more modules to patch"),void logger$5((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$5(e,t)})}):logger$5("must provide one or more functions to unwrap on modules")};let InstrumentationAbstract$4=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$5.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$5;_unwrap=unwrap$5;_massWrap=massWrap$4;_massUnwrap=massUnwrap$4;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},InstrumentationBase$4=class extends InstrumentationAbstract$4{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function safeExecuteInTheMiddle$3(e,t,r){let n,i;try{i=e()}catch(e){n=e}finally{return t(n,i),i}}var AttributeNames$3;!function(e){e.DOCUMENT_LOAD="documentLoad",e.DOCUMENT_FETCH="documentFetch",e.RESOURCE_FETCH="resourceFetch"}(AttributeNames$3||(AttributeNames$3={}));const PACKAGE_VERSION$1="0.47.1",PACKAGE_NAME$1="@opentelemetry/instrumentation-document-load";var EventNames$1;!function(e){e.FIRST_PAINT="firstPaint",e.FIRST_CONTENTFUL_PAINT="firstContentfulPaint"}(EventNames$1||(EventNames$1={}));const getPerformanceNavigationEntries=()=>{const e={},t=otperformance$4.getEntriesByType?.("navigation")[0];if(t){Object.values(PerformanceTimingNames).forEach(r=>{if(hasKey(t,r)){const n=t[r];"number"==typeof n&&(e[r]=n)}})}else{const t=otperformance$4.timing;if(t){Object.values(PerformanceTimingNames).forEach(r=>{if(hasKey(t,r)){const n=t[r];"number"==typeof n&&(e[r]=n)}})}}return e},performancePaintNames={"first-paint":EventNames$1.FIRST_PAINT,"first-contentful-paint":EventNames$1.FIRST_CONTENTFUL_PAINT},addSpanPerformancePaintEvents=e=>{const t=otperformance$4.getEntriesByType?.("paint");t&&t.forEach(({name:t,startTime:r})=>{hasKey(performancePaintNames,t)&&e.addEvent(performancePaintNames[t],r)})};class DocumentLoadInstrumentation extends InstrumentationBase$4{component="document-load";version="1";moduleName=this.component;constructor(e={}){super(PACKAGE_NAME$1,PACKAGE_VERSION$1,e)}init(){}_onDocumentLoaded(){window.setTimeout(()=>{this._collectPerformance()})}_addResourcesSpans(e){const t=otperformance$4.getEntriesByType?.("resource");t&&t.forEach(t=>{this._initResourceSpan(t,e)})}_collectPerformance(){const e=Array.from(document.getElementsByTagName("meta")).find(e=>e.getAttribute("name")===TRACE_PARENT_HEADER),t=getPerformanceNavigationEntries(),r=e&&e.content||"";context.with(propagation.extract(ROOT_CONTEXT,{traceparent:r}),()=>{const e=this._startSpan(AttributeNames$3.DOCUMENT_LOAD,PerformanceTimingNames.FETCH_START,t);e&&(context.with(trace.setSpan(context.active(),e),()=>{const e=this._startSpan(AttributeNames$3.DOCUMENT_FETCH,PerformanceTimingNames.FETCH_START,t);e&&(e.setAttribute(SEMATTRS_HTTP_URL,location.href),context.with(trace.setSpan(context.active(),e),()=>{addSpanNetworkEvents(e,t,this.getConfig().ignoreNetworkEvents),this._addCustomAttributesOnSpan(e,this.getConfig().applyCustomAttributesOnSpan?.documentFetch),this._endSpan(e,PerformanceTimingNames.RESPONSE_END,t)}))}),e.setAttribute(SEMATTRS_HTTP_URL,location.href),e.setAttribute(SEMATTRS_HTTP_USER_AGENT,navigator.userAgent),this._addResourcesSpans(e),this.getConfig().ignoreNetworkEvents||(addSpanNetworkEvent(e,PerformanceTimingNames.FETCH_START,t),addSpanNetworkEvent(e,PerformanceTimingNames.UNLOAD_EVENT_START,t),addSpanNetworkEvent(e,PerformanceTimingNames.UNLOAD_EVENT_END,t),addSpanNetworkEvent(e,PerformanceTimingNames.DOM_INTERACTIVE,t),addSpanNetworkEvent(e,PerformanceTimingNames.DOM_CONTENT_LOADED_EVENT_START,t),addSpanNetworkEvent(e,PerformanceTimingNames.DOM_CONTENT_LOADED_EVENT_END,t),addSpanNetworkEvent(e,PerformanceTimingNames.DOM_COMPLETE,t),addSpanNetworkEvent(e,PerformanceTimingNames.LOAD_EVENT_START,t),addSpanNetworkEvent(e,PerformanceTimingNames.LOAD_EVENT_END,t)),this.getConfig().ignorePerformancePaintEvents||addSpanPerformancePaintEvents(e),this._addCustomAttributesOnSpan(e,this.getConfig().applyCustomAttributesOnSpan?.documentLoad),this._endSpan(e,PerformanceTimingNames.LOAD_EVENT_END,t))})}_endSpan(e,t,r){e&&(hasKey(r,t)?e.end(r[t]):e.end())}_initResourceSpan(e,t){const r=this._startSpan(AttributeNames$3.RESOURCE_FETCH,PerformanceTimingNames.FETCH_START,e,t);r&&(r.setAttribute(SEMATTRS_HTTP_URL,e.name),addSpanNetworkEvents(r,e,this.getConfig().ignoreNetworkEvents),this._addCustomAttributesOnResourceSpan(r,e,this.getConfig().applyCustomAttributesOnSpan?.resourceFetch),this._endSpan(r,PerformanceTimingNames.RESPONSE_END,e))}_startSpan(e,t,r,n){if(hasKey(r,t)&&"number"==typeof r[t]){return this.tracer.startSpan(e,{startTime:r[t]},n?trace.setSpan(context.active(),n):void 0)}}_waitForPageLoad(){"complete"===window.document.readyState?this._onDocumentLoaded():(this._onDocumentLoaded=this._onDocumentLoaded.bind(this),window.addEventListener("load",this._onDocumentLoaded))}_addCustomAttributesOnSpan(e,t){t&&safeExecuteInTheMiddle$3(()=>t(e),e=>{e&&this._diag.error("addCustomAttributesOnSpan",e)})}_addCustomAttributesOnResourceSpan(e,t,r){r&&safeExecuteInTheMiddle$3(()=>r(e,t),e=>{e&&this._diag.error("addCustomAttributesOnResourceSpan",e)})}enable(){window.removeEventListener("load",this._onDocumentLoaded),this._waitForPageLoad()}disable(){window.removeEventListener("load",this._onDocumentLoaded)}}var esm$6=Object.freeze({__proto__:null,get AttributeNames(){return AttributeNames$3},DocumentLoadInstrumentation:DocumentLoadInstrumentation}),require$$10=getAugmentedNamespace(esm$6);let NoopLogger$4=class{emit(e){}};const NOOP_LOGGER$4=new NoopLogger$4;let NoopLoggerProvider$3=class{getLogger(e,t,r){return new NoopLogger$4}};const NOOP_LOGGER_PROVIDER$3=new NoopLoggerProvider$3;let ProxyLogger$3=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$4}},ProxyLoggerProvider$3=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger$3(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER$3}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const _globalThis$4="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY$3=Symbol.for("io.opentelemetry.js.api.logs"),_global$4=_globalThis$4;function makeGetter$3(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION$3=1;let LogsAPI$3=class e{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider$3}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return _global$4[GLOBAL_LOGS_API_KEY$3]?this.getLoggerProvider():(_global$4[GLOBAL_LOGS_API_KEY$3]=makeGetter$3(API_BACKWARDS_COMPATIBILITY_VERSION$3,e,NOOP_LOGGER_PROVIDER$3),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$4[GLOBAL_LOGS_API_KEY$3])||void 0===e?void 0:e.call(_global$4,API_BACKWARDS_COMPATIBILITY_VERSION$3))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$4[GLOBAL_LOGS_API_KEY$3],this._proxyLoggerProvider=new ProxyLoggerProvider$3}};const logs$4=LogsAPI$3.getInstance();let logger$4=console.error.bind(console);function defineProperty$5(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$4=(e,t,r)=>{if(!e||!e[t])return void logger$4("no original function "+String(t)+" to wrap");if(!r)return logger$4("no wrapper function"),void logger$4((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$4("original object and wrapper must be functions");const i=r(n,t);return defineProperty$5(i,"__original",n),defineProperty$5(i,"__unwrap",()=>{e[t]===i&&defineProperty$5(e,t,n)}),defineProperty$5(i,"__wrapped",!0),defineProperty$5(e,t,i),i},massWrap$3=(e,t,r)=>{if(!e)return logger$4("must provide one or more modules to patch"),void logger$4((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$4(e,t,r)})}):logger$4("must provide one or more functions to wrap on modules")},unwrap$4=(e,t)=>{if(!e||!e[t])return logger$4("no function to unwrap."),void logger$4((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$4("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap$3=(e,t)=>{if(!e)return logger$4("must provide one or more modules to patch"),void logger$4((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$4(e,t)})}):logger$4("must provide one or more functions to unwrap on modules")};let InstrumentationAbstract$3=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$4.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$4;_unwrap=unwrap$4;_massWrap=massWrap$3;_massUnwrap=massUnwrap$3;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},InstrumentationBase$3=class extends InstrumentationAbstract$3{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function isWrapped$3(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var AttributeNames$2;!function(e){e.EVENT_TYPE="event_type",e.TARGET_ELEMENT="target_element",e.TARGET_XPATH="target_xpath",e.HTTP_URL="http.url"}(AttributeNames$2||(AttributeNames$2={}));const PACKAGE_VERSION="0.47.0",PACKAGE_NAME="@opentelemetry/instrumentation-user-interaction",ZONE_CONTEXT_KEY="OT_ZONE_CONTEXT",EVENT_NAVIGATION_NAME="Navigation:",DEFAULT_EVENT_NAMES=["click"];function defaultShouldPreventSpanCreation(){return!1}class UserInteractionInstrumentation extends InstrumentationBase$3{version=PACKAGE_VERSION;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(e={}){super(PACKAGE_NAME,PACKAGE_VERSION,e),this._eventNames=new Set(e?.eventNames??DEFAULT_EVENT_NAMES),this._shouldPreventSpanCreation="function"==typeof e?.shouldPreventSpanCreation?e.shouldPreventSpanCreation:defaultShouldPreventSpanCreation}init(){}_checkForTimeout(e,t){const r=this._spansData.get(t);r&&("setTimeout"===e.source?r.hrTimeLastTimeout=hrTime$4():"Promise.then"!==e.source&&"setTimeout"!==e.source&&(r.hrTimeLastTimeout=void 0))}_allowEventName(e){return this._eventNames.has(e)}_createSpan(e,t,r){if(!(e instanceof HTMLElement))return;if(!e.getAttribute)return;if(e.hasAttribute("disabled"))return;if(!this._allowEventName(t))return;const n=getElementXPath(e,!0);try{const i=this.tracer.startSpan(t,{attributes:{[AttributeNames$2.EVENT_TYPE]:t,[AttributeNames$2.TARGET_ELEMENT]:e.tagName,[AttributeNames$2.TARGET_XPATH]:n,[AttributeNames$2.HTTP_URL]:window.location.href}},r?trace.setSpan(context.active(),r):void 0);if(!0===this._shouldPreventSpanCreation(t,e,i))return;return this._spansData.set(i,{taskCount:0}),i}catch(e){this._diag.error("failed to start create new user interaction span",e)}}_decrementTask(e){const t=this._spansData.get(e);t&&(t.taskCount--,0===t.taskCount&&this._tryToEndSpan(e,t.hrTimeLastTimeout))}_getCurrentSpan(e){const t=e.get(ZONE_CONTEXT_KEY);return t?trace.getSpan(t):t}_incrementTask(e){const t=this._spansData.get(e);t&&t.taskCount++}addPatchedListener(e,t,r,n){let i=this._wrappedListeners.get(r);i||(i=new Map,this._wrappedListeners.set(r,i));let o=i.get(t);return o||(o=new Map,i.set(t,o)),!o.has(e)&&(o.set(e,n),!0)}removePatchedListener(e,t,r){const n=this._wrappedListeners.get(r);if(!n)return;const i=n.get(t);if(!i)return;const o=i.get(e);return o&&(i.delete(e),0===i.size&&(n.delete(t),0===n.size&&this._wrappedListeners.delete(r))),o}_invokeListener(e,t,r){return"function"==typeof e?e.apply(t,r):e.handleEvent(r[0])}_patchAddEventListener(){const e=this;return t=>function(r,n,i){if(!n)return t.call(this,r,n,i);const o=i&&"object"==typeof i&&i.once,s=function(...t){let i;const s=t[0],a=s?.target;s&&(i=e._eventsSpanMap.get(s)),o&&e.removePatchedListener(this,r,n);const c=e._createSpan(a,r,i);return c?(s&&e._eventsSpanMap.set(s,c),context.with(trace.setSpan(context.active(),c),()=>{const r=e._invokeListener(n,this,t);return c.end(),r})):e._invokeListener(n,this,t)};return e.addPatchedListener(this,r,n,s)?t.call(this,r,s,i):void 0}}_patchRemoveEventListener(){const e=this;return t=>function(r,n,i){const o=e.removePatchedListener(this,r,n);return o?t.call(this,r,o,i):t.call(this,r,n,i)}}_getPatchableEventTargets(){return window.EventTarget?[EventTarget.prototype]:[Node.prototype,Window.prototype]}_patchHistoryApi(){this._unpatchHistoryApi(),this._wrap(history,"replaceState",this._patchHistoryMethod()),this._wrap(history,"pushState",this._patchHistoryMethod()),this._wrap(history,"back",this._patchHistoryMethod()),this._wrap(history,"forward",this._patchHistoryMethod()),this._wrap(history,"go",this._patchHistoryMethod())}_patchHistoryMethod(){const e=this;return t=>function(...r){const n=`${location.pathname}${location.hash}${location.search}`,i=t.apply(this,r),o=`${location.pathname}${location.hash}${location.search}`;return n!==o&&e._updateInteractionName(o),i}}_unpatchHistoryApi(){isWrapped$3(history.replaceState)&&this._unwrap(history,"replaceState"),isWrapped$3(history.pushState)&&this._unwrap(history,"pushState"),isWrapped$3(history.back)&&this._unwrap(history,"back"),isWrapped$3(history.forward)&&this._unwrap(history,"forward"),isWrapped$3(history.go)&&this._unwrap(history,"go")}_updateInteractionName(e){const t=trace.getSpan(context.active());t&&"function"==typeof t.updateName&&t.updateName(`${EVENT_NAVIGATION_NAME} ${e}`)}_patchZoneCancelTask(){const e=this;return t=>function(r){const n=Zone.current,i=e._getCurrentSpan(n);return i&&e._shouldCountTask(r,n)&&e._decrementTask(i),t.call(this,r)}}_patchZoneScheduleTask(){const e=this;return t=>function(r){const n=Zone.current,i=e._getCurrentSpan(n);return i&&e._shouldCountTask(r,n)&&(e._incrementTask(i),e._checkForTimeout(r,i)),t.call(this,r)}}_patchZoneRunTask(){const e=this;return t=>function(r,n,i){const o=Array.isArray(i)&&i[0]instanceof Event?i[0]:void 0,s=o?.target;let a;const c=this;if(s){if(a=e._createSpan(s,r.eventName),a)return e._incrementTask(a),c.run(()=>{try{return context.with(trace.setSpan(context.active(),a),()=>{const e=Zone.current;return r._zone=e,t.call(e,r,n,i)})}finally{e._decrementTask(a)}})}else a=e._getCurrentSpan(c);try{return t.call(c,r,n,i)}finally{a&&e._shouldCountTask(r,c)&&e._decrementTask(a)}}}_shouldCountTask(e,t){if(e._zone&&(t=e._zone),!t||!e.data||e.data.isPeriodic)return!1;const r=this._getCurrentSpan(t);return!!r&&(!!this._spansData.get(r)&&("macroTask"===e.type||"microTask"===e.type))}_tryToEndSpan(e,t){if(e){this._spansData.get(e)&&(e.end(t),this._spansData.delete(e))}}enable(){const e=this._getZoneWithPrototype();if(this._diag.debug("applying patch to",this.moduleName,this.version,"zone:",!!e),e)isWrapped$3(e.prototype.runTask)&&(this._unwrap(e.prototype,"runTask"),this._diag.debug("removing previous patch from method runTask")),isWrapped$3(e.prototype.scheduleTask)&&(this._unwrap(e.prototype,"scheduleTask"),this._diag.debug("removing previous patch from method scheduleTask")),isWrapped$3(e.prototype.cancelTask)&&(this._unwrap(e.prototype,"cancelTask"),this._diag.debug("removing previous patch from method cancelTask")),this._zonePatched=!0,this._wrap(e.prototype,"runTask",this._patchZoneRunTask()),this._wrap(e.prototype,"scheduleTask",this._patchZoneScheduleTask()),this._wrap(e.prototype,"cancelTask",this._patchZoneCancelTask());else{this._zonePatched=!1;this._getPatchableEventTargets().forEach(e=>{isWrapped$3(e.addEventListener)&&(this._unwrap(e,"addEventListener"),this._diag.debug("removing previous patch from method addEventListener")),isWrapped$3(e.removeEventListener)&&(this._unwrap(e,"removeEventListener"),this._diag.debug("removing previous patch from method removeEventListener")),this._wrap(e,"addEventListener",this._patchAddEventListener()),this._wrap(e,"removeEventListener",this._patchRemoveEventListener())})}this._patchHistoryApi()}disable(){const e=this._getZoneWithPrototype();if(this._diag.debug("removing patch from",this.moduleName,this.version,"zone:",!!e),e&&this._zonePatched)isWrapped$3(e.prototype.runTask)&&this._unwrap(e.prototype,"runTask"),isWrapped$3(e.prototype.scheduleTask)&&this._unwrap(e.prototype,"scheduleTask"),isWrapped$3(e.prototype.cancelTask)&&this._unwrap(e.prototype,"cancelTask");else{this._getPatchableEventTargets().forEach(e=>{isWrapped$3(e.addEventListener)&&this._unwrap(e,"addEventListener"),isWrapped$3(e.removeEventListener)&&this._unwrap(e,"removeEventListener")})}this._unpatchHistoryApi()}_getZoneWithPrototype(){return window.Zone}}var esm$5=Object.freeze({__proto__:null,get AttributeNames(){return AttributeNames$2},UserInteractionInstrumentation:UserInteractionInstrumentation}),require$$11=getAugmentedNamespace(esm$5);let NoopLogger$3=class{emit(e){}};const NOOP_LOGGER$3=new NoopLogger$3;let NoopLoggerProvider$2=class{getLogger(e,t,r){return new NoopLogger$3}};const NOOP_LOGGER_PROVIDER$2=new NoopLoggerProvider$2;let ProxyLogger$2=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$3}},ProxyLoggerProvider$2=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger$2(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER$2}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const _globalThis$3="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY$2=Symbol.for("io.opentelemetry.js.api.logs"),_global$3=_globalThis$3;function makeGetter$2(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION$2=1;let LogsAPI$2=class e{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider$2}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return _global$3[GLOBAL_LOGS_API_KEY$2]?this.getLoggerProvider():(_global$3[GLOBAL_LOGS_API_KEY$2]=makeGetter$2(API_BACKWARDS_COMPATIBILITY_VERSION$2,e,NOOP_LOGGER_PROVIDER$2),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$3[GLOBAL_LOGS_API_KEY$2])||void 0===e?void 0:e.call(_global$3,API_BACKWARDS_COMPATIBILITY_VERSION$2))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$3[GLOBAL_LOGS_API_KEY$2],this._proxyLoggerProvider=new ProxyLoggerProvider$2}};const logs$3=LogsAPI$2.getInstance();let logger$3=console.error.bind(console);function defineProperty$4(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$3=(e,t,r)=>{if(!e||!e[t])return void logger$3("no original function "+String(t)+" to wrap");if(!r)return logger$3("no wrapper function"),void logger$3((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$3("original object and wrapper must be functions");const i=r(n,t);return defineProperty$4(i,"__original",n),defineProperty$4(i,"__unwrap",()=>{e[t]===i&&defineProperty$4(e,t,n)}),defineProperty$4(i,"__wrapped",!0),defineProperty$4(e,t,i),i},massWrap$2=(e,t,r)=>{if(!e)return logger$3("must provide one or more modules to patch"),void logger$3((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$3(e,t,r)})}):logger$3("must provide one or more functions to wrap on modules")},unwrap$3=(e,t)=>{if(!e||!e[t])return logger$3("no function to unwrap."),void logger$3((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$3("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap$2=(e,t)=>{if(!e)return logger$3("must provide one or more modules to patch"),void logger$3((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$3(e,t)})}):logger$3("must provide one or more functions to unwrap on modules")};let InstrumentationAbstract$2=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$3.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$3;_unwrap=unwrap$3;_massWrap=massWrap$2;_massUnwrap=massUnwrap$2;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},InstrumentationBase$2=class extends InstrumentationAbstract$2{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function safeExecuteInTheMiddle$2(e,t,r){let n,i;try{i=e()}catch(e){n=e}finally{return t(n,i),i}}function isWrapped$2(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var SemconvStability$2;function semconvStabilityFromStr$2(e,t){let r=SemconvStability$2.OLD;const n=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of n??[]){if(t.toLowerCase()===e+"/dup"){r=SemconvStability$2.DUPLICATE;break}t.toLowerCase()===e&&(r=SemconvStability$2.STABLE)}return r}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(SemconvStability$2||(SemconvStability$2={}));const _globalThis$2="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},otperformance$1=performance,NANOSECOND_DIGITS$1=9,NANOSECOND_DIGITS_IN_MILLIS$1=6,MILLISECONDS_TO_NANOSECONDS$1=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS$1),SECOND_TO_NANOSECONDS$1=Math.pow(10,NANOSECOND_DIGITS$1);function millisToHrTime$1(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS$1)]}function getTimeOrigin$1(){let e=otperformance$1.timeOrigin;if("number"!=typeof e){const t=otperformance$1;e=t.timing&&t.timing.fetchStart}return e}function hrTime$1(e){return addHrTimes$1(millisToHrTime$1(getTimeOrigin$1()),millisToHrTime$1(otperformance$1.now()))}function addHrTimes$1(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS$1&&(r[1]-=SECOND_TO_NANOSECONDS$1,r[0]+=1),r}function urlMatches$1(e,t){return"string"==typeof t?e===t:!!e.match(t)}function isUrlIgnored$1(e,t){if(!t)return!1;for(const r of t)if(urlMatches$1(e,r))return!0;return!1}var AttributeNames$1;!function(e){e.COMPONENT="component",e.HTTP_STATUS_TEXT="http.status_text"}(AttributeNames$1||(AttributeNames$1={}));var semconv={};Object.defineProperty(semconv,"__esModule",{value:!0});var ATTR_HTTP_USER_AGENT$1=semconv.ATTR_HTTP_USER_AGENT=ATTR_HTTP_URL$1=semconv.ATTR_HTTP_URL=ATTR_HTTP_STATUS_CODE$1=semconv.ATTR_HTTP_STATUS_CODE=ATTR_HTTP_SCHEME$1=semconv.ATTR_HTTP_SCHEME=semconv.ATTR_HTTP_RESPONSE_CONTENT_LENGTH=ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED$1=semconv.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=ATTR_HTTP_REQUEST_BODY_SIZE$1=semconv.ATTR_HTTP_REQUEST_BODY_SIZE=ATTR_HTTP_METHOD$1=semconv.ATTR_HTTP_METHOD=ATTR_HTTP_HOST$1=semconv.ATTR_HTTP_HOST=void 0,ATTR_HTTP_HOST$1=semconv.ATTR_HTTP_HOST="http.host",ATTR_HTTP_METHOD$1=semconv.ATTR_HTTP_METHOD="http.method",ATTR_HTTP_REQUEST_BODY_SIZE$1=semconv.ATTR_HTTP_REQUEST_BODY_SIZE="http.request.body.size",ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED$1=semconv.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED="http.request_content_length_uncompressed";semconv.ATTR_HTTP_RESPONSE_CONTENT_LENGTH="http.response_content_length";var ATTR_HTTP_SCHEME$1=semconv.ATTR_HTTP_SCHEME="http.scheme",ATTR_HTTP_STATUS_CODE$1=semconv.ATTR_HTTP_STATUS_CODE="http.status_code",ATTR_HTTP_URL$1=semconv.ATTR_HTTP_URL="http.url";ATTR_HTTP_USER_AGENT$1=semconv.ATTR_HTTP_USER_AGENT="http.user_agent";const DIAG_LOGGER$1=diag.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-fetch/utils"});function getFetchBodyLength(...e){if(e[0]instanceof URL||"string"==typeof e[0]){const t=e[1];if(!t?.body)return Promise.resolve();if(t.body instanceof ReadableStream){const{body:e,length:r}=_getBodyNonDestructively(t.body);return t.body=e,r}return Promise.resolve(getXHRBodyLength$1(t.body))}{const t=e[0];return t?.body?t.clone().text().then(e=>getByteLength$1(e)):Promise.resolve()}}function _getBodyNonDestructively(e){if(!e.pipeThrough)return DIAG_LOGGER$1.warn("Platform has ReadableStream but not pipeThrough!"),{body:e,length:Promise.resolve(void 0)};let t,r=0;const n=new Promise(e=>{t=e}),i=new TransformStream({start(){},async transform(e,t){const n=await e;r+=n.byteLength,t.enqueue(e)},flush(){t(r)}});return{body:e.pipeThrough(i),length:n}}function isDocument$1(e){return"undefined"!=typeof Document&&e instanceof Document}function getXHRBodyLength$1(e){return isDocument$1(e)?(new XMLSerializer).serializeToString(document).length:"string"==typeof e?getByteLength$1(e):e instanceof Blob?e.size:e instanceof FormData?getFormDataSize$1(e):e instanceof URLSearchParams?getByteLength$1(e.toString()):void 0!==e.byteLength?e.byteLength:void DIAG_LOGGER$1.warn("unknown body type")}const TEXT_ENCODER$1=new TextEncoder;function getByteLength$1(e){return TEXT_ENCODER$1.encode(e).byteLength}function getFormDataSize$1(e){let t=0;for(const[r,n]of e.entries())t+=r.length,n instanceof Blob?t+=n.size:t+=n.length;return t}function normalizeHttpRequestMethod$1(e){const t=getKnownMethods$1(),r=e.toUpperCase();return r in t?r:"_OTHER"}const DEFAULT_KNOWN_METHODS$1={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let knownMethods$1;function getKnownMethods$1(){return void 0===knownMethods$1&&(knownMethods$1=DEFAULT_KNOWN_METHODS$1),knownMethods$1}const HTTP_PORT_FROM_PROTOCOL$1={"https:":"443","http:":"80"};function serverPortFromUrl$1(e){const t=Number(e.port||HTTP_PORT_FROM_PROTOCOL$1[e.protocol]);return t&&!isNaN(t)?t:void 0}const VERSION$3="0.202.0",OBSERVER_WAIT_TIME_MS$1=300;class FetchInstrumentation extends InstrumentationBase$2{component="fetch";version=VERSION$3;moduleName=this.component;_usedResources=new WeakSet;_tasksCount=0;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-fetch",VERSION$3,e),this._semconvStability=semconvStabilityFromStr$2("http",e?.semconvStabilityOptIn)}init(){}_addChildSpan(e,t){const r=this.tracer.startSpan("CORS Preflight",{startTime:t[PerformanceTimingNames.FETCH_START]},trace.setSpan(context.active(),e)),n=!(this._semconvStability&SemconvStability$2.OLD);addSpanNetworkEvents(r,t,this.getConfig().ignoreNetworkEvents,void 0,n),r.end(t[PerformanceTimingNames.RESPONSE_END])}_addFinalSpanAttributes(e,t){const r=parseUrl(t.url);if(this._semconvStability&SemconvStability$2.OLD&&(e.setAttribute(ATTR_HTTP_STATUS_CODE$1,t.status),null!=t.statusText&&e.setAttribute(AttributeNames$1.HTTP_STATUS_TEXT,t.statusText),e.setAttribute(ATTR_HTTP_HOST$1,r.host),e.setAttribute(ATTR_HTTP_SCHEME$1,r.protocol.replace(":","")),"undefined"!=typeof navigator&&e.setAttribute(ATTR_HTTP_USER_AGENT$1,navigator.userAgent)),this._semconvStability&SemconvStability$2.STABLE){e.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,t.status),e.setAttribute(ATTR_SERVER_ADDRESS,r.hostname);const n=serverPortFromUrl$1(r);n&&e.setAttribute(ATTR_SERVER_PORT,n)}}_addHeaders(e,t){if(!shouldPropagateTraceHeaders(t,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return propagation.inject(context.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}if(e instanceof Request)propagation.inject(context.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else if(e.headers instanceof Headers)propagation.inject(context.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else if(e.headers instanceof Map)propagation.inject(context.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else{const t={};propagation.inject(context.active(),t),e.headers=Object.assign({},t,e.headers||{})}}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(performance.clearResourceTimings(),this._usedResources=new WeakSet)}_createSpan(e,t={}){if(isUrlIgnored$1(e,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let r="";const n={};if(this._semconvStability&SemconvStability$2.OLD){const i=(t.method||"GET").toUpperCase();r=`HTTP ${i}`,n[AttributeNames$1.COMPONENT]=this.moduleName,n[ATTR_HTTP_METHOD$1]=i,n[ATTR_HTTP_URL$1]=e}if(this._semconvStability&SemconvStability$2.STABLE){const i=t.method,o=normalizeHttpRequestMethod$1(t.method||"GET");r||(r=o),n[ATTR_HTTP_REQUEST_METHOD]=o,o!==i&&(n[ATTR_HTTP_REQUEST_METHOD_ORIGINAL]=i),n[ATTR_URL_FULL]=e}return this.tracer.startSpan(r,{kind:SpanKind.CLIENT,attributes:n})}_findResourceAndAddNetworkEvents(e,t,r){let n=t.entries;if(!n.length){if(!performance.getEntriesByType)return;n=performance.getEntriesByType("resource")}const i=getResource(t.spanUrl,t.startTime,r,n,this._usedResources,"fetch");if(i.mainRequest){const t=i.mainRequest;this._markResourceAsUsed(t);const r=i.corsPreFlightRequest;r&&(this._addChildSpan(e,r),this._markResourceAsUsed(r));const n=!(this._semconvStability&SemconvStability$2.OLD);addSpanNetworkEvents(e,t,this.getConfig().ignoreNetworkEvents,void 0,n)}}_markResourceAsUsed(e){this._usedResources.add(e)}_endSpan(e,t,r){const n=millisToHrTime$1(Date.now()),i=hrTime$1();this._addFinalSpanAttributes(e,r),this._semconvStability&SemconvStability$2.STABLE&&r.status>=400&&(e.setStatus({code:SpanStatusCode.ERROR}),e.setAttribute(ATTR_ERROR_TYPE,String(r.status))),setTimeout(()=>{t.observer?.disconnect(),this._findResourceAndAddNetworkEvents(e,t,i),this._tasksCount--,this._clearResources(),e.end(n)},OBSERVER_WAIT_TIME_MS$1)}_patchConstructor(){return e=>{const t=this;return function(...r){const n=this,i=parseUrl(r[0]instanceof Request?r[0].url:String(r[0])).href,o=r[0]instanceof Request?r[0]:r[1]||{},s=t._createSpan(i,o);if(!s)return e.apply(this,r);const a=t._prepareSpanData(i);function c(e,r){t._applyAttributesAfterFetch(e,o,r),t._endSpan(e,a,{status:r.status||0,statusText:r.message,url:i})}function l(e,r){t._applyAttributesAfterFetch(e,o,r),r.status>=200&&r.status<400?t._endSpan(e,a,r):t._endSpan(e,a,{status:r.status,statusText:r.statusText,url:i})}function u(e,t,r){try{const t=r.clone().body;if(t){const n=t.getReader(),i=()=>{n.read().then(({done:t})=>{t?l(e,r):i()},t=>{c(e,t)})};i()}else l(e,r)}finally{t(r)}}function d(e,t,r){try{c(e,r)}finally{t(r)}}return t.getConfig().measureRequestSize&&getFetchBodyLength(...r).then(e=>{e&&(t._semconvStability&SemconvStability$2.OLD&&s.setAttribute(ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED$1,e),t._semconvStability&SemconvStability$2.STABLE&&s.setAttribute(ATTR_HTTP_REQUEST_BODY_SIZE$1,e))}).catch(e=>{t._diag.warn("getFetchBodyLength",e)}),new Promise((r,a)=>context.with(trace.setSpan(context.active(),s),()=>(t._addHeaders(o,i),t._callRequestHook(s,o),t._tasksCount++,e.apply(n,o instanceof Request?[o]:[i,o]).then(u.bind(n,s,r),d.bind(n,s,a)))))}}}_applyAttributesAfterFetch(e,t,r){const n=this.getConfig().applyCustomAttributesOnSpan;n&&safeExecuteInTheMiddle$2(()=>n(e,t,r),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)})}_callRequestHook(e,t){const r=this.getConfig().requestHook;r&&safeExecuteInTheMiddle$2(()=>r(e,t),e=>{e&&this._diag.error("requestHook",e)})}_prepareSpanData(e){const t=hrTime$1(),r=[];if("function"!=typeof PerformanceObserver)return{entries:r,startTime:t,spanUrl:e};const n=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{"fetch"===t.initiatorType&&t.name===e&&r.push(t)})});return n.observe({entryTypes:["resource"]}),{entries:r,observer:n,startTime:t,spanUrl:e}}enable(){isWrapped$2(fetch)&&(this._unwrap(_globalThis$2,"fetch"),this._diag.debug("removing previous patch for constructor")),this._wrap(_globalThis$2,"fetch",this._patchConstructor())}disable(){this._unwrap(_globalThis$2,"fetch"),this._usedResources=new WeakSet}}var esm$4=Object.freeze({__proto__:null,FetchInstrumentation:FetchInstrumentation}),require$$12=getAugmentedNamespace(esm$4);let NoopLogger$2=class{emit(e){}};const NOOP_LOGGER$2=new NoopLogger$2;let NoopLoggerProvider$1=class{getLogger(e,t,r){return new NoopLogger$2}};const NOOP_LOGGER_PROVIDER$1=new NoopLoggerProvider$1;let ProxyLogger$1=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$2}},ProxyLoggerProvider$1=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger$1(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER$1}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const _globalThis$1="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY$1=Symbol.for("io.opentelemetry.js.api.logs"),_global$2=_globalThis$1;function makeGetter$1(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION$1=1;let LogsAPI$1=class e{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider$1}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return _global$2[GLOBAL_LOGS_API_KEY$1]?this.getLoggerProvider():(_global$2[GLOBAL_LOGS_API_KEY$1]=makeGetter$1(API_BACKWARDS_COMPATIBILITY_VERSION$1,e,NOOP_LOGGER_PROVIDER$1),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$2[GLOBAL_LOGS_API_KEY$1])||void 0===e?void 0:e.call(_global$2,API_BACKWARDS_COMPATIBILITY_VERSION$1))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$2[GLOBAL_LOGS_API_KEY$1],this._proxyLoggerProvider=new ProxyLoggerProvider$1}};const logs$2=LogsAPI$1.getInstance();let logger$2=console.error.bind(console);function defineProperty$3(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$2=(e,t,r)=>{if(!e||!e[t])return void logger$2("no original function "+String(t)+" to wrap");if(!r)return logger$2("no wrapper function"),void logger$2((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$2("original object and wrapper must be functions");const i=r(n,t);return defineProperty$3(i,"__original",n),defineProperty$3(i,"__unwrap",()=>{e[t]===i&&defineProperty$3(e,t,n)}),defineProperty$3(i,"__wrapped",!0),defineProperty$3(e,t,i),i},massWrap$1=(e,t,r)=>{if(!e)return logger$2("must provide one or more modules to patch"),void logger$2((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$2(e,t,r)})}):logger$2("must provide one or more functions to wrap on modules")},unwrap$2=(e,t)=>{if(!e||!e[t])return logger$2("no function to unwrap."),void logger$2((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$2("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap$1=(e,t)=>{if(!e)return logger$2("must provide one or more modules to patch"),void logger$2((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$2(e,t)})}):logger$2("must provide one or more functions to unwrap on modules")};let InstrumentationAbstract$1=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$2.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$2;_unwrap=unwrap$2;_massWrap=massWrap$1;_massUnwrap=massUnwrap$1;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},InstrumentationBase$1=class extends InstrumentationAbstract$1{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function safeExecuteInTheMiddle$1(e,t,r){let n,i;try{i=e()}catch(e){n=e}finally{return t(n,i),i}}function isWrapped$1(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var SemconvStability$1;function semconvStabilityFromStr$1(e,t){let r=SemconvStability$1.OLD;const n=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of n??[]){if(t.toLowerCase()===e+"/dup"){r=SemconvStability$1.DUPLICATE;break}t.toLowerCase()===e&&(r=SemconvStability$1.STABLE)}return r}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(SemconvStability$1||(SemconvStability$1={}));const otperformance=performance,NANOSECOND_DIGITS=9,NANOSECOND_DIGITS_IN_MILLIS=6,MILLISECONDS_TO_NANOSECONDS=Math.pow(10,NANOSECOND_DIGITS_IN_MILLIS),SECOND_TO_NANOSECONDS=Math.pow(10,NANOSECOND_DIGITS);function millisToHrTime(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*MILLISECONDS_TO_NANOSECONDS)]}function getTimeOrigin(){let e=otperformance.timeOrigin;if("number"!=typeof e){const t=otperformance;e=t.timing&&t.timing.fetchStart}return e}function hrTime(e){return addHrTimes(millisToHrTime(getTimeOrigin()),millisToHrTime(otperformance.now()))}function addHrTimes(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=SECOND_TO_NANOSECONDS&&(r[1]-=SECOND_TO_NANOSECONDS,r[0]+=1),r}function urlMatches(e,t){return"string"==typeof t?e===t:!!e.match(t)}function isUrlIgnored(e,t){if(!t)return!1;for(const r of t)if(urlMatches(e,r))return!0;return!1}const ATTR_HTTP_HOST="http.host",ATTR_HTTP_METHOD="http.method",ATTR_HTTP_REQUEST_BODY_SIZE="http.request.body.size",ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED="http.request_content_length_uncompressed",ATTR_HTTP_SCHEME="http.scheme",ATTR_HTTP_STATUS_CODE="http.status_code",ATTR_HTTP_URL="http.url",ATTR_HTTP_USER_AGENT="http.user_agent";var EventNames;!function(e){e.METHOD_OPEN="open",e.METHOD_SEND="send",e.EVENT_ABORT="abort",e.EVENT_ERROR="error",e.EVENT_LOAD="loaded",e.EVENT_TIMEOUT="timeout"}(EventNames||(EventNames={}));const DIAG_LOGGER=diag.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-xml-http-request/utils"});function isDocument(e){return"undefined"!=typeof Document&&e instanceof Document}function getXHRBodyLength(e){return isDocument(e)?(new XMLSerializer).serializeToString(document).length:"string"==typeof e?getByteLength(e):e instanceof Blob?e.size:e instanceof FormData?getFormDataSize(e):e instanceof URLSearchParams?getByteLength(e.toString()):void 0!==e.byteLength?e.byteLength:void DIAG_LOGGER.warn("unknown body type")}const TEXT_ENCODER=new TextEncoder;function getByteLength(e){return TEXT_ENCODER.encode(e).byteLength}function getFormDataSize(e){let t=0;for(const[r,n]of e.entries())t+=r.length,n instanceof Blob?t+=n.size:t+=n.length;return t}function normalizeHttpRequestMethod(e){const t=getKnownMethods(),r=e.toUpperCase();return r in t?r:"_OTHER"}const DEFAULT_KNOWN_METHODS={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let knownMethods;function getKnownMethods(){return void 0===knownMethods&&(knownMethods=DEFAULT_KNOWN_METHODS),knownMethods}const HTTP_PORT_FROM_PROTOCOL={"https:":"443","http:":"80"};function serverPortFromUrl(e){const t=Number(e.port||HTTP_PORT_FROM_PROTOCOL[e.protocol]);return t&&!isNaN(t)?t:void 0}const VERSION$2="0.202.0";var AttributeNames;!function(e){e.HTTP_STATUS_TEXT="http.status_text"}(AttributeNames||(AttributeNames={}));const OBSERVER_WAIT_TIME_MS=300;class XMLHttpRequestInstrumentation extends InstrumentationBase$1{component="xml-http-request";version=VERSION$2;moduleName=this.component;_tasksCount=0;_xhrMem=new WeakMap;_usedResources=new WeakSet;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-xml-http-request",VERSION$2,e),this._semconvStability=semconvStabilityFromStr$1("http",e?.semconvStabilityOptIn)}init(){}_addHeaders(e,t){if(!shouldPropagateTraceHeaders(parseUrl(t).href,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return propagation.inject(context.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}const r={};propagation.inject(context.active(),r),Object.keys(r).forEach(t=>{e.setRequestHeader(t,String(r[t]))})}_addChildSpan(e,t){context.with(trace.setSpan(context.active(),e),()=>{const e=this.tracer.startSpan("CORS Preflight",{startTime:t[PerformanceTimingNames.FETCH_START]}),r=!(this._semconvStability&SemconvStability$1.OLD);addSpanNetworkEvents(e,t,this.getConfig().ignoreNetworkEvents,void 0,r),e.end(t[PerformanceTimingNames.RESPONSE_END])})}_addFinalSpanAttributes(e,t,r){if(this._semconvStability&SemconvStability$1.OLD){if(void 0!==t.status&&e.setAttribute(ATTR_HTTP_STATUS_CODE,t.status),void 0!==t.statusText&&e.setAttribute(AttributeNames.HTTP_STATUS_TEXT,t.statusText),"string"==typeof r){const t=parseUrl(r);e.setAttribute(ATTR_HTTP_HOST,t.host),e.setAttribute(ATTR_HTTP_SCHEME,t.protocol.replace(":",""))}e.setAttribute(ATTR_HTTP_USER_AGENT,navigator.userAgent)}this._semconvStability&SemconvStability$1.STABLE&&t.status&&e.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE,t.status)}_applyAttributesAfterXHR(e,t){const r=this.getConfig().applyCustomAttributesOnSpan;"function"==typeof r&&safeExecuteInTheMiddle$1(()=>r(e,t),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)})}_addResourceObserver(e,t){const r=this._xhrMem.get(e);r&&"function"==typeof PerformanceObserver&&"function"==typeof PerformanceResourceTiming&&(r.createdResources={observer:new PerformanceObserver(e=>{const n=e.getEntries(),i=parseUrl(t);n.forEach(e=>{"xmlhttprequest"===e.initiatorType&&e.name===i.href&&r.createdResources&&r.createdResources.entries.push(e)})}),entries:[]},r.createdResources.observer.observe({entryTypes:["resource"]}))}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(otperformance.clearResourceTimings(),this._xhrMem=new WeakMap,this._usedResources=new WeakSet)}_findResourceAndAddNetworkEvents(e,t,r,n,i){if(!(r&&n&&i&&e.createdResources))return;let o=e.createdResources.entries;o&&o.length||(o=otperformance.getEntriesByType("resource"));const s=getResource(parseUrl(r).href,n,i,o,this._usedResources);if(s.mainRequest){const e=s.mainRequest;this._markResourceAsUsed(e);const r=s.corsPreFlightRequest;r&&(this._addChildSpan(t,r),this._markResourceAsUsed(r));const n=!(this._semconvStability&SemconvStability$1.OLD);addSpanNetworkEvents(t,e,this.getConfig().ignoreNetworkEvents,void 0,n)}}_cleanPreviousSpanInformation(e){const t=this._xhrMem.get(e);if(t){const r=t.callbackToRemoveEvents;r&&r(),this._xhrMem.delete(e)}}_createSpan(e,t,r){if(isUrlIgnored(t,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let n="";const i=parseUrl(t),o={};if(this._semconvStability&SemconvStability$1.OLD&&(n=r.toUpperCase(),o[ATTR_HTTP_METHOD]=r,o[ATTR_HTTP_URL]=i.toString()),this._semconvStability&SemconvStability$1.STABLE){const e=r,t=normalizeHttpRequestMethod(r);n||(n=t),o[ATTR_HTTP_REQUEST_METHOD]=t,t!==e&&(o[ATTR_HTTP_REQUEST_METHOD_ORIGINAL]=e),o[ATTR_URL_FULL]=i.toString(),o[ATTR_SERVER_ADDRESS]=i.hostname;const s=serverPortFromUrl(i);s&&(o[ATTR_SERVER_PORT]=s)}const s=this.tracer.startSpan(n,{kind:SpanKind.CLIENT,attributes:o});return s.addEvent(EventNames.METHOD_OPEN),this._cleanPreviousSpanInformation(e),this._xhrMem.set(e,{span:s,spanUrl:t}),s}_markResourceAsUsed(e){this._usedResources.add(e)}_patchOpen(){return e=>{const t=this;return function(...r){const n=r[0],i=r[1];return t._createSpan(this,i,n),e.apply(this,r)}}}_patchSend(){const e=this;function t(t,r,n,i){const o=e._xhrMem.get(r);if(!o)return;if(o.status=r.status,o.statusText=r.statusText,e._xhrMem.delete(r),o.span){const t=o.span;e._applyAttributesAfterXHR(t,r),e._semconvStability&SemconvStability$1.STABLE&&(n?i&&(t.setStatus({code:SpanStatusCode.ERROR,message:i}),t.setAttribute(ATTR_ERROR_TYPE,i)):o.status&&o.status>=400&&(t.setStatus({code:SpanStatusCode.ERROR}),t.setAttribute(ATTR_ERROR_TYPE,String(o.status))))}const s=hrTime(),a=Date.now();setTimeout(()=>{!function(t,r,n,i){const o=r.callbackToRemoveEvents;"function"==typeof o&&o();const{span:s,spanUrl:a,sendStartTime:c}=r;s&&(e._findResourceAndAddNetworkEvents(r,s,a,c,n),s.addEvent(t,i),e._addFinalSpanAttributes(s,r,a),s.end(i),e._tasksCount--),e._clearResources()}(t,o,s,a)},OBSERVER_WAIT_TIME_MS)}function r(){t(EventNames.EVENT_ERROR,this,!0,"error")}function n(){t(EventNames.EVENT_ABORT,this,!1)}function i(){t(EventNames.EVENT_TIMEOUT,this,!0,"timeout")}function o(){this.status<299?t(EventNames.EVENT_LOAD,this,!1):t(EventNames.EVENT_ERROR,this,!1)}return t=>function(...s){const a=e._xhrMem.get(this);if(!a)return t.apply(this,s);const c=a.span,l=a.spanUrl;if(c&&l){if(e.getConfig().measureRequestSize&&s?.[0]){const t=getXHRBodyLength(s[0]);void 0!==t&&(e._semconvStability&SemconvStability$1.OLD&&c.setAttribute(ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,t),e._semconvStability&SemconvStability$1.STABLE&&c.setAttribute(ATTR_HTTP_REQUEST_BODY_SIZE,t))}context.with(trace.setSpan(context.active(),c),()=>{e._tasksCount++,a.sendStartTime=hrTime(),c.addEvent(EventNames.METHOD_SEND),this.addEventListener("abort",n),this.addEventListener("error",r),this.addEventListener("load",o),this.addEventListener("timeout",i),a.callbackToRemoveEvents=()=>{!function(t){t.removeEventListener("abort",n),t.removeEventListener("error",r),t.removeEventListener("load",o),t.removeEventListener("timeout",i);const s=e._xhrMem.get(t);s&&(s.callbackToRemoveEvents=void 0)}(this),a.createdResources&&a.createdResources.observer.disconnect()},e._addHeaders(this,l),e._addResourceObserver(this,l)})}return t.apply(this,s)}}enable(){this._diag.debug("applying patch to",this.moduleName,this.version),isWrapped$1(XMLHttpRequest.prototype.open)&&(this._unwrap(XMLHttpRequest.prototype,"open"),this._diag.debug("removing previous patch from method open")),isWrapped$1(XMLHttpRequest.prototype.send)&&(this._unwrap(XMLHttpRequest.prototype,"send"),this._diag.debug("removing previous patch from method send")),this._wrap(XMLHttpRequest.prototype,"open",this._patchOpen()),this._wrap(XMLHttpRequest.prototype,"send",this._patchSend())}disable(){this._diag.debug("removing patch from",this.moduleName,this.version),this._unwrap(XMLHttpRequest.prototype,"open"),this._unwrap(XMLHttpRequest.prototype,"send"),this._tasksCount=0,this._xhrMem=new WeakMap,this._usedResources=new WeakSet}}var esm$3=Object.freeze({__proto__:null,XMLHttpRequestInstrumentation:XMLHttpRequestInstrumentation}),require$$13=getAugmentedNamespace(esm$3);let NoopLogger$1=class{emit(e){}};const NOOP_LOGGER$1=new NoopLogger$1;class NoopLoggerProvider{getLogger(e,t,r){return new NoopLogger$1}}const NOOP_LOGGER_PROVIDER=new NoopLoggerProvider;class ProxyLogger{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):NOOP_LOGGER$1}}class ProxyLoggerProvider{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new ProxyLogger(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:NOOP_LOGGER_PROVIDER}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}}const _globalThis="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},GLOBAL_LOGS_API_KEY=Symbol.for("io.opentelemetry.js.api.logs"),_global$1=_globalThis;function makeGetter(e,t,r){return n=>n===e?t:r}const API_BACKWARDS_COMPATIBILITY_VERSION=1;class LogsAPI{constructor(){this._proxyLoggerProvider=new ProxyLoggerProvider}static getInstance(){return this._instance||(this._instance=new LogsAPI),this._instance}setGlobalLoggerProvider(e){return _global$1[GLOBAL_LOGS_API_KEY]?this.getLoggerProvider():(_global$1[GLOBAL_LOGS_API_KEY]=makeGetter(API_BACKWARDS_COMPATIBILITY_VERSION,e,NOOP_LOGGER_PROVIDER),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return null!==(t=null===(e=_global$1[GLOBAL_LOGS_API_KEY])||void 0===e?void 0:e.call(_global$1,API_BACKWARDS_COMPATIBILITY_VERSION))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete _global$1[GLOBAL_LOGS_API_KEY],this._proxyLoggerProvider=new ProxyLoggerProvider}}const logs$1=LogsAPI.getInstance();function enableInstrumentations(e,t,r,n){for(let i=0,o=e.length;ie.disable())}function registerInstrumentations(e){const t=e.tracerProvider||trace.getTracerProvider(),r=e.meterProvider||metrics$1.getMeterProvider(),n=e.loggerProvider||logs$1.getLoggerProvider(),i=e.instrumentations?.flat()??[];return enableInstrumentations(i,t,r,n),()=>{disableInstrumentations(i)}}let logger$1=console.error.bind(console);function defineProperty$2(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const wrap$1=(e,t,r)=>{if(!e||!e[t])return void logger$1("no original function "+String(t)+" to wrap");if(!r)return logger$1("no wrapper function"),void logger$1((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void logger$1("original object and wrapper must be functions");const i=r(n,t);return defineProperty$2(i,"__original",n),defineProperty$2(i,"__unwrap",()=>{e[t]===i&&defineProperty$2(e,t,n)}),defineProperty$2(i,"__wrapped",!0),defineProperty$2(e,t,i),i},massWrap=(e,t,r)=>{if(!e)return logger$1("must provide one or more modules to patch"),void logger$1((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{wrap$1(e,t,r)})}):logger$1("must provide one or more functions to wrap on modules")},unwrap$1=(e,t)=>{if(!e||!e[t])return logger$1("no function to unwrap."),void logger$1((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():logger$1("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},massUnwrap=(e,t)=>{if(!e)return logger$1("must provide one or more modules to patch"),void logger$1((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{unwrap$1(e,t)})}):logger$1("must provide one or more functions to unwrap on modules")};class InstrumentationAbstract{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=diag.createComponentLogger({namespace:e}),this._tracer=trace.getTracer(e,t),this._meter=metrics$1.getMeter(e,t),this._logger=logs$1.getLogger(e,t),this._updateMetricInstruments()}_wrap=wrap$1;_unwrap=unwrap$1;_massWrap=massWrap;_massUnwrap=massUnwrap;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}}class InstrumentationBase extends InstrumentationAbstract{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}}function normalize(e){return diag.warn("Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)"),e}class InstrumentationNodeModuleDefinition{name;supportedVersions;patch;unpatch;files;constructor(e,t,r,n,i){this.name=e,this.supportedVersions=t,this.patch=r,this.unpatch=n,this.files=i||[]}}class InstrumentationNodeModuleFile{supportedVersions;patch;unpatch;name;constructor(e,t,r,n){this.supportedVersions=t,this.patch=r,this.unpatch=n,this.name=normalize(e)}}function safeExecuteInTheMiddle(e,t,r){let n,i;try{i=e()}catch(e){n=e}finally{if(t(n,i),n&&!r)throw n;return i}}async function safeExecuteInTheMiddleAsync(e,t,r){let n,i;try{i=await e()}catch(e){n=e}finally{if(t(n,i),n&&!r)throw n;return i}}function isWrapped(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var SemconvStability;function semconvStabilityFromStr(e,t){let r=SemconvStability.OLD;const n=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of n??[]){if(t.toLowerCase()===e+"/dup"){r=SemconvStability.DUPLICATE;break}t.toLowerCase()===e&&(r=SemconvStability.STABLE)}return r}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(SemconvStability||(SemconvStability={}));var esm$2=Object.freeze({__proto__:null,InstrumentationBase:InstrumentationBase,InstrumentationNodeModuleDefinition:InstrumentationNodeModuleDefinition,InstrumentationNodeModuleFile:InstrumentationNodeModuleFile,get SemconvStability(){return SemconvStability},isWrapped:isWrapped,registerInstrumentations:registerInstrumentations,safeExecuteInTheMiddle:safeExecuteInTheMiddle,safeExecuteInTheMiddleAsync:safeExecuteInTheMiddleAsync,semconvStabilityFromStr:semconvStabilityFromStr}),require$$14=getAugmentedNamespace(esm$2),__createBinding=commonjsGlobal$1&&commonjsGlobal$1.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),__setModuleDefault=commonjsGlobal$1&&commonjsGlobal$1.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=commonjsGlobal$1&&commonjsGlobal$1.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&__createBinding(t,e,r);return __setModuleDefault(t,e),t},__awaiter=commonjsGlobal$1&&commonjsGlobal$1.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},__importDefault=commonjsGlobal$1&&commonjsGlobal$1.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(manager$2,"__esModule",{value:!0}),manager$2.TracesManager=void 0;const api_1$1=require$$13$1,utils_1=requireUtils(),manager_1$2=manager$1,tracingState_1=tracingState,withSpan_1=withSpan,nullTracingState_1=__importDefault(nullTracingState),traces_1=__importStar(requireTraces()),constants_1$1=constants$3,otelUtils_1$1=otelUtils,safe_stringify_1$3=safeStringify$1,instrumentation_document_load_1=require$$10,instrumentation_user_interaction_1=require$$11,instrumentation_fetch_1=require$$12,instrumentation_xml_http_request_1=require$$13,instrumentation_1=require$$14,container_1$3=container$1;class TracesManager{constructor(e,t,r,n,i,o,s,a,c,l,u){var d,h,p,g,m,f;this.otelSettings=e,this.logger=t,this.traceLogger=r,this.started=!1,this.traceLogger=null!==(d=this.traceLogger)&&void 0!==d?d:this.logger,this.settings=e.traces||{enabled:!1},!1!==e.logSettingsOnStartup&&(null==t||t.info(`Starting TracesManager with settings ${(0,safe_stringify_1$3.safeStringify)(this.settings)}`)),this.filters=this.settings.filters||[];if((new manager_1$2.TracesManagerValidator).validate(this),(0,utils_1.setTracerProvider)(n,i,o,s,a,c,l,this.logger,e),this.settings.autoInstrumentations){const e=this.settings.autoInstrumentations,t="object"==typeof e.documentLoad?e.documentLoad:void 0,r="object"==typeof e.userInteraction?e.userInteraction:void 0,n="object"==typeof e.fetch?e.fetch:void 0,i="object"==typeof e.xhr?e.xhr:void 0;(0,instrumentation_1.registerInstrumentations)({instrumentations:[e.documentLoad&&new instrumentation_document_load_1.DocumentLoadInstrumentation(t),e.userInteraction&&new instrumentation_user_interaction_1.UserInteractionInstrumentation(Object.assign(Object.assign({eventNames:["submit","click","keypress"]},r),{shouldPreventSpanCreation:(e,t,n)=>{var i;return n.setAttribute("target.id",t.id),null===(i=null==r?void 0:r.shouldPreventSpanCreation)||void 0===i?void 0:i.call(r,e,t,n)}})),e.fetch&&new instrumentation_fetch_1.FetchInstrumentation(n),e.xhr&&new instrumentation_xml_http_request_1.XMLHttpRequestInstrumentation(Object.assign(Object.assign({},i),{ignoreUrls:!1!==e.ignoreObservabilityUrls?[...(null==i?void 0:i.ignoreUrls)||[],this.settings.url,null===(h=this.otelSettings.metrics)||void 0===h?void 0:h.url,null===(p=this.otelSettings.logs)||void 0===p?void 0:p.url].filter(e=>e):null==i?void 0:i.ignoreUrls}))].filter(e=>e)})}traces_1.default.instance=this,null!==this.settings.countMetric&&(this.traceMetric=null==u?void 0:u.getFromSettings({enabled:!0,description:"Counts number of hits for io.Insights spans",name:null!==(g=this.settings.countMetric)&&void 0!==g?g:"insights_trace_count",type:"custom_counter"})),null!==this.settings.resultMetric&&(this.traceMetricResult=null==u?void 0:u.getFromSettings({enabled:!0,description:"Counts results of io.Insights spans",name:null!==(m=this.settings.resultMetric)&&void 0!==m?m:"insights_trace_result",type:"custom_counter"})),null!==this.settings.durationMetric&&(this.traceMetricDuration=null==u?void 0:u.getFromSettings({enabled:!0,description:"Counts durations of io.Insights spans",name:null!==(f=this.settings.durationMetric)&&void 0!==f?f:"insights_trace_duration",type:"custom_histogram"}))}waitForFinalExport(e){return Promise.resolve()}get currentTracingState(){return this.resolveCurrentTracingState()}set currentTracingState(e){traces_1.default.currentTracingState=e}resolveCurrentTracingState(){if(this.settings.useOTELContextManager){const e=api_1$1.context.active(),t=null==e?void 0:e.getValue(Symbol.for("interopio.insights.currentTracingStateGetter"));return"function"==typeof t?t():null}return(0,traces_1.getCurrentTracingStateInternal)()}withSpan(e,t,r,n,i){var o,s,a,c,l,u,d,h,p,g,m,f;(new withSpan_1.TracesWithSpanValidator).validate(e,t,r,n,i);let y={};(0,utils_1.isFunctionType)(t)||(y=Object.assign({},t));const $=Object.assign(Object.assign({},container_1$3.Container.errorless(this.settings.additionalAttributes)),y),b=Object.assign(Object.assign({},container_1$3.Container.errorless(this.settings.additionalResourceAttributes)),$),v=n,w=this.filters.concat((!1!==this.settings.useDefaultFilters&&null!==(o=null==v?void 0:v.defaultFilters)&&void 0!==o?o:[]).map(t=>Object.assign(Object.assign({},t),{source:e}))),S=(0,utils_1.findMatchingFilters)(w,b,e);null===(s=this.logger)||void 0===s||s.debug(`beginSpan() source:${e} context:${b} `+(S?"filter: "+JSON.stringify(S):"default: "+JSON.stringify(this.settings.defaults)));let _=api_1$1.context.active(),E=null;!0!==(null==S?void 0:S.disableNesting)&&!0!==(null==v?void 0:v.disableNesting)&&(E||r&&"function"!=typeof r&&(E=traces_1.default.extractPropagationInfo(r)),E||"function"!=typeof(null==v?void 0:v.getPropagationInfo)||(E=null==v?void 0:v.getPropagationInfo(e,b)),E||"function"!=typeof(null===(c=null===(a=this.settings)||void 0===a?void 0:a.defaults)||void 0===c?void 0:c.getPropagationInfo)||(E=null===(u=null===(l=this.settings)||void 0===l?void 0:l.defaults)||void 0===u?void 0:u.getPropagationInfo(e,b)),E||(traces_1.default.currentTracingState&&!0!==this.settings.useOTELContextManager?E=traces_1.default.currentTracingState.getPropagationInfo():this.settings.useOTELContextManager&&(E=(null===(d=this.resolveCurrentTracingState())||void 0===d?void 0:d.getPropagationInfo())||null))),_=E?api_1$1.propagation.extract(api_1$1.context.active(),E):api_1$1.ROOT_CONTEXT;const C=this.resolveProperty("canBeRoot",S,v),I=this.started&&((null==E?void 0:E.forceTracing)||(0,utils_1.isSpanEnabled)(S,v,this.settings.defaults))&&(C||!!E),T=I&&(null!==(h=null==E?void 0:E.forceTracing)&&void 0!==h?h:this.resolveProperty("forceChildTracing",S,v)),A=this.resolveProperty("level",S,v),D=this.resolveProperty(I?"countMetric":"countMetricOnDisabledSpans",S,v),x=this.resolveProperty("maxAttributeDepth",S,v);D&&(null===(g=null===(p=this.traceMetric)||void 0===p?void 0:p.add)||void 0===g||g.call(p,1,Object.assign({source:e},(0,otelUtils_1$1.flattenOtelAtributes)($,x))));const R=this.resolveProperty(I?"resultMetric":"resultMetricOnDisabledSpans",S,v),O=this.resolveProperty(I?"durationMetric":"durationMetricOnDisabledSpans",S,v),N=this.resolveProperty(I?"log":"logOnDisabledSpans",S,v),P=this.resolveProperty("minDurationMs",S,v);let k;if(null===(m=this.logger)||void 0===m||m.debug(JSON.stringify({started:this.started,enabled:I,level:A})),"function"==typeof t)k=i=t;else if("function"==typeof r)k=i=r;else if("function"==typeof n)k=i=n;else{if(!i)throw new Error("callback agument must be provided");k=i}const M=this.resolveProperty("disablePropagation",S,v);if(I){const t=api_1$1.trace.getTracer(e);let r=null;_=_.setValue(Symbol.for(constants_1$1.Defaults.currentTracingStateGetterContextName),()=>r);const n=this.resolveProperty("otelSpanOptions",S,v);return t.startActiveSpan(e,n,_,t=>{r=new tracingState_1.TracingState(e,A,t,this.logger,constants_1$1.Defaults.TRACE_VERSION,M,T,x,_),P&&(0,utils_1.saveDataInAttribute)({insightsMinDurationMs:P},t,x),this.otelSettings.platformVersion&&(0,utils_1.saveDataInAttribute)({platformVersion:this.otelSettings.platformVersion},t,x),this.otelSettings.additionalAttributes&&(0,utils_1.saveDataInAttribute)(container_1$3.Container.errorlessDefined(this.otelSettings.additionalAttributes,{}),t,x),this.settings.additionalAttributes&&(0,utils_1.saveDataInAttribute)(container_1$3.Container.errorlessDefined(this.settings.additionalAttributes,{}),t,x);return this.resolveProperty("addContextToTrace",S,v)&&(0,utils_1.saveDataInAttribute)($,t,x),this.handleCallbackAndResult(r,k,S,v,R,O,N,$,x)})}{let t=null;if(!this.resolveProperty("stopPropagationIfSpanIsDisabled",S,v))if(r){let e={};(0,utils_1.isFunctionType)(r)||(e=Object.assign({},r)),t=traces_1.default.extractPropagationInfo(e)}else traces_1.default.currentTracingState&&!0!==this.settings.useOTELContextManager?t=traces_1.default.currentTracingState.getPropagationInfo():this.settings.useOTELContextManager&&(E=(null===(f=this.resolveCurrentTracingState())||void 0===f?void 0:f.getPropagationInfo())||null);const n=new nullTracingState_1.default(e,t,M);return _=_.setValue(Symbol.for(constants_1$1.Defaults.currentTracingStateGetterContextName),()=>n),api_1$1.context.with(_,()=>this.handleCallbackAndResult(n,k,S,v,R,O,N,$,x))}}handleCallbackAndResult(e,t,r,n,i,o,s,a,c){var l,u,d,h,p;const g=new Date,m=null===(p=null!==(u=null!==(l=null==r?void 0:r.autoSetSuccessStatus)&&void 0!==l?l:null==n?void 0:n.addContextToTrace)&&void 0!==u?u:null===(h=null===(d=this.settings)||void 0===d?void 0:d.defaults)||void 0===h?void 0:h.autoSetSuccessStatus)||void 0===p||p;let f;try{traces_1.default.currentTracingState=e;const r=t(e);return traces_1.default.currentTracingState=null,f=r&&"function"==typeof r.then&&"function"==typeof r.catch&&"function"==typeof r.finally,f?r.then(y.bind(this)).catch($.bind(this)).finally(b.bind(this)):y.apply(this,[r])}catch(e){$.call(this,e)}finally{f||b.apply(this)}function y(t){var r;return m&&(null===(r=e.status)||void 0===r?void 0:r.code)===api_1$1.SpanStatusCode.UNSET&&(e.status={code:api_1$1.SpanStatusCode.OK}),t}function $(t){throw e.status={message:"string"==typeof t?t:null==t?void 0:t.message,code:api_1$1.SpanStatusCode.ERROR},e.recordException(t),t}function b(){var t,r,n,l,u,d,h,p,m,f,y,$,b,v,w,S;if(i&&(null===(r=null===(t=this.traceMetricResult)||void 0===t?void 0:t.add)||void 0===r||r.call(t,1,Object.assign(Object.assign({source:e.source},(0,otelUtils_1$1.flattenOtelAtributes)(a,c)),{code:e.status.code}))),o&&(null===(l=null===(n=this.traceMetricDuration)||void 0===n?void 0:n.record)||void 0===l||l.call(n,(new Date).getTime()-g.getTime(),Object.assign({source:e.source},(0,otelUtils_1$1.flattenOtelAtributes)(a,c)))),e.end(),s){let t="none";switch(e.level){case"OFF":t="none";break;case"LOWEST":case"DIAGNOSTIC":t="verbose";break;case"DEBUG":t="debug";break;case"INFO":t="info";break;case"WARN":t="warn";break;case"HIGHEST":t="error"}if("none"!==t){const r=null!==(h=null===(d=null===(u=null==e?void 0:e.span)||void 0===u?void 0:u.parentSpanContext)||void 0===d?void 0:d.spanId)&&void 0!==h?h:"0000000000000000",n=`${e.traceId}-${e.id}-${r}`,i=1e3*(null===(m=null===(p=e.span)||void 0===p?void 0:p.endTime)||void 0===m?void 0:m[0])+(null===(y=null===(f=e.span)||void 0===f?void 0:f.endTime)||void 0===y?void 0:y[1])/1e6-1e3*(null===(b=null===($=e.span)||void 0===$?void 0:$.startTime)||void 0===b?void 0:b[0])-(null===(w=null===(v=e.span)||void 0===v?void 0:v.startTime)||void 0===w?void 0:w[1])/1e6;this.traceLogger[t](`span ${n} ${e.source} ${Math.floor(i)} ${JSON.stringify(null===(S=null==e?void 0:e.span)||void 0===S?void 0:S.attributes)}`)}}}}start(){return __awaiter(this,void 0,void 0,function*(){this.started=!0})}stop(){return __awaiter(this,void 0,void 0,function*(){this.started=!1})}resolveProperty(e,t,r,n){var i,o,s,a,c,l;return null!==(l=null!==(c=null!==(o=null!==(i=null==t?void 0:t[e])&&void 0!==i?i:null==r?void 0:r[e])&&void 0!==o?o:null===(a=null===(s=this.settings)||void 0===s?void 0:s.defaults)||void 0===a?void 0:a[e])&&void 0!==c?c:constants_1$1.Defaults[e])&&void 0!==l?l:n}}manager$2.TracesManager=TracesManager,Object.defineProperty(builder$2,"__esModule",{value:!0}),builder$2.TracesManagerBuilder=void 0;const manager_1$1=manager$2,nullTracesManager_1$1=requireNullTracesManager(),container_1$2=container$1;class TracesManagerBuilder{constructor(){this.traceLogger=null}withLogger(e){return this.logger=e,this}withTraceLogger(e){return this.traceLogger=e,this}withSettings(e){return this.settings=e,this}withMetrics(e){return this.metrics=e,this}withTracerProvider(e){return this.tracerProvider=e,this}withSamplerGetter(e){return this.samplerGetter=e,this}withSpanProcessors(e){return this.spanProcessors=e,this}withSpanExporters(e){return this.spanExporters=e,this}withProviderRegistrationSettings(e){var t;return this.providerRegistrationSettings=Object.assign({contextManager:null===(t=this.providerRegistrationSettings)||void 0===t?void 0:t.contextManager},e),this}withContextManager(e){return this.providerRegistrationSettings=Object.assign(Object.assign({},this.providerRegistrationSettings),{contextManager:e}),this.contextManager=e,this}withPropagator(e){return this.providerRegistrationSettings=Object.assign(Object.assign({},this.providerRegistrationSettings),{propagator:e}),this.propagator=e,this}build(){return this.contextManager&&this.settings.traces&&(this.settings.traces.useOTELContextManager=!0),this.buildCore()}buildCore(){var e,t,r,n,i,o;if(!0!==(null===(e=this.settings)||void 0===e?void 0:e.enabled)||!0!==(null===(r=null===(t=this.settings)||void 0===t?void 0:t.traces)||void 0===r?void 0:r.enabled))return new nullTracesManager_1$1.NullTracesManager(null===(n=this.settings)||void 0===n?void 0:n.traces,this.settings,this.logger);return new manager_1$1.TracesManager(this.settings,this.logger,null!==(i=this.traceLogger)&&void 0!==i?i:this.logger,this.getOrMake("contextManager"),this.getOrMake("propagator"),this.getOrMake("tracerProvider"),null===(o=this.settings.traces)||void 0===o?void 0:o.samplerGetter,this.getOrMake("spanProcessors"),this.getOrMake("spanExporters"),this.getOrMake("providerRegistrationSettings"),this.metrics)}getOrMake(e,t){var r,n,i,o;return this[e]?this[e]:!1!==t&&"function"==typeof(null===(n=null===(r=this.settings)||void 0===r?void 0:r.traces)||void 0===n?void 0:n[e])?container_1$2.Container.errorless(()=>{var t,r;return null===(r=(t=this.settings.traces)[e])||void 0===r?void 0:r.call(t)}):null===(o=null===(i=this.settings)||void 0===i?void 0:i.traces)||void 0===o?void 0:o[e]}}builder$2.TracesManagerBuilder=TracesManagerBuilder;var _null$3={};Object.defineProperty(_null$3,"__esModule",{value:!0}),_null$3.NullLogger=void 0;class NullLogger{get level(){return 60}error(){}warn(){}info(){}debug(){}verbose(){}}_null$3.NullLogger=NullLogger;var builder$1={};Object.defineProperty(builder$1,"__esModule",{value:!0}),builder$1.BuilderValidator=void 0;const validator_1=validator$1;class BuilderValidator{validate(e){validator_1.Validator.throwIfNullOrUndefined(e,"builder"),validator_1.Validator.throwIfNullOrUndefined(e.logger,"logger")}}builder$1.BuilderValidator=BuilderValidator;var nullManager={};Object.defineProperty(nullManager,"__esModule",{value:!0}),nullManager.NullLogsManager=void 0;const nullManager_1$2=nullManager$1,safe_stringify_1$2=safeStringify$1;class NullLogsManager extends nullManager_1$2.NullManager{constructor(e,t,r){!1!==(null==t?void 0:t.logSettingsOnStartup)&&(null==r||r.info(`Starting NullLogsManager with settings ${(0,safe_stringify_1$2.safeStringify)(e)}`)),super()}emit(e){return null}}nullManager.NullLogsManager=NullLogsManager;var manager={};class OTLPLogExporter extends OTLPExporterBase{constructor(e={}){super(createLegacyOtlpBrowserExportDelegate(e,JsonLogsSerializer,"v1/logs",{"Content-Type":"application/json"}))}}var esm$1=Object.freeze({__proto__:null,OTLPLogExporter:OTLPLogExporter}),require$$0$1=getAugmentedNamespace(esm$1);class NoopLogger{emit(e){}}const NOOP_LOGGER=new NoopLogger;function defaultServiceName(){return"unknown_service"}const isPromiseLike=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;class ResourceImpl{_rawAttributes;_asyncAttributesPending=!1;_memoizedAttributes;static FromAttributeList(e){const t=new ResourceImpl({});return t._rawAttributes=e,t._asyncAttributesPending=e.filter(([e,t])=>isPromiseLike(t)).length>0,t}constructor(e){const t=e.attributes??{};this._rawAttributes=Object.entries(t).map(([e,t])=>(isPromiseLike(t)&&(this._asyncAttributesPending=!0),[e,t]))}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e0?(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(1===this.droppedAttributesCount&&diag.warn("Dropping extra attributes."),this):(isAttributeValue$1(t)?this.attributes[e]=this._truncateToSize(t):this.attributes[e]=t,this)):(diag.warn(`Invalid attribute value set for key: ${e}`),this)}setAttributes(e){for(const[t,r]of Object.entries(e))this.setAttribute(t,r);return this}setBody(e){return this.body=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){const t=this._logRecordLimits.attributeValueLengthLimit;return t<=0?(diag.warn(`Attribute value limit must be positive, got ${t}`),e):"string"==typeof e?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>"string"==typeof e?this._truncateToLimitUtil(e,t):e):e}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_isLogRecordReadonly(){return this._isReadonly&&diag.warn("Can not execute the operation on emitted log record"),this._isReadonly}}let Logger$1=class{instrumentationScope;_sharedState;constructor(e,t){this.instrumentationScope=e,this._sharedState=t}emit(e){const t=e.context||context.active(),r=new LogRecord(this._sharedState,this.instrumentationScope,{context:t,...e});this._sharedState.activeProcessor.onEmit(r,t),r._makeReadonly()}};function loadDefaultConfig(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128},includeTraceContext:!0}}function reconfigureLimits(e){return{attributeCountLimit:e.attributeCountLimit??getNumberFromEnv$1()??getNumberFromEnv$1()??128,attributeValueLengthLimit:e.attributeValueLengthLimit??getNumberFromEnv$1()??getNumberFromEnv$1()??1/0}}class MultiLogRecordProcessor{processors;forceFlushTimeoutMillis;constructor(e,t){this.processors=e,this.forceFlushTimeoutMillis=t}async forceFlush(){const e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(t=>callWithTimeout$1(t.forceFlush(),e)))}onEmit(e,t){this.processors.forEach(r=>r.onEmit(e,t))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}}class NoopLogRecordProcessor{forceFlush(){return Promise.resolve()}onEmit(e,t){}shutdown(){return Promise.resolve()}}class LoggerProviderSharedState{resource;forceFlushTimeoutMillis;logRecordLimits;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,t,r){this.resource=e,this.forceFlushTimeoutMillis=t,this.logRecordLimits=r,this.activeProcessor=new NoopLogRecordProcessor}}const DEFAULT_LOGGER_NAME="unknown";class LoggerProvider{_shutdownOnce;_sharedState;constructor(e={}){const t=merge$3({},loadDefaultConfig(),e),r=e.resource??defaultResource();this._sharedState=new LoggerProviderSharedState(r,t.forceFlushTimeoutMillis,reconfigureLimits(t.logRecordLimits)),this._shutdownOnce=new BindOnceFuture$1(this._shutdown,this)}getLogger(e,t,r){if(this._shutdownOnce.isCalled)return diag.warn("A shutdown LoggerProvider cannot provide a Logger"),NOOP_LOGGER;e||diag.warn("Logger requested without instrumentation scope name.");const n=e||DEFAULT_LOGGER_NAME,i=`${n}@${t||""}:${r?.schemaUrl||""}`;return this._sharedState.loggers.has(i)||this._sharedState.loggers.set(i,new Logger$1({name:n,version:t,schemaUrl:r?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(i)}addLogRecordProcessor(e){0===this._sharedState.registeredLogRecordProcessors.length&&this._sharedState.activeProcessor.shutdown().catch(e=>diag.error("Error while trying to shutdown current log record processor",e)),this._sharedState.registeredLogRecordProcessors.push(e),this._sharedState.activeProcessor=new MultiLogRecordProcessor(this._sharedState.registeredLogRecordProcessors,this._sharedState.forceFlushTimeoutMillis)}forceFlush(){return this._shutdownOnce.isCalled?(diag.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(diag.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}}class ConsoleLogRecordExporter{export(e,t){this._sendLogRecords(e,t)}shutdown(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,timestamp:hrTimeToMicroseconds$2(e.hrTime),traceId:e.spanContext?.traceId,spanId:e.spanContext?.spanId,traceFlags:e.spanContext?.traceFlags,severityText:e.severityText,severityNumber:e.severityNumber,body:e.body,attributes:e.attributes}}_sendLogRecords(e,t){for(const t of e)console.dir(this._exportInfo(t),{depth:3});t?.({code:ExportResultCode$2.SUCCESS})}}class SimpleLogRecordProcessor{_exporter;_shutdownOnce;_unresolvedExports;constructor(e){this._exporter=e,this._shutdownOnce=new BindOnceFuture$1(this._shutdown,this),this._unresolvedExports=new Set}onEmit(e){if(this._shutdownOnce.isCalled)return;const t=()=>internal$2._export(this._exporter,[e]).then(e=>{e.code!==ExportResultCode$2.SUCCESS&&globalErrorHandler$2(e.error??new Error(`SimpleLogRecordProcessor: log record export failed (status ${e})`))}).catch(globalErrorHandler$2);if(e.resource.asyncAttributesPending){const r=e.resource.waitForAsyncAttributes?.().then(()=>(this._unresolvedExports.delete(r),t()),globalErrorHandler$2);null!=r&&this._unresolvedExports.add(r)}else t()}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports))}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}class InMemoryLogRecordExporter{_finishedLogRecords=[];_stopped=!1;export(e,t){if(this._stopped)return t({code:ExportResultCode$2.FAILED,error:new Error("Exporter has been stopped")});this._finishedLogRecords.push(...e),t({code:ExportResultCode$2.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}}class BatchLogRecordProcessorBase{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,t){this._exporter=e,this._maxExportBatchSize=t?.maxExportBatchSize??getNumberFromEnv$1()??512,this._maxQueueSize=t?.maxQueueSize??getNumberFromEnv$1()??2048,this._scheduledDelayMillis=t?.scheduledDelayMillis??getNumberFromEnv$1()??5e3,this._exportTimeoutMillis=t?.exportTimeoutMillis??getNumberFromEnv$1()??3e4,this._shutdownOnce=new BindOnceFuture$1(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}onEmit(e){this._shutdownOnce.isCalled||this._addToBuffer(e)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}_addToBuffer(e){this._finishedLogRecords.length>=this._maxQueueSize||(this._finishedLogRecords.push(e),this._maybeStartTimer())}_flushAll(){return new Promise((e,t)=>{const r=[],n=Math.ceil(this._finishedLogRecords.length/this._maxExportBatchSize);for(let e=0;e{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),0===this._finishedLogRecords.length?Promise.resolve():new Promise((e,t)=>{callWithTimeout$1(this._export(this._finishedLogRecords.splice(0,this._maxExportBatchSize)),this._exportTimeoutMillis).then(()=>e()).catch(t)})}_maybeStartTimer(){void 0===this._timer&&(this._timer=setTimeout(()=>{this._flushOneBatch().then(()=>{this._finishedLogRecords.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{globalErrorHandler$2(e)})},this._scheduledDelayMillis),unrefTimer$2(this._timer))}_clearTimer(){void 0!==this._timer&&(clearTimeout(this._timer),this._timer=void 0)}_export(e){const t=()=>internal$2._export(this._exporter,e).then(e=>{e.code!==ExportResultCode$2.SUCCESS&&globalErrorHandler$2(e.error??new Error(`BatchLogRecordProcessor: log record export failed (status ${e})`))}).catch(globalErrorHandler$2),r=e.map(e=>e.resource).filter(e=>e.asyncAttributesPending);return 0===r.length?t():Promise.all(r.map(e=>e.waitForAsyncAttributes?.())).then(t,globalErrorHandler$2)}}class BatchLogRecordProcessor extends BatchLogRecordProcessorBase{_visibilityChangeListener;_pageHideListener;constructor(e,t){super(e,t),this._onInit(t)}onShutdown(){"undefined"!=typeof document&&(this._visibilityChangeListener&&document.removeEventListener("visibilitychange",this._visibilityChangeListener),this._pageHideListener&&document.removeEventListener("pagehide",this._pageHideListener))}_onInit(e){!0!==e?.disableAutoFlushOnDocumentHide&&"undefined"!=typeof document&&(this._visibilityChangeListener=()=>{"hidden"===document.visibilityState&&this.forceFlush()},this._pageHideListener=()=>{this.forceFlush()},document.addEventListener("visibilitychange",this._visibilityChangeListener),document.addEventListener("pagehide",this._pageHideListener))}}var esm=Object.freeze({__proto__:null,BatchLogRecordProcessor:BatchLogRecordProcessor,ConsoleLogRecordExporter:ConsoleLogRecordExporter,InMemoryLogRecordExporter:InMemoryLogRecordExporter,LogRecord:LogRecord,LoggerProvider:LoggerProvider,NoopLogRecordProcessor:NoopLogRecordProcessor,SimpleLogRecordProcessor:SimpleLogRecordProcessor}),require$$1=getAugmentedNamespace(esm),logs={};Object.defineProperty(logs,"__esModule",{value:!0}),logs.Logs=void 0;const nullManager_1$1=nullManager;class Logs{static get instance(){return Logs._instance}static set instance(e){Logs._instance=e}static emit(e){return Logs._instance.emit(e)}}logs.Logs=Logs,Logs._instance=new nullManager_1$1.NullLogsManager(void 0,void 0,void 0),Object.defineProperty(manager,"__esModule",{value:!0}),manager.LogsManager=void 0;const exporter_logs_otlp_http_1=require$$0$1,sdk_logs_1=require$$1,resources_1=require$$2,logs_1=logs,otelUtils_1=otelUtils,safe_stringify_1$1=safeStringify$1,container_1$1=container$1;class LogsManager{constructor(e,t,r){var n,i,o,s;this.logger=e,this.settings=t,this.otelSettings=r,this.started=!1,!1!==r.logSettingsOnStartup&&(null==e||e.info(`Starting LogManager with settings ${(0,safe_stringify_1$1.safeStringify)(t)}`));const a=(0,resources_1.resourceFromAttributes)(null!==(n=container_1$1.Container.errorless(t.additionalResourceAttributes))&&void 0!==n?n:{});this.additionalAttributes=()=>{var e,r;return(0,otelUtils_1.flattenOtelAtributes)(null!==(e=container_1$1.Container.errorless(this.settings.additionalAttributes))&&void 0!==e?e:{},null!==(r=t.maxAttributeDepth)&&void 0!==r?r:5)};const c=null!==(i=t.loggerProvider)&&void 0!==i?i:new sdk_logs_1.LoggerProvider(Object.assign({resource:a},t.providerSettings));if(null===(o=t.logExporters)||void 0===o?void 0:o.length)for(const e of t.logExporters)c.addLogRecordProcessor(new sdk_logs_1.BatchLogRecordProcessor(e,t.batchSettings));if(null===(s=t.logProcessors)||void 0===s?void 0:s.length)for(const e of t.logProcessors)c.addLogRecordProcessor(e);t.url&&c.addLogRecordProcessor(new sdk_logs_1.BatchLogRecordProcessor(new exporter_logs_otlp_http_1.OTLPLogExporter(Object.assign({url:t.url,keepAlive:t.keepAlive,headers:Object.assign(Object.assign({},container_1$1.Container.errorless(r.headers)),container_1$1.Container.errorless(t.headers))},t.exporterSettings)),t.batchSettings)),this.loggerOtel=c.getLogger("default"),logs_1.Logs.instance=this}emit(e){if(this.started){if(!this.applyFilters(e))return Promise.resolve();this.loggerOtel.emit(e)}return Promise.resolve()}applyFilters(e){var t,r,n,i,o;if(!(null===(t=this.settings.filters)||void 0===t?void 0:t.length)&&!this.settings.defaults)return!0;const s=null!==(n=null===(r=this.settings.filters)||void 0===r?void 0:r.find(t=>{var r;return(!t.categoryName||(null===(r=e.attributes)||void 0===r?void 0:r.categoryName)===t.categoryName)&&(!!(!t.severity||e.severityText&&asSevereOrMore(e.severityText,t.severity))&&!(t.bodyRegex&&!new RegExp(t.bodyRegex).test(e.body+"")))}))&&void 0!==n?n:this.settings.defaults;if(!s)return!0;if(!1===s.enabled)return!1;const a=null===(i=this.additionalAttributes)||void 0===i?void 0:i.call(this);for(const t in null!=a?a:{})e.setAttribute(t,a[t]);if(null===(o=s.allowedAttributes)||void 0===o?void 0:o.length)for(const t of Object.keys(e.attributes))~s.allowedAttributes.indexOf(t)||delete e.attributes[t];return s.hideRegex&&(e.body=(e.body+"").replace(new RegExp(s.hideRegex),"*****")),!0}start(){return this.started=!0,Promise.resolve()}stop(){return this.started=!1,Promise.resolve()}waitForFinalExport(e){return Promise.resolve()}}manager.LogsManager=LogsManager;const severityHierarchy=["TRACE","DEBUG","INFO","WARN","ERROR","FATAL"];function asSevereOrMore(e,t){const r=severityHierarchy.indexOf(e.toUpperCase());if(r<0)return!1;const n=severityHierarchy.indexOf(t.toUpperCase());return!(n<0)&&r>=n}Object.defineProperty(builder$7,"__esModule",{value:!0}),builder$7.Builder=void 0;const api_1=require$$13$1,builder_1=builder$6,builder_2=builder$2,null_1=_null$3,builder_3=builder$1,container_1=container$1,nullMetricsManager_1=nullMetricsManager,nullTracesManager_1=requireNullTracesManager(),nullManager_1=nullManager,manager_1=manager,safe_stringify_1=safeStringify$1,constants_1=constants$3;let Builder$1=class e{constructor(){this.logger=new null_1.NullLogger}withLogger(e){var t;if(this.logger=null!=e?e:this.logger,this.logger.level){const e=null===(t=this.logger.level)||void 0===t?void 0:t.valueOf();api_1.diag.setLogger(this.logger,e)}else api_1.diag.setLogger(this.logger,70);return this}withSettings(e){return this.settings=e,this}withMetrics(){return this.metricsBuilder=new builder_1.MetricsManagerBuilder,this.metricsBuilder.withLogger(this.logger),this.metricsBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.metricsBuilder}withTraces(){return this.tracesBuilder=new builder_2.TracesManagerBuilder,this.tracesBuilder.withLogger(this.logger),this.tracesBuilder.withSettings(Object.assign({enabled:!1},this.settings)),this.tracesBuilder}build(){return(new builder_3.BuilderValidator).validate(this),this.buildCore()}buildCore(){var t,r,n,i,o,s,a,c,l,u;this.settings=null!==(t=this.settings)&&void 0!==t?t:{enabled:!1};const d=Object.assign({enabled:!1},this.settings);if(!1!==(null===(r=this.settings)||void 0===r?void 0:r.logSettingsOnStartup)&&this.logger.info(`Starting interop.io OTEL with settings ${(0,safe_stringify_1.safeStringify)(this.settings)}`),!1!==(null===(n=this.settings)||void 0===n?void 0:n.enabled)){if((null===(o=null===(i=this.settings)||void 0===i?void 0:i.metrics)||void 0===o?void 0:o.enabled)&&(null===(s=this.settings)||void 0===s?void 0:s.metrics.platformMetricsEnabled)&&!this.metricsBuilder)throw new Error("metrics.platformMetricsEnabled is true, but .withMetrics() method not called.");const t=this.settings.additionalResourceAttributes;this.settings.additionalResourceAttributes=()=>{var e,r,n,i,o,s,a,c,l,u,d,h,p,g,m,f,y,$,b;const v=null!==(e=container_1.Container.errorlessDefined(t,{}))&&void 0!==e?e:{};return Object.assign(Object.assign({},v),{user:null!==(i=null!==(r=v.userId)&&void 0!==r?r:null===(n=this.settings)||void 0===n?void 0:n.userId)&&void 0!==i?i:constants_1.Defaults.DEFAULT_USER,"user.id":null!==(a=null!==(o=v.userId)&&void 0!==o?o:null===(s=this.settings)||void 0===s?void 0:s.userId)&&void 0!==a?a:constants_1.Defaults.DEFAULT_USER,"service.name":null!==(u=null!==(c=v.serviceName)&&void 0!==c?c:null===(l=this.settings)||void 0===l?void 0:l.serviceName)&&void 0!==u?u:constants_1.Defaults.DEFAULT_SERVICE_NAME,"service.instance.id":null!==(p=null!==(d=v.serviceId)&&void 0!==d?d:null===(h=this.settings)||void 0===h?void 0:h.serviceId)&&void 0!==p?p:constants_1.Defaults.DEFAULT_SERVICE_ID,"service.version":null!==(f=null!==(g=v.serviceVersion)&&void 0!==g?g:null===(m=this.settings)||void 0===m?void 0:m.serviceVersion)&&void 0!==f?f:constants_1.Defaults.DEFAULT_SERVICE_VERSION,platformVersion:null!==(b=null!==(y=v.platformVersion)&&void 0!==y?y:null===($=this.settings)||void 0===$?void 0:$.platformVersion)&&void 0!==b?b:constants_1.Defaults.DEFAULT_PLATFORM_VERSION})},e.maybeAddReferenceAttributes(this.settings),e.maybeAddReferenceAttributes(this.settings.logs),e.maybeAddReferenceAttributes(this.settings.metrics),e.maybeAddReferenceAttributes(this.settings.traces),e.propagateAttributesDown("additionalAttributes",this.settings,this.settings.logs),e.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.logs),e.propagateAttributesDown("additionalAttributes",this.settings,this.settings.metrics),e.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.metrics),e.propagateAttributesDown("additionalAttributes",this.settings,this.settings.traces),e.propagateAttributesDown("additionalResourceAttributes",this.settings,this.settings.traces);const r=(null!==(a=this.metricsBuilder)&&void 0!==a?a:this.withMetrics()).withSettings(this.settings).build(),n=null!==(c=this.tracesBuilder)&&void 0!==c?c:this.withTraces();n.withMetrics(r);const h=n.withSettings(this.settings).build(),p=(null===(u=null===(l=null==this?void 0:this.settings)||void 0===l?void 0:l.logs)||void 0===u?void 0:u.enabled)?new manager_1.LogsManager(this.logger,this.settings.logs,d):new nullManager_1.NullLogsManager(this.settings.logs,d,this.logger);return new container_1.Container(d,h,r,p,this.logger)}return new container_1.Container(d,new nullTracesManager_1.NullTracesManager(this.settings.traces,d,this.logger),new nullMetricsManager_1.NullMetricsManager(this.settings.metrics,d,this.logger),new nullManager_1.NullLogsManager(this.settings.logs,d,this.logger),this.logger)}static propagateAttributesDown(e,t,r){var n,i;if(!r)return;const o=null!==(n=t[e])&&void 0!==n?n:{},s=null!==(i=r[e])&&void 0!==i?i:{};r[e]=()=>Object.assign(Object.assign({},container_1.Container.errorless(o)),container_1.Container.errorless(s))}static maybeAddReferenceAttributes(e){if(null==e?void 0:e.addResourceAttributesToAttributes){const t=e.additionalAttributes,r=e.additionalAttributes;e.additionalAttributes=()=>Object.assign(Object.assign({},container_1.Container.errorless(t)),container_1.Container.errorless(r))}}};builder$7.Builder=Builder$1;var log4jsWrapper={};Object.defineProperty(log4jsWrapper,"__esModule",{value:!0}),log4jsWrapper.Log4jsWrapper=void 0;class Log4jsWrapper{constructor(e){this.logger=e}get level(){return this.convert("level"in this.logger?this.logger.level:this.logger.publishLevel())}error(e,...t){this.logger.warn(e,...t)}warn(e,...t){this.logger.warn(e,...t)}info(e,...t){this.logger.info(e,...t)}debug(e,...t){this.logger.debug(e,...t)}verbose(e,...t){this.logger.trace(e,...t)}convert(e){if(void 0===e)return 60;switch("string"!=typeof e?e.levelStr.toLowerCase():e.toLowerCase()){case"off":return 0;case"error":return 30;case"warn":return 50;case"info":default:return 60;case"debug":return 70;case"trace":return 80}}}log4jsWrapper.Log4jsWrapper=Log4jsWrapper;var builder={},nullPerfProvider={};Object.defineProperty(nullPerfProvider,"__esModule",{value:!0}),nullPerfProvider.NullPerformanceProvider=void 0;class NullPerformanceProvider{getAppsCPU(){return Promise.resolve(void 0)}getAppsMemory(){return Promise.resolve(void 0)}getSystemCPU(){return Promise.resolve(void 0)}getSystemMemory(){return Promise.resolve(void 0)}}nullPerfProvider.NullPerformanceProvider=NullPerformanceProvider,Object.defineProperty(builder,"__esModule",{value:!0}),builder.MetricsDependencyBuilder=void 0;const nullPerfProvider_1=nullPerfProvider;class MetricsDependencyBuilder{constructor(){this.performanceProvider=new nullPerfProvider_1.NullPerformanceProvider,this.instanceFocusedHandler=()=>()=>{},this.instanceStartedHandler=()=>()=>{},this.instanceStoppedHandler=()=>()=>{},this.instanceReadyHandler=()=>()=>{},this.instanceErrorHandler=()=>()=>{},this.instanceCrashHandler=()=>()=>{},this.layoutRestoredHandler=()=>()=>{},this.workspaceLoadedHandler=()=>()=>{},this.workspaceRestoredHandler=()=>()=>{},this.workspaceSavedHandler=()=>()=>{},this.workspaceStartedHandler=()=>()=>{},this.workspaceStoppedHandler=()=>()=>{},this.workspaceSelectedHandler=()=>()=>{},this.platformStartedHandler=()=>()=>{},this.platformErrorHandler=()=>()=>{}}build(){return{performanceProvider:this.performanceProvider,instanceStartedHandler:this.instanceStartedHandler,instanceStoppedHandler:this.instanceStoppedHandler,instanceReadyHandler:this.instanceReadyHandler,instanceFocusedHandler:this.instanceFocusedHandler,instanceErrorHandler:this.instanceErrorHandler,instanceCrashHandler:this.instanceCrashHandler,layoutRestoredHandler:this.layoutRestoredHandler,workspaceLoadedHandler:this.workspaceLoadedHandler,workspaceSavedHandler:this.workspaceSavedHandler,workspaceStartedHandler:this.workspaceStartedHandler,workspaceStoppedHandler:this.workspaceStoppedHandler,workspaceSelectedHandler:this.workspaceSelectedHandler,platformStartedHandler:this.platformStartedHandler,platformErrorHandler:this.platformErrorHandler,workspaceRestoredHandler:this.workspaceRestoredHandler}}withInstanceStartedHandler(e){return this.instanceStartedHandler=e,this}withInstanceStoppedHandler(e){return this.instanceStoppedHandler=e,this}withInstanceReadyHandler(e){return this.instanceReadyHandler=e,this}withInstanceFocusedHandler(e){return this.instanceFocusedHandler=e,this}withInstanceErrorHandler(e){return this.instanceErrorHandler=e,this}withInstanceCrashHandler(e){return this.instanceCrashHandler=e,this}withLayoutRestoredHandler(e){return this.layoutRestoredHandler=e,this}withWorkspaceLoadedHandler(e){return this.workspaceLoadedHandler=e,this}withWorkspaceSavedHandler(e){return this.workspaceSavedHandler=e,this}withWorkspaceStartedHandler(e){return this.workspaceRestoredHandler=()=>()=>{},this.workspaceStartedHandler=e,this}withWorkspaceStoppedHandler(e){return this.workspaceStoppedHandler=e,this}withWorkspaceSelectedHandler(e){return this.workspaceSelectedHandler=e,this}withPlatformStartedHandler(e){return this.platformStartedHandler=e,this}withPlatformErrorHandler(e){return this.platformErrorHandler=e,this}withPerfProvider(e){return this.performanceProvider=e,this}withWorkspaceRestoredHandler(e){return this.workspaceRestoredHandler=e,this.workspaceStartedHandler=()=>()=>{},this}}builder.MetricsDependencyBuilder=MetricsDependencyBuilder;var types={};Object.defineProperty(types,"__esModule",{value:!0}),function(e){var t=commonjsGlobal$1&&commonjsGlobal$1.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),r=commonjsGlobal$1&&commonjsGlobal$1.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=commonjsGlobal$1&&commonjsGlobal$1.__exportStar||function(e,r){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(r,n)||t(r,e,n)},i=commonjsGlobal$1&&commonjsGlobal$1.__importStar||function(e){if(e&&e.__esModule)return e;var n={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&t(n,e,i);return r(n,e),n};Object.defineProperty(e,"__esModule",{value:!0}),e.OtelExporterTraceOtlpHttp=e.OtelExporterMetricsOtlpHttp=e.OtelMetricsSDK=e.OtelTraceBaseSDK=e.OtelAPI=e.isPlainObject=e.safeStringify=e.flattenOtelAtributes=e.Logs=e.OTEL_PI_KEY=e.withSpan=e.Traces=e.MetricsDependencyBuilder=e.OTLPMetricExporter=e.InMemoryMetricExporter=e.Container=e.Log4jsWrapper=e.ioInsightsSampler=e.Builder=void 0;var o=builder$7;Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return o.Builder}});var s=requireIoInsightsSampler();Object.defineProperty(e,"ioInsightsSampler",{enumerable:!0,get:function(){return s.ioInsightsSampler}});var a=log4jsWrapper;Object.defineProperty(e,"Log4jsWrapper",{enumerable:!0,get:function(){return a.Log4jsWrapper}});var c=container$1;Object.defineProperty(e,"Container",{enumerable:!0,get:function(){return c.Container}});var l=require$$4;Object.defineProperty(e,"InMemoryMetricExporter",{enumerable:!0,get:function(){return l.InMemoryMetricExporter}});var u=require$$5;Object.defineProperty(e,"OTLPMetricExporter",{enumerable:!0,get:function(){return u.OTLPMetricExporter}});var d=builder;Object.defineProperty(e,"MetricsDependencyBuilder",{enumerable:!0,get:function(){return d.MetricsDependencyBuilder}}),n(types,e);const h=i(requireTraces());e.Traces=h.default,Object.defineProperty(e,"withSpan",{enumerable:!0,get:function(){return h.withSpan}}),e.OTEL_PI_KEY="__interopIOTracePropagationInfo";var p=logs;Object.defineProperty(e,"Logs",{enumerable:!0,get:function(){return p.Logs}});var g=otelUtils;Object.defineProperty(e,"flattenOtelAtributes",{enumerable:!0,get:function(){return g.flattenOtelAtributes}});var m=safeStringify$1;Object.defineProperty(e,"safeStringify",{enumerable:!0,get:function(){return m.safeStringify}});var f=isPlainObject$6;Object.defineProperty(e,"isPlainObject",{enumerable:!0,get:function(){return f.isPlainObject}});const y=i(require$$13$1);e.OtelAPI=y;const $=i(require$$14$1);e.OtelTraceBaseSDK=$;const b=i(require$$4);e.OtelMetricsSDK=b;const v=i(require$$5);e.OtelExporterMetricsOtlpHttp=v;const w=i(require$$15);e.OtelExporterTraceOtlpHttp=w}(dist);var c$2=(e=>(e[e.off=0]="off",e[e.error=200]="error",e[e.warn=300]="warn",e[e.info=400]="info",e[e.debug=500]="debug",e[e.trace=600]="trace",e[e.all=Number.MAX_SAFE_INTEGER]="all",e))(c$2||{}),u$1=Object.create(null),g$5={},f$1="gateway";g$5[f$1]=600;var l$2=e=>{console[e.level](`${e.time.toISOString()} ${e.level.toUpperCase()} [${e.name}] - ${e.message}`,...e.data)};function E$2(e){let{name:t,level:r}=e;L$2(t),d$1(r,t)&&l$2(e)}function a$1(e,t,r,...n){this.enabledFor(t)&&l$2({time:new Date,level:t,name:e,message:r,data:n})}function d$1(e,t){let r=c$2[e];return g$5[t]>=r}function y$3(e){L$2(e);let t=function(r,n,...i){a$1.call(t,e,r,n,...i)};for(let r of Object.keys(c$2).filter(function(e){return isNaN(Number(e))}))t[r]=function(n,...i){a$1.call(t,e,r,n,...i)};return t.enabledFor=function(t){return d$1(t,e)},t.child=function(t){return v$3(`${e}.${t}`)},t}function L$2(e){if(!e.startsWith(f$1))throw new Error(`Logger name must start with ${f$1}`);if(void 0===g$5[e]){let t=Object.entries(g$5).sort(([e],[t])=>t.localeCompare(e)),[,r]=t.find(([t])=>e.startsWith(t));g$5[e]=r}}function v$3(e){let t=u$1[e];return void 0===t&&(t=y$3(e),u$1[e]=t),t}function b$2(e){function t(e,t){for(let r of Object.keys(g$5).filter(t=>t.startsWith(e)))g$5[r]=c$2[t];void 0===g$5[e]&&(g$5[e]=c$2[t])}let r=e.level;if("string"==typeof r)g$5[f$1]=c$2[r],t(f$1,r);else if("object"==typeof r){let e=Object.entries(r).sort(([e],[t])=>e.localeCompare(t));for(let[r,n]of e)t(r,n)}l$2=e.appender??l$2}var my=Object.freeze({__proto__:null,ROOT_LOGGER_NAME:f$1,configure:b$2,getLogger:v$3,logEvent:E$2}),NOTHING=Symbol.for("immer-nothing"),DRAFTABLE=Symbol.for("immer-draftable"),DRAFT_STATE=Symbol.for("immer-state");function die(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var O$1=Object,getPrototypeOf$1=O$1.getPrototypeOf,CONSTRUCTOR="constructor",PROTOTYPE="prototype",CONFIGURABLE="configurable",ENUMERABLE="enumerable",WRITABLE="writable",VALUE="value",isDraft=e=>!!e&&!!e[DRAFT_STATE];function isDraftable(e){return!!e&&(isPlainObject$2(e)||isArray$5(e)||!!e[DRAFTABLE]||!!e[CONSTRUCTOR]?.[DRAFTABLE]||isMap$4(e)||isSet$4(e))}var objectCtorString=O$1[PROTOTYPE][CONSTRUCTOR].toString(),cachedCtorStrings=new WeakMap;function isPlainObject$2(e){if(!e||!isObjectish(e))return!1;const t=getPrototypeOf$1(e);if(null===t||t===O$1[PROTOTYPE])return!0;const r=O$1.hasOwnProperty.call(t,CONSTRUCTOR)&&t[CONSTRUCTOR];if(r===Object)return!0;if(!isFunction$3(r))return!1;let n=cachedCtorStrings.get(r);return void 0===n&&(n=Function.toString.call(r),cachedCtorStrings.set(r,n)),n===objectCtorString}function each(e,t,r=!0){if(0===getArchtype(e)){(r?Reflect.ownKeys(e):O$1.keys(e)).forEach(r=>{t(r,e[r],e)})}else e.forEach((r,n)=>t(n,r,e))}function getArchtype(e){const t=e[DRAFT_STATE];return t?t.type_:isArray$5(e)?1:isMap$4(e)?2:isSet$4(e)?3:0}var has$1=(e,t,r=getArchtype(e))=>2===r?e.has(t):O$1[PROTOTYPE].hasOwnProperty.call(e,t),get$1=(e,t,r=getArchtype(e))=>2===r?e.get(t):e[t],set$1=(e,t,r,n=getArchtype(e))=>{2===n?e.set(t,r):3===n?e.add(r):e[t]=r};function is$3(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}var isArray$5=Array.isArray,isMap$4=e=>e instanceof Map,isSet$4=e=>e instanceof Set,isObjectish=e=>"object"==typeof e,isFunction$3=e=>"function"==typeof e,isBoolean$3=e=>"boolean"==typeof e,getProxyDraft=e=>isObjectish(e)?e?.[DRAFT_STATE]:null,latest=e=>e.copy_||e.base_,getValue=e=>{const t=getProxyDraft(e);return t?t.copy_??t.base_:e},getFinalValue=e=>e.modified_?e.copy_:e.base_;function shallowCopy(e,t){if(isMap$4(e))return new Map(e);if(isSet$4(e))return new Set(e);if(isArray$5(e))return Array[PROTOTYPE].slice.call(e);const r=isPlainObject$2(e);if(!0===t||"class_only"===t&&!r){const t=O$1.getOwnPropertyDescriptors(e);delete t[DRAFT_STATE];let r=Reflect.ownKeys(t);for(let n=0;n1&&O$1.defineProperties(e,{set:dontMutateMethodOverride,add:dontMutateMethodOverride,clear:dontMutateMethodOverride,delete:dontMutateMethodOverride}),O$1.freeze(e),t&&each(e,(e,t)=>{freeze(t,!0)},!1)),e}function dontMutateFrozenCollections(){die(2)}var dontMutateMethodOverride={[VALUE]:dontMutateFrozenCollections};function isFrozen(e){return null===e||!isObjectish(e)||O$1.isFrozen(e)}var PluginMapSet="MapSet",PluginPatches="Patches",plugins={};function getPlugin(e){const t=plugins[e];return t||die(0,e),t}var isPluginLoaded=e=>!!plugins[e],currentScope;function loadPlugin(e,t){plugins[e]||(plugins[e]=t)}var getCurrentScope=()=>currentScope,createScope=(e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:isPluginLoaded(PluginMapSet)?getPlugin(PluginMapSet):void 0});function usePatchesInScope(e,t){t&&(e.patchPlugin_=getPlugin(PluginPatches),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function revokeScope(e){leaveScope(e),e.drafts_.forEach(revokeDraft),e.drafts_=null}function leaveScope(e){e===currentScope&&(currentScope=e.parent_)}var enterScope=e=>currentScope=createScope(currentScope,e);function revokeDraft(e){const t=e[DRAFT_STATE];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function processResult(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];if(void 0!==e&&e!==r){r[DRAFT_STATE].modified_&&(revokeScope(t),die(4)),isDraftable(e)&&(e=finalize(t,e));const{patchPlugin_:n}=t;n&&n.generateReplacementPatches_(r[DRAFT_STATE].base_,e,t)}else e=finalize(t,r);return maybeFreeze(t,e,!0),revokeScope(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==NOTHING?e:void 0}function finalize(e,t){if(isFrozen(t))return t;const r=t[DRAFT_STATE];if(!r){return handleValue(t,e.handledSet_,e)}if(!isSameScope(r,e))return t;if(!r.modified_)return r.base_;if(!r.finalized_){const{callbacks_:t}=r;if(t)for(;t.length>0;){t.pop()(e)}generatePatchesAndFinalize(r,e)}return r.copy_}function maybeFreeze(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&freeze(t,r)}function markStateFinalized(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var isSameScope=(e,t)=>e.scope_===t,EMPTY_LOCATIONS_RESULT=[];function updateDraftInParent(e,t,r,n){const i=latest(e),o=e.type_;if(void 0!==n){if(get$1(i,n,o)===t)return void set$1(i,n,r,o)}if(!e.draftLocations_){const t=e.draftLocations_=new Map;each(i,(e,r)=>{if(isDraft(r)){const n=t.get(r)||[];n.push(e),t.set(r,n)}})}const s=e.draftLocations_.get(t)??EMPTY_LOCATIONS_RESULT;for(const e of s)set$1(i,e,r,o)}function registerChildFinalizationCallback(e,t,r){e.callbacks_.push(function(n){const i=t;if(!i||!isSameScope(i,n))return;n.mapSetPlugin_?.fixSetContents(i);const o=getFinalValue(i);updateDraftInParent(e,i.draft_??i,o,r),generatePatchesAndFinalize(i,n)})}function generatePatchesAndFinalize(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||(e.assigned_?.size??0)>0)){const{patchPlugin_:r}=t;if(r){const n=r.getPath(e);n&&r.generatePatches_(e,n,t)}markStateFinalized(e)}}function handleCrossReference(e,t,r){const{scope_:n}=e;if(isDraft(r)){const i=r[DRAFT_STATE];isSameScope(i,n)&&i.callbacks_.push(function(){prepareCopy(e);const n=getFinalValue(i);updateDraftInParent(e,r,n,t)})}else isDraftable(r)&&e.callbacks_.push(function(){const i=latest(e);get$1(i,t,e.type_)===r&&n.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&handleValue(get$1(e.copy_,t,e.type_),n.handledSet_,n)})}function handleValue(e,t,r){return!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1||isDraft(e)||t.has(e)||!isDraftable(e)||isFrozen(e)||(t.add(e),each(e,(n,i)=>{if(isDraft(i)){const t=i[DRAFT_STATE];if(isSameScope(t,r)){const r=getFinalValue(t);set$1(e,n,r,e.type_),markStateFinalized(t)}}else isDraftable(i)&&handleValue(i,t,r)})),e}function createProxyProxy(e,t){const r=isArray$5(e),n={type_:r?1:0,scope_:t?t.scope_:getCurrentScope(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let i=n,o=objectTraps;r&&(i=[n],o=arrayTraps);const{revoke:s,proxy:a}=Proxy.revocable(i,o);return n.draft_=a,n.revoke_=s,[a,n]}var objectTraps={get(e,t){if(t===DRAFT_STATE)return e;const r=latest(e);if(!has$1(r,t,e.type_))return readPropFromProto(e,r,t);const n=r[t];if(e.finalized_||!isDraftable(n))return n;if(n===peek(e.base_,t)){prepareCopy(e);const r=1===e.type_?+t:t,i=createProxy(e.scope_,n,e,r);return e.copy_[r]=i}return n},has:(e,t)=>t in latest(e),ownKeys:e=>Reflect.ownKeys(latest(e)),set(e,t,r){const n=getDescriptorFromProto(latest(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const n=peek(latest(e),t),i=n?.[DRAFT_STATE];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_.set(t,!1),!0;if(is$3(r,n)&&(void 0!==r||has$1(e.base_,t,e.type_)))return!0;prepareCopy(e),markChanged(e)}return e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_.set(t,!0),handleCrossReference(e,t,r)),!0},deleteProperty:(e,t)=>(prepareCopy(e),void 0!==peek(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),markChanged(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const r=latest(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{[WRITABLE]:!0,[CONFIGURABLE]:1!==e.type_||"length"!==t,[ENUMERABLE]:n[ENUMERABLE],[VALUE]:r[t]}:n},defineProperty(){die(11)},getPrototypeOf:e=>getPrototypeOf$1(e.base_),setPrototypeOf(){die(12)}},arrayTraps={};function peek(e,t){const r=e[DRAFT_STATE];return(r?latest(r):e)[t]}function readPropFromProto(e,t,r){const n=getDescriptorFromProto(t,r);return n?VALUE in n?n[VALUE]:n.get?.call(e.draft_):void 0}function getDescriptorFromProto(e,t){if(!(t in e))return;let r=getPrototypeOf$1(e);for(;r;){const e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=getPrototypeOf$1(r)}}function markChanged(e){e.modified_||(e.modified_=!0,e.parent_&&markChanged(e.parent_))}function prepareCopy(e){e.copy_||(e.assigned_=new Map,e.copy_=shallowCopy(e.base_,e.scope_.immer_.useStrictShallowCopy_))}each(objectTraps,(e,t)=>{arrayTraps[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}),arrayTraps.deleteProperty=function(e,t){return arrayTraps.set.call(this,e,t,void 0)},arrayTraps.set=function(e,t,r){return objectTraps.set.call(this,e[0],t,r,e[0])};var Immer2=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,r)=>{if(isFunction$3(e)&&!isFunction$3(t)){const r=t;t=e;const n=this;return function(e=r,...i){return n.produce(e,e=>t.call(this,e,...i))}}let n;if(isFunction$3(t)||die(6),void 0===r||isFunction$3(r)||die(7),isDraftable(e)){const i=enterScope(this),o=createProxy(i,e,void 0);let s=!0;try{n=t(o),s=!1}finally{s?revokeScope(i):leaveScope(i)}return usePatchesInScope(i,r),processResult(n,i)}if(!e||!isObjectish(e)){if(n=t(e),void 0===n&&(n=e),n===NOTHING&&(n=void 0),this.autoFreeze_&&freeze(n,!0),r){const t=[],i=[];getPlugin(PluginPatches).generateReplacementPatches_(e,n,{patches_:t,inversePatches_:i}),r(t,i)}return n}die(1,e)},this.produceWithPatches=(e,t)=>{if(isFunction$3(e))return(t,...r)=>this.produceWithPatches(t,t=>e(t,...r));let r,n;const i=this.produce(e,t,(e,t)=>{r=e,n=t});return[i,r,n]},isBoolean$3(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),isBoolean$3(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),isBoolean$3(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){isDraftable(e)||die(8),isDraft(e)&&(e=current(e));const t=enterScope(this),r=createProxy(t,e,void 0);return r[DRAFT_STATE].isManual_=!0,leaveScope(t),r}finishDraft(e,t){const r=e&&e[DRAFT_STATE];r&&r.isManual_||die(9);const{scope_:n}=r;return usePatchesInScope(n,t),processResult(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const n=t[r];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));const n=getPlugin(PluginPatches).applyPatches_;return isDraft(e)?n(e,t):this.produce(e,e=>n(e,t))}};function createProxy(e,t,r,n){const[i,o]=isMap$4(t)?getPlugin(PluginMapSet).proxyMap_(t,r):isSet$4(t)?getPlugin(PluginMapSet).proxySet_(t,r):createProxyProxy(t,r);return(r?.scope_??getCurrentScope()).drafts_.push(i),o.callbacks_=r?.callbacks_??[],o.key_=n,r&&void 0!==n?registerChildFinalizationCallback(r,o,n):o.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(o);const{patchPlugin_:t}=e;o.modified_&&t&&t.generatePatches_(o,[],e)}),i}function current(e){return isDraft(e)||die(10,e),currentImpl(e)}function currentImpl(e){if(!isDraftable(e)||isFrozen(e))return e;const t=e[DRAFT_STATE];let r,n=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=shallowCopy(e,t.scope_.immer_.useStrictShallowCopy_),n=t.scope_.immer_.shouldUseStrictIteration()}else r=shallowCopy(e,!0);return each(r,(e,t)=>{set$1(r,e,currentImpl(t))},n),t&&(t.finalized_=!1),r}function enableMapSet(){class e extends Map{constructor(e,t){super(),this[DRAFT_STATE]={type_:2,parent_:t,scope_:t?t.scope_:getCurrentScope(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:e,draft_:this,isManual_:!1,revoked_:!1,callbacks_:[]}}get size(){return latest(this[DRAFT_STATE]).size}has(e){return latest(this[DRAFT_STATE]).has(e)}set(e,r){const n=this[DRAFT_STATE];return i(n),latest(n).has(e)&&latest(n).get(e)===r||(t(n),markChanged(n),n.assigned_.set(e,!0),n.copy_.set(e,r),n.assigned_.set(e,!0)),this}delete(e){if(!this.has(e))return!1;const r=this[DRAFT_STATE];return i(r),t(r),markChanged(r),r.base_.has(e)?r.assigned_.set(e,!1):r.assigned_.delete(e),r.copy_.delete(e),!0}clear(){const e=this[DRAFT_STATE];i(e),latest(e).size&&(t(e),markChanged(e),e.assigned_=new Map,each(e.base_,t=>{e.assigned_.set(t,!1)}),e.copy_.clear())}forEach(e,t){const r=this[DRAFT_STATE];latest(r).forEach((r,n,i)=>{e.call(t,this.get(n),n,this)})}get(e){const r=this[DRAFT_STATE];i(r);const n=latest(r).get(e);if(r.finalized_||!isDraftable(n))return n;if(n!==r.base_.get(e))return n;const o=createProxy(r.scope_,n,r,e);return t(r),r.copy_.set(e,o),o}keys(){return latest(this[DRAFT_STATE]).keys()}values(){const e=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{const t=e.next();if(t.done)return t;return{done:!1,value:this.get(t.value)}}}}entries(){const e=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const r=this.get(t.value);return{done:!1,value:[t.value,r]}}}}[Symbol.iterator](){return this.entries()}}function t(e){e.copy_||(e.assigned_=new Map,e.copy_=new Map(e.base_))}class r extends Set{constructor(e,t){super(),this[DRAFT_STATE]={type_:3,parent_:t,scope_:t?t.scope_:getCurrentScope(),modified_:!1,finalized_:!1,copy_:void 0,base_:e,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1,assigned_:void 0,callbacks_:[]}}get size(){return latest(this[DRAFT_STATE]).size}has(e){const t=this[DRAFT_STATE];return i(t),t.copy_?!!t.copy_.has(e)||!(!t.drafts_.has(e)||!t.copy_.has(t.drafts_.get(e))):t.base_.has(e)}add(e){const t=this[DRAFT_STATE];return i(t),this.has(e)||(n(t),markChanged(t),t.copy_.add(e)),this}delete(e){if(!this.has(e))return!1;const t=this[DRAFT_STATE];return i(t),n(t),markChanged(t),t.copy_.delete(e)||!!t.drafts_.has(e)&&t.copy_.delete(t.drafts_.get(e))}clear(){const e=this[DRAFT_STATE];i(e),latest(e).size&&(n(e),markChanged(e),e.copy_.clear())}values(){const e=this[DRAFT_STATE];return i(e),n(e),e.copy_.values()}entries(){const e=this[DRAFT_STATE];return i(e),n(e),e.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(e,t){const r=this.values();let n=r.next();for(;!n.done;)e.call(t,n.value,n.value,this),n=r.next()}}function n(e){e.copy_||(e.copy_=new Set,e.base_.forEach(t=>{if(isDraftable(t)){const r=createProxy(e.scope_,t,e,t);e.drafts_.set(t,r),e.copy_.add(r)}else e.copy_.add(t)}))}function i(e){e.revoked_&&die(3,JSON.stringify(latest(e)))}loadPlugin(PluginMapSet,{proxyMap_:function(t,r){const n=new e(t,r);return[n,n[DRAFT_STATE]]},proxySet_:function(e,t){const n=new r(e,t);return[n,n[DRAFT_STATE]]},fixSetContents:function(e){if(3===e.type_&&e.copy_){const t=new Set(e.copy_);e.copy_.clear(),t.forEach(t=>{e.copy_.add(getValue(t))})}}})}var immer=new Immer2,produce=immer.produce,castDraft=e=>e;const list=[Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError,globalThis.DOMException,globalThis.AssertionError,globalThis.SystemError].filter(Boolean).map(e=>[e.name,e]),errorConstructors=new Map(list);class NonError extends Error{name="NonError";constructor(e){super(NonError._prepareSuperMessage(e))}static _prepareSuperMessage(e){try{return JSON.stringify(e)}catch{return String(e)}}}const errorProperties=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1},{property:"errors",enumerable:!1}],toJsonWasCalled=new WeakSet,toJSON=e=>{toJsonWasCalled.add(e);const t=e.toJSON();return toJsonWasCalled.delete(e),t},newError=e=>{const t=errorConstructors.get(e)??Error;return t===AggregateError?new t([]):new t},destroyCircular=({from:e,seen:t,to:r,forceEnumerable:n,maxDepth:i,depth:o,useToJSON:s,serialize:a})=>{if(r||(r=Array.isArray(e)?[]:isErrorLike(e)?newError(e.name):{}),t.push(e),o>=i)return r;if(s&&"function"==typeof e.toJSON&&!toJsonWasCalled.has(e))return toJSON(e);const c=e=>destroyCircular({from:e,seen:[...t],forceEnumerable:n,maxDepth:i,depth:o,useToJSON:s,serialize:a});for(const[n,i]of Object.entries(e))if(i&&i instanceof Uint8Array&&"Buffer"===i.constructor.name)r[n]="[object Buffer]";else if(null===i||"object"!=typeof i||"function"!=typeof i.pipe){if("function"!=typeof i)if(i&&"object"==typeof i)t.includes(e[n])?r[n]="[Circular]":(o++,r[n]=c(e[n]));else try{r[n]=i}catch{}}else r[n]="[object Stream]";if(r instanceof Error)for(const{property:t,enumerable:i}of errorProperties)void 0!==e[t]&&null!==e[t]&&Object.defineProperty(r,t,{value:isErrorLike(e[t])||Array.isArray(e[t])?c(e[t]):e[t],enumerable:!!n||i,configurable:!0,writable:!0});return r};function deserializeError(e,t={}){const{maxDepth:r=Number.POSITIVE_INFINITY}=t;return e instanceof Error?e:isMinimumViableSerializedError(e)?destroyCircular({from:e,seen:[],to:newError(e.name),maxDepth:r,depth:0,serialize:!1}):new NonError(e)}function isErrorLike(e){return Boolean(e)&&"object"==typeof e&&"string"==typeof e.name&&"string"==typeof e.message&&"string"==typeof e.stack}function isMinimumViableSerializedError(e){return Boolean(e)&&"object"==typeof e&&"string"==typeof e.message&&!Array.isArray(e)}var transit={exports:{}},goog=goog||{};goog.global=commonjsGlobal$1||self,goog.exportPath_=function(e,t,r,n){e=e.split("."),n=n||goog.global,e[0]in n||void 0===n.execScript||n.execScript("var "+e[0]);for(var i;e.length&&(i=e.shift());)if(e.length||void 0===t)n=n[i]&&n[i]!==Object.prototype[i]?n[i]:n[i]={};else if(!r&&goog.isObject(t)&&goog.isObject(n[i]))for(var o in t)t.hasOwnProperty(o)&&(n[i][o]=t[o]);else n[i]=t},goog.define=function(e,t){return t},goog.FEATURESET_YEAR=2012,goog.DEBUG=!0,goog.LOCALE="en",goog.TRUSTED_SITE=!0,goog.DISALLOW_TEST_ONLY_CODE=!goog.DEBUG,goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING=!1,goog.provide=function(e){if(goog.isInModuleLoader_())throw Error("goog.provide cannot be used within a module.");goog.constructNamespace_(e)},goog.constructNamespace_=function(e,t,r){goog.exportPath_(e,t,r)},goog.getScriptNonce=function(e){return e&&e!=goog.global?goog.getScriptNonce_(e.document):(null===goog.cspNonce_&&(goog.cspNonce_=goog.getScriptNonce_(goog.global.document)),goog.cspNonce_)},goog.NONCE_PATTERN_=/^[\w+/_-]+[=]{0,2}$/,goog.cspNonce_=null,goog.getScriptNonce_=function(e){return(e=e.querySelector&&e.querySelector("script[nonce]"))&&(e=e.nonce||e.getAttribute("nonce"))&&goog.NONCE_PATTERN_.test(e)?e:""},goog.VALID_MODULE_RE_=/^[a-zA-Z_$][a-zA-Z0-9._$]*$/,goog.module=function(e){if("string"!=typeof e||!e||-1==e.search(goog.VALID_MODULE_RE_))throw Error("Invalid module identifier");if(!goog.isInGoogModuleLoader_())throw Error("Module "+e+" has been loaded incorrectly. Note, modules cannot be loaded as normal scripts. They require some kind of pre-processing step. You're likely trying to load a module via a script tag or as a part of a concatenated bundle without rewriting the module. For more info see: https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.");if(goog.moduleLoaderState_.moduleName)throw Error("goog.module may only be called once per module.");goog.moduleLoaderState_.moduleName=e},goog.module.get=function(e){return goog.module.getInternal_(e)},goog.module.getInternal_=function(e){return null},goog.ModuleType={ES6:"es6",GOOG:"goog"},goog.moduleLoaderState_=null,goog.isInModuleLoader_=function(){return goog.isInGoogModuleLoader_()||goog.isInEs6ModuleLoader_()},goog.isInGoogModuleLoader_=function(){return!!goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.GOOG},goog.isInEs6ModuleLoader_=function(){if(goog.moduleLoaderState_&&goog.moduleLoaderState_.type==goog.ModuleType.ES6)return!0;var e=goog.global.$jscomp;return!!e&&("function"==typeof e.getCurrentModulePath&&!!e.getCurrentModulePath())},goog.module.declareLegacyNamespace=function(){goog.moduleLoaderState_.declareLegacyNamespace=!0},goog.declareModuleId=function(e){if(goog.moduleLoaderState_)goog.moduleLoaderState_.moduleName=e;else{var t=goog.global.$jscomp;if(!t||"function"!=typeof t.getCurrentModulePath)throw Error('Module with namespace "'+e+'" has been loaded incorrectly.');t=t.require(t.getCurrentModulePath()),goog.loadedModules_[e]={exports:t,type:goog.ModuleType.ES6,moduleId:e}}},goog.setTestOnly=function(e){if(goog.DISALLOW_TEST_ONLY_CODE)throw e=e||"",Error("Importing test-only code into non-debug environment"+(e?": "+e:"."))},goog.forwardDeclare=function(e){},goog.getObjectByName=function(e,t){e=e.split("."),t=t||goog.global;for(var r=0;r>>0),goog.uidCounter_=0,goog.cloneObject=function(e){var t=goog.typeOf(e);if("object"==t||"array"==t){if("function"==typeof e.clone)return e.clone();for(var r in t="array"==t?[]:{},e)t[r]=goog.cloneObject(e[r]);return t}return e},goog.bindNative_=function(e,t,r){return e.call.apply(e.bind,arguments)},goog.bindJs_=function(e,t,r){if(!e)throw Error();if(2").replace(/'/g,"'").replace(/"/g,'"').replace(/&/g,"&")),t&&(e=e.replace(/\{\$([^}]+)}/g,function(e,r){return null!=t&&r in t?t[r]:e})),e},goog.getMsgWithFallback=function(e,t){return e},goog.exportSymbol=function(e,t,r){goog.exportPath_(e,t,!0,r)},goog.exportProperty=function(e,t,r){e[t]=r},goog.inherits=function(e,t){function r(){}r.prototype=t.prototype,e.superClass_=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.base=function(e,r,n){for(var i=Array(arguments.length-2),o=2;o>8-n%1*8)){if(255<(r=e.charCodeAt(n+=.75)))throw Error("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");t=t<<8|r}return o},com.cognitect.transit.util.atob=function(e){if("undefined"!=typeof atob)return atob(e);if(1==(e=String(e).replace(/=+$/,"")).length%4)throw Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,r,n=0,i=0,o="";r=e.charAt(i++);~r&&(t=n%4?64*t+r:r,n++%4)?o+=String.fromCharCode(255&t>>(-2*n&6)):0)r=com.cognitect.transit.util.chars.indexOf(r);return o},com.cognitect.transit.util.Uint8ToBase64=function(e){for(var t,r=0,n=e.length,i="";rcom.cognitect.transit.caching.MIN_SIZE_CACHEABLE&&(!!t||(t=e.charAt(0),e=e.charAt(1),t===com.cognitect.transit.delimiters.ESC&&(":"===e||"$"===e||"#"===e)))},com.cognitect.transit.caching.idxToCode=function(e){var t=Math.floor(e/com.cognitect.transit.caching.CACHE_CODE_DIGITS);return e=String.fromCharCode(e%com.cognitect.transit.caching.CACHE_CODE_DIGITS+com.cognitect.transit.caching.BASE_CHAR_IDX),0===t?com.cognitect.transit.delimiters.SUB+e:com.cognitect.transit.delimiters.SUB+String.fromCharCode(t+com.cognitect.transit.caching.BASE_CHAR_IDX)+e},com.cognitect.transit.caching.WriteCache=function(){this.cacheSize=this.gen=this.idx=0,this.cache={}},com.cognitect.transit.caching.WriteCache.prototype.write=function(e,t){return com.cognitect.transit.caching.isCacheable(e,t)?(this.cacheSize===com.cognitect.transit.caching.MAX_CACHE_SIZE?(this.clear(),this.gen=0,this.cache={}):this.idx===com.cognitect.transit.caching.MAX_CACHE_ENTRIES&&this.clear(),null==(t=this.cache[e])?(this.cache[e]=[com.cognitect.transit.caching.idxToCode(this.idx),this.gen],this.idx++,e):t[1]!=this.gen?(t[1]=this.gen,t[0]=com.cognitect.transit.caching.idxToCode(this.idx),this.idx++,e):t[0]):e},com.cognitect.transit.caching.WriteCache.prototype.clear=function(){this.idx=0,this.gen++},com.cognitect.transit.caching.writeCache=function(){return new com.cognitect.transit.caching.WriteCache},com.cognitect.transit.caching.isCacheCode=function(e){return e.charAt(0)===com.cognitect.transit.delimiters.SUB&&" "!==e.charAt(1)},com.cognitect.transit.caching.codeToIdx=function(e){return 2===e.length?e.charCodeAt(1)-com.cognitect.transit.caching.BASE_CHAR_IDX:(e.charCodeAt(1)-com.cognitect.transit.caching.BASE_CHAR_IDX)*com.cognitect.transit.caching.CACHE_CODE_DIGITS+(e=e.charCodeAt(2)-com.cognitect.transit.caching.BASE_CHAR_IDX)},com.cognitect.transit.caching.ReadCache=function(){this.idx=0,this.cache=[]},com.cognitect.transit.caching.ReadCache.prototype.write=function(e,t){return this.idx==com.cognitect.transit.caching.MAX_CACHE_ENTRIES&&(this.idx=0),this.cache[this.idx]=e,this.idx++,e},com.cognitect.transit.caching.ReadCache.prototype.read=function(e,t){return this.cache[com.cognitect.transit.caching.codeToIdx(e)]},com.cognitect.transit.caching.ReadCache.prototype.clear=function(){this.idx=0},com.cognitect.transit.caching.readCache=function(){return new com.cognitect.transit.caching.ReadCache},com.cognitect.transit.eq={},com.cognitect.transit.eq.hashCodeProperty="transit$hashCode$",com.cognitect.transit.eq.hashCodeCounter=1,com.cognitect.transit.eq.equals=function(e,t){if(null==e)return null==t;if(e===t)return!0;if("object"==typeof e){if(com.cognitect.transit.util.isArray(e)){if(com.cognitect.transit.util.isArray(t)&&e.length===t.length){for(var r=0;r>2)},com.cognitect.transit.eq.stringCodeCache={},com.cognitect.transit.eq.stringCodeCacheSize=0,com.cognitect.transit.eq.STR_CACHE_MAX=256,com.cognitect.transit.eq.hashString=function(e){var t=com.cognitect.transit.eq.stringCodeCache[e];if(null!=t)return t;for(var r=t=0;r=com.cognitect.transit.eq.STR_CACHE_MAX&&(com.cognitect.transit.eq.stringCodeCache={},com.cognitect.transit.eq.stringCodeCacheSize=1),com.cognitect.transit.eq.stringCodeCache[e]=t},com.cognitect.transit.eq.hashMapLike=function(e){var t=0;if(null!=e.forEach)e.forEach(function(e,r,n){t=(t+(com.cognitect.transit.eq.hashCode(r)^com.cognitect.transit.eq.hashCode(e)))%4503599627370496});else for(var r=com.cognitect.transit.util.objectKeys(e),n=0;n>21;return 0==e||-1==e&&!(0==this.low_&&-2097152==this.high_)}toString(e){if(2>(e=e||10)||36>2);var r=Math.pow(e,t),n=module$contents$goog$math$Long_Long.fromBits(r,r/module$contents$goog$math$Long_TWO_PWR_32_DBL_);r=this.div(n),n=Math.abs(this.subtract(r.multiply(n)).toNumber());var i=10==e?""+n:n.toString(e);return i.length>>0}getNumBitsAbs(){if(this.isNegative())return this.equals(module$contents$goog$math$Long_Long.getMinValue())?64:this.negate().getNumBitsAbs();for(var e=0!=this.high_?this.high_:this.low_,t=31;0this.high_}isOdd(){return!(1&~this.low_)}equals(e){return this.low_==e.low_&&this.high_==e.high_}notEquals(e){return!this.equals(e)}lessThan(e){return 0>this.compare(e)}lessThanOrEqual(e){return 0>=this.compare(e)}greaterThan(e){return 0e.getLowBitsUnsigned()?1:-1:this.high_>e.high_?1:-1}negate(){var e=1+~this.low_|0;return module$contents$goog$math$Long_Long.fromBits(e,~this.high_+!e|0)}add(e){var t=this.high_>>>16,r=65535&this.high_,n=this.low_>>>16,i=e.high_>>>16,o=65535&e.high_,s=e.low_>>>16;return n=(s=((e=(65535&this.low_)+(65535&e.low_))>>>16)+(n+s))>>>16,t=((n+=r+o)>>>16)+(t+i)&65535,module$contents$goog$math$Long_Long.fromBits((65535&s)<<16|65535&e,t<<16|65535&n)}subtract(e){return this.add(e.negate())}multiply(e){if(this.isZero())return this;if(e.isZero())return e;var t=this.high_>>>16,r=65535&this.high_,n=this.low_>>>16,i=65535&this.low_,o=e.high_>>>16,s=65535&e.high_,a=e.low_>>>16,c=i*(e=65535&e.low_),l=(c>>>16)+n*e,u=l>>>16;u+=(l=(65535&l)+i*a)>>>16;var d=(u+=r*e)>>>16;return d=(d+=(u=(65535&u)+n*a)>>>16)+((u=(65535&u)+i*s)>>>16)+(t*e+r*a+n*s+i*o)&65535,module$contents$goog$math$Long_Long.fromBits((65535&l)<<16|65535&c,d<<16|65535&u)}div(e){if(e.isZero())throw Error("division by zero");if(this.isNegative()){if(this.equals(module$contents$goog$math$Long_Long.getMinValue())){if(e.equals(module$contents$goog$math$Long_Long.getOne())||e.equals(module$contents$goog$math$Long_Long.getNegOne()))return module$contents$goog$math$Long_Long.getMinValue();if(e.equals(module$contents$goog$math$Long_Long.getMinValue()))return module$contents$goog$math$Long_Long.getOne();var t=this.shiftRight(1).div(e).shiftLeft(1);if(t.equals(module$contents$goog$math$Long_Long.getZero()))return e.isNegative()?module$contents$goog$math$Long_Long.getOne():module$contents$goog$math$Long_Long.getNegOne();var r=this.subtract(e.multiply(t));return t.add(r.div(e))}return e.isNegative()?this.negate().div(e.negate()):this.negate().div(e).negate()}if(this.isZero())return module$contents$goog$math$Long_Long.getZero();if(e.isNegative())return e.equals(module$contents$goog$math$Long_Long.getMinValue())?module$contents$goog$math$Long_Long.getZero():this.div(e.negate()).negate();var n=module$contents$goog$math$Long_Long.getZero();for(r=this;r.greaterThanOrEqual(e);){t=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));var i=Math.ceil(Math.log(t)/Math.LN2);i=48>=i?1:Math.pow(2,i-48);for(var o=module$contents$goog$math$Long_Long.fromNumber(t),s=o.multiply(e);s.isNegative()||s.greaterThan(r);)t-=i,s=(o=module$contents$goog$math$Long_Long.fromNumber(t)).multiply(e);o.isZero()&&(o=module$contents$goog$math$Long_Long.getOne()),n=n.add(o),r=r.subtract(s)}return n}modulo(e){return this.subtract(this.div(e).multiply(e))}not(){return module$contents$goog$math$Long_Long.fromBits(~this.low_,~this.high_)}and(e){return module$contents$goog$math$Long_Long.fromBits(this.low_&e.low_,this.high_&e.high_)}or(e){return module$contents$goog$math$Long_Long.fromBits(this.low_|e.low_,this.high_|e.high_)}xor(e){return module$contents$goog$math$Long_Long.fromBits(this.low_^e.low_,this.high_^e.high_)}shiftLeft(e){if(0==(e&=63))return this;var t=this.low_;return 32>e?module$contents$goog$math$Long_Long.fromBits(t<>>32-e):module$contents$goog$math$Long_Long.fromBits(0,t<e?module$contents$goog$math$Long_Long.fromBits(this.low_>>>e|t<<32-e,t>>e):module$contents$goog$math$Long_Long.fromBits(t>>e-32,0<=t?0:-1)}shiftRightUnsigned(e){if(0==(e&=63))return this;var t=this.high_;return 32>e?module$contents$goog$math$Long_Long.fromBits(this.low_>>>e|t<<32-e,t>>>e):32==e?module$contents$goog$math$Long_Long.fromBits(t,0):module$contents$goog$math$Long_Long.fromBits(t>>>e-32,0)}static fromInt(e){var t=0|e;return goog.asserts.assert(e===t,"value should be a 32-bit integer"),-128<=t&&128>t?module$contents$goog$math$Long_getCachedIntValue_(t):new module$contents$goog$math$Long_Long(t,0>t?-1:0)}static fromNumber(e){return 0=module$contents$goog$math$Long_TWO_PWR_63_DBL_?module$contents$goog$math$Long_Long.getMaxValue():new module$contents$goog$math$Long_Long(e,e/module$contents$goog$math$Long_TWO_PWR_32_DBL_):0>e?e<=-module$contents$goog$math$Long_TWO_PWR_63_DBL_?module$contents$goog$math$Long_Long.getMinValue():new module$contents$goog$math$Long_Long(-e,-e/module$contents$goog$math$Long_TWO_PWR_32_DBL_).negate():module$contents$goog$math$Long_Long.getZero()}static fromBits(e,t){return new module$contents$goog$math$Long_Long(e,t)}static fromString(e,t){if("-"==e.charAt(0))return module$contents$goog$math$Long_Long.fromString(e.substring(1),t).negate();var r=parseInt(e,t||10);if(r<=module$contents$goog$math$Long_MAX_SAFE_INTEGER_)return new module$contents$goog$math$Long_Long(r%module$contents$goog$math$Long_TWO_PWR_32_DBL_|0,r/module$contents$goog$math$Long_TWO_PWR_32_DBL_|0);if(0==e.length)throw Error("number format error: empty string");if(0<=e.indexOf("-"))throw Error('number format error: interior "-" character: '+e);if(2>(t=t||10)||36o?(o=module$contents$goog$math$Long_Long.fromNumber(Math.pow(t,o)),n=n.multiply(o).add(module$contents$goog$math$Long_Long.fromNumber(s))):n=(n=n.multiply(r)).add(module$contents$goog$math$Long_Long.fromNumber(s))}return n}static isStringInRange(e,t){if(2>(t=t||10)||36e?-1:0)})}const module$contents$goog$math$Long_MAX_VALUE_FOR_RADIX_=" 111111111111111111111111111111111111111111111111111111111111111 2021110011022210012102010021220101220221 13333333333333333333333333333333 1104332401304422434310311212 1540241003031030222122211 22341010611245052052300 777777777777777777777 67404283172107811827 9223372036854775807 1728002635214590697 41a792678515120367 10b269549075433c37 4340724c6c71dc7a7 160e2ad3246366807 7fffffffffffffff 33d3d8307b214008 16agh595df825fa7 ba643dci0ffeehh 5cbfjia3fh26ja7 2heiciiie82dh97 1adaibb21dckfa7 i6k448cf4192c2 acd772jnc9l0l7 64ie1focnn5g77 3igoecjbmca687 27c48l5b37oaop 1bk39f3ah3dmq7 q1se8f0m04isb hajppbc1fc207 bm03i95hia437 7vvvvvvvvvvvv 5hg4ck9jd4u37 3tdtk1v8j6tpp 2pijmikexrxp7 1y2p0ij32e8e7".split(" "),module$contents$goog$math$Long_MIN_VALUE_FOR_RADIX_=" -1000000000000000000000000000000000000000000000000000000000000000 -2021110011022210012102010021220101220222 -20000000000000000000000000000000 -1104332401304422434310311213 -1540241003031030222122212 -22341010611245052052301 -1000000000000000000000 -67404283172107811828 -9223372036854775808 -1728002635214590698 -41a792678515120368 -10b269549075433c38 -4340724c6c71dc7a8 -160e2ad3246366808 -8000000000000000 -33d3d8307b214009 -16agh595df825fa8 -ba643dci0ffeehi -5cbfjia3fh26ja8 -2heiciiie82dh98 -1adaibb21dckfa8 -i6k448cf4192c3 -acd772jnc9l0l8 -64ie1focnn5g78 -3igoecjbmca688 -27c48l5b37oaoq -1bk39f3ah3dmq8 -q1se8f0m04isc -hajppbc1fc208 -bm03i95hia438 -8000000000000 -5hg4ck9jd4u38 -3tdtk1v8j6tpq -2pijmikexrxp8 -1y2p0ij32e8e8".split(" "),module$contents$goog$math$Long_MAX_SAFE_INTEGER_=9007199254740991,module$contents$goog$math$Long_TWO_PWR_32_DBL_=4294967296,module$contents$goog$math$Long_TWO_PWR_63_DBL_=0x8000000000000000,module$contents$goog$math$Long_ZERO_=module$contents$goog$math$Long_Long.fromBits(0,0),module$contents$goog$math$Long_ONE_=module$contents$goog$math$Long_Long.fromBits(1,0),module$contents$goog$math$Long_NEG_ONE_=module$contents$goog$math$Long_Long.fromBits(-1,-1),module$contents$goog$math$Long_MAX_VALUE_=module$contents$goog$math$Long_Long.fromBits(4294967295,2147483647),module$contents$goog$math$Long_MIN_VALUE_=module$contents$goog$math$Long_Long.fromBits(0,2147483648),module$contents$goog$math$Long_TWO_PWR_24_=module$contents$goog$math$Long_Long.fromBits(16777216,0);com.cognitect.transit.types={},com.cognitect.transit.types.ITERATOR="undefined"!=typeof Symbol?Symbol.iterator:"@@iterator",com.cognitect.transit.types.TaggedValue=function(e,t){this.tag=e,this.rep=t,this.hashCode=-1},com.cognitect.transit.types.TaggedValue.prototype.toString=function(){return"[TaggedValue: "+this.tag+", "+this.rep+"]"},com.cognitect.transit.types.TaggedValue.prototype.equiv=function(e){return com.cognitect.transit.eq.equals(this,e)},com.cognitect.transit.types.TaggedValue.prototype.equiv=com.cognitect.transit.types.TaggedValue.prototype.equiv,com.cognitect.transit.types.TaggedValue.prototype.com$cognitect$transit$equals=function(e){return e instanceof com.cognitect.transit.types.TaggedValue&&(this.tag===e.tag&&com.cognitect.transit.eq.equals(this.rep,e.rep))},com.cognitect.transit.types.TaggedValue.prototype.com$cognitect$transit$hashCode=function(){return-1===this.hashCode&&(this.hashCode=com.cognitect.transit.eq.hashCombine(com.cognitect.transit.eq.hashCode(this.tag),com.cognitect.transit.eq.hashCode(this.rep))),this.hashCode},com.cognitect.transit.types.taggedValue=function(e,t){return new com.cognitect.transit.types.TaggedValue(e,t)},com.cognitect.transit.types.isTaggedValue=function(e){return e instanceof com.cognitect.transit.types.TaggedValue},com.cognitect.transit.types.nullValue=function(){return null},com.cognitect.transit.types.boolValue=function(e){return"t"===e},com.cognitect.transit.types.MAX_INT=module$contents$goog$math$Long_Long.fromString("9007199254740991"),com.cognitect.transit.types.MIN_INT=module$contents$goog$math$Long_Long.fromString("-9007199254740991"),com.cognitect.transit.types.intValue=function(e){return"number"==typeof e||e instanceof module$contents$goog$math$Long_Long||(e=module$contents$goog$math$Long_Long.fromString(e,10)).greaterThan(com.cognitect.transit.types.MAX_INT)||e.lessThan(com.cognitect.transit.types.MIN_INT)?e:e.toNumber()},module$contents$goog$math$Long_Long.prototype.equiv=function(e){return com.cognitect.transit.eq.equals(this,e)},module$contents$goog$math$Long_Long.prototype.equiv=module$contents$goog$math$Long_Long.prototype.equiv,module$contents$goog$math$Long_Long.prototype.com$cognitect$transit$equals=function(e){return e instanceof module$contents$goog$math$Long_Long&&this.equals(e)},module$contents$goog$math$Long_Long.prototype.com$cognitect$transit$hashCode=function(){return this.toInt()},com.cognitect.transit.types.isInteger=function(e){return e instanceof module$contents$goog$math$Long_Long||"number"==typeof e&&!isNaN(e)&&1/0!==e&&parseFloat(e)===parseInt(e,10)},com.cognitect.transit.types.floatValue=function(e){return parseFloat(e)},com.cognitect.transit.types.bigInteger=function(e){return com.cognitect.transit.types.taggedValue("n",e)},com.cognitect.transit.types.isBigInteger=function(e){return e instanceof com.cognitect.transit.types.TaggedValue&&"n"===e.tag},com.cognitect.transit.types.bigDecimalValue=function(e){return com.cognitect.transit.types.taggedValue("f",e)},com.cognitect.transit.types.isBigDecimal=function(e){return e instanceof com.cognitect.transit.types.TaggedValue&&"f"===e.tag},com.cognitect.transit.types.charValue=function(e){return e},com.cognitect.transit.types.Keyword=function(e){this._name=e,this.hashCode=-1},com.cognitect.transit.types.Keyword.prototype.toString=function(){return":"+this._name},com.cognitect.transit.types.Keyword.prototype.namespace=function(){var e=this._name.indexOf("/");return-1!=e?this._name.substring(0,e):null},com.cognitect.transit.types.Keyword.prototype.name=function(){var e=this._name.indexOf("/");return-1!=e?this._name.substring(e+1,this._name.length):this._name},com.cognitect.transit.types.Keyword.prototype.equiv=function(e){return com.cognitect.transit.eq.equals(this,e)},com.cognitect.transit.types.Keyword.prototype.equiv=com.cognitect.transit.types.Keyword.prototype.equiv,com.cognitect.transit.types.Keyword.prototype.com$cognitect$transit$equals=function(e){return e instanceof com.cognitect.transit.types.Keyword&&this._name==e._name},com.cognitect.transit.types.Keyword.prototype.com$cognitect$transit$hashCode=function(){return-1===this.hashCode&&(this.hashCode=com.cognitect.transit.eq.hashCode(this._name)),this.hashCode},com.cognitect.transit.types.keyword=function(e){return new com.cognitect.transit.types.Keyword(e)},com.cognitect.transit.types.isKeyword=function(e){return e instanceof com.cognitect.transit.types.Keyword},com.cognitect.transit.types.Symbol=function(e){this._name=e,this.hashCode=-1},com.cognitect.transit.types.Symbol.prototype.namespace=function(){var e=this._name.indexOf("/");return-1!=e?this._name.substring(0,e):null},com.cognitect.transit.types.Symbol.prototype.name=function(){var e=this._name.indexOf("/");return-1!=e?this._name.substring(e+1,this._name.length):this._name},com.cognitect.transit.types.Symbol.prototype.toString=function(){return this._name},com.cognitect.transit.types.Symbol.prototype.equiv=function(e){return com.cognitect.transit.eq.equals(this,e)},com.cognitect.transit.types.Symbol.prototype.equiv=com.cognitect.transit.types.Symbol.prototype.equiv,com.cognitect.transit.types.Symbol.prototype.com$cognitect$transit$equals=function(e){return e instanceof com.cognitect.transit.types.Symbol&&this._name==e._name},com.cognitect.transit.types.Symbol.prototype.com$cognitect$transit$hashCode=function(){return-1===this.hashCode&&(this.hashCode=com.cognitect.transit.eq.hashCode(this._name)),this.hashCode},com.cognitect.transit.types.symbol=function(e){return new com.cognitect.transit.types.Symbol(e)},com.cognitect.transit.types.isSymbol=function(e){return e instanceof com.cognitect.transit.types.Symbol},com.cognitect.transit.types.hexFor=function(e,t,r){var n="";r=r||t+1;for(var i=8*(7-t),o=module$contents$goog$math$Long_Long.fromInt(255).shiftLeft(i);tn;n+=2,r-=8)t|=parseInt(e.substring(n,n+2),16)<n;n+=2,r-=8)i|=parseInt(e.substring(n,n+2),16)<n;n+=2,r-=8)t|=parseInt(e.substring(n,n+2),16)<n;n+=2,r-=8)i|=parseInt(e.substring(n,n+2),16)< "+com.cognitect.transit.types.print(n),tcom.cognitect.transit.types.ARRAY_MAP_ACCESS_THRESHOLD&&(this.backingMap=com.cognitect.transit.types.map(this._entries,!1,!0),this._entries=[],!0))},com.cognitect.transit.types.TransitArrayMap.prototype.clear=function(){this.hashCode=-1,this.backingMap?this.backingMap.clear():this._entries=[],this.size=0},com.cognitect.transit.types.TransitArrayMap.prototype.clear=com.cognitect.transit.types.TransitArrayMap.prototype.clear,com.cognitect.transit.types.TransitArrayMap.prototype.keys=function(){return this.backingMap?this.backingMap.keys():new com.cognitect.transit.types.TransitArrayMapIterator(this._entries,com.cognitect.transit.types.KEYS)},com.cognitect.transit.types.TransitArrayMap.prototype.keys=com.cognitect.transit.types.TransitArrayMap.prototype.keys,com.cognitect.transit.types.TransitArrayMap.prototype.keySet=function(){if(this.backingMap)return this.backingMap.keySet();for(var e=[],t=0,r=0;rcom.cognitect.transit.types.ARRAY_MAP_THRESHOLD&&(this.backingMap=com.cognitect.transit.types.map(this._entries,!1,!0),this._entries=null)}},com.cognitect.transit.types.TransitArrayMap.prototype.set=com.cognitect.transit.types.TransitArrayMap.prototype.set,com.cognitect.transit.types.TransitArrayMap.prototype.delete=function(e){if(this.hashCode=-1,this.backingMap)return e=this.backingMap.delete(e),this.size=this.backingMap.size,e;for(var t=0;t=e.length&&this.arrayBuilder.fromArray){for(i=[],n=0;n{}},e={};function n(t){var r=e[t];if(void 0!==r)return r.exports;var i=e[t]={exports:{}};return t$1[t](i,i.exports,n),i.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var s={};n.d(s,{MG:()=>$$2,fr:()=>Lt$1,sR:()=>Ae,Zo:()=>ke$1,iH:()=>Re$1,rt:()=>Pt,jB:()=>be$1,M8:()=>le,$t:()=>Ce,aq:()=>me$1,pG:()=>Ot$1,eP:()=>Te$1,KU:()=>xe,zW:()=>Ie,IX:()=>E$1,mY:()=>_$1,a7:()=>j$1,JG:()=>Ut$1,ay:()=>Xt$1,X2:()=>ee$1,WU:()=>de$2,Uw:()=>ge$1,gw:()=>pe$1,iX:()=>Fe,re:()=>se$1,Pg:()=>Be$1,tD:()=>ie$1,R$:()=>te$1,Dj:()=>Ft$1,m7:()=>U$2,NZ:()=>P$1,xo:()=>b$1,ou:()=>i,qC:()=>ze$1,mD:()=>d,Ay:()=>Ye$1});class i{constructor(){this.source=null,this.type=null,this.channel=null,this.start=null,this.stop=null,this.tokenIndex=null,this.line=null,this.column=null,this._text=null}getTokenSource(){return this.source[0]}getInputStream(){return this.source[1]}get text(){return this._text}set text(e){this._text=e}}function r(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r>>16)*l&65535)<<16)&4294967295,i=i<<15|i>>>17,i=(65535&i)*u+(((i>>>16)*u&65535)<<16)&4294967295,c^=i,c=c<<13|c>>>19,n=5*(65535&c)+((5*(c>>>16)&65535)<<16)&4294967295,c=27492+(65535&n)+((58964+(n>>>16)&65535)<<16);switch(i=0,s){case 3:i^=(255&r.charCodeAt(d+2))<<16;case 2:i^=(255&r.charCodeAt(d+1))<<8;case 1:i^=255&r.charCodeAt(d),i=(65535&i)*l+(((i>>>16)*l&65535)<<16)&4294967295,i=i<<15|i>>>17,i=(65535&i)*u+(((i>>>16)*u&65535)<<16)&4294967295,c^=i}return c^=r.length,c^=c>>>16,c=2246822507*(65535&c)+((2246822507*(c>>>16)&65535)<<16)&4294967295,c^=c>>>13,c=3266489909*(65535&c)+((3266489909*(c>>>16)&65535)<<16)&4294967295,c^=c>>>16,c>>>0}let l$1=class e{constructor(){this.count=0,this.hash=0}update(){for(let e=0;e>>17,e*=461845907,this.count=this.count+1;let r=this.hash^e;r=r<<13|r>>>19,r=5*r+3864292196,this.hash=r}}}finish(){let e=this.hash^4*this.count;return e^=e>>>16,e*=2246822507,e^=e>>>13,e*=3266489909,e^=e>>>16,e}static hashStuff(){const t=new e;return t.update.apply(t,arguments),t.finish()}};function h$2(e){return e?"string"==typeof e?a(e):e.hashCode():-1}function c$1(e,t){return e&&e.equals?e.equals(t):e===t}function u(e){return null===e?"null":e}function d(e){return Array.isArray(e)?"["+e.map(u).join(", ")+"]":"null"}let g$4=class{constructor(e,t){this.buckets=new Array(16),this.threshold=Math.floor(12),this.itemCount=0,this.hashFunction=e||h$2,this.equalsFunction=t||c$1}get(e){if(null==e)return e;const t=this._getBucket(e);if(!t)return null;for(const r of t)if(this.equalsFunction(r,e))return r;return null}add(e){return this.getOrAdd(e)===e}getOrAdd(e){this._expand();const t=this._getSlot(e);let r=this.buckets[t];if(!r)return r=[e],this.buckets[t]=r,this.itemCount++,e;for(const t of r)if(this.equalsFunction(t,e))return t;return r.push(e),this.itemCount++,e}has(e){return null!=this.get(e)}values(){return this.buckets.filter(e=>null!=e).flat(1)}toString(){return d(this.values())}get length(){return this.itemCount}_getSlot(e){return this.hashFunction(e)&this.buckets.length-1}_getBucket(e){return this.buckets[this._getSlot(e)]}_expand(){if(this.itemCount<=this.threshold)return;const e=this.buckets,t=2*this.buckets.length;this.buckets=new Array(t),this.threshold=Math.floor(.75*t);for(const t of e)if(t)for(const e of t){const t=this._getSlot(e);let r=this.buckets[t];r||(r=[],this.buckets[t]=r),r.push(e)}}};class p{hashCode(){const e=new l$1;return this.updateHashCode(e),e.finish()}evaluate(e,t){}evalPrecedence(e,t){return this}static andContext(e,t){if(null===e||e===p.NONE)return t;if(null===t||t===p.NONE)return e;const r=new f(e,t);return 1===r.opnds.length?r.opnds[0]:r}static orContext(e,t){if(null===e)return t;if(null===t)return e;if(e===p.NONE||t===p.NONE)return p.NONE;const r=new x$2(e,t);return 1===r.opnds.length?r.opnds[0]:r}}class f extends p{constructor(e,t){super();const r=new g$4;e instanceof f?e.opnds.map(function(e){r.add(e)}):r.add(e),t instanceof f?t.opnds.map(function(e){r.add(e)}):r.add(t);const n=T$2(r);if(n.length>0){let e=null;n.map(function(t){(null===e||t.precedencee.toString());return(e.length>3?e.slice(3):e).join("&&")}}let x$2=class e extends p{constructor(t,r){super();const n=new g$4;t instanceof e?t.opnds.map(function(e){n.add(e)}):n.add(t),r instanceof e?r.opnds.map(function(e){n.add(e)}):n.add(r);const i=T$2(n);if(i.length>0){const e=i.sort(function(e,t){return e.compareTo(t)}),t=e[e.length-1];n.add(t)}this.opnds=Array.from(n.values())}equals(t){return this===t||t instanceof e&&r(this.opnds,t.opnds)}updateHashCode(e){e.update(this.opnds,"OR")}evaluate(e,t){for(let r=0;re.toString());return(e.length>3?e.slice(3):e).join("||")}};function T$2(e){const t=[];return e.values().map(function(e){e instanceof p.PrecedencePredicate&&t.push(e)}),t}function S$2(e,t){if(null===e){const e={state:null,alt:null,context:null,semanticContext:null};return t&&(e.reachesIntoOuterContext=0),e}{const r={};return r.state=e.state||null,r.alt=void 0===e.alt?null:e.alt,r.context=e.context||null,r.semanticContext=e.semanticContext||null,t&&(r.reachesIntoOuterContext=e.reachesIntoOuterContext||0,r.precedenceFilterSuppressed=e.precedenceFilterSuppressed||!1),r}}let m$1=class e{constructor(e,t){this.checkContext(e,t),e=S$2(e),t=S$2(t,!0),this.state=null!==e.state?e.state:t.state,this.alt=null!==e.alt?e.alt:t.alt,this.context=null!==e.context?e.context:t.context,this.semanticContext=null!==e.semanticContext?e.semanticContext:null!==t.semanticContext?t.semanticContext:p.NONE,this.reachesIntoOuterContext=t.reachesIntoOuterContext,this.precedenceFilterSuppressed=t.precedenceFilterSuppressed}checkContext(e,t){null!==e.context&&void 0!==e.context||null!==t&&null!==t.context&&void 0!==t.context||(this.context=null)}hashCode(){const e=new l$1;return this.updateHashCode(e),e.finish()}updateHashCode(e){e.update(this.state.stateNumber,this.alt,this.context,this.semanticContext)}equals(t){return this===t||t instanceof e&&this.state.stateNumber===t.state.stateNumber&&this.alt===t.alt&&(null===this.context?null===t.context:this.context.equals(t.context))&&this.semanticContext.equals(t.semanticContext)&&this.precedenceFilterSuppressed===t.precedenceFilterSuppressed}hashCodeForConfigSet(){const e=new l$1;return e.update(this.state.stateNumber,this.alt,this.semanticContext),e.finish()}equalsForConfigSet(t){return this===t||t instanceof e&&this.state.stateNumber===t.state.stateNumber&&this.alt===t.alt&&this.semanticContext.equals(t.semanticContext)}toString(){return"("+this.state+","+this.alt+(null!==this.context?",["+this.context.toString()+"]":"")+(this.semanticContext!==p.NONE?","+this.semanticContext.toString():"")+(this.reachesIntoOuterContext>0?",up="+this.reachesIntoOuterContext:"")+")"}},E$1=class e{constructor(e,t){this.start=e,this.stop=t}clone(){return new e(this.start,this.stop)}contains(e){return e>=this.start&&ethis.addInterval(e),this),this}reduce(e){if(e=r.stop?(this.intervals.splice(e+1,1),this.reduce(e)):t.stop>=r.start&&(this.intervals[e]=new E$1(t.start,r.stop),this.intervals.splice(e+1,1))}}complement(t,r){const n=new e;return n.addInterval(new E$1(t,r+1)),null!==this.intervals&&this.intervals.forEach(e=>n.removeRange(e)),n}contains(e){if(null===this.intervals)return!1;for(let t=0;tr.start&&e.stop=r.stop?(this.intervals.splice(t,1),t-=1):e.start"):e.push("'"+String.fromCharCode(r.start)+"'"):e.push("'"+String.fromCharCode(r.start)+"'..'"+String.fromCharCode(r.stop-1)+"'")}return e.length>1?"{"+e.join(", ")+"}":e[0]}toIndexString(){const e=[];for(let t=0;t"):e.push(r.start.toString()):e.push(r.start.toString()+".."+(r.stop-1).toString())}return e.length>1?"{"+e.join(", ")+"}":e[0]}toTokenString(e,t){const r=[];for(let n=0;n1?"{"+r.join(", ")+"}":r[0]}elementName(e,t,r){return r===i.EOF?"":r===i.EPSILON?"":e[r]||t[r]}get length(){return this.intervals.map(e=>e.length).reduce((e,t)=>e+t)}},C$1=class e{constructor(){this.atn=null,this.stateNumber=e.INVALID_STATE_NUMBER,this.stateType=null,this.ruleIndex=0,this.epsilonOnlyTransitions=!1,this.transitions=[],this.nextTokenWithinRule=null}toString(){return this.stateNumber}equals(t){return t instanceof e&&this.stateNumber===t.stateNumber}isNonGreedyExitState(){return!1}addTransition(e,t){void 0===t&&(t=-1),0===this.transitions.length?this.epsilonOnlyTransitions=e.isEpsilon:this.epsilonOnlyTransitions!==e.isEpsilon&&(this.epsilonOnlyTransitions=!1),-1===t?this.transitions.push(e):this.transitions.splice(t,1,e)}};C$1.INVALID_TYPE=0,C$1.BASIC=1,C$1.RULE_START=2,C$1.BLOCK_START=3,C$1.PLUS_BLOCK_START=4,C$1.STAR_BLOCK_START=5,C$1.TOKEN_START=6,C$1.RULE_STOP=7,C$1.BLOCK_END=8,C$1.STAR_LOOP_BACK=9,C$1.STAR_LOOP_ENTRY=10,C$1.PLUS_LOOP_BACK=11,C$1.LOOP_END=12,C$1.serializationNames=["INVALID","BASIC","RULE_START","BLOCK_START","PLUS_BLOCK_START","STAR_BLOCK_START","TOKEN_START","RULE_STOP","BLOCK_END","STAR_LOOP_BACK","STAR_LOOP_ENTRY","PLUS_LOOP_BACK","LOOP_END"],C$1.INVALID_STATE_NUMBER=-1;let A$2=class extends C$1{constructor(){return super(),this.stateType=C$1.RULE_STOP,this}},N$1=class{constructor(e){if(null==e)throw"target cannot be null.";this.target=e,this.isEpsilon=!1,this.label=null}};N$1.EPSILON=1,N$1.RANGE=2,N$1.RULE=3,N$1.PREDICATE=4,N$1.ATOM=5,N$1.ACTION=6,N$1.SET=7,N$1.NOT_SET=8,N$1.WILDCARD=9,N$1.PRECEDENCE=10,N$1.serializationNames=["INVALID","EPSILON","RANGE","RULE","PREDICATE","ATOM","ACTION","SET","NOT_SET","WILDCARD","PRECEDENCE"],N$1.serializationTypes={EpsilonTransition:N$1.EPSILON,RangeTransition:N$1.RANGE,RuleTransition:N$1.RULE,PredicateTransition:N$1.PREDICATE,AtomTransition:N$1.ATOM,ActionTransition:N$1.ACTION,SetTransition:N$1.SET,NotSetTransition:N$1.NOT_SET,WildcardTransition:N$1.WILDCARD,PrecedencePredicateTransition:N$1.PRECEDENCE};let k$1=class extends N$1{constructor(e,t,r,n){super(e),this.ruleIndex=t,this.precedence=r,this.followState=n,this.serializationType=N$1.RULE,this.isEpsilon=!0}matches(e,t,r){return!1}},I$2=class extends N$1{constructor(e,t){super(e),this.serializationType=N$1.SET,null!=t?this.label=t:(this.label=new _$1,this.label.addOne(i.INVALID_TYPE))}matches(e,t,r){return this.label.contains(e)}toString(){return this.label.toString()}},y$2=class extends I$2{constructor(e,t){super(e,t),this.serializationType=N$1.NOT_SET}matches(e,t,r){return e>=t&&e<=r&&!super.matches(e,t,r)}toString(){return"~"+super.toString()}},L$1=class extends N$1{constructor(e){super(e),this.serializationType=N$1.WILDCARD}matches(e,t,r){return e>=t&&e<=r}toString(){return"."}};class O extends N$1{constructor(e){super(e)}}let R$2=class{},w$2=class extends R$2{},v$2=class extends w$2{},P$1=class extends v$2{get ruleContext(){throw new Error("missing interface implementation")}},b$1=class extends v$2{},D$1=class extends b$1{};const F$1={toStringTree:function(e,t,r){t=t||null,null!==(r=r||null)&&(t=r.ruleNames);let n=F$1.getNodeText(e,t);n=function(e){return e.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r")}(n);const i=e.getChildCount();if(0===i)return n;let o="("+n+" ";i>0&&(n=F$1.toStringTree(e.getChild(0),t),o=o.concat(n));for(let r=1;r=0&&t0&&(e+=", "),this.returnStates[t]!==B$2.EMPTY_RETURN_STATE?(e+=this.returnStates[t],null!==this.parents[t]?e=e+" "+this.parents[t]:e+="null"):e+="$";return e+"]"}}get length(){return this.returnStates.length}},V$2=class e extends B$2{constructor(e,t){let r=0;const n=new l$1;null!==e?n.update(e,t):n.update(1),r=n.finish(),super(r),this.parentCtx=e,this.returnState=t}getParent(e){return this.parentCtx}getReturnState(e){return this.returnState}equals(t){return this===t||t instanceof e&&this.hashCode()===t.hashCode()&&this.returnState===t.returnState&&(null==this.parentCtx?null==t.parentCtx:this.parentCtx.equals(t.parentCtx))}toString(){const e=null===this.parentCtx?"":this.parentCtx.toString();return 0===e.length?this.returnState===B$2.EMPTY_RETURN_STATE?"$":""+this.returnState:this.returnState+" "+e}get length(){return 1}static create(t,r){return r===B$2.EMPTY_RETURN_STATE&&null===t?B$2.EMPTY:new e(t,r)}},q$2=class extends V$2{constructor(){super(null,B$2.EMPTY_RETURN_STATE)}isEmpty(){return!0}getParent(e){return null}getReturnState(e){return this.returnState}equals(e){return this===e}toString(){return"$"}};B$2.EMPTY=new q$2;let H$1=class{constructor(e,t){this.buckets=new Array(16),this.threshold=Math.floor(12),this.itemCount=0,this.hashFunction=e||h$2,this.equalsFunction=t||c$1}set(e,t){this._expand();const r=this._getSlot(e);let n=this.buckets[r];if(!n)return n=[[e,t]],this.buckets[r]=n,this.itemCount++,t;const i=n.find(t=>this.equalsFunction(t[0],e),this);if(i){const e=i[1];return i[1]=t,e}return n.push([e,t]),this.itemCount++,t}containsKey(e){const t=this._getBucket(e);return!!t&&!!t.find(t=>this.equalsFunction(t[0],e),this)}get(e){const t=this._getBucket(e);if(!t)return null;const r=t.find(t=>this.equalsFunction(t[0],e),this);return r?r[1]:null}entries(){return this.buckets.filter(e=>null!=e).flat(1)}getKeys(){return this.entries().map(e=>e[0])}getValues(){return this.entries().map(e=>e[1])}toString(){return"["+this.entries().map(e=>"{"+e[0]+":"+e[1]+"}").join(", ")+"]"}get length(){return this.itemCount}_getSlot(e){return this.hashFunction(e)&this.buckets.length-1}_getBucket(e){return this.buckets[this._getSlot(e)]}_expand(){if(this.itemCount<=this.threshold)return;const e=this.buckets,t=2*this.buckets.length;this.buckets=new Array(t),this.threshold=Math.floor(.75*t);for(const t of e)if(t)for(const e of t){const t=this._getSlot(e[0]);let r=this.buckets[t];r||(r=[],this.buckets[t]=r),r.push(e)}}};function K$2(e,t){if(null==t&&(t=U$2.EMPTY),null===t.parentCtx||t===U$2.EMPTY)return B$2.EMPTY;const r=K$2(e,t.parentCtx),n=e.states[t.invokingState].transitions[0];return V$2.create(r,n.followState.stateNumber)}function Y$1(e,t,r){if(e.isEmpty())return e;let n=r.get(e)||null;if(null!==n)return n;if(n=t.get(e),null!==n)return r.set(e,n),n;let i=!1,o=[];for(let n=0;nt.returnState&&(i[0]=t.returnState,i[1]=e.returnState);const o=new z$4([r,r],i);return null!==n&&n.set(e,t,o),o}const i=[e.returnState,t.returnState];let o=[e.parentCtx,t.parentCtx];e.returnState>t.returnState&&(i[0]=t.returnState,i[1]=e.returnState,o=[t.parentCtx,e.parentCtx]);const s=new z$4(o,i);return null!==n&&n.set(e,t,s),s}}(e,t,r,n);if(r){if(e instanceof q$2)return e;if(t instanceof q$2)return t}return e instanceof V$2&&(e=new z$4([e.getParent()],[e.returnState])),t instanceof V$2&&(t=new z$4([t.getParent()],[t.returnState])),function(e,t,r,n){if(null!==n){let r=n.get(e,t);if(null!==r)return B$2.trace_atn_sim&&console.log("mergeArrays a="+e+",b="+t+" -> previous"),r;if(r=n.get(t,e),null!==r)return B$2.trace_atn_sim&&console.log("mergeArrays a="+e+",b="+t+" -> previous"),r}let i=0,o=0,s=0,a=new Array(e.returnStates.length+t.returnStates.length).fill(0),c=new Array(e.returnStates.length+t.returnStates.length).fill(null);for(;i a"),e):l.equals(t)?(null!==n&&n.set(e,t,t),B$2.trace_atn_sim&&console.log("mergeArrays a="+e+",b="+t+" -> b"),t):(function(e){const t=new H$1;for(let r=0;r "+l),l)}(e,t,r,n)}let W$2=class e{constructor(){this.data=new Uint32Array(1)}set(t){e._checkIndex(t),this._resize(t),this.data[t>>>5]|=1<>>5;return!(r>=this.data.length||!(this.data[r]&1<>>5;r>=1;return r+32*e}}return 0}hashCode(){return l$1.hashStuff(this.values())}equals(t){return t instanceof e&&r(this.data,t.data)}toString(){return"{"+this.values().join(", ")+"}"}get length(){return this.data.map(t=>e._bitCount(t)).reduce((e,t)=>e+t,0)}_resize(e){const t=e+32>>>5;if(t<=this.data.length)return;const r=new Uint32Array(t);r.set(this.data),r.fill(0,this.data.length),this.data=r}static _checkIndex(e){if(e<0)throw new RangeError("index cannot be negative")}static _bitCount(e){return e=(e=(858993459&(e-=e>>1&1431655765))+(e>>2&858993459))+(e>>4)&252645135,e+=e>>8,0+(e+=e>>16)&63}},j$1=class e{constructor(e){this.atn=e}getDecisionLookahead(t){if(null===t)return null;const r=t.transitions.length,n=[];for(let i=0;i=this.states.length)throw"Invalid state number.";const r=this.states[e];let n=this.nextTokens(r);if(!n.contains(i.EPSILON))return n;const o=new _$1;for(o.addSet(n),o.removeOne(i.EPSILON);null!==t&&t.invokingState>=0&&n.contains(i.EPSILON);){const e=this.states[t.invokingState].transitions[0];n=this.nextTokens(e.followState),o.addSet(n),o.removeOne(i.EPSILON),t=t.parentCtx}return n.contains(i.EPSILON)&&o.addOne(i.EOF),o}};$$2.INVALID_ALT_NUMBER=0;let X$2=class extends C$1{constructor(){super(),this.stateType=C$1.BASIC}},J$2=class extends C$1{constructor(){return super(),this.decision=-1,this.nonGreedy=!1,this}},Z$2=class extends J$2{constructor(){return super(),this.endState=null,this}},Q$2=class extends C$1{constructor(){return super(),this.stateType=C$1.BLOCK_END,this.startState=null,this}},tt$1=class extends C$1{constructor(){return super(),this.stateType=C$1.LOOP_END,this.loopBackState=null,this}},et$1=class extends C$1{constructor(){return super(),this.stateType=C$1.RULE_START,this.stopState=null,this.isPrecedenceRule=!1,this}},nt$1=class extends J$2{constructor(){return super(),this.stateType=C$1.TOKEN_START,this}},st$1=class extends J$2{constructor(){return super(),this.stateType=C$1.PLUS_LOOP_BACK,this}},it$2=class extends C$1{constructor(){return super(),this.stateType=C$1.STAR_LOOP_BACK,this}},rt$1=class extends J$2{constructor(){return super(),this.stateType=C$1.STAR_LOOP_ENTRY,this.loopBackState=null,this.isPrecedenceDecision=null,this}},ot$1=class extends Z$2{constructor(){return super(),this.stateType=C$1.PLUS_BLOCK_START,this.loopBackState=null,this}};class at extends Z$2{constructor(){return super(),this.stateType=C$1.STAR_BLOCK_START,this}}let lt$1=class extends Z$2{constructor(){return super(),this.stateType=C$1.BLOCK_START,this}},ht$1=class extends N$1{constructor(e,t){super(e),this.label_=t,this.label=this.makeLabel(),this.serializationType=N$1.ATOM}makeLabel(){const e=new _$1;return e.addOne(this.label_),e}matches(e,t,r){return this.label_===e}toString(){return this.label_}};class ct extends N$1{constructor(e,t,r){super(e),this.serializationType=N$1.RANGE,this.start=t,this.stop=r,this.label=this.makeLabel()}makeLabel(){const e=new _$1;return e.addRange(this.start,this.stop),e}matches(e,t,r){return e>=this.start&&e<=this.stop}toString(){return"'"+String.fromCharCode(this.start)+"'..'"+String.fromCharCode(this.stop)+"'"}}let ut$1=class extends N$1{constructor(e,t,r,n){super(e),this.serializationType=N$1.ACTION,this.ruleIndex=t,this.actionIndex=void 0===r?-1:r,this.isCtxDependent=void 0!==n&&n,this.isEpsilon=!0}matches(e,t,r){return!1}toString(){return"action_"+this.ruleIndex+":"+this.actionIndex}},dt$1=class extends N$1{constructor(e,t){super(e),this.serializationType=N$1.EPSILON,this.isEpsilon=!0,this.outermostPrecedenceReturn=t}matches(e,t,r){return!1}toString(){return"epsilon"}},gt$1=class e extends p{constructor(e,t,r){super(),this.ruleIndex=void 0===e?-1:e,this.predIndex=void 0===t?-1:t,this.isCtxDependent=void 0!==r&&r}evaluate(e,t){const r=this.isCtxDependent?t:null;return e.sempred(r,this.ruleIndex,this.predIndex)}updateHashCode(e){e.update(this.ruleIndex,this.predIndex,this.isCtxDependent)}equals(t){return this===t||t instanceof e&&this.ruleIndex===t.ruleIndex&&this.predIndex===t.predIndex&&this.isCtxDependent===t.isCtxDependent}toString(){return"{"+this.ruleIndex+":"+this.predIndex+"}?"}};p.NONE=new gt$1;let pt$2=class extends O{constructor(e,t,r,n){super(e),this.serializationType=N$1.PREDICATE,this.ruleIndex=t,this.predIndex=r,this.isCtxDependent=n,this.isEpsilon=!0}matches(e,t,r){return!1}getPredicate(){return new gt$1(this.ruleIndex,this.predIndex,this.isCtxDependent)}toString(){return"pred_"+this.ruleIndex+":"+this.predIndex}},ft$1=class e extends p{constructor(e){super(),this.precedence=void 0===e?0:e}evaluate(e,t){return e.precpred(t,this.precedence)}evalPrecedence(e,t){return e.precpred(t,this.precedence)?p.NONE:null}compareTo(e){return this.precedence-e.precedence}updateHashCode(e){e.update(this.precedence)}equals(t){return this===t||t instanceof e&&this.precedence===t.precedence}toString(){return"{"+this.precedence+">=prec}?"}};p.PrecedencePredicate=ft$1;let xt$1=class extends O{constructor(e,t){super(e),this.serializationType=N$1.PRECEDENCE,this.precedence=t,this.isEpsilon=!0}matches(e,t,r){return!1}getPredicate(){return new ft$1(this.precedence)}toString(){return this.precedence+" >= _p"}},Tt$1=class{constructor(e){void 0===e&&(e=null),this.readOnly=!1,this.verifyATN=null===e||e.verifyATN,this.generateRuleBypassTransitions=null!==e&&e.generateRuleBypassTransitions}};Tt$1.defaultOptions=new Tt$1,Tt$1.defaultOptions.readOnly=!0;let St$1=class{constructor(e){this.actionType=e,this.isPositionDependent=!1}hashCode(){const e=new l$1;return this.updateHashCode(e),e.finish()}updateHashCode(e){e.update(this.actionType)}equals(e){return this===e}},mt$1=class extends St$1{constructor(){super(6)}execute(e){e.skip()}toString(){return"skip"}};mt$1.INSTANCE=new mt$1;let Et$1=class e extends St$1{constructor(e){super(0),this.channel=e}execute(e){e._channel=this.channel}updateHashCode(e){e.update(this.actionType,this.channel)}equals(t){return this===t||t instanceof e&&this.channel===t.channel}toString(){return"channel("+this.channel+")"}},_t$1=class e extends St$1{constructor(e,t){super(1),this.ruleIndex=e,this.actionIndex=t,this.isPositionDependent=!0}execute(e){e.action(null,this.ruleIndex,this.actionIndex)}updateHashCode(e){e.update(this.actionType,this.ruleIndex,this.actionIndex)}equals(t){return this===t||t instanceof e&&this.ruleIndex===t.ruleIndex&&this.actionIndex===t.actionIndex}},Ct$1=class extends St$1{constructor(){super(3)}execute(e){e.more()}toString(){return"more"}};Ct$1.INSTANCE=new Ct$1;let At$1=class e extends St$1{constructor(e){super(7),this.type=e}execute(e){e.type=this.type}updateHashCode(e){e.update(this.actionType,this.type)}equals(t){return this===t||t instanceof e&&this.type===t.type}toString(){return"type("+this.type+")"}},Nt$1=class e extends St$1{constructor(e){super(5),this.mode=e}execute(e){e.pushMode(this.mode)}updateHashCode(e){e.update(this.actionType,this.mode)}equals(t){return this===t||t instanceof e&&this.mode===t.mode}toString(){return"pushMode("+this.mode+")"}},kt$1=class extends St$1{constructor(){super(4)}execute(e){e.popMode()}toString(){return"popMode"}};kt$1.INSTANCE=new kt$1;let It$1=class e extends St$1{constructor(e){super(2),this.mode=e}execute(e){e.setMode(this.mode)}updateHashCode(e){e.update(this.actionType,this.mode)}equals(t){return this===t||t instanceof e&&this.mode===t.mode}toString(){return"mode("+this.mode+")"}};function yt$1(e,t){const r=[];return r[e-1]=t,r.map(function(e){return t})}let Lt$1=class{constructor(e){null==e&&(e=Tt$1.defaultOptions),this.deserializationOptions=e,this.stateFactories=null,this.actionFactories=null}deserialize(e){const t=this.reset(e);this.checkVersion(t),t&&this.skipUUID();const r=this.readATN();this.readStates(r,t),this.readRules(r,t),this.readModes(r);const n=[];return this.readSets(r,n,this.readInt.bind(this)),t&&this.readSets(r,n,this.readInt32.bind(this)),this.readEdges(r,n),this.readDecisions(r),this.readLexerActions(r,t),this.markPrecedenceDecisions(r),this.verifyATN(r),this.deserializationOptions.generateRuleBypassTransitions&&1===r.grammarType&&(this.generateRuleBypassTransitions(r),this.verifyATN(r)),r}reset(e){if(3===(e.charCodeAt?e.charCodeAt(0):e[0])){const t=function(e){const t=e.charCodeAt(0);return t>1?t-2:t+65534},r=e.split("").map(t);return r[0]=e.charCodeAt(0),this.data=r,this.pos=0,!0}return this.data=e,this.pos=0,!1}skipUUID(){let e=0;for(;e++<8;)this.readInt()}checkVersion(e){const t=this.readInt();if(!e&&4!==t)throw"Could not deserialize ATN with version "+t+" (expected 4)."}readATN(){const e=this.readInt(),t=this.readInt();return new $$2(e,t)}readStates(e,t){let r,n,i;const o=[],s=[],a=this.readInt();for(let r=0;r0;)i.addTransition(c.transitions[l-1]),c.transitions=c.transitions.slice(-1);e.ruleToStartState[t].addTransition(new dt$1(i)),o.addTransition(new dt$1(a));const u=new X$2;e.addState(u),u.addTransition(new ht$1(o,e.ruleToTokenType[t])),i.addTransition(new dt$1(u))}stateIsEndStateFor(e,t){if(e.ruleIndex!==t)return null;if(!(e instanceof rt$1))return null;const r=e.transitions[e.transitions.length-1].target;return r instanceof tt$1&&r.epsilonOnlyTransitions&&r.transitions[0].target instanceof A$2?e:null}markPrecedenceDecisions(e){for(let t=0;t=0):this.checkCondition(r.transitions.length<=1||r instanceof A$2)}}checkCondition(e,t){if(!e)throw null==t&&(t="IllegalState"),t}readInt(){return this.data[this.pos++]}readInt32(){return this.readInt()|this.readInt()<<16}edgeFactory(e,t,r,n,o,s,a,c){const l=e.states[n];switch(t){case N$1.EPSILON:return new dt$1(l);case N$1.RANGE:return new ct(l,0!==a?i.EOF:o,s);case N$1.RULE:return new k$1(e.states[o],s,a,l);case N$1.PREDICATE:return new pt$2(l,o,s,0!==a);case N$1.PRECEDENCE:return new xt$1(l,o);case N$1.ATOM:return new ht$1(l,0!==a?i.EOF:o);case N$1.ACTION:return new ut$1(l,o,s,0!==a);case N$1.SET:return new I$2(l,c[o]);case N$1.NOT_SET:return new y$2(l,c[o]);case N$1.WILDCARD:return new L$1(l);default:throw"The specified transition type: "+t+" is not valid."}}stateFactory(e,t){if(null===this.stateFactories){const e=[];e[C$1.INVALID_TYPE]=null,e[C$1.BASIC]=()=>new X$2,e[C$1.RULE_START]=()=>new et$1,e[C$1.BLOCK_START]=()=>new lt$1,e[C$1.PLUS_BLOCK_START]=()=>new ot$1,e[C$1.STAR_BLOCK_START]=()=>new at,e[C$1.TOKEN_START]=()=>new nt$1,e[C$1.RULE_STOP]=()=>new A$2,e[C$1.BLOCK_END]=()=>new Q$2,e[C$1.STAR_LOOP_BACK]=()=>new it$2,e[C$1.STAR_LOOP_ENTRY]=()=>new rt$1,e[C$1.PLUS_LOOP_BACK]=()=>new st$1,e[C$1.LOOP_END]=()=>new tt$1,this.stateFactories=e}if(e>this.stateFactories.length||null===this.stateFactories[e])throw"The specified state type "+e+" is not valid.";{const r=this.stateFactories[e]();if(null!==r)return r.ruleIndex=t,r}}lexerActionFactory(e,t,r){if(null===this.actionFactories){const e=[];e[0]=(e,t)=>new Et$1(e),e[1]=(e,t)=>new _t$1(e,t),e[2]=(e,t)=>new It$1(e),e[3]=(e,t)=>Ct$1.INSTANCE,e[4]=(e,t)=>kt$1.INSTANCE,e[5]=(e,t)=>new Nt$1(e),e[6]=(e,t)=>mt$1.INSTANCE,e[7]=(e,t)=>new At$1(e),this.actionFactories=e}if(e>this.actionFactories.length||null===this.actionFactories[e])throw"The specified lexer action type "+e+" is not valid.";return this.actionFactories[e](t,r)}},Ot$1=class{syntaxError(e,t,r,n,i,o){}reportAmbiguity(e,t,r,n,i,o,s){}reportAttemptingFullContext(e,t,r,n,i,o){}reportContextSensitivity(e,t,r,n,i,o){}},Rt$1=class extends Ot$1{constructor(){super()}syntaxError(e,t,r,n,i,o){console.error("line "+r+":"+n+" "+i)}};Rt$1.INSTANCE=new Rt$1;let wt$1=class extends Ot$1{constructor(e){if(super(),null===e)throw"delegates";return this.delegates=e,this}syntaxError(e,t,r,n,i,o){this.delegates.map(s=>s.syntaxError(e,t,r,n,i,o))}reportAmbiguity(e,t,r,n,i,o,s){this.delegates.map(a=>a.reportAmbiguity(e,t,r,n,i,o,s))}reportAttemptingFullContext(e,t,r,n,i,o){this.delegates.map(s=>s.reportAttemptingFullContext(e,t,r,n,i,o))}reportContextSensitivity(e,t,r,n,i,o){this.delegates.map(s=>s.reportContextSensitivity(e,t,r,n,i,o))}},vt$1=class{constructor(){this._listeners=[Rt$1.INSTANCE],this._interp=null,this._stateNumber=-1}checkVersion(e){const t="4.13.2";t!==e&&console.log("ANTLR runtime and generated code versions disagree: "+t+"!="+e)}addErrorListener(e){this._listeners.push(e)}removeErrorListeners(){this._listeners=[]}getLiteralNames(){return Object.getPrototypeOf(this).constructor.literalNames||[]}getSymbolicNames(){return Object.getPrototypeOf(this).constructor.symbolicNames||[]}getTokenNames(){if(!this.tokenNames){const e=this.getLiteralNames(),t=this.getSymbolicNames(),r=e.length>t.length?e.length:t.length;this.tokenNames=[];for(let n=0;n";let t=e.text;return null===t&&(t=e.type===i.EOF?"":"<"+e.type+">"),t=t.replace("\n","\\n").replace("\r","\\r").replace("\t","\\t"),"'"+t+"'"}getErrorListenerDispatch(){return console.warn("Calling deprecated method in Recognizer class: getErrorListenerDispatch()"),this.getErrorListener()}getErrorListener(){return new wt$1(this._listeners)}sempred(e,t,r){return!0}precpred(e,t){return!0}get atn(){return this._interp.atn}get state(){return this._stateNumber}set state(e){this._stateNumber=e}};vt$1.tokenTypeMapCache={},vt$1.ruleIndexMapCache={};class Pt extends i{constructor(e,t,r,n,o){super(),this.source=void 0!==e?e:Pt.EMPTY_SOURCE,this.type=void 0!==t?t:null,this.channel=void 0!==r?r:i.DEFAULT_CHANNEL,this.start=void 0!==n?n:-1,this.stop=void 0!==o?o:-1,this.tokenIndex=-1,null!==this.source[0]?(this.line=e[0].line,this.column=e[0].column):this.column=-1}clone(){const e=new Pt(this.source,this.type,this.channel,this.start,this.stop);return e.tokenIndex=this.tokenIndex,e.line=this.line,e.column=this.column,e.text=this.text,e}cloneWithType(e){const t=new Pt(this.source,e,this.channel,this.start,this.stop);return t.tokenIndex=this.tokenIndex,t.line=this.line,t.column=this.column,e===i.EOF&&(t.text=""),t}toString(){let e=this.text;return e=null!==e?e.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"):"","[@"+this.tokenIndex+","+this.start+":"+this.stop+"='"+e+"',<"+this.type+">"+(this.channel>0?",channel="+this.channel:"")+","+this.line+":"+this.column+"]"}get text(){if(null!==this._text)return this._text;const e=this.getInputStream();if(null===e)return null;const t=e.size;return this.start"}set text(e){this._text=e}}Pt.EMPTY_SOURCE=[null,null];class bt{}class Dt extends bt{constructor(e){super(),this.copyText=void 0!==e&&e}create(e,t,r,n,i,o,s,a){const c=new Pt(e,t,n,i,o);return c.line=s,c.column=a,null!==r?c.text=r:this.copyText&&null!==e[1]&&(c.text=e[1].getText(i,o)),c}createThin(e,t){const r=new Pt(null,e);return r.text=t,r}}Dt.DEFAULT=new Dt;let Ft$1=class e extends Error{constructor(t){super(t.message),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.message=t.message,this.recognizer=t.recognizer,this.input=t.input,this.ctx=t.ctx,this.offendingToken=null,this.offendingState=-1,null!==this.recognizer&&(this.offendingState=this.recognizer.state)}getExpectedTokens(){return null!==this.recognizer?this.recognizer.atn.getExpectedTokens(this.offendingState,this.ctx):null}toString(){return this.message}},Mt$1=class extends Ft$1{constructor(e,t,r,n){super({message:"",recognizer:e,input:t,ctx:null}),this.startIndex=r,this.deadEndConfigs=n}toString(){let e="";return this.startIndex>=0&&this.startIndex":"\n"===e?"\\n":"\t"===e?"\\t":"\r"===e?"\\r":e}getCharErrorDisplay(e){return"'"+this.getErrorDisplayForChar(e)+"'"}recover(e){this._input.LA(1)!==i.EOF&&(e instanceof Mt$1?this._interp.consume(this._input):this._input.consume())}get inputStream(){return this._input}set inputStream(e){this._input=null,this._tokenFactorySourcePair=[this,this._input],this.reset(),this._input=e,this._tokenFactorySourcePair=[this,this._input]}get sourceName(){return this._input.sourceName}get type(){return this._type}set type(e){this._type=e}get line(){return this._interp.line}set line(e){this._interp.line=e}get column(){return this._interp.column}set column(e){this._interp.column=e}get text(){return null!==this._text?this._text:this._interp.getText(this._input)}set text(e){this._text=e}};function Bt$1(e){return e.hashCodeForConfigSet()}function zt$1(e,t){return e===t||null!==e&&null!==t&&e.equalsForConfigSet(t)}Ut$1.DEFAULT_MODE=0,Ut$1.MORE=-2,Ut$1.SKIP=-3,Ut$1.DEFAULT_TOKEN_CHANNEL=i.DEFAULT_CHANNEL,Ut$1.HIDDEN=i.HIDDEN_CHANNEL,Ut$1.MIN_CHAR_VALUE=0,Ut$1.MAX_CHAR_VALUE=1114111;class Vt{constructor(e){this.configLookup=new g$4(Bt$1,zt$1),this.fullCtx=void 0===e||e,this.readOnly=!1,this.configs=[],this.uniqueAlt=0,this.conflictingAlts=null,this.hasSemanticContext=!1,this.dipsIntoOuterContext=!1,this.cachedHashCode=-1}add(e,t){if(void 0===t&&(t=null),this.readOnly)throw"This set is readonly";e.semanticContext!==p.NONE&&(this.hasSemanticContext=!0),e.reachesIntoOuterContext>0&&(this.dipsIntoOuterContext=!0);const r=this.configLookup.getOrAdd(e);if(r===e)return this.cachedHashCode=-1,this.configs.push(e),!0;const n=!this.fullCtx,i=G$1(r.context,e.context,n,t);return r.reachesIntoOuterContext=Math.max(r.reachesIntoOuterContext,e.reachesIntoOuterContext),e.precedenceFilterSuppressed&&(r.precedenceFilterSuppressed=!0),r.context=i,!0}getStates(){const e=new g$4;for(let t=0;te.MAX_DFA_EDGE)return null;let n=t.edges[r-e.MIN_DFA_EDGE];return void 0===n&&(n=null),e.debug&&null!==n&&console.log("reuse state "+t.stateNumber+" edge to "+n.stateNumber),n}computeTargetState(e,t,r){const n=new Kt$1;return this.getReachableConfigSet(e,t.configs,n,r),0===n.items.length?(n.hasSemanticContext||this.addDFAEdge(t,r,Ht$1.ERROR),Ht$1.ERROR):this.addDFAEdge(t,r,null,n)}failOrAccept(e,t,r,n){if(null!==this.prevAccept.dfaState){const r=e.dfaState.lexerActionExecutor;return this.accept(t,r,this.startIndex,e.index,e.line,e.column),e.dfaState.prediction}if(n===i.EOF&&t.index===this.startIndex)return i.EOF;throw new Mt$1(this.recog,t,this.startIndex,r)}getReachableConfigSet(t,r,n,o){let s=$$2.INVALID_ALT_NUMBER;for(let a=0;ae.MAX_DFA_EDGE||(e.debug&&console.log("EDGE "+t+" -> "+n+" upon "+r),null===t.edges&&(t.edges=[]),t.edges[r-e.MIN_DFA_EDGE]=n),n}addDFAState(e){const t=new qt$1(null,e);let r=null;for(let t=0;te.startsWith("k-")).map(e=>this.data[e],this)}};const Qt$1={SLL:0,LL:1,LL_EXACT_AMBIG_DETECTION:2,hasSLLConflictTerminatingPrediction:function(e,t){if(Qt$1.allConfigsInRuleStopStates(t))return!0;if(e===Qt$1.SLL&&t.hasSemanticContext){const e=new Vt;for(let r=0;r1)return!0;return!1},allSubsetsEqual:function(e){let t=null;for(let r=0;r "+s),0===s.items.length?null:s}removeAllConfigsNotInRuleStopState(e,t){if(te$1.allConfigsInRuleStopStates(e))return e;const r=new Vt(e.fullCtx);for(let n=0;n0&&(o=this.getAltThatFinishedDecisionEntryRule(i),o!==$$2.INVALID_ALT_NUMBER)?o:$$2.INVALID_ALT_NUMBER}getAltThatFinishedDecisionEntryRule(e){const t=[];for(let r=0;r0||n.state instanceof A$2&&n.context.hasEmptyPath())&&t.indexOf(n.alt)<0&&t.push(n.alt)}return 0===t.length?$$2.INVALID_ALT_NUMBER:Math.min.apply(null,t)}splitAccordingToSemanticValidity(e,t){const r=new Vt(e.fullCtx),n=new Vt(e.fullCtx);for(let i=0;i=0&&(n+=1)}this.closureCheckingStopState(d,t,r,u,i,n,s)}}}canDropLoopEntryEdgeInLeftRecursiveRule(e){const t=e.state;if(t.stateType!==C$1.STAR_LOOP_ENTRY)return!1;if(t.stateType!==C$1.STAR_LOOP_ENTRY||!t.isPrecedenceDecision||e.context.isEmpty()||e.context.hasEmptyPath())return!1;const r=e.context.length;for(let n=0;n=0?this.parser.ruleNames[e]:""}getEpsilonTarget(e,t,r,n,o,s){switch(t.serializationType){case N$1.RULE:return this.ruleTransition(e,t);case N$1.PRECEDENCE:return this.precedenceTransition(e,t,r,n,o);case N$1.PREDICATE:return this.predTransition(e,t,r,n,o);case N$1.ACTION:return this.actionTransition(e,t);case N$1.EPSILON:return new m$1({state:t.target},e);case N$1.ATOM:case N$1.RANGE:case N$1.SET:return s&&t.matches(i.EOF,0,1)?new m$1({state:t.target},e):null;default:return null}}actionTransition(e,t){if(this.debug){const e=-1===t.actionIndex?65535:t.actionIndex;console.log("ACTION edge "+t.ruleIndex+":"+e)}return new m$1({state:t.target},e)}precedenceTransition(e,t,r,n,i){this.debug&&(console.log("PRED (collectPredicates="+r+") "+t.precedence+">=_p, ctx dependent=true"),null!==this.parser&&console.log("context surrounding pred is "+d(this.parser.getRuleInvocationStack())));let o=null;if(r&&n)if(i){const r=this._input.index;this._input.seek(this._startIndex);const n=t.getPredicate().evaluate(this.parser,this._outerContext);this._input.seek(r),n&&(o=new m$1({state:t.target},e))}else{const r=p.andContext(e.semanticContext,t.getPredicate());o=new m$1({state:t.target,semanticContext:r},e)}else o=new m$1({state:t.target},e);return this.debug&&console.log("config from pred transition="+o),o}predTransition(e,t,r,n,i){this.debug&&(console.log("PRED (collectPredicates="+r+") "+t.ruleIndex+":"+t.predIndex+", ctx dependent="+t.isCtxDependent),null!==this.parser&&console.log("context surrounding pred is "+d(this.parser.getRuleInvocationStack())));let o=null;if(r&&(t.isCtxDependent&&n||!t.isCtxDependent))if(i){const r=this._input.index;this._input.seek(this._startIndex);const n=t.getPredicate().evaluate(this.parser,this._outerContext);this._input.seek(r),n&&(o=new m$1({state:t.target},e))}else{const r=p.andContext(e.semanticContext,t.getPredicate());o=new m$1({state:t.target,semanticContext:r},e)}else o=new m$1({state:t.target},e);return this.debug&&console.log("config from pred transition="+o),o}ruleTransition(e,t){this.debug&&console.log("CALL rule "+this.getRuleName(t.target.ruleIndex)+", ctx="+e.context);const r=t.followState,n=V$2.create(e.context,r.stateNumber);return new m$1({state:t.target,context:n},e)}getConflictingAlts(e){const t=te$1.getConflictingAltSubsets(e);return te$1.getAlts(t)}getConflictingAltsOrUniqueAlt(e){let t=null;return e.uniqueAlt!==$$2.INVALID_ALT_NUMBER?(t=new W$2,t.set(e.uniqueAlt)):t=e.conflictingAlts,t}getTokenName(e){if(e===i.EOF)return"EOF";if(null!==this.parser&&null!==this.parser.literalNames){if(!(e>=this.parser.literalNames.length&&e>=this.parser.symbolicNames.length))return(this.parser.literalNames[e]||this.parser.symbolicNames[e])+"<"+e+">";console.log(e+" ttype out of range: "+this.parser.literalNames),console.log(""+this.parser.getInputStream().getTokens())}return""+e}getLookaheadName(e){return this.getTokenName(e.LA(1))}dumpDeadEndConfigs(e){console.log("dead end configs: ");const t=e.getDeadEndConfigs();for(let e=0;e0){const e=r.state.transitions[0];e instanceof ht$1?n="Atom "+this.getTokenName(e.label):e instanceof I$2&&(n=(e instanceof y$2?"~":"")+"Set "+e.set)}console.error(r.toString(this.parser,!0)+":"+n)}}noViableAlt(e,t,r,n){return new ee$1(this.parser,e,e.get(n),e.LT(1),r,t)}getUniqueAlt(e){let t=$$2.INVALID_ALT_NUMBER;for(let r=0;r "+n+" upon "+this.getTokenName(r)),null===n)return null;if(n=this.addDFAState(e,n),null===t||r<-1||r>this.atn.maxTokenType)return n;if(null===t.edges&&(t.edges=[]),t.edges[r+1]=n,this.debug){const t=null===this.parser?null:this.parser.literalNames,r=null===this.parser?null:this.parser.symbolicNames;console.log("DFA=\n"+e.toString(t,r))}return n}addDFAState(e,t){if(t===Ht$1.ERROR)return t;const r=e.states.get(t);return null!==r?(this.trace_atn_sim&&console.log("addDFAState "+t+" exists"),r):(t.stateNumber=e.states.length,t.configs.readOnly||(t.configs.optimizeConfigs(this),t.configs.setReadonly(!0)),this.trace_atn_sim&&console.log("addDFAState new "+t),e.states.add(t),this.debug&&console.log("adding new DFA state: "+t),t)}reportAttemptingFullContext(e,t,r,n,i){if(this.debug||this.retry_debug){const t=new E$1(n,i+1);console.log("reportAttemptingFullContext decision="+e.decision+":"+r+", input="+this.parser.getTokenStream().getText(t))}null!==this.parser&&this.parser.getErrorListener().reportAttemptingFullContext(this.parser,e,n,i,t,r)}reportContextSensitivity(e,t,r,n,i){if(this.debug||this.retry_debug){const t=new E$1(n,i+1);console.log("reportContextSensitivity decision="+e.decision+":"+r+", input="+this.parser.getTokenStream().getText(t))}null!==this.parser&&this.parser.getErrorListener().reportContextSensitivity(this.parser,e,n,i,t,r)}reportAmbiguity(e,t,r,n,i,o,s){if(this.debug||this.retry_debug){const e=new E$1(r,n+1);console.log("reportAmbiguity "+o+":"+s+", input="+this.parser.getTokenStream().getText(e))}null!==this.parser&&this.parser.getErrorListener().reportAmbiguity(this.parser,e,r,n,i,o,s)}},ie$1=class{constructor(){this.cache=new H$1}add(e){if(e===B$2.EMPTY)return B$2.EMPTY;const t=this.cache.get(e)||null;return null!==t?t:(this.cache.set(e,e),e)}get(e){return this.cache.get(e)||null}get length(){return this.cache.length}};const re$1={ATN:$$2,ATNDeserializer:Lt$1,LexerATNSimulator:Xt$1,ParserATNSimulator:se$1,PredictionMode:te$1,PredictionContextCache:ie$1};let oe$1=class{constructor(e,t,r){this.dfa=e,this.literalNames=t||[],this.symbolicNames=r||[]}toString(){if(null===this.dfa.s0)return null;let e="";const t=this.dfa.sortedStates();for(let r=0;r"),e=e.concat(this.getStateString(t)),e=e.concat("\n"))}}}return 0===e.length?null:e}getEdgeLabel(e){return 0===e?"EOF":null!==this.literalNames||null!==this.symbolicNames?this.literalNames[e-1]||this.symbolicNames[e-1]:String.fromCharCode(e-1)}getStateString(e){const t=(e.isAcceptState?":":"")+"s"+e.stateNumber+(e.requiresFullContext?"^":"");return e.isAcceptState?null!==e.predicates?t+"=>"+d(e.predicates):t+"=>"+e.prediction.toString():t}},ae$1=class extends oe$1{constructor(e){super(e,null)}getEdgeLabel(e){return"'"+String.fromCharCode(e)+"'"}};class le{constructor(e,t){if(void 0===t&&(t=0),this.atnStartState=e,this.decision=t,this._states=new g$4,this.s0=null,this.precedenceDfa=!1,e instanceof rt$1&&e.isPrecedenceDecision){this.precedenceDfa=!0;const e=new qt$1(null,new Vt);e.edges=[],e.isAcceptState=!1,e.requiresFullContext=!1,this.s0=e}}getPrecedenceStartState(e){if(!this.precedenceDfa)throw"Only precedence DFAs may contain a precedence start state.";return e<0||e>=this.s0.edges.length?null:this.s0.edges[e]||null}setPrecedenceStartState(e,t){if(!this.precedenceDfa)throw"Only precedence DFAs may contain a precedence start state.";e<0||(this.s0.edges[e]=t)}setPrecedenceDfa(e){if(this.precedenceDfa!==e){if(this._states=new g$4,e){const e=new qt$1(null,new Vt);e.edges=[],e.isAcceptState=!1,e.requiresFullContext=!1,this.s0=e}else this.s0=null;this.precedenceDfa=e}}sortedStates(){return this._states.values().sort(function(e,t){return e.stateNumber-t.stateNumber})}toString(e,t){return e=e||null,t=t||null,null===this.s0?"":new oe$1(this,e,t).toString()}toLexerString(){return null===this.s0?"":new ae$1(this).toString()}get states(){return this._states}}const he$2={DFA:le,DFASerializer:oe$1,LexerDFASerializer:ae$1,PredPrediction:Jt$1},ce={PredictionContext:B$2},ue$1={Interval:E$1,IntervalSet:_$1};let de$2=class{visitTerminal(e){}visitErrorNode(e){}enterEveryRule(e){}exitEveryRule(e){}},ge$1=class{visit(e){return Array.isArray(e)?e.map(function(e){return e.accept(this)},this):e.accept(this)}visitChildren(e){return e.children?this.visit(e.children):null}visitTerminal(e){}visitErrorNode(e){}},pe$1=class{walk(e,t){if(t instanceof D$1||void 0!==t.isErrorNode&&t.isErrorNode())e.visitErrorNode(t);else if(t instanceof b$1)e.visitTerminal(t);else{this.enterRule(e,t);for(let r=0;r=i.length)return""+r;const o=i[n]||null;return null===o||0===o.length?""+r:`${r} (${o})`}getConflictingAlts(e,t){if(null!==e)return e;const r=new W$2;for(let e=0;e=0&&e.consume(),this.lastErrorIndex=e._input.index,null===this.lastErrorStates&&(this.lastErrorStates=[]),this.lastErrorStates.push(e.state);const r=this.getErrorRecoverySet(e);this.consumeUntil(e,r)}sync(e){if(this.inErrorRecoveryMode(e))return;const t=e._interp.atn.states[e.state],r=e.getTokenStream().LA(1),n=e.atn.nextTokens(t);if(n.contains(r))return this.nextTokensContext=null,void(this.nextTokenState=C$1.INVALID_STATE_NUMBER);if(n.contains(i.EPSILON))null===this.nextTokensContext&&(this.nextTokensContext=e._ctx,this.nextTokensState=e._stateNumber);else switch(t.stateType){case C$1.BLOCK_START:case C$1.STAR_BLOCK_START:case C$1.PLUS_BLOCK_START:case C$1.STAR_LOOP_ENTRY:if(null!==this.singleTokenDeletion(e))return;throw new xe(e);case C$1.PLUS_LOOP_BACK:case C$1.STAR_LOOP_BACK:{this.reportUnwantedToken(e);const t=new _$1;t.addSet(e.getExpectedTokens());const r=t.addSet(this.getErrorRecoverySet(e));this.consumeUntil(e,r)}}}reportNoViableAlternative(e,t){const r=e.getTokenStream();let n;n=null!==r?t.startToken.type===i.EOF?"":r.getText(new E$1(t.startToken.tokenIndex,t.offendingToken.tokenIndex)):"";const o="no viable alternative at input "+this.escapeWSAndQuote(n);e.notifyErrorListeners(o,t.offendingToken,t)}reportInputMismatch(e,t){const r="mismatched input "+this.getTokenErrorDisplay(t.offendingToken)+" expecting "+t.getExpectedTokens().toString(e.literalNames,e.symbolicNames);e.notifyErrorListeners(r,t.offendingToken,t)}reportFailedPredicate(e,t){const r="rule "+e.ruleNames[e._ctx.ruleIndex]+" "+t.message;e.notifyErrorListeners(r,t.offendingToken,t)}reportUnwantedToken(e){if(this.inErrorRecoveryMode(e))return;this.beginErrorCondition(e);const t=e.getCurrentToken(),r="extraneous input "+this.getTokenErrorDisplay(t)+" expecting "+this.getExpectedTokens(e).toString(e.literalNames,e.symbolicNames);e.notifyErrorListeners(r,t,null)}reportMissingToken(e){if(this.inErrorRecoveryMode(e))return;this.beginErrorCondition(e);const t=e.getCurrentToken(),r="missing "+this.getExpectedTokens(e).toString(e.literalNames,e.symbolicNames)+" at "+this.getTokenErrorDisplay(t);e.notifyErrorListeners(r,t,null)}recoverInline(e){const t=this.singleTokenDeletion(e);if(null!==t)return e.consume(),t;if(this.singleTokenInsertion(e))return this.getMissingSymbol(e);throw new xe(e)}singleTokenInsertion(e){const t=e.getTokenStream().LA(1),r=e._interp.atn,n=r.states[e.state].transitions[0].target;return!!r.nextTokens(n,e._ctx).contains(t)&&(this.reportMissingToken(e),!0)}singleTokenDeletion(e){const t=e.getTokenStream().LA(2);if(this.getExpectedTokens(e).contains(t)){this.reportUnwantedToken(e),e.consume();const t=e.getCurrentToken();return this.reportMatch(e),t}return null}getMissingSymbol(e){const t=e.getCurrentToken(),r=this.getExpectedTokens(e).first();let n;n=r===i.EOF?"":"";let o=t;const s=e.getTokenStream().LT(-1);return o.type===i.EOF&&null!==s&&(o=s),e.getTokenFactory().create(o.source,r,n,i.DEFAULT_CHANNEL,-1,-1,o.line,o.column)}getExpectedTokens(e){return e.getExpectedTokens()}getTokenErrorDisplay(e){if(null===e)return"";let t=e.text;return null===t&&(t=e.type===i.EOF?"":"<"+e.type+">"),this.escapeWSAndQuote(t)}escapeWSAndQuote(e){return"'"+(e=(e=(e=e.replace(/\n/g,"\\n")).replace(/\r/g,"\\r")).replace(/\t/g,"\\t"))+"'"}getErrorRecoverySet(e){const t=e._interp.atn;let r=e._ctx;const n=new _$1;for(;null!==r&&r.invokingState>=0;){const e=t.states[r.invokingState].transitions[0],i=t.nextTokens(e.followState);n.addSet(i),r=r.parentCtx}return n.removeOne(i.EPSILON),n}consumeUntil(e,t){let r=e.getTokenStream().LA(1);for(;r!==i.EOF&&!t.contains(r);)e.consume(),r=e.getTokenStream().LA(1)}}class Ae extends Ce{constructor(){super()}recover(e,t){let r=e._ctx;for(;null!==r;)r.exception=t,r=r.parentCtx;throw new Ee$1(t)}recoverInline(e){this.recover(e,new xe(e))}sync(e){}}const Ne$1={RecognitionException:Ft$1,NoViableAltException:ee$1,LexerNoViableAltException:Mt$1,InputMismatchException:xe,FailedPredicateException:Te$1,DiagnosticErrorListener:me$1,BailErrorStrategy:Ae,DefaultErrorStrategy:Ce,ErrorListener:Ot$1};let ke$1=class{constructor(e,t){if(this.name="",this.strdata=e,this.decodeToUnicodeCodePoints=t||!1,this._index=0,this.data=[],this.decodeToUnicodeCodePoints)for(let e=0;e=this._size)throw"cannot consume EOF";this._index+=1}LA(e){if(0===e)return 0;e<0&&(e+=1);const t=this._index+e-1;return t<0||t>=this._size?i.EOF:this.data[t]}LT(e){return this.LA(e)}mark(){return-1}release(e){}seek(e){e<=this._index?this._index=e:this._index=Math.min(e,this._size)}getText(e,t){if(t>=this._size&&(t=this._size-1),e>=this._size)return"";if(this.decodeToUnicodeCodePoints){let r="";for(let n=e;n<=t;n++)r+=String.fromCodePoint(this.data[n]);return r}return this.strdata.slice(e,t+1)}toString(){return this.strdata}get index(){return this._index}get size(){return this._size}};class Ie extends ke$1{constructor(e,t){super(e,t)}}n(763);class Oe extends Ie{static fromPath(e,t,r){throw new Error("FileStream is only available when running in Node!")}constructor(e,t,r){throw new Error("FileStream is only available when running in Node!")}}const Re$1={fromString:function(e){return new ke$1(e,!0)},fromBlob:function(e,t,r,n){const i=new window.FileReader;i.onload=function(e){const t=new ke$1(e.target.result,!0);r(t)},i.onerror=n,i.readAsText(e,t)},fromBuffer:function(e,t){return new ke$1(e.toString(t),!0)},fromPath:function(e,t,r){Oe.fromPath(e,t,r)},fromPathSync:function(e,t){return new Oe(e,t)}},we={arrayToString:d,stringToCharArray:function(e){let t=new Uint16Array(e.length);for(let r=0;r=0&&(this.fetchedEOF?this.index0)||this.fetch(t)>=t}fetch(e){if(this.fetchedEOF)return 0;for(let t=0;t=this.tokens.length&&(t=this.tokens.length-1);for(let o=e;o=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[t]}adjustSeekIndex(e){return e}lazyInit(){-1===this.index&&this.setup()}setup(){this.sync(0),this.index=this.adjustSeekIndex(0)}setTokenSource(e){this.tokenSource=e,this.tokens=[],this.index=-1,this.fetchedEOF=!1}nextTokenOnChannel(e,t){if(this.sync(e),e>=this.tokens.length)return-1;let r=this.tokens[e];for(;r.channel!==t;){if(r.type===i.EOF)return-1;e+=1,this.sync(e),r=this.tokens[e]}return e}previousTokenOnChannel(e,t){for(;e>=0&&this.tokens[e].channel!==t;)e-=1;return e}getHiddenTokensToRight(e,t){if(void 0===t&&(t=-1),this.lazyInit(),e<0||e>=this.tokens.length)throw e+" not in 0.."+this.tokens.length-1;const r=this.nextTokenOnChannel(e+1,Ut$1.DEFAULT_TOKEN_CHANNEL),n=e+1,i=-1===r?this.tokens.length-1:r;return this.filterForChannel(n,i,t)}getHiddenTokensToLeft(e,t){if(void 0===t&&(t=-1),this.lazyInit(),e<0||e>=this.tokens.length)throw e+" not in 0.."+this.tokens.length-1;const r=this.previousTokenOnChannel(e-1,Ut$1.DEFAULT_TOKEN_CHANNEL);if(r===e-1)return null;const n=r+1,i=e-1;return this.filterForChannel(n,i,t)}filterForChannel(e,t,r){const n=[];for(let i=e;i=this.tokens.length&&(r=this.tokens.length-1);let n="";for(let e=t;e=0&&this._parseListeners.splice(t,1),0===this._parseListeners.length&&(this._parseListeners=null)}}removeParseListeners(){this._parseListeners=null}triggerEnterRuleEvent(){if(null!==this._parseListeners){const e=this._ctx;this._parseListeners.forEach(function(t){t.enterEveryRule(e),e.enterRule(t)})}}triggerExitRuleEvent(){if(null!==this._parseListeners){const e=this._ctx;this._parseListeners.slice(0).reverse().forEach(function(t){e.exitRule(t),t.exitEveryRule(e)})}}getTokenFactory(){return this._input.tokenSource._factory}setTokenFactory(e){this._input.tokenSource._factory=e}getATNWithBypassAlts(){const e=this.getSerializedATN();if(null===e)throw"The current parser does not support an ATN with bypass alternatives.";let t=this.bypassAltsAtnCache[e];if(null===t){const r=new Tt$1;r.generateRuleBypassTransitions=!0,t=new Lt$1(r).deserialize(e),this.bypassAltsAtnCache[e]=t}return t}getInputStream(){return this.getTokenStream()}setInputStream(e){this.setTokenStream(e)}getTokenStream(){return this._input}setTokenStream(e){this._input=null,this.reset(),this._input=e}get syntaxErrorsCount(){return this._syntaxErrors}getCurrentToken(){return this._input.LT(1)}notifyErrorListeners(e,t,r){r=r||null,null===(t=t||null)&&(t=this.getCurrentToken()),this._syntaxErrors+=1;const n=t.line,i=t.column;this.getErrorListener().syntaxError(this,t,n,i,e,r)}consume(){const e=this.getCurrentToken();e.type!==i.EOF&&this.getInputStream().consume();const t=null!==this._parseListeners&&this._parseListeners.length>0;if(this.buildParseTrees||t){let r;r=this._errHandler.inErrorRecoveryMode(this)?this._ctx.addErrorNode(e):this._ctx.addTokenNode(e),r.invokingState=this.state,t&&this._parseListeners.forEach(function(e){r instanceof D$1||void 0!==r.isErrorNode&&r.isErrorNode()?e.visitErrorNode(r):r instanceof b$1&&e.visitTerminal(r)})}return e}addContextToParseTree(){null!==this._ctx.parentCtx&&this._ctx.parentCtx.addChild(this._ctx)}enterRule(e,t,r){this.state=t,this._ctx=e,this._ctx.start=this._input.LT(1),this.buildParseTrees&&this.addContextToParseTree(),this.triggerEnterRuleEvent()}exitRule(){this._ctx.stop=this._input.LT(-1),this.triggerExitRuleEvent(),this.state=this._ctx.invokingState,this._ctx=this._ctx.parentCtx}enterOuterAlt(e,t){e.setAltNumber(t),this.buildParseTrees&&this._ctx!==e&&null!==this._ctx.parentCtx&&(this._ctx.parentCtx.removeLastChild(),this._ctx.parentCtx.addChild(e)),this._ctx=e}getPrecedence(){return 0===this._precedenceStack.length?-1:this._precedenceStack[this._precedenceStack.length-1]}enterRecursionRule(e,t,r,n){this.state=t,this._precedenceStack.push(n),this._ctx=e,this._ctx.start=this._input.LT(1),this.triggerEnterRuleEvent()}pushNewRecursionContext(e,t,r){const n=this._ctx;n.parentCtx=e,n.invokingState=t,n.stop=this._input.LT(-1),this._ctx=e,this._ctx.start=n.start,this.buildParseTrees&&this._ctx.addChild(n),this.triggerEnterRuleEvent()}unrollRecursionContexts(e){this._precedenceStack.pop(),this._ctx.stop=this._input.LT(-1);const t=this._ctx,r=this.getParseListeners();if(null!==r&&r.length>0)for(;this._ctx!==e;)this.triggerExitRuleEvent(),this._ctx=this._ctx.parentCtx;else this._ctx=e;t.parentCtx=e,this.buildParseTrees&&null!==e&&e.addChild(t)}getInvokingContext(e){let t=this._ctx;for(;null!==t;){if(t.ruleIndex===e)return t;t=t.parentCtx}return null}precpred(e,t){return t>=this._precedenceStack[this._precedenceStack.length-1]}inContext(e){return!1}isExpectedToken(e){const t=this._interp.atn;let r=this._ctx;const n=t.states[this.state];let o=t.nextTokens(n);if(o.contains(e))return!0;if(!o.contains(i.EPSILON))return!1;for(;null!==r&&r.invokingState>=0&&o.contains(i.EPSILON);){const n=t.states[r.invokingState].transitions[0];if(o=t.nextTokens(n.followState),o.contains(e))return!0;r=r.parentCtx}return!(!o.contains(i.EPSILON)||e!==i.EOF)}getExpectedTokens(){return this._interp.atn.getExpectedTokens(this.state,this._ctx)}getExpectedTokensWithinCurrentRule(){const e=this._interp.atn,t=e.states[this.state];return e.nextTokens(t)}getRuleIndex(e){const t=this.getRuleIndexMap()[e];return null!==t?t:-1}getRuleInvocationStack(e){null===(e=e||null)&&(e=this._ctx);const t=[];for(;null!==e;){const r=e.ruleIndex;r<0?t.push("n/a"):t.push(this.ruleNames[r]),e=e.parentCtx}return t}getDFAStrings(){return this._interp.decisionToDFA.toString()}dumpDFA(){let e=!1;for(let t=0;t0&&(e&&console.log(),this.printer.println("Decision "+r.decision+":"),this.printer.print(r.toString(this.literalNames,this.symbolicNames)),e=!0)}}getSourceName(){return this._input.getSourceName()}setTrace(e){e?(null!==this._tracer&&this.removeParseListener(this._tracer),this._tracer=new De$1(this),this.addParseListener(this._tracer)):(this.removeParseListener(this._tracer),this._tracer=null)}}Fe.bypassAltsAtnCache={};let Me$1=class extends b$1{constructor(e){super(),this.parentCtx=null,this.symbol=e}getChild(e){return null}getSymbol(){return this.symbol}getParent(){return this.parentCtx}getPayload(){return this.symbol}getSourceInterval(){if(null===this.symbol)return E$1.INVALID_INTERVAL;const e=this.symbol.tokenIndex;return new E$1(e,e)}getChildCount(){return 0}accept(e){return e.visitTerminal(this)}getText(){return this.symbol.text}toString(){return this.symbol.type===i.EOF?"":this.symbol.text}},Ue$1=class extends Me$1{constructor(e){super(e)}isErrorNode(){return!0}accept(e){return e.visitErrorNode(this)}},Be$1=class extends U$2{constructor(e,t){super(e,t),this.children=null,this.start=null,this.stop=null,this.exception=null}copyFrom(e){this.parentCtx=e.parentCtx,this.invokingState=e.invokingState,this.children=null,this.start=e.start,this.stop=e.stop,e.children&&(this.children=[],e.children.map(function(e){e instanceof Ue$1&&(this.children.push(e),e.parentCtx=this)},this))}enterRule(e){}exitRule(e){}addChild(e){return null===this.children&&(this.children=[]),this.children.push(e),e}removeLastChild(){null!==this.children&&this.children.pop()}addTokenNode(e){const t=new Me$1(e);return this.addChild(t),t.parentCtx=this,t}addErrorNode(e){const t=new Ue$1(e);return this.addChild(t),t.parentCtx=this,t}getChild(e,t){if(t=t||null,null===this.children||e<0||e>=this.children.length)return null;if(null===t)return this.children[e];for(let r=0;r=this.children.length)return null;for(let r=0;r2&&void 0!==arguments[2]?arguments[2]:e.DEFAULT_PROGRAM_NAME;n="number"==typeof t?t:t.tokenIndex;let o=this.getProgram(i),s=new He$1(this.tokens,n,o.length,r);o.push(s)}insertBefore(t,r){let n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.DEFAULT_PROGRAM_NAME;n="number"==typeof t?t:t.tokenIndex;const o=this.getProgram(i),s=new qe$1(this.tokens,n,o.length,r);o.push(s)}replaceSingle(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.DEFAULT_PROGRAM_NAME;this.replace(t,t,r,n)}replace(t,r,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.DEFAULT_PROGRAM_NAME;if("number"!=typeof t&&(t=t.tokenIndex),"number"!=typeof r&&(r=r.tokenIndex),t>r||t<0||r<0||r>=this.tokens.size)throw new RangeError(`replace: range invalid: ${t}..${r}(size=${this.tokens.size})`);let o=this.getProgram(i),s=new Ke$1(this.tokens,t,r,o.length,n);o.push(s)}delete(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.DEFAULT_PROGRAM_NAME;void 0===r&&(r=t),this.replace(t,r,null,n)}getProgram(e){let t=this.programs.get(e);return null==t&&(t=this.initializeProgram(e)),t}initializeProgram(e){const t=[];return this.programs.set(e,t),t}getText(t){let r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.DEFAULT_PROGRAM_NAME;r=t instanceof E$1?t:new E$1(0,this.tokens.size-1),"string"==typeof t&&(n=t);const o=this.programs.get(n);let s=r.start,a=r.stop;if(a>this.tokens.size-1&&(a=this.tokens.size-1),s<0&&(s=0),null==o||0===o.length)return this.tokens.getText(new E$1(s,a));let c=[],l=this.reduceToSingleOperationPerIndex(o),u=s;for(;u<=a&&u=this.tokens.size-1&&c.push(e.text.toString());return c.join("")}reduceToSingleOperationPerIndex(e){for(let t=0;tn.index&&t.index<=n.lastIndex&&(e[t.instructionIndex]=void 0);let o=this.getKindOfOps(e,Ke$1,t);for(let t of o){if(t.index>=n.index&&t.lastIndex<=n.lastIndex){e[t.instructionIndex]=void 0;continue}let r=t.lastIndexn.lastIndex;if(null!=t.text||null!=n.text||r){if(!r)throw new Error(`replace op boundaries of ${n} overlap with previous ${t}`)}else e[t.instructionIndex]=void 0,n.index=Math.min(t.index,n.index),n.lastIndex=Math.max(t.lastIndex,n.lastIndex)}}for(let t=0;t=r.index&&n.index<=r.lastIndex)throw new Error(`insert op ${n} within boundaries of previous ${r}`)}else r.text=this.catOpText(n.text,r.text),e[t]=void 0}let t=new Map;for(let r of e)if(null!=r){if(null!=t.get(r.index))throw new Error("should only be one op per index");t.set(r.index,r)}return t}catOpText(e,t){let r="",n="";return null!=e&&(r=e.toString()),null!=t&&(n=t.toString()),r+n}getKindOfOps(e,t,r){return e.slice(0,r).filter(e=>e&&e instanceof t)}};class Ve{constructor(e,t,r,n){this.tokens=e,this.instructionIndex=r,this.index=t,this.text=void 0===n?"":n}toString(){let e=this.constructor.name;const t=e.indexOf("$");return e=e.substring(t+1,e.length),"<"+e+"@"+this.tokens.get(this.index)+':"'+this.text+'">'}}let qe$1=class extends Ve{constructor(e,t,r,n){super(e,t,r,n)}execute(e){return this.text&&e.push(this.text.toString()),this.tokens.get(this.index).type!==i.EOF&&e.push(String(this.tokens.get(this.index).text)),this.index+1}},He$1=class extends qe$1{constructor(e,t,r,n){super(e,t+1,r,n)}},Ke$1=class extends Ve{constructor(e,t,r,n,i){super(e,t,n,i),this.lastIndex=r}execute(e){return this.text&&e.push(this.text.toString()),this.lastIndex+1}toString(){return null==this.text?"":"'}};const Ye$1={atn:re$1,dfa:he$2,context:ce,misc:ue$1,tree:fe$1,error:Ne$1,Token:i,CommonToken:Pt,CharStreams:Re$1,CharStream:ke$1,InputStream:Ie,CommonTokenStream:be$1,Lexer:Ut$1,Parser:Fe,ParserRuleContext:Be$1,Interval:E$1,IntervalSet:_$1,LL1Analyzer:j$1,Utils:we,TokenStreamRewriter:ze$1};var Ge$1=s.MG,We$1=s.fr;s.sR,s.Zo;var Xe$1=s.iH;s.rt;var Ze$1=s.jB,Qe$1=s.M8;s.$t,s.aq,s.pG;var sn$1=s.eP;s.KU,s.zW,s.IX,s.mY,s.a7;var cn$1=s.JG,un$1=s.ay;s.X2,s.WU;var pn$1=s.Uw;s.gw;var xn$1=s.iX,Tn$1=s.re,Sn$1=s.Pg,mn$1=s.tD;s.R$;var _n$1=s.Dj;s.m7,s.NZ,s.xo;var kn$1=s.ou;s.qC,s.mD,s.Ay;var navigator$1={userAgent:!1},window$1={},CryptoJS=CryptoJS||function(e,t){var r={},n=r.lib={},i=n.Base=function(){function e(){}return{extend:function(t){e.prototype=this;var r=new e;return t&&r.mixIn(t),r.hasOwnProperty("init")||(r.init=function(){r.$super.init.apply(this,arguments)}),r.init.prototype=r,r.$super=this,r},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||a).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=s<<24-(n+o)%4*8}else for(o=0;o>>2]=r[o>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r=[],n=0;n>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new o.init(r,t/2)}},c=s.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new o.init(r,t)}},l=s.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},u=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,n=r.words,i=r.sigBytes,s=this.blockSize,a=i/(4*s),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*s,l=e.min(4*c,i);if(c){for(var u=0;u>>2]}},t.BlockCipher=a.extend({cfg:a.cfg.extend({mode:c,padding:u}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var r=t.createEncryptor;else r=t.createDecryptor,this._minBufferSize=1;this._mode=r.call(t,this,e&&e.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else t=this._process(!0),e.unpad(t);return t},blockSize:4});var d=t.CipherParams=r.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(c=(p.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?n.create([1398893684,1701076831]).concat(e).concat(t):t).toString(o)},parse:function(e){var t=(e=o.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var r=n.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return d.create({ciphertext:e,salt:r})}},t.SerializableCipher=r.extend({cfg:r.extend({format:c}),encrypt:function(e,t,r,n){n=this.cfg.extend(n);var i=e.createEncryptor(r,n);return t=i.finalize(t),i=i.cfg,d.create({ciphertext:t,key:r,iv:i.iv,algorithm:e,mode:i.mode,padding:i.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,r,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(r,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),p=(p.kdf={}).OpenSSL={execute:function(e,t,r,i){return i||(i=n.random(8)),e=s.create({keySize:t+r}).compute(e,i),r=n.create(e.words.slice(t),4*r),e.sigBytes=4*t,d.create({key:e,iv:r,salt:i})}},g=t.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:p}),encrypt:function(e,t,r,n){return r=(n=this.cfg.extend(n)).kdf.execute(r,e.keySize,e.ivSize),n.iv=r.iv,(e=h.encrypt.call(this,e,t,r.key,n)).mixIn(r),e},decrypt:function(e,t,r,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),r=n.kdf.execute(r,e.keySize,e.ivSize,t.salt),n.iv=r.iv,h.decrypt.call(this,e,t,r.key,n)}})}(),function(){for(var e=CryptoJS,t=e.lib.BlockCipher,r=e.algo,n=[],i=[],o=[],s=[],a=[],c=[],l=[],u=[],d=[],h=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var m=0,f=0;for(g=0;256>g;g++){var y=(y=f^f<<1^f<<2^f<<3^f<<4)>>>8^255&y^99;n[m]=y,i[y]=m;var $=p[m],b=p[$],v=p[b],w=257*p[y]^16843008*y;o[m]=w<<24|w>>>8,s[m]=w<<16|w>>>16,a[m]=w<<8|w>>>24,c[m]=w,w=16843009*v^65537*b^257*$^16843008*m,l[y]=w<<24|w>>>8,u[y]=w<<16|w>>>16,d[y]=w<<8|w>>>24,h[y]=w,m?(m=$^p[p[p[v^$]]],f^=p[p[f]]):m=f=1}var S=[0,1,2,4,8,16,32,64,128,27,54];r=r.AES=t.extend({_doReset:function(){for(var e=(r=this._key).words,t=r.sigBytes/4,r=4*((this._nRounds=t+6)+1),i=this._keySchedule=[],o=0;o>>24]<<24|n[s>>>16&255]<<16|n[s>>>8&255]<<8|n[255&s]):(s=n[(s=s<<8|s>>>24)>>>24]<<24|n[s>>>16&255]<<16|n[s>>>8&255]<<8|n[255&s],s^=S[o/t|0]<<24),i[o]=i[o-t]^s}for(e=this._invKeySchedule=[],t=0;tt||4>=o?s:l[n[s>>>24]]^u[n[s>>>16&255]]^d[n[s>>>8&255]]^h[n[255&s]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,o,s,a,c,n)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,l,u,d,h,i),r=e[t+1],e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,n,i,o,s,a){for(var c=this._nRounds,l=e[t]^r[0],u=e[t+1]^r[1],d=e[t+2]^r[2],h=e[t+3]^r[3],p=4,g=1;g>>24]^i[u>>>16&255]^o[d>>>8&255]^s[255&h]^r[p++],f=n[u>>>24]^i[d>>>16&255]^o[h>>>8&255]^s[255&l]^r[p++],y=n[d>>>24]^i[h>>>16&255]^o[l>>>8&255]^s[255&u]^r[p++];h=n[h>>>24]^i[l>>>16&255]^o[u>>>8&255]^s[255&d]^r[p++],l=m,u=f,d=y}m=(a[l>>>24]<<24|a[u>>>16&255]<<16|a[d>>>8&255]<<8|a[255&h])^r[p++],f=(a[u>>>24]<<24|a[d>>>16&255]<<16|a[h>>>8&255]<<8|a[255&l])^r[p++],y=(a[d>>>24]<<24|a[h>>>16&255]<<16|a[l>>>8&255]<<8|a[255&u])^r[p++],h=(a[h>>>24]<<24|a[l>>>16&255]<<16|a[u>>>8&255]<<8|a[255&d])^r[p++],e[t]=m,e[t+1]=f,e[t+2]=y,e[t+3]=h},keySize:8});e.AES=t._createHelper(r)}(),function(){function e(e,t){var r=(this._lBlock>>>e^this._rBlock)&t;this._rBlock^=r,this._lBlock^=r<>>e^this._lBlock)&t;this._lBlock^=r,this._rBlock^=r<r;r++){var n=s[r]-1;t[r]=e[n>>>5]>>>31-n%32&1}for(e=this._subKeys=[],n=0;16>n;n++){var i=e[n]=[],o=c[n];for(r=0;24>r;r++)i[r/6|0]|=t[(a[r]-1+o)%28]<<31-r%6,i[4+(r/6|0)]|=t[28+(a[r+24]-1+o)%28]<<31-r%6;for(i[0]=i[0]<<1|i[0]>>>31,r=1;7>r;r++)i[r]>>>=4*(r-1)+3;i[7]=i[7]<<5|i[7]>>>27}for(t=this._invSubKeys=[],r=0;16>r;r++)t[r]=e[15-r]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._subKeys)},decryptBlock:function(e,t){this._doCryptBlock(e,t,this._invSubKeys)},_doCryptBlock:function(r,n,i){this._lBlock=r[n],this._rBlock=r[n+1],e.call(this,4,252645135),e.call(this,16,65535),t.call(this,2,858993459),t.call(this,8,16711935),e.call(this,1,1431655765);for(var o=0;16>o;o++){for(var s=i[o],a=this._lBlock,c=this._rBlock,d=0,h=0;8>h;h++)d|=l[h][((c^s[h])&u[h])>>>0];this._lBlock=c,this._rBlock=a^d}i=this._lBlock,this._lBlock=this._rBlock,this._rBlock=i,e.call(this,1,1431655765),t.call(this,8,16711935),t.call(this,2,858993459),e.call(this,16,65535),e.call(this,4,252645135),r[n]=this._lBlock,r[n+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});r.DES=i._createHelper(d),o=o.TripleDES=i.extend({_doReset:function(){var e=this._key.words;this._des1=d.createEncryptor(n.create(e.slice(0,2))),this._des2=d.createEncryptor(n.create(e.slice(2,4))),this._des3=d.createEncryptor(n.create(e.slice(4,6)))},encryptBlock:function(e,t){this._des1.encryptBlock(e,t),this._des2.decryptBlock(e,t),this._des3.encryptBlock(e,t)},decryptBlock:function(e,t){this._des3.decryptBlock(e,t),this._des2.encryptBlock(e,t),this._des1.decryptBlock(e,t)},keySize:6,ivSize:2,blockSize:2}),r.TripleDES=i._createHelper(o)}(),function(){var e=CryptoJS,t=e.lib.WordArray;e.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,n=this._map;e.clamp(),e=[];for(var i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,s=0;4>s&&i+.75*s>>6*(3-s)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var r=e.length,n=this._map;(i=n.charAt(64))&&(-1!=(i=e.indexOf(i))&&(r=i));for(var i=[],o=0,s=0;s>>6-s%4*2;i[o>>>2]|=(a|c)<<24-o%4*8,o++}return t.create(i,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(e){function t(e,t,r,n,i,o,s){return((e=e+(t&r|~t&n)+i+s)<>>32-o)+t}function r(e,t,r,n,i,o,s){return((e=e+(t&n|r&~n)+i+s)<>>32-o)+t}function n(e,t,r,n,i,o,s){return((e=e+(t^r^n)+i+s)<>>32-o)+t}function i(e,t,r,n,i,o,s){return((e=e+(r^(t|~n))+i+s)<>>32-o)+t}for(var o=CryptoJS,s=(c=o.lib).WordArray,a=c.Hasher,c=o.algo,l=[],u=0;64>u;u++)l[u]=4294967296*e.abs(e.sin(u+1))|0;c=c.MD5=a.extend({_doReset:function(){this._hash=new s.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,o){for(var s=0;16>s;s++){var a=e[c=o+s];e[c]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}s=this._hash.words;var c=e[o+0],u=(a=e[o+1],e[o+2]),d=e[o+3],h=e[o+4],p=e[o+5],g=e[o+6],m=e[o+7],f=e[o+8],y=e[o+9],$=e[o+10],b=e[o+11],v=e[o+12],w=e[o+13],S=e[o+14],_=e[o+15],E=t(E=s[0],T=s[1],I=s[2],C=s[3],c,7,l[0]),C=t(C,E,T,I,a,12,l[1]),I=t(I,C,E,T,u,17,l[2]),T=t(T,I,C,E,d,22,l[3]);E=t(E,T,I,C,h,7,l[4]),C=t(C,E,T,I,p,12,l[5]),I=t(I,C,E,T,g,17,l[6]),T=t(T,I,C,E,m,22,l[7]),E=t(E,T,I,C,f,7,l[8]),C=t(C,E,T,I,y,12,l[9]),I=t(I,C,E,T,$,17,l[10]),T=t(T,I,C,E,b,22,l[11]),E=t(E,T,I,C,v,7,l[12]),C=t(C,E,T,I,w,12,l[13]),I=t(I,C,E,T,S,17,l[14]),E=r(E,T=t(T,I,C,E,_,22,l[15]),I,C,a,5,l[16]),C=r(C,E,T,I,g,9,l[17]),I=r(I,C,E,T,b,14,l[18]),T=r(T,I,C,E,c,20,l[19]),E=r(E,T,I,C,p,5,l[20]),C=r(C,E,T,I,$,9,l[21]),I=r(I,C,E,T,_,14,l[22]),T=r(T,I,C,E,h,20,l[23]),E=r(E,T,I,C,y,5,l[24]),C=r(C,E,T,I,S,9,l[25]),I=r(I,C,E,T,d,14,l[26]),T=r(T,I,C,E,f,20,l[27]),E=r(E,T,I,C,w,5,l[28]),C=r(C,E,T,I,u,9,l[29]),I=r(I,C,E,T,m,14,l[30]),E=n(E,T=r(T,I,C,E,v,20,l[31]),I,C,p,4,l[32]),C=n(C,E,T,I,f,11,l[33]),I=n(I,C,E,T,b,16,l[34]),T=n(T,I,C,E,S,23,l[35]),E=n(E,T,I,C,a,4,l[36]),C=n(C,E,T,I,h,11,l[37]),I=n(I,C,E,T,m,16,l[38]),T=n(T,I,C,E,$,23,l[39]),E=n(E,T,I,C,w,4,l[40]),C=n(C,E,T,I,c,11,l[41]),I=n(I,C,E,T,d,16,l[42]),T=n(T,I,C,E,g,23,l[43]),E=n(E,T,I,C,y,4,l[44]),C=n(C,E,T,I,v,11,l[45]),I=n(I,C,E,T,_,16,l[46]),E=i(E,T=n(T,I,C,E,u,23,l[47]),I,C,c,6,l[48]),C=i(C,E,T,I,m,10,l[49]),I=i(I,C,E,T,S,15,l[50]),T=i(T,I,C,E,p,21,l[51]),E=i(E,T,I,C,v,6,l[52]),C=i(C,E,T,I,d,10,l[53]),I=i(I,C,E,T,$,15,l[54]),T=i(T,I,C,E,a,21,l[55]),E=i(E,T,I,C,f,6,l[56]),C=i(C,E,T,I,_,10,l[57]),I=i(I,C,E,T,g,15,l[58]),T=i(T,I,C,E,w,21,l[59]),E=i(E,T,I,C,h,6,l[60]),C=i(C,E,T,I,b,10,l[61]),I=i(I,C,E,T,u,15,l[62]),T=i(T,I,C,E,y,21,l[63]);s[0]=s[0]+E|0,s[1]=s[1]+T|0,s[2]=s[2]+I|0,s[3]=s[3]+C|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;r[i>>>5]|=128<<24-i%32;var o=e.floor(n/4294967296);for(r[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(i+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(r.length+1),this._process(),r=(t=this._hash).words,n=0;4>n;n++)i=r[n],r[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8);return t},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),o.MD5=a._createHelper(c),o.HmacMD5=a._createHmacHelper(c)}(Math),function(){var e=CryptoJS,t=(i=e.lib).WordArray,r=i.Hasher,n=[],i=e.algo.SHA1=r.extend({_doReset:function(){this._hash=new t.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=this._hash.words,i=r[0],o=r[1],s=r[2],a=r[3],c=r[4],l=0;80>l;l++){if(16>l)n[l]=0|e[t+l];else{var u=n[l-3]^n[l-8]^n[l-14]^n[l-16];n[l]=u<<1|u>>>31}u=(i<<5|i>>>27)+c+n[l],u=20>l?u+(1518500249+(o&s|~o&a)):40>l?u+(1859775393+(o^s^a)):60>l?u+((o&s|o&a|s&a)-1894007588):u+((o^s^a)-899497514),c=a,a=s,s=o<<30|o>>>2,o=i,i=u}r[0]=r[0]+i|0,r[1]=r[1]+o|0,r[2]=r[2]+s|0,r[3]=r[3]+a|0,r[4]=r[4]+c|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=Math.floor(r/4294967296),t[15+(n+64>>>9<<4)]=r,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(i),e.HmacSHA1=r._createHmacHelper(i)}(),function(e){for(var t=CryptoJS,r=(i=t.lib).WordArray,n=i.Hasher,i=t.algo,o=[],s=[],a=function(e){return 4294967296*(e-(0|e))|0},c=2,l=0;64>l;){var u;e:{u=c;for(var d=e.sqrt(u),h=2;h<=d;h++)if(!(u%h)){u=!1;break e}u=!0}u&&(8>l&&(o[l]=a(e.pow(c,.5))),s[l]=a(e.pow(c,1/3)),l++),c++}var p=[];i=i.SHA256=n.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],i=r[1],o=r[2],a=r[3],c=r[4],l=r[5],u=r[6],d=r[7],h=0;64>h;h++){if(16>h)p[h]=0|e[t+h];else{var g=p[h-15],m=p[h-2];p[h]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[h-7]+((m<<15|m>>>17)^(m<<13|m>>>19)^m>>>10)+p[h-16]}g=d+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&l^~c&u)+s[h]+p[h],m=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&i^n&o^i&o),d=u,u=l,l=c,c=a+g|0,a=o,o=i,i=n,n=g+m|0}r[0]=r[0]+n|0,r[1]=r[1]+i|0,r[2]=r[2]+o|0,r[3]=r[3]+a|0,r[4]=r[4]+c|0,r[5]=r[5]+l|0,r[6]=r[6]+u|0,r[7]=r[7]+d|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;return r[i>>>5]|=128<<24-i%32,r[14+(i+64>>>9<<4)]=e.floor(n/4294967296),r[15+(i+64>>>9<<4)]=n,t.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(i),t.HmacSHA256=n._createHmacHelper(i)}(Math),function(){var e=CryptoJS,t=e.lib.WordArray,r=(n=e.algo).SHA256,n=n.SHA224=r.extend({_doReset:function(){this._hash=new t.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var e=r._doFinalize.call(this);return e.sigBytes-=4,e}});e.SHA224=r._createHelper(n),e.HmacSHA224=r._createHmacHelper(n)}(),function(){function e(){return n.create.apply(n,arguments)}for(var t=CryptoJS,r=t.lib.Hasher,n=(o=t.x64).Word,i=o.WordArray,o=t.algo,s=[e(1116352408,3609767458),e(1899447441,602891725),e(3049323471,3964484399),e(3921009573,2173295548),e(961987163,4081628472),e(1508970993,3053834265),e(2453635748,2937671579),e(2870763221,3664609560),e(3624381080,2734883394),e(310598401,1164996542),e(607225278,1323610764),e(1426881987,3590304994),e(1925078388,4068182383),e(2162078206,991336113),e(2614888103,633803317),e(3248222580,3479774868),e(3835390401,2666613458),e(4022224774,944711139),e(264347078,2341262773),e(604807628,2007800933),e(770255983,1495990901),e(1249150122,1856431235),e(1555081692,3175218132),e(1996064986,2198950837),e(2554220882,3999719339),e(2821834349,766784016),e(2952996808,2566594879),e(3210313671,3203337956),e(3336571891,1034457026),e(3584528711,2466948901),e(113926993,3758326383),e(338241895,168717936),e(666307205,1188179964),e(773529912,1546045734),e(1294757372,1522805485),e(1396182291,2643833823),e(1695183700,2343527390),e(1986661051,1014477480),e(2177026350,1206759142),e(2456956037,344077627),e(2730485921,1290863460),e(2820302411,3158454273),e(3259730800,3505952657),e(3345764771,106217008),e(3516065817,3606008344),e(3600352804,1432725776),e(4094571909,1467031594),e(275423344,851169720),e(430227734,3100823752),e(506948616,1363258195),e(659060556,3750685593),e(883997877,3785050280),e(958139571,3318307427),e(1322822218,3812723403),e(1537002063,2003034995),e(1747873779,3602036899),e(1955562222,1575990012),e(2024104815,1125592928),e(2227730452,2716904306),e(2361852424,442776044),e(2428436474,593698344),e(2756734187,3733110249),e(3204031479,2999351573),e(3329325298,3815920427),e(3391569614,3928383900),e(3515267271,566280711),e(3940187606,3454069534),e(4118630271,4000239992),e(116418474,1914138554),e(174292421,2731055270),e(289380356,3203993006),e(460393269,320620315),e(685471733,587496836),e(852142971,1086792851),e(1017036298,365543100),e(1126000580,2618297676),e(1288033470,3409855158),e(1501505948,4234509866),e(1607167915,987167468),e(1816402316,1246189591)],a=[],c=0;80>c;c++)a[c]=e();o=o.SHA512=r.extend({_doReset:function(){this._hash=new i.init([new n.init(1779033703,4089235720),new n.init(3144134277,2227873595),new n.init(1013904242,4271175723),new n.init(2773480762,1595750129),new n.init(1359893119,2917565137),new n.init(2600822924,725511199),new n.init(528734635,4215389547),new n.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var r=(d=this._hash.words)[0],n=d[1],i=d[2],o=d[3],c=d[4],l=d[5],u=d[6],d=d[7],h=r.high,p=r.low,g=n.high,m=n.low,f=i.high,y=i.low,$=o.high,b=o.low,v=c.high,w=c.low,S=l.high,_=l.low,E=u.high,C=u.low,I=d.high,T=d.low,A=h,D=p,x=g,R=m,O=f,N=y,P=$,k=b,M=v,L=w,F=S,j=_,U=E,B=C,H=I,q=T,z=0;80>z;z++){var W=a[z];if(16>z)var G=W.high=0|e[t+2*z],J=W.low=0|e[t+2*z+1];else{G=((J=(G=a[z-15]).high)>>>1|(K=G.low)<<31)^(J>>>8|K<<24)^J>>>7;var K=(K>>>1|J<<31)^(K>>>8|J<<24)^(K>>>7|J<<25),V=((J=(V=a[z-2]).high)>>>19|(Z=V.low)<<13)^(J<<3|Z>>>29)^J>>>6,Z=(Z>>>19|J<<13)^(Z<<3|J>>>29)^(Z>>>6|J<<26),X=(J=a[z-7]).high,Y=(Q=a[z-16]).high,Q=Q.low;G=(G=(G=G+X+((J=K+J.low)>>>0>>0?1:0))+V+((J=J+Z)>>>0>>0?1:0))+Y+((J=J+Q)>>>0>>0?1:0);W.high=G,W.low=J}X=M&F^~M&U,Q=L&j^~L&B,W=A&x^A&O^x&O;var ee=D&R^D&N^R&N,te=(K=(A>>>28|D<<4)^(A<<30|D>>>2)^(A<<25|D>>>7),V=(D>>>28|A<<4)^(D<<30|A>>>2)^(D<<25|A>>>7),(Z=s[z]).high),re=Z.low;Y=H+((M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9))+((Z=q+((L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9)))>>>0>>0?1:0),H=U,q=B,U=F,B=j,F=M,j=L,M=P+(Y=(Y=(Y=Y+X+((Z=Z+Q)>>>0>>0?1:0))+te+((Z=Z+re)>>>0>>0?1:0))+G+((Z=Z+J)>>>0>>0?1:0))+((L=k+Z|0)>>>0>>0?1:0)|0,P=O,k=N,O=x,N=R,x=A,R=D,A=Y+(W=K+W+((J=V+ee)>>>0>>0?1:0))+((D=Z+J|0)>>>0>>0?1:0)|0}p=r.low=p+D,r.high=h+A+(p>>>0>>0?1:0),m=n.low=m+R,n.high=g+x+(m>>>0>>0?1:0),y=i.low=y+N,i.high=f+O+(y>>>0>>0?1:0),b=o.low=b+k,o.high=$+P+(b>>>0>>0?1:0),w=c.low=w+L,c.high=v+M+(w>>>0>>0?1:0),_=l.low=_+j,l.high=S+F+(_>>>0>>0?1:0),C=u.low=C+B,u.high=E+U+(C>>>0>>0?1:0),T=d.low=T+q,d.high=I+H+(T>>>0>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(r/4294967296),t[31+(n+128>>>10<<5)]=r,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32}),t.SHA512=r._createHelper(o),t.HmacSHA512=r._createHmacHelper(o)}(),function(){var e=CryptoJS,t=(i=e.x64).Word,r=i.WordArray,n=(i=e.algo).SHA512,i=i.SHA384=n.extend({_doReset:function(){this._hash=new r.init([new t.init(3418070365,3238371032),new t.init(1654270250,914150663),new t.init(2438529370,812702999),new t.init(355462360,4144912697),new t.init(1731405415,4290775857),new t.init(2394180231,1750603025),new t.init(3675008525,1694076839),new t.init(1203062813,3204075428)])},_doFinalize:function(){var e=n._doFinalize.call(this);return e.sigBytes-=16,e}});e.SHA384=n._createHelper(i),e.HmacSHA384=n._createHmacHelper(i)}(),function(){var e=CryptoJS,t=(n=e.lib).WordArray,r=n.Hasher,n=e.algo,i=t.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=t.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),s=t.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),a=t.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),c=t.create([0,1518500249,1859775393,2400959708,2840853838]),l=t.create([1352829926,1548603684,1836072691,2053994217,0]);n=n.RIPEMD160=r.extend({_doReset:function(){this._hash=t.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=0;16>r;r++){var n=e[v=t+r];e[v]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8)}var u,d,h,p,g,m,f,y,$,b,v=this._hash.words,w=(n=c.words,l.words),S=i.words,_=o.words,E=s.words,C=a.words;m=u=v[0],f=d=v[1],y=h=v[2],$=p=v[3],b=g=v[4];var I;for(r=0;80>r;r+=1)I=u+e[t+S[r]]|0,I=16>r?I+((d^h^p)+n[0]):32>r?I+((d&h|~d&p)+n[1]):48>r?I+(((d|~h)^p)+n[2]):64>r?I+((d&p|h&~p)+n[3]):I+((d^(h|~p))+n[4]),I=(I=(I|=0)<>>32-E[r])+g|0,u=g,g=p,p=h<<10|h>>>22,h=d,d=I,I=m+e[t+_[r]]|0,I=16>r?I+((f^(y|~$))+w[0]):32>r?I+((f&$|y&~$)+w[1]):48>r?I+(((f|~y)^$)+w[2]):64>r?I+((f&y|~f&$)+w[3]):I+((f^y^$)+w[4]),I=(I=(I|=0)<>>32-C[r])+b|0,m=b,b=$,$=y<<10|y>>>22,y=f,f=I;I=v[1]+h+$|0,v[1]=v[2]+p+b|0,v[2]=v[3]+g+m|0,v[3]=v[4]+u+f|0,v[4]=v[0]+d+y|0,v[0]=I},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;for(t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),e.sigBytes=4*(t.length+1),this._process(),t=(e=this._hash).words,r=0;5>r;r++)n=t[r],t[r]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8);return e},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.RIPEMD160=r._createHelper(n),e.HmacRIPEMD160=r._createHmacHelper(n)}(),function(){var e=CryptoJS,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,r){e=this._hasher=new e.init,"string"==typeof r&&(r=t.parse(r));var n=e.blockSize,i=4*n;r.sigBytes>i&&(r=e.finalize(r)),r.clamp();for(var o=this._oKey=r.clone(),s=this._iKey=r.clone(),a=o.words,c=s.words,l=0;l>6)+b64map.charAt(63&r);for(t+1==e.length?(r=parseInt(e.substring(t,t+1),16),n+=b64map.charAt(r<<2)):t+2==e.length&&(r=parseInt(e.substring(t,t+2),16),n+=b64map.charAt(r>>2)+b64map.charAt((3&r)<<4));(3&n.length)>0;)n+=b64pad;return n}function b64tohex(e){var t,r,n,i="",o=0;for(t=0;t>2),r=3&n,o=1):1==o?(i+=int2char(r<<2|n>>4),r=15&n,o=2):2==o?(i+=int2char(r),i+=int2char(n>>2),r=3&n,o=3):(i+=int2char(r<<2|n>>4),i+=int2char(15&n),o=0));return 1==o&&(i+=int2char(r<<2)),i} -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */function BigInteger(e,t,r){null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function nbi(){return new BigInteger(null)}function am1(e,t,r,n,i,o){for(;--o>=0;){var s=t*this[e++]+r[n]+i;i=Math.floor(s/67108864),r[n++]=67108863&s}return i}function am2(e,t,r,n,i,o){for(var s=32767&t,a=t>>15;--o>=0;){var c=32767&this[e],l=this[e++]>>15,u=a*c+l*s;i=((c=s*c+((32767&u)<<15)+r[n]+(1073741823&i))>>>30)+(u>>>15)+a*l+(i>>>30),r[n++]=1073741823&c}return i}function am3(e,t,r,n,i,o){for(var s=16383&t,a=t>>14;--o>=0;){var c=16383&this[e],l=this[e++]>>14,u=a*c+l*s;i=((c=s*c+((16383&u)<<14)+r[n]+i)>>28)+(u>>14)+a*l,r[n++]=268435455&c}return i}"Microsoft Internet Explorer"==navigator$1.appName?(BigInteger.prototype.am=am2,dbits=30):"Netscape"!=navigator$1.appName?(BigInteger.prototype.am=am1,dbits=26):(BigInteger.prototype.am=am3,dbits=28),BigInteger.prototype.DB=dbits,BigInteger.prototype.DM=(1<=0;--t)e[t]=this[t];e.t=this.t,e.s=this.s}function bnpFromInt(e){this.t=1,this.s=e<0?-1:0,e>0?this[0]=e:e<-1?this[0]=e+this.DV:this.t=0}function nbv(e){var t=nbi();return t.fromInt(e),t}function bnpFromString(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,o=0;--n>=0;){var s=8==r?255&e[n]:intAt(e,n);s<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==o?this[this.t++]=s:o+r>this.DB?(this[this.t-1]|=(s&(1<>this.DB-o):this[this.t-1]|=s<=this.DB&&(o-=this.DB))}8==r&&128&e[0]&&(this.s=-1,o>0&&(this[this.t-1]|=(1<0&&this[this.t-1]==e;)--this.t}function bnToString(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(a>a)>0&&(i=!0,o=int2char(r));s>=0;)a>(a+=this.DB-t)):(r=this[s]>>(a-=t)&n,a<=0&&(a+=this.DB,--s)),r>0&&(i=!0),i&&(o+=int2char(r));return i?o:"0"}function bnNegate(){var e=nbi();return BigInteger.ZERO.subTo(this,e),e}function bnAbs(){return this.s<0?this.negate():this}function bnCompareTo(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this[r]-e[r]))return t;return 0}function nbits(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function bnBitLength(){return this.t<=0?0:this.DB*(this.t-1)+nbits(this[this.t-1]^this.s&this.DM)}function bnpDLShiftTo(e,t){var r;for(r=this.t-1;r>=0;--r)t[r+e]=this[r];for(r=e-1;r>=0;--r)t[r]=0;t.t=this.t+e,t.s=this.s}function bnpDRShiftTo(e,t){for(var r=e;r=0;--r)t[r+s+1]=this[r]>>i|a,a=(this[r]&o)<=0;--r)t[r]=0;t[s]=a,t.t=this.t+s+1,t.s=this.s,t.clamp()}function bnpRShiftTo(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)t.t=0;else{var n=e%this.DB,i=this.DB-n,o=(1<>n;for(var s=r+1;s>n;n>0&&(t[this.t-r-1]|=(this.s&o)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t[r++]=this.DV+n:n>0&&(t[r++]=n),t.t=r,t.clamp()}function bnpMultiplyTo(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t[i]=0;for(i=0;i=0;)e[r]=0;for(r=0;r=t.DV&&(e[r+t.t]-=t.DV,e[r+t.t+1]=1)}e.t>0&&(e[e.t-1]+=t.am(r,t[r],e,2*r,0,1)),e.s=0,e.clamp()}function bnpDivRemTo(e,t,r){var n=e.abs();if(!(n.t<=0)){var i=this.abs();if(i.t0?(n.lShiftTo(c,o),i.lShiftTo(c,r)):(n.copyTo(o),i.copyTo(r));var l=o.t,u=o[l-1];if(0!=u){var d=u*(1<1?o[l-2]>>this.F2:0),h=this.FV/d,p=(1<=0&&(r[r.t++]=1,r.subTo(y,r)),BigInteger.ONE.dlShiftTo(l,y),y.subTo(o,o);o.t=0;){var $=r[--m]==u?this.DM:Math.floor(r[m]*h+(r[m-1]+g)*p);if((r[m]+=o.am(0,$,r,f,0,l))<$)for(o.dlShiftTo(f,y),r.subTo(y,r);r[m]<--$;)r.subTo(y,r)}null!=t&&(r.drShiftTo(l,t),s!=a&&BigInteger.ZERO.subTo(t,t)),r.t=l,r.clamp(),c>0&&r.rShiftTo(c,r),s<0&&BigInteger.ZERO.subTo(r,r)}}}function bnMod(e){var t=nbi();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(BigInteger.ZERO)>0&&e.subTo(t,t),t}function Classic(e){this.m=e}function cConvert(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function cRevert(e){return e}function cReduce(e){e.divRemTo(this.m,null,e)}function cMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function cSqrTo(e,t){e.squareTo(t),this.reduce(t)}function bnpInvDigit(){if(this.t<1)return 0;var e=this[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t}function Montgomery(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(t,t),t}function montRevert(e){var t=nbi();return e.copyTo(t),this.reduce(t),t}function montReduce(e){for(;e.t<=this.mt2;)e[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(e[r=t+this.m.t]+=this.m.am(0,n,e,t,0,this.m.t);e[r]>=e.DV;)e[r]-=e.DV,e[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function montSqrTo(e,t){e.squareTo(t),this.reduce(t)}function montMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function bnpIsEven(){return 0==(this.t>0?1&this[0]:this.s)}function bnpExp(e,t){if(e>4294967295||e<1)return BigInteger.ONE;var r=nbi(),n=nbi(),i=t.convert(this),o=nbits(e)-1;for(i.copyTo(r);--o>=0;)if(t.sqrTo(r,n),(e&1<0)t.mulTo(n,i,r);else{var s=r;r=n,n=s}return t.revert(r)}function bnModPowInt(e,t){var r;return r=e<256||t.isEven()?new Classic(t):new Montgomery(t),this.exp(e,r)} -/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ - */ -function bnClone(){var e=nbi();return this.copyTo(e),e}function bnIntValue(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<>24}function bnShortValue(){return 0==this.t?this.s:this[0]<<16>>16}function bnpChunkSize(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function bnSigNum(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1}function bnpToRadix(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=nbv(r),i=nbi(),o=nbi(),s="";for(this.divRemTo(n,i,o);i.signum()>0;)s=(r+o.intValue()).toString(e).substr(1)+s,i.divRemTo(n,i,o);return o.intValue().toString(e)+s}function bnpFromRadix(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,o=0,s=0,a=0;a=r&&(this.dMultiply(n),this.dAddOffset(s,0),o=0,s=0))}o>0&&(this.dMultiply(Math.pow(t,o)),this.dAddOffset(s,0)),i&&BigInteger.ZERO.subTo(this,this)}function bnpFromNumber(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(BigInteger.ONE.shiftLeft(e-1),op_or,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(BigInteger.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<0)for(n>n)!=(this.s&this.DM)>>n&&(t[i++]=r|this.s<=0;)n<8?(r=(this[e]&(1<>(n+=this.DB-8)):(r=this[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),128&r&&(r|=-256),0==i&&(128&this.s)!=(128&r)&&++i,(i>0||r!=this.s)&&(t[i++]=r);return t}function bnEquals(e){return 0==this.compareTo(e)}function bnMin(e){return this.compareTo(e)<0?this:e}function bnMax(e){return this.compareTo(e)>0?this:e}function bnpBitwiseTo(e,t,r){var n,i,o=Math.min(e.t,this.t);for(n=0;n>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function bnGetLowestSetBit(){for(var e=0;e=this.t?0!=this.s:!!(this[t]&1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t[r++]=n:n<-1&&(t[r++]=this.DV+n),t.t=r,t.clamp()}function bnAdd(e){var t=nbi();return this.addTo(e,t),t}function bnSubtract(e){var t=nbi();return this.subTo(e,t),t}function bnMultiply(e){var t=nbi();return this.multiplyTo(e,t),t}function bnSquare(){var e=nbi();return this.squareTo(e),e}function bnDivide(e){var t=nbi();return this.divRemTo(e,t,null),t}function bnRemainder(e){var t=nbi();return this.divRemTo(e,null,t),t}function bnDivideAndRemainder(e){var t=nbi(),r=nbi();return this.divRemTo(e,t,r),new Array(t,r)}function bnpDMultiply(e){this[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function bnpDAddOffset(e,t){if(0!=e){for(;this.t<=t;)this[this.t++]=0;for(this[t]+=e;this[t]>=this.DV;)this[t]-=this.DV,++t>=this.t&&(this[this.t++]=0),++this[t]}}function NullExp(){}function nNop(e){return e}function nMulTo(e,t,r){e.multiplyTo(t,r)}function nSqrTo(e,t){e.squareTo(t)}function bnPow(e){return this.exp(e,new NullExp)}function bnpMultiplyLowerTo(e,t,r){var n,i=Math.min(this.t+e.t,t);for(r.s=0,r.t=i;i>0;)r[--i]=0;for(n=r.t-this.t;i=0;)r[n]=0;for(n=Math.max(t-this.t,0);n2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=nbi();return e.copyTo(t),this.reduce(t),t}function barrettRevert(e){return e}function barrettReduce(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function barrettSqrTo(e,t){e.squareTo(t),this.reduce(t)}function barrettMulTo(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function bnModPow(e,t){var r,n,i=e.bitLength(),o=nbv(1);if(i<=0)return o;r=i<18?1:i<48?3:i<144?4:i<768?5:6,n=i<8?new Classic(t):t.isEven()?new Barrett(t):new Montgomery(t);var s=new Array,a=3,c=r-1,l=(1<1){var u=nbi();for(n.sqrTo(s[1],u);a<=l;)s[a]=nbi(),n.mulTo(u,s[a-2],s[a]),a+=2}var d,h,p=e.t-1,g=!0,m=nbi();for(i=nbits(e[p])-1;p>=0;){for(i>=c?d=e[p]>>i-c&l:(d=(e[p]&(1<0&&(d|=e[p-1]>>this.DB+i-c)),a=r;!(1&d);)d>>=1,--a;if((i-=a)<0&&(i+=this.DB,--p),g)s[d].copyTo(o),g=!1;else{for(;a>1;)n.sqrTo(o,m),n.sqrTo(m,o),a-=2;a>0?n.sqrTo(o,m):(h=o,o=m,m=h),n.mulTo(m,s[d],o)}for(;p>=0&&!(e[p]&1<0&&(t.rShiftTo(o,t),r.rShiftTo(o,r));t.signum()>0;)(i=t.getLowestSetBit())>0&&t.rShiftTo(i,t),(i=r.getLowestSetBit())>0&&r.rShiftTo(i,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return o>0&&r.lShiftTo(o,r),r}function bnpModInt(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this[n])%e;return r}function bnModInverse(e){var t=e.isEven();if(this.isEven()&&t||0==e.signum())return BigInteger.ZERO;for(var r=e.clone(),n=this.clone(),i=nbv(1),o=nbv(0),s=nbv(0),a=nbv(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),t?(i.isEven()&&o.isEven()||(i.addTo(this,i),o.subTo(e,o)),i.rShiftTo(1,i)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);for(;n.isEven();)n.rShiftTo(1,n),t?(s.isEven()&&a.isEven()||(s.addTo(this,s),a.subTo(e,a)),s.rShiftTo(1,s)):a.isEven()||a.subTo(e,a),a.rShiftTo(1,a);r.compareTo(n)>=0?(r.subTo(n,r),t&&i.subTo(s,i),o.subTo(a,o)):(n.subTo(r,n),t&&s.subTo(i,s),a.subTo(o,a))}return 0!=n.compareTo(BigInteger.ONE)?BigInteger.ZERO:a.compareTo(e)>=0?a.subtract(e):a.signum()<0?(a.addTo(e,a),a.signum()<0?a.add(e):a):a}Classic.prototype.convert=cConvert,Classic.prototype.revert=cRevert,Classic.prototype.reduce=cReduce,Classic.prototype.mulTo=cMulTo,Classic.prototype.sqrTo=cSqrTo,Montgomery.prototype.convert=montConvert,Montgomery.prototype.revert=montRevert,Montgomery.prototype.reduce=montReduce,Montgomery.prototype.mulTo=montMulTo,Montgomery.prototype.sqrTo=montSqrTo,BigInteger.prototype.copyTo=bnpCopyTo,BigInteger.prototype.fromInt=bnpFromInt,BigInteger.prototype.fromString=bnpFromString,BigInteger.prototype.clamp=bnpClamp,BigInteger.prototype.dlShiftTo=bnpDLShiftTo,BigInteger.prototype.drShiftTo=bnpDRShiftTo,BigInteger.prototype.lShiftTo=bnpLShiftTo,BigInteger.prototype.rShiftTo=bnpRShiftTo,BigInteger.prototype.subTo=bnpSubTo,BigInteger.prototype.multiplyTo=bnpMultiplyTo,BigInteger.prototype.squareTo=bnpSquareTo,BigInteger.prototype.divRemTo=bnpDivRemTo,BigInteger.prototype.invDigit=bnpInvDigit,BigInteger.prototype.isEven=bnpIsEven,BigInteger.prototype.exp=bnpExp,BigInteger.prototype.toString=bnToString,BigInteger.prototype.negate=bnNegate,BigInteger.prototype.abs=bnAbs,BigInteger.prototype.compareTo=bnCompareTo,BigInteger.prototype.bitLength=bnBitLength,BigInteger.prototype.mod=bnMod,BigInteger.prototype.modPowInt=bnModPowInt,BigInteger.ZERO=nbv(0),BigInteger.ONE=nbv(1),NullExp.prototype.convert=nNop,NullExp.prototype.revert=nNop,NullExp.prototype.mulTo=nMulTo,NullExp.prototype.sqrTo=nSqrTo,Barrett.prototype.convert=barrettConvert,Barrett.prototype.revert=barrettRevert,Barrett.prototype.reduce=barrettReduce,Barrett.prototype.mulTo=barrettMulTo,Barrett.prototype.sqrTo=barrettSqrTo;var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(e){var t,r=this.abs();if(1==r.t&&r[0]<=lowprimes[lowprimes.length-1]){for(t=0;t>1)>lowprimes.length&&(e=lowprimes.length);for(var i=nbi(),o=0;o>8&255,rng_pool[rng_pptr++]^=e>>16&255,rng_pool[rng_pptr++]^=e>>24&255,rng_pptr>=rng_psize&&(rng_pptr-=rng_psize)}function rng_seed_time(){rng_seed_int((new Date).getTime())}if(null==rng_pool){var t;if(rng_pool=new Array,rng_pptr=0,void 0!==window$1&&(void 0!==window$1.crypto||void 0!==window$1.msCrypto)){var crypto$1=window$1.crypto||window$1.msCrypto;if(crypto$1.getRandomValues){var ua$2=new Uint8Array(32);for(crypto$1.getRandomValues(ua$2),t=0;t<32;++t)rng_pool[rng_pptr++]=ua$2[t]}else if("Netscape"==navigator$1.appName&&navigator$1.appVersion<"5"){var z$3=window$1.crypto.random(32);for(t=0;t>>8,rng_pool[rng_pptr++]=255&t;rng_pptr=0,rng_seed_time()}function rng_get_byte(){if(null==rng_state){for(rng_seed_time(),(rng_state=prng_newstate()).init(rng_pool),rng_pptr=0;rng_pptr0&&t.length>0))throw"Invalid RSA public key";this.n=parseBigInt(e,16),this.e=parseInt(t,16)}}function RSADoPublic(e){return e.modPowInt(this.e,this.n)}function RSASetPrivate(e,t,r){if(this.isPrivate=!0,"string"!=typeof e)this.n=e,this.e=t,this.d=r;else{if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA private key";this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(r,16)}}function RSASetPrivateEx(e,t,r,n,i,o,s,a){if(this.isPrivate=!0,this.isPublic=!1,null==e)throw"RSASetPrivateEx N == null";if(null==t)throw"RSASetPrivateEx E == null";if(0==e.length)throw"RSASetPrivateEx N.length == 0";if(0==t.length)throw"RSASetPrivateEx E.length == 0";if(!(null!=e&&null!=t&&e.length>0&&t.length>0))throw"Invalid RSA private key in RSASetPrivateEx";this.n=parseBigInt(e,16),this.e=parseInt(t,16),this.d=parseBigInt(r,16),this.p=parseBigInt(n,16),this.q=parseBigInt(i,16),this.dmp1=parseBigInt(o,16),this.dmq1=parseBigInt(s,16),this.coeff=parseBigInt(a,16)}function RSAGenerate(e,t){var r=new SecureRandom,n=e>>1;this.e=parseInt(t,16);for(var i=new BigInteger(t,16),o=e/2-100,s=BigInteger.ONE.shiftLeft(o);;){for(;this.p=new BigInteger(e-n,1,r),0!=this.p.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.p.isProbablePrime(10););for(;this.q=new BigInteger(n,1,r),0!=this.q.subtract(BigInteger.ONE).gcd(i).compareTo(BigInteger.ONE)||!this.q.isProbablePrime(10););if(this.p.compareTo(this.q)<=0){var a=this.p;this.p=this.q,this.q=a}var c=this.q.subtract(this.p).abs();if(!(c.bitLength()0;--t){o=o.twice();var u=n.testBit(t);u!=r.testBit(t)&&(o=o.add(u?this:i))}for(t=a.bitLength()-2;t>0;--t){c=c.twice();var d=a.testBit(t);d!=s.testBit(t)&&(c=c.add(d?c:l))}return o}function pointFpMultiplyTwo(e,t,r){var n;n=e.bitLength()>r.bitLength()?e.bitLength()-1:r.bitLength()-1;for(var i=this.curve.getInfinity(),o=this.add(t);n>=0;)i=i.twice(),e.testBit(n)?i=r.testBit(n)?i.add(o):i.add(this):r.testBit(n)&&(i=i.add(t)),--n;return i}function ECCurveFp(e,t,r){this.q=e,this.a=this.fromBigInteger(t),this.b=this.fromBigInteger(r),this.infinity=new ECPointFp(this,null,null)}function curveFpGetQ(){return this.q}function curveFpGetA(){return this.a}function curveFpGetB(){return this.b}function curveFpEquals(e){return e==this||this.q.equals(e.q)&&this.a.equals(e.a)&&this.b.equals(e.b)}function curveFpGetInfinity(){return this.infinity}function curveFpFromBigInteger(e){return new ECFieldElementFp(this.q,e)}function curveFpDecodePointHex(e){switch(parseInt(e.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:var t=e.substr(0,2);e.substr(2);var r=this.fromBigInteger(new BigInteger(a,16)),n=this.getA(),i=this.getB(),o=r.square().add(n).multiply(r).add(i).sqrt();return"03"==t&&(o=o.negate()),new ECPointFp(this,r,o);case 4:case 6:case 7:var s=(e.length-2)/2,a=e.substr(2,s),c=e.substr(s+2,s);return new ECPointFp(this,this.fromBigInteger(new BigInteger(a,16)),this.fromBigInteger(new BigInteger(c,16)));default:return null}}SecureRandom.prototype.nextBytes=rng_get_bytes,RSAKey.prototype.doPublic=RSADoPublic,RSAKey.prototype.setPublic=RSASetPublic,RSAKey.prototype.type="RSA",RSAKey.prototype.doPrivate=RSADoPrivate,RSAKey.prototype.setPrivate=RSASetPrivate,RSAKey.prototype.setPrivateEx=RSASetPrivateEx,RSAKey.prototype.generate=RSAGenerate,ECFieldElementFp.prototype.equals=feFpEquals,ECFieldElementFp.prototype.toBigInteger=feFpToBigInteger,ECFieldElementFp.prototype.negate=feFpNegate,ECFieldElementFp.prototype.add=feFpAdd,ECFieldElementFp.prototype.subtract=feFpSubtract,ECFieldElementFp.prototype.multiply=feFpMultiply,ECFieldElementFp.prototype.square=feFpSquare,ECFieldElementFp.prototype.divide=feFpDivide,ECFieldElementFp.prototype.sqrt=function(){return new ECFieldElementFp(this.q,this.x.sqrt().mod(this.q))},ECPointFp.prototype.getX=pointFpGetX,ECPointFp.prototype.getY=pointFpGetY,ECPointFp.prototype.equals=pointFpEquals,ECPointFp.prototype.isInfinity=pointFpIsInfinity,ECPointFp.prototype.negate=pointFpNegate,ECPointFp.prototype.add=pointFpAdd,ECPointFp.prototype.twice=pointFpTwice,ECPointFp.prototype.multiply=pointFpMultiply,ECPointFp.prototype.multiplyTwo=pointFpMultiplyTwo,ECCurveFp.prototype.getQ=curveFpGetQ,ECCurveFp.prototype.getA=curveFpGetA,ECCurveFp.prototype.getB=curveFpGetB,ECCurveFp.prototype.equals=curveFpEquals,ECCurveFp.prototype.getInfinity=curveFpGetInfinity,ECCurveFp.prototype.fromBigInteger=curveFpFromBigInteger,ECCurveFp.prototype.decodePointHex=curveFpDecodePointHex, -/*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib - */ -ECFieldElementFp.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)},ECPointFp.prototype.getEncoded=function(e){var t=function(e,t){var r=e.toByteArrayUnsigned();if(tr.length;)r.unshift(0);return r},r=this.getX().toBigInteger(),n=this.getY().toBigInteger(),i=t(r,32);return e?n.isEven()?i.unshift(2):i.unshift(3):(i.unshift(4),i=i.concat(t(n,32))),i},ECPointFp.decodeFrom=function(e,t){t[0];var r=t.length-1,n=t.slice(1,1+r/2),i=t.slice(1+r/2,1+r);n.unshift(0),i.unshift(0);var o=new BigInteger(n),s=new BigInteger(i);return new ECPointFp(e,e.fromBigInteger(o),e.fromBigInteger(s))},ECPointFp.decodeFromHex=function(e,t){t.substr(0,2);var r=t.length-2,n=t.substr(2,r/2),i=t.substr(2+r/2,r/2),o=new BigInteger(n,16),s=new BigInteger(i,16);return new ECPointFp(e,e.fromBigInteger(o),e.fromBigInteger(s))},ECPointFp.prototype.add2D=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;if(this.x.equals(e.x))return this.y.equals(e.y)?this.twice():this.curve.getInfinity();var t=e.x.subtract(this.x),r=e.y.subtract(this.y).divide(t),n=r.square().subtract(this.x).subtract(e.x),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new ECPointFp(this.curve,n,i)},ECPointFp.prototype.twice2D=function(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var e=this.curve.fromBigInteger(BigInteger.valueOf(2)),t=this.curve.fromBigInteger(BigInteger.valueOf(3)),r=this.x.square().multiply(t).add(this.curve.a).divide(this.y.multiply(e)),n=r.square().subtract(this.x.multiply(e)),i=r.multiply(this.x.subtract(n)).subtract(this.y);return new ECPointFp(this.curve,n,i)},ECPointFp.prototype.multiply2D=function(e){if(this.isInfinity())return this;if(0==e.signum())return this.curve.getInfinity();var t,r=e,n=r.multiply(new BigInteger("3")),i=this.negate(),o=this;for(t=n.bitLength()-2;t>0;--t){o=o.twice();var s=n.testBit(t);s!=r.testBit(t)&&(o=o.add2D(s?this:i))}return o},ECPointFp.prototype.isOnCurve=function(){var e=this.getX().toBigInteger(),t=this.getY().toBigInteger(),r=this.curve.getA().toBigInteger(),n=this.curve.getB().toBigInteger(),i=this.curve.getQ(),o=t.multiply(t).mod(i),s=e.multiply(e).multiply(e).add(r.multiply(e)).add(n).mod(i);return o.equals(s)},ECPointFp.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"},ECPointFp.prototype.validate=function(){var e=this.curve.getQ();if(this.isInfinity())throw new Error("Point is at infinity.");var t=this.getX().toBigInteger(),r=this.getY().toBigInteger();if(t.compareTo(BigInteger.ONE)<0||t.compareTo(e.subtract(BigInteger.ONE))>0)throw new Error("x coordinate out of bounds");if(r.compareTo(BigInteger.ONE)<0||r.compareTo(e.subtract(BigInteger.ONE))>0)throw new Error("y coordinate out of bounds");if(!this.isOnCurve())throw new Error("Point is not on the curve.");if(this.multiply(e).isInfinity())throw new Error("Point is not a scalar multiple of G.");return!0}; -/*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval - */ -var jsonParse=function(){var e=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]|(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)|(?:"(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))*"))',"g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),r={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function n(e,t,n){return t?r[t]:String.fromCharCode(parseInt(n,16))}var i=new String(""),o=Object.hasOwnProperty;return function(r,s){var a,c,l=r.match(e),u=l[0],d=!1;"{"===u?a={}:"["===u?a=[]:(a=[],d=!0);for(var h=[a],p=1-d,g=l.length;p=0;)delete r[n[c]]}return s.call(e,t,r)};a=f({"":a},"")}return a}}();void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.asn1&&KJUR.asn1||(KJUR.asn1={}),KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(e){var t=e.toString(16);return t.length%2==1&&(t="0"+t),t},this.bigIntToMinTwosComplementsHex=function(e){return twoscompl(e)},this.getPEMStringFromHex=function(e,t){return hextopem(e,t)},this.newObject=function(e){var t=KJUR.asn1,r=t.ASN1Object,n=t.DERBoolean,i=t.DERInteger,o=t.DERBitString,s=t.DEROctetString,a=t.DERNull,c=t.DERObjectIdentifier,l=t.DEREnumerated,u=t.DERUTF8String,d=t.DERNumericString,h=t.DERPrintableString,p=t.DERTeletexString,g=t.DERIA5String,m=t.DERUTCTime,f=t.DERGeneralizedTime,y=t.DERVisibleString,$=t.DERBMPString,b=t.DERSequence,v=t.DERSet,w=t.DERTaggedObject,S=t.ASN1Util.newObject;if(e instanceof t.ASN1Object)return e;var _=Object.keys(e);if(1!=_.length)throw new Error("key of param shall be only one.");var E=_[0];if(-1==":asn1:bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:visstr:bmpstr:seq:set:tag:".indexOf(":"+E+":"))throw new Error("undefined key: "+E);if("bool"==E)return new n(e[E]);if("int"==E)return new i(e[E]);if("bitstr"==E)return new o(e[E]);if("octstr"==E)return new s(e[E]);if("null"==E)return new a(e[E]);if("oid"==E)return new c(e[E]);if("enum"==E)return new l(e[E]);if("utf8str"==E)return new u(e[E]);if("numstr"==E)return new d(e[E]);if("prnstr"==E)return new h(e[E]);if("telstr"==E)return new p(e[E]);if("ia5str"==E)return new g(e[E]);if("utctime"==E)return new m(e[E]);if("gentime"==E)return new f(e[E]);if("visstr"==E)return new y(e[E]);if("bmpstr"==E)return new $(e[E]);if("asn1"==E)return new r(e[E]);if("seq"==E){for(var C=e[E],I=[],T=0;T15)throw new Error("ASN.1 length too long to represent by 8x: n = "+e.toString(16));return(128+r).toString(16)+t},this.tohex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getEncodedHex=function(){return this.tohex()},this.getValueHex=function(){return this.tohex(),this.hV},this.getFreshValueHex=function(){return""},this.setByParam=function(e){this.params=e},null!=e&&null!=e.tlv&&(this.hTLV=e.tlv,this.isModified=!1)},KJUR.asn1.DERAbstractString=function(e){KJUR.asn1.DERAbstractString.superclass.constructor.call(this),this.getString=function(){return this.s},this.setString=function(e){this.hTLV=null,this.isModified=!0,this.s=e,this.hV=utf8tohex(this.s).toLowerCase()},this.setStringHex=function(e){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=e},this.getFreshValueHex=function(){return this.hV},void 0!==e&&("string"==typeof e?this.setString(e):void 0!==e.str?this.setString(e.str):void 0!==e.hex&&this.setStringHex(e.hex))},extendClass(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractTime=function(e){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this),this.localDateToUTC=function(e){var t=e.getTime()+6e4*e.getTimezoneOffset();return new Date(t)},this.formatDate=function(e,t,r){var n=this.zeroPadding,i=this.localDateToUTC(e),o=String(i.getFullYear());"utc"==t&&(o=o.substr(2,2));var s=o+n(String(i.getMonth()+1),2)+n(String(i.getDate()),2)+n(String(i.getHours()),2)+n(String(i.getMinutes()),2)+n(String(i.getSeconds()),2);if(!0===r){var a=i.getMilliseconds();if(0!=a){var c=n(String(a),3);s=s+"."+(c=c.replace(/[0]+$/,""))}}return s+"Z"},this.zeroPadding=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},this.setByParam=function(e){this.hV=null,this.hTLV=null,this.params=e},this.getString=function(){},this.setString=function(e){this.hTLV=null,this.isModified=!0,null==this.params&&(this.params={}),this.params.str=e},this.setByDate=function(e){this.hTLV=null,this.isModified=!0,null==this.params&&(this.params={}),this.params.date=e},this.setByDateValue=function(e,t,r,n,i,o){var s=new Date(Date.UTC(e,t-1,r,n,i,o,0));this.setByDate(s)},this.getFreshValueHex=function(){return this.hV}},extendClass(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object),KJUR.asn1.DERAbstractStructured=function(e){KJUR.asn1.DERAbstractString.superclass.constructor.call(this),this.setByASN1ObjectArray=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array=e},this.appendASN1Object=function(e){this.hTLV=null,this.isModified=!0,this.asn1Array.push(e)},this.asn1Array=new Array,void 0!==e&&void 0!==e.array&&(this.asn1Array=e.array)},extendClass(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object),KJUR.asn1.DERBoolean=function(e){KJUR.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV=0==e?"010100":"0101ff"},extendClass(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object),KJUR.asn1.DERInteger=function(e){KJUR.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.params=null;var t=twoscompl;this.setByBigInteger=function(e){this.isModified=!0,this.params={bigint:e}},this.setByInteger=function(e){this.isModified=!0,this.params=e},this.setValueHex=function(e){this.isModified=!0,this.params={hex:e}},this.getFreshValueHex=function(){var e=this.params,r=null;if(null==e)throw new Error("value not set");if("object"==typeof e&&null!=e.hex)return this.hV=e.hex,this.hV;if("number"==typeof e)r=new BigInteger(String(e),10);else if(null!=e.int)r=new BigInteger(String(e.int),10);else{if(null==e.bigint)throw new Error("wrong parameter");r=e.bigint}return this.hV=t(r),this.hV},null!=e&&(this.params=e)},extendClass(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object),KJUR.asn1.DERBitString=function(e){if(void 0!==e&&void 0!==e.obj){var t=KJUR.asn1.ASN1Util.newObject(e.obj);e.hex="00"+t.tohex()}KJUR.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(e){this.hTLV=null,this.isModified=!0,this.hV=e},this.setUnusedBitsAndHexValue=function(e,t){if(e<0||7>6).toString(16)+n.toString(16))}n=128|(15&t)<<2|(192&r)>>6;var i=128|63&r;return hextoutf8((224|(240&t)>>4).toString(16)+n.toString(16)+i.toString(16))});return t.join("")}function encodeURIComponentAll(e){for(var t=encodeURIComponent(e),r="",n=0;n"7"?"00"+e:e}function oidtohex(e){var t=function(e){var t=e.toString(16);return 1==t.length&&(t="0"+t),t},r=function(e){var r="",n=parseInt(e,10).toString(2),i=7-n.length%7;7==i&&(i=0);for(var o="",s=0;s0&&(l=l+"."+a.join(".")),l}catch(e){return null}}function inttohex(e){return twoscompl(new BigInteger(String(e),10))}function twoscompl(e){var t=e.toString(16);if("-"!=t.substr(0,1))return t.length%2==1?t="0"+t:t.match(/^[0-7]/)||(t="00"+t),t;var r=t.substr(1).length;r%2==1?r+=1:t.match(/^[0-7]/)||(r+=2);for(var n="",i=0;i=n)break}return s},ASN1HEX.getNthChildIdx=function(e,t,r){return ASN1HEX.getChildIdx(e,t)[r]},ASN1HEX.getIdxbyList=function(e,t,r,n){var i,o,s=ASN1HEX;return 0==r.length?void 0!==n&&e.substr(t,2)!==n?-1:t:(i=r.shift())>=(o=s.getChildIdx(e,t)).length?-1:s.getIdxbyList(e,o[i],r,n)},ASN1HEX.getIdxbyListEx=function(e,t,r,n){var i,o,s=ASN1HEX;if(0==r.length)return void 0!==n&&e.substr(t,2)!==n?-1:t;i=r.shift(),o=s.getChildIdx(e,t);for(var a=0,c=0;c=e.length?null:i.getTLV(e,o)},ASN1HEX.getTLVbyListEx=function(e,t,r,n){var i=ASN1HEX,o=i.getIdxbyListEx(e,t,r,n);return-1==o?null:i.getTLV(e,o)},ASN1HEX.getVbyList=function(e,t,r,n,i){var o,s,a=ASN1HEX;return-1==(o=a.getIdxbyList(e,t,r,n))||o>=e.length?null:(s=a.getV(e,o),!0===i&&(s=s.substr(2)),s)},ASN1HEX.getVbyListEx=function(e,t,r,n,i){var o,s,a=ASN1HEX;return-1==(o=a.getIdxbyListEx(e,t,r,n))?null:(s=a.getV(e,o),"03"==e.substr(o,2)&&!1!==i&&(s=s.substr(2)),s)},ASN1HEX.getInt=function(e,t,r){null==r&&(r=-1);try{var n=e.substr(t,2);if("02"!=n&&"03"!=n)return r;var i=ASN1HEX.getV(e,t);return"02"==n?parseInt(i,16):bitstrtoint(i)}catch(e){return r}},ASN1HEX.getOID=function(e,t,r){null==r&&(r=null);try{return"06"!=e.substr(t,2)?r:hextooid(ASN1HEX.getV(e,t))}catch(e){return r}},ASN1HEX.getOIDName=function(e,t,r){null==r&&(r=null);try{var n=ASN1HEX.getOID(e,t,r);if(n==r)return r;var i=KJUR.asn1.x509.OID.oid2name(n);return""==i?n:i}catch(e){return r}},ASN1HEX.getString=function(e,t,r){null==r&&(r=null);try{return hextorstr(ASN1HEX.getV(e,t))}catch(e){return r}},ASN1HEX.hextooidstr=function(e){var t=function(e,t){return e.length>=t?e:new Array(t-e.length+1).join("0")+e},r=[],n=e.substr(0,2),i=parseInt(n,16);r[0]=new String(Math.floor(i/40)),r[1]=new String(i%40);for(var o=e.substr(2),s=[],a=0;a0&&(u=u+"."+c.join(".")),u},ASN1HEX.dump=function(e,t,r,n){var i=ASN1HEX,o=i.getV,s=i.dump,a=i.getChildIdx,c=e;e instanceof KJUR.asn1.ASN1Object&&(c=e.tohex());var l=function(e,t){return e.length<=2*t?e:e.substr(0,t)+"..(total "+e.length/2+"bytes).."+e.substr(e.length-t,t)};void 0===t&&(t={ommit_long_octet:32}),void 0===r&&(r=0),void 0===n&&(n="");var u,d=t.ommit_long_octet;if("01"==(u=c.substr(r,2)))return"00"==(h=o(c,r))?n+"BOOLEAN FALSE\n":n+"BOOLEAN TRUE\n";if("02"==u)return n+"INTEGER "+l(h=o(c,r),d)+"\n";if("03"==u){var h=o(c,r);if(i.isASN1HEX(h.substr(2))){var p=n+"BITSTRING, encapsulates\n";return p+=s(h.substr(2),t,0,n+" ")}return n+"BITSTRING "+l(h,d)+"\n"}if("04"==u){h=o(c,r);if(i.isASN1HEX(h)){p=n+"OCTETSTRING, encapsulates\n";return p+=s(h,t,0,n+" ")}return n+"OCTETSTRING "+l(h,d)+"\n"}if("05"==u)return n+"NULL\n";if("06"==u){var g=o(c,r),m=KJUR.asn1.ASN1Util.oidHexToInt(g),f=KJUR.asn1.x509.OID.oid2name(m),y=m.replace(/\./g," ");return""!=f?n+"ObjectIdentifier "+f+" ("+y+")\n":n+"ObjectIdentifier ("+y+")\n"}if("0a"==u)return n+"ENUMERATED "+parseInt(o(c,r))+"\n";if("0c"==u)return n+"UTF8String '"+hextoutf8(o(c,r))+"'\n";if("13"==u)return n+"PrintableString '"+hextoutf8(o(c,r))+"'\n";if("14"==u)return n+"TeletexString '"+hextoutf8(o(c,r))+"'\n";if("16"==u)return n+"IA5String '"+hextoutf8(o(c,r))+"'\n";if("17"==u)return n+"UTCTime "+hextoutf8(o(c,r))+"\n";if("18"==u)return n+"GeneralizedTime "+hextoutf8(o(c,r))+"\n";if("1a"==u)return n+"VisualString '"+hextoutf8(o(c,r))+"'\n";if("1e"==u)return n+"BMPString '"+ucs2hextoutf8(o(c,r))+"'\n";if("30"==u){if("3000"==c.substr(r,4))return n+"SEQUENCE {}\n";p=n+"SEQUENCE\n";var $=t;if((2==(w=a(c,r)).length||3==w.length)&&"06"==c.substr(w[0],2)&&"04"==c.substr(w[w.length-1],2)){f=i.oidname(o(c,w[0]));var b=JSON.parse(JSON.stringify(t));b.x509ExtName=f,$=b}for(var v=0;v4?{enum:{hex:f}}:{enum:parseInt(f,16)};if("30"==g||"31"==g)return m[p[g]]=function(e){for(var t=[],n=s(e,0),i=0;i31)&&(128==(192&r)&&(31&r)==n))}catch(e){return!1}},ASN1HEX.isASN1HEX=function(e){var t=ASN1HEX;if(e.length%2==1)return!1;var r=t.getVblen(e,0),n=e.substr(0,2),i=t.getL(e,0);return e.length-n.length-i.length==2*r},ASN1HEX.checkStrictDER=function(e,t,r,n,i){var o=ASN1HEX;if(void 0===r){if("string"!=typeof e)throw new Error("not hex string");if(e=e.toLowerCase(),!KJUR.lang.String.isHex(e))throw new Error("not hex string");r=e.length,i=(n=e.length/2)<128?1:Math.ceil(n.toString(16))+1}if(o.getL(e,t).length>2*i)throw new Error("L of TLV too long: idx="+t);var s=o.getVblen(e,t);if(s>n)throw new Error("value of L too long than hex: idx="+t);var a=o.getTLV(e,t),c=a.length-2-o.getL(e,t).length;if(c!==2*s)throw new Error("V string length and L's value not the same:"+c+"/"+2*s);if(0===t&&e.length!=a.length)throw new Error("total length and TLV length unmatch:"+e.length+"!="+a.length);var l=e.substr(t,2);if("02"===l){var u=o.getVidx(e,t);if("00"==e.substr(u,2)&&e.charCodeAt(u+2)<56)throw new Error("not least zeros for DER INTEGER")}if(32&parseInt(l,16)){for(var d=o.getVblen(e,t),h=0,p=o.getChildIdx(e,t),g=0;g0&&e.push(new n({tag:"a3",obj:new l(t.ext)})),new KJUR.asn1.DERSequence({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.TBSCertificate,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Extensions=function(e){KJUR.asn1.x509.Extensions.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERSequence,n=t.x509;this.aParam=[],this.setByParam=function(e){this.aParam=e},this.tohex=function(){for(var e=[],t=0;t-1&&e.push(new n({int:this.pathLen}));var t=new i({array:e});return this.asn1ExtnValue=t,this.asn1ExtnValue.tohex()},this.oid="2.5.29.19",this.cA=!1,this.pathLen=-1,void 0!==e&&(void 0!==e.cA&&(this.cA=e.cA),void 0!==e.pathLen&&(this.pathLen=e.pathLen))},extendClass(KJUR.asn1.x509.BasicConstraints,KJUR.asn1.x509.Extension),KJUR.asn1.x509.CRLDistributionPoints=function(e){KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.x509;this.getExtnValueHex=function(){return this.asn1ExtnValue.tohex()},this.setByDPArray=function(e){for(var n=[],i=0;i0&&e.push(new r({array:t}))}return new r({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyInformation,KJUR.asn1.ASN1Object),KJUR.asn1.x509.PolicyQualifierInfo=function(e){KJUR.asn1.x509.PolicyQualifierInfo.superclass.constructor.call(this,e);var t=KJUR.asn1,r=t.DERSequence,n=t.DERIA5String,i=t.DERObjectIdentifier,o=t.x509.UserNotice;this.params=null,this.tohex=function(){return void 0!==this.params.cps?new r({array:[new i({oid:"1.3.6.1.5.5.7.2.1"}),new n({str:this.params.cps})]}).tohex():null!=this.params.unotice?new r({array:[new i({oid:"1.3.6.1.5.5.7.2.2"}),new o(this.params.unotice)]}).tohex():void 0},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.PolicyQualifierInfo,KJUR.asn1.ASN1Object),KJUR.asn1.x509.UserNotice=function(e){KJUR.asn1.x509.UserNotice.superclass.constructor.call(this,e);var t=KJUR.asn1.DERSequence;KJUR.asn1.DERInteger;var r=KJUR.asn1.x509.DisplayText,n=KJUR.asn1.x509.NoticeReference;this.params=null,this.tohex=function(){var e=[];return void 0!==this.params.noticeref&&e.push(new n(this.params.noticeref)),void 0!==this.params.exptext&&e.push(new r(this.params.exptext)),new t({array:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.x509.UserNotice,KJUR.asn1.ASN1Object),KJUR.asn1.x509.NoticeReference=function(e){KJUR.asn1.x509.NoticeReference.superclass.constructor.call(this,e);var t=KJUR.asn1.DERSequence,r=KJUR.asn1.DERInteger,n=KJUR.asn1.x509.DisplayText;this.params=null,this.tohex=function(){var e=[];if(void 0!==this.params.org&&e.push(new n(this.params.org)),void 0!==this.params.noticenum){for(var i=[],o=this.params.noticenum,s=0;s0)for(var e=0;e0;i++){var o=t.shift();if(!0===r){var s=(n.pop()+","+o).replace(/\\,/g,",");n.push(s),r=!1}else n.push(o);"\\"===o.substr(-1,1)&&(r=!0)}return n=n.map(function(e){return e.replace("/","\\/")}),n.reverse(),"/"+n.join("/")},KJUR.asn1.x509.X500Name.ldapToOneline=function(e){return KJUR.asn1.x509.X500Name.ldapToCompat(e)},KJUR.asn1.x509.RDN=function(e){KJUR.asn1.x509.RDN.superclass.constructor.call(this),this.asn1Array=[],this.paramArray=[],this.sRule="utf8";var t=KJUR.asn1.x509.AttributeTypeAndValue;this.setByParam=function(e){void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.str&&this.addByMultiValuedString(e.str),void 0!==e.array&&(this.paramArray=e.array)},this.addByString=function(e){this.asn1Array.push(new KJUR.asn1.x509.AttributeTypeAndValue({str:e,rule:this.sRule}))},this.addByMultiValuedString=function(e){for(var t=KJUR.asn1.x509.RDN.parseString(e),r=0;r0)for(var e=0;e0;i++){var o=t.shift();if(!0===r){var s=(n.pop()+"+"+o).replace(/\\\+/g,"+");n.push(s),r=!1}else n.push(o);"\\"===o.substr(-1,1)&&(r=!0)}var a=!1,c=[];for(i=0;n.length>0;i++){o=n.shift();if(!0===a){var l=c.pop();if(o.match(/"$/)){s=(l+"+"+o).replace(/^([^=]+)="(.*)"$/,"$1=$2");c.push(s),a=!1}else c.push(l+"+"+o)}else c.push(o);o.match(/^[^=]+="/)&&(a=!0)}return c},KJUR.asn1.x509.AttributeTypeAndValue=function(e){KJUR.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this),this.sRule="utf8",this.sType=null,this.sValue=null,this.dsType=null;var t=KJUR,r=t.asn1,n=r.DERSequence,i=r.DERUTF8String,o=r.DERPrintableString,s=r.DERTeletexString,a=r.DERIA5String,c=r.DERVisibleString,l=r.DERBMPString,u=t.lang.String.isMail,d=t.lang.String.isPrintable;this.setByParam=function(e){if(void 0!==e.rule&&(this.sRule=e.rule),void 0!==e.ds&&(this.dsType=e.ds),void 0===e.value&&void 0!==e.str){var t=e.str.match(/^([^=]+)=(.+)$/);if(!t)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.sType=t[1],this.sValue=t[2]}else this.sType=e.type,this.sValue=e.value},this.setByString=function(e,t){void 0!==t&&(this.sRule=t);var r=e.match(/^([^=]+)=(.+)$/);if(!r)throw new Error("malformed attrTypeAndValueStr: "+attrTypeAndValueStr);this.setByAttrTypeAndValueStr(r[1],r[2])},this._getDsType=function(){var e=this.sType,t=this.sValue,r=this.sRule;return"prn"===r?"CN"==e&&u(t)?"ia5":d(t)?"prn":"utf8":"utf8"===r?"CN"==e&&u(t)?"ia5":"C"==e?"prn":"utf8":"utf8"},this.setByAttrTypeAndValueStr=function(e,t,r){void 0!==r&&(this.sRule=r),this.sType=e,this.sValue=t},this.getValueObj=function(e,t){if("utf8"==e)return new i({str:t});if("prn"==e)return new o({str:t});if("tel"==e)return new s({str:t});if("ia5"==e)return new a({str:t});if("vis"==e)return new c({str:t});if("bmp"==e)return new l({str:t});throw new Error("unsupported directory string type: type="+e+" value="+t)},this.tohex=function(){null==this.dsType&&(this.dsType=this._getDsType());var e=KJUR.asn1.x509.OID.atype2obj(this.sType),t=this.getValueObj(this.dsType,this.sValue),r=new n({array:[e,t]});return this.TLV=r.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.AttributeTypeAndValue,KJUR.asn1.ASN1Object),KJUR.asn1.x509.SubjectPublicKeyInfo=function(e){KJUR.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);var t=KJUR,r=t.asn1,n=r.DERInteger,i=r.DERBitString,o=r.DERObjectIdentifier,s=r.DERSequence,a=r.ASN1Util.newObject,c=r.x509.AlgorithmIdentifier,l=t.crypto;l.ECDSA,l.DSA,this.getASN1Object=function(){if(null==this.asn1AlgId||null==this.asn1SubjPKey)throw"algId and/or subjPubKey not set";return new s({array:[this.asn1AlgId,this.asn1SubjPKey]})},this.tohex=function(){var e=this.getASN1Object();return this.hTLV=e.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},this.setPubKey=function(e){try{if(e instanceof RSAKey){var t=a({seq:[{int:{bigint:e.n}},{int:{int:e.e}}]}).tohex();this.asn1AlgId=new c({name:"rsaEncryption"}),this.asn1SubjPKey=new i({hex:"00"+t})}}catch(e){}try{if(e instanceof KJUR.crypto.ECDSA){var r=new o({name:e.curveName});this.asn1AlgId=new c({name:"ecPublicKey",asn1params:r}),this.asn1SubjPKey=new i({hex:"00"+e.pubKeyHex})}}catch(e){}try{if(e instanceof KJUR.crypto.DSA){r=new a({seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]});this.asn1AlgId=new c({name:"dsa",asn1params:r});var s=new n({bigint:e.y});this.asn1SubjPKey=new i({hex:"00"+s.tohex()})}}catch(e){}},void 0!==e&&this.setPubKey(e)},extendClass(KJUR.asn1.x509.SubjectPublicKeyInfo,KJUR.asn1.ASN1Object),KJUR.asn1.x509.Time=function(e){KJUR.asn1.x509.Time.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERUTCTime,n=t.DERGeneralizedTime;this.params=null,this.type=null,this.setTimeParams=function(e){this.timeParams=e},this.setByParam=function(e){this.params=e},this.getType=function(e){return e.match(/^[0-9]{12}Z$/)?"utc":e.match(/^[0-9]{14}Z$/)?"gen":e.match(/^[0-9]{12}\.[0-9]+Z$/)?"utc":e.match(/^[0-9]{14}\.[0-9]+Z$/)?"gen":null},this.tohex=function(){var e=this.params,t=null;if("string"==typeof e&&(e={str:e}),null==e||!e.str||null!=e.type&&null!=e.type||(e.type=this.getType(e.str)),null!=e&&e.str?("utc"==e.type&&(t=new r(e.str)),"gen"==e.type&&(t=new n(e.str))):t="gen"==this.type?new n:new r,null==t)throw new Error("wrong setting for Time");return this.TLV=t.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},KJUR.asn1.x509.Time_bak=function(e){KJUR.asn1.x509.Time_bak.superclass.constructor.call(this);var t=KJUR.asn1,r=t.DERUTCTime,n=t.DERGeneralizedTime;this.setTimeParams=function(e){this.timeParams=e},this.tohex=function(){var e=null;return e=null!=this.timeParams?"utc"==this.type?new r(this.timeParams):new n(this.timeParams):"utc"==this.type?new r:new n,this.TLV=e.tohex(),this.TLV},this.getEncodedHex=function(){return this.tohex()},this.type="utc",void 0!==e&&(void 0!==e.type?this.type=e.type:void 0!==e.str&&(e.str.match(/^[0-9]{12}Z$/)&&(this.type="utc"),e.str.match(/^[0-9]{14}Z$/)&&(this.type="gen")),this.timeParams=e)},extendClass(KJUR.asn1.x509.Time,KJUR.asn1.ASN1Object),KJUR.asn1.x509.AlgorithmIdentifier=function(e){KJUR.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this),this.nameAlg=null,this.asn1Alg=null,this.asn1Params=null,this.paramEmpty=!1;var t=KJUR.asn1,r=t.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV;if(this.tohex=function(){if(null===this.nameAlg&&null===this.asn1Alg)throw new Error("algorithm not specified");if(null!==this.nameAlg){var e=null;for(var n in r)n===this.nameAlg&&(e=r[n]);if(null!==e)return this.hTLV=e,this.hTLV}null!==this.nameAlg&&null===this.asn1Alg&&(this.asn1Alg=t.x509.OID.name2obj(this.nameAlg));var i=[this.asn1Alg];null!==this.asn1Params&&i.push(this.asn1Params);var o=new t.DERSequence({array:i});return this.hTLV=o.tohex(),this.hTLV},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&(void 0!==e.name&&(this.nameAlg=e.name),void 0!==e.asn1params&&(this.asn1Params=e.asn1params),void 0!==e.paramempty&&(this.paramEmpty=e.paramempty)),null===this.asn1Params&&!1===this.paramEmpty&&null!==this.nameAlg){void 0!==this.nameAlg.name&&(this.nameAlg=this.nameAlg.name);var n=this.nameAlg.toLowerCase();"withdsa"!==n.substr(-7,7)&&"withecdsa"!==n.substr(-9,9)&&(this.asn1Params=new t.DERNull)}},extendClass(KJUR.asn1.x509.AlgorithmIdentifier,KJUR.asn1.ASN1Object),KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV={SHAwithRSAandMGF1:"300d06092a864886f70d01010a3000",SHA256withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040201a11a301806092a864886f70d010108300b0609608648016503040201a203020120",SHA384withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040202a11a301806092a864886f70d010108300b0609608648016503040202a203020130",SHA512withRSAandMGF1:"303d06092a864886f70d01010a3030a00d300b0609608648016503040203a11a301806092a864886f70d010108300b0609608648016503040203a203020140"},KJUR.asn1.x509.GeneralName=function(e){KJUR.asn1.x509.GeneralName.superclass.constructor.call(this);var t=KJUR.asn1,r=t.x509,n=r.X500Name,i=r.OtherName,o=t.DERIA5String;t.DERPrintableString;var s=t.DEROctetString,a=t.DERTaggedObject,c=t.ASN1Object,l=Error;this.params=null,this.setByParam=function(e){this.params=e},this.tohex=function(){var e,t,r=this.params,u=!1;if(void 0!==r.other)e="a0",t=new i(r.other);else if(void 0!==r.rfc822)e="81",t=new o({str:r.rfc822});else if(void 0!==r.dns)e="82",t=new o({str:r.dns});else if(void 0!==r.dn)e="a4",u=!0,t="string"==typeof r.dn?new n({str:r.dn}):r.dn instanceof KJUR.asn1.x509.X500Name?r.dn:new n(r.dn);else if(void 0!==r.ldapdn)e="a4",u=!0,t=new n({ldapstr:r.ldapdn});else if(void 0!==r.certissuer||void 0!==r.certsubj){var d,h;e="a4",u=!0;var p=null;if(void 0!==r.certsubj?(d=!1,h=r.certsubj):(d=!0,h=r.certissuer),h.match(/^[0-9A-Fa-f]+$/),-1!=h.indexOf("-----BEGIN ")&&(p=pemtohex(h)),null==p)throw new Error("certsubj/certissuer not cert");var g,m=new X509;m.hex=p,g=d?m.getIssuerHex():m.getSubjectHex(),(t=new c).hTLV=g}else if(void 0!==r.uri)e="86",t=new o({str:r.uri});else{if(void 0===r.ip)throw new l("improper params");var f;e="87";var y=r.ip;try{if(y.match(/^[0-9a-f]+$/)){var $=y.length;if(8!=$&&16!=$&&32!=$&&64!=$)throw"err";f=y}else f=iptohex(y)}catch(e){throw new l("malformed IP address: "+r.ip+":"+e.message)}t=new s({hex:f})}return new a({tag:e,explicit:u,obj:t}).tohex()},this.getEncodedHex=function(){return this.tohex()},void 0!==e&&this.setByParam(e)},extendClass(KJUR.asn1.x509.GeneralName,KJUR.asn1.ASN1Object),KJUR.asn1.x509.GeneralNames=function(e){KJUR.asn1.x509.GeneralNames.superclass.constructor.call(this);var t=KJUR.asn1;this.setByParamArray=function(e){for(var r=0;r0){for(var r=o(e.valhex,t[0]),n=u(r,0),i=[],s=0;s1){var l=o(e.valhex,t[1]);e.polhex=l}delete e.valhex},this.setSignaturePolicyIdentifier=function(e){var r=u(e.valhex,0);if(r.length>0){var s=n.getOID(e.valhex,r[0]);e.oid=s}if(r.length>1){var a=new t,c=u(e.valhex,r[1]),l=o(e.valhex,c[0]),d=a.getAlgorithmIdentifierName(l);e.alg=d;var h=i(e.valhex,c[1]);e.hash=h}delete e.valhex},this.setSigningCertificateV2=function(e){var t=u(e.valhex,0);if(t.length>0){for(var r=o(e.valhex,t[0]),n=u(r,0),i=[],s=0;s1){var l=o(e.valhex,t[1]);e.polhex=l}delete e.valhex},this.getESSCertID=function(e){var t={},r=u(e,0);if(r.length>0){var n=i(e,r[0]);t.hash=n}if(r.length>1){var s=o(e,r[1]),a=this.getIssuerSerial(s);null!=a.serial&&(t.serial=a.serial),null!=a.issuer&&(t.issuer=a.issuer)}return t},this.getESSCertIDv2=function(t){var n={},s=u(t,0);if(s.length<1||3a+1){var d=o(t,s[a+1]),h=this.getIssuerSerial(d);n.issuer=h.issuer,n.serial=h.serial}return n},this.getIssuerSerial=function(e){var t={},n=u(e,0),s=o(e,n[0]),a=r.getGeneralNames(s)[0].dn;t.issuer=a;var c=i(e,n[1]);return t.serial={hex:c},t},this.getCertificateSet=function(e){for(var t=u(e,0),r=[],n=0;n=0;s--)i+=n[s];return i}if("string"==typeof e&&null!=o[e])return namearraytobinstr([e],o);if("object"==typeof e&&null!=e.length)return namearraytobinstr(e,o);throw new t("wrong params")},this.tohex=function(){this.params;var e=this.getBinValue();return new n({bin:e}).tohex()},this.getEncodedHex=function(){return this.tohex()},null!=e&&this.setByParam(e)},extendClass(KJUR.asn1.tsp.PKIFailureInfo,KJUR.asn1.ASN1Object),KJUR.asn1.tsp.AbstractTSAAdapter=function(e){this.getTSTHex=function(e,t){throw"not implemented yet"}},KJUR.asn1.tsp.SimpleTSAAdapter=function(e){var t=KJUR,r=t.asn1.tsp,n=t.crypto.Util.hashHex;r.SimpleTSAAdapter.superclass.constructor.call(this),this.params=null,this.serial=0,this.getTSTHex=function(e,t){var i=n(e,t);this.params.econtent.content.messageImprint={alg:t,hash:i},this.params.econtent.content.serial={int:this.serial++};var o=Math.floor(1e9*Math.random());return this.params.econtent.content.nonce={int:o},new r.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.tsp.SimpleTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter),KJUR.asn1.tsp.FixedTSAAdapter=function(e){var t=KJUR,r=t.asn1.tsp,n=t.crypto.Util.hashHex;r.FixedTSAAdapter.superclass.constructor.call(this),this.params=null,this.getTSTHex=function(e,t){var i=n(e,t);return this.params.econtent.content.messageImprint={alg:t,hash:i},new r.TimeStampToken(this.params).getContentInfoEncodedHex()},void 0!==e&&(this.params=e)},extendClass(KJUR.asn1.tsp.FixedTSAAdapter,KJUR.asn1.tsp.AbstractTSAAdapter),KJUR.asn1.tsp.TSPUtil=new function(){},KJUR.asn1.tsp.TSPUtil.newTimeStampToken=function(e){return new KJUR.asn1.tsp.TimeStampToken(e)},KJUR.asn1.tsp.TSPUtil.parseTimeStampReq=function(e){return(new KJUR.asn1.tsp.TSPParser).getTimeStampReq(e)},KJUR.asn1.tsp.TSPUtil.parseMessageImprint=function(e){return(new KJUR.asn1.tsp.TSPParser).getMessageImprint(e)},KJUR.asn1.tsp.TSPParser=function(){var e=new X509,t=ASN1HEX,r=t.getV,n=t.getTLV,i=t.getIdxbyList;t.getTLVbyListEx;var o=t.getChildIdx,s=["granted","grantedWithMods","rejection","waiting","revocationWarning","revocationNotification"],a={0:"badAlg",2:"badRequest",5:"badDataFormat",14:"timeNotAvailable",15:"unacceptedPolicy",16:"unacceptedExtension",17:"addInfoNotAvailable",25:"systemFailure"};this.getResponse=function(e){var t=o(e,0);if(1==t.length)return this.getPKIStatusInfo(n(e,t[0]));if(t.length>1){var r=this.getPKIStatusInfo(n(e,t[0])),i=n(e,t[1]),s=this.getToken(i);return s.statusinfo=r,s}},this.getToken=function(e){var t=(new KJUR.asn1.cms.CMSParser).getCMSSignedData(e);return this.setTSTInfo(t),t},this.setTSTInfo=function(e){var t=e.econtent;if("tstinfo"==t.type){var r=t.content.hex,n=this.getTSTInfo(r);t.content=n}},this.getTSTInfo=function(t){var i={},s=o(t,0),a=r(t,s[1]);i.policy=hextooid(a);var c=n(t,s[2]);i.messageImprint=this.getMessageImprint(c);var l=r(t,s[3]);i.serial={hex:l};var u=r(t,s[4]);i.genTime={str:hextoutf8(u)};var d=0;if(s.length>5&&"30"==t.substr(s[5],2)){var h=n(t,s[5]);i.accuracy=this.getAccuracy(h),d++}s.length>5+d&&"01"==t.substr(s[5+d],2)&&("ff"==r(t,s[5+d])&&(i.ordering=!0),d++);if(s.length>5+d&&"02"==t.substr(s[5+d],2)){var p=r(t,s[5+d]);i.nonce={hex:p},d++}if(s.length>5+d&&"a0"==t.substr(s[5+d],2)){var g=n(t,s[5+d]);g="30"+g.substr(2),pGeneralNames=e.getGeneralNames(g);var m=pGeneralNames[0].dn;i.tsa=m,d++}if(s.length>5+d&&"a1"==t.substr(s[5+d],2)){var f=n(t,s[5+d]);f="30"+f.substr(2);var y=e.getExtParamArray(f);i.ext=y,d++}return i},this.getAccuracy=function(e){for(var t={},n=o(e,0),i=0;i1&&"30"==e.substr(i[1],2)){var u=n(e,i[1]);t.statusstr=this.getPKIFreeText(u),a++}if(i.length>a&&"03"==e.substr(i[1+a],2)){var d=n(e,i[1+a]);t.failinfo=this.getPKIFailureInfo(d)}return t},this.getPKIFreeText=function(e){for(var r=[],n=o(e,0),i=0;i=t?e:new Array(t-e.length+1).join(r)+e};function bitstrtoint(e){if(e.length%2!=0)return-1;if(null==(e=e.toLowerCase()).match(/^[0-9a-f]+$/))return-1;try{var t=e.substr(0,2);if("00"==t)return parseInt(e.substr(2),16);var r=parseInt(t,16);if(r>7)return-1;var n=e.substr(2),i=parseInt(n,16).toString(2);"0"==i&&(i="00000000"),i=i.slice(0,0-r);var o=parseInt(i,2);return NaN==o?-1:o}catch(e){return-1}}function bitstrtobinstr(e){if("string"!=typeof e)return null;if(e.length%2!=0)return null;if(!e.match(/^[0-9a-f]+$/))return null;try{var t=parseInt(e.substr(0,2),16);if(t<0||7=0;n--)o+=i[n];return o}function aryval(e,t,r){if("object"==typeof e){t=String(t).split(".");for(var n=0;ni)throw"key is too short for SigAlg: keylen="+r+","+t;for(var o="0001",s="00"+n,a="",c=i-4-s.length,l=0;l=0)return!1;if(n.compareTo(r.ONE)<0||n.compareTo(o)>=0)return!1;var a=n.modInverse(o),c=e.multiply(a).mod(o),l=t.multiply(a).mod(o);return s.multiply(c).add(i.multiply(l)).getX().toBigInteger().mod(o).equals(t)},this.serializeSig=function(e,t){var r=e.toByteArraySigned(),n=t.toByteArraySigned(),i=[];return i.push(2),i.push(r.length),(i=i.concat(r)).push(2),i.push(n.length),(i=i.concat(n)).unshift(i.length),i.unshift(48),i},this.parseSig=function(e){var t;if(48!=e[0])throw new Error("Signature not a valid DERSequence");if(2!=e[t=2])throw new Error("First element in signature must be a DERInteger");var n=e.slice(t+2,t+2+e[t+1]);if(2!=e[t+=2+e[t+1]])throw new Error("Second element in signature must be a DERInteger");var i=e.slice(t+2,t+2+e[t+1]);return t+=2+e[t+1],{r:r.fromByteArrayUnsigned(n),s:r.fromByteArrayUnsigned(i)}},this.parseSigCompact=function(e){if(65!==e.length)throw"Signature has the wrong length";var t=e[0]-27;if(t<0||t>7)throw"Invalid signature type";var n=this.ecparams.n;return{r:r.fromByteArrayUnsigned(e.slice(1,33)).mod(n),s:r.fromByteArrayUnsigned(e.slice(33,65)).mod(n),i:t}},this.readPKCS5PrvKeyHex=function(e){if(!1===l(e))throw new Error("not ASN.1 hex string");var t,r,n;try{t=c(e,0,["[0]",0],"06"),r=c(e,0,[1],"04");try{n=c(e,0,["[1]",0],"03")}catch(e){}}catch(e){throw new Error("malformed PKCS#1/5 plain ECC private key")}if(this.curveName=s(t),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(n),this.setPrivateKeyHex(r),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n,i;try{c(e,0,[1,0],"06"),r=c(e,0,[1,1],"06"),n=c(e,0,[2,0,1],"04");try{i=c(e,0,[2,0,"[1]",0],"03")}catch(e){}}catch(e){throw new t("malformed PKCS#8 plain ECC private key")}if(this.curveName=s(r),void 0===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i),this.setPrivateKeyHex(n),this.isPublic=!1},this.readPKCS8PubKeyHex=function(e){if(!1===l(e))throw new t("not ASN.1 hex string");var r,n;try{c(e,0,[0,0],"06"),r=c(e,0,[0,1],"06"),n=c(e,0,[1],"03")}catch(e){throw new t("malformed PKCS#8 ECC public key")}if(this.curveName=s(r),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(n)},this.readCertPubKeyHex=function(e,r){if(!1===l(e))throw new t("not ASN.1 hex string");var n,i;try{n=c(e,0,[0,5,0,1],"06"),i=c(e,0,[0,5,1],"03")}catch(e){throw new t("malformed X.509 certificate ECC public key")}if(this.curveName=s(n),null===this.curveName)throw new t("unsupported curve name");this.setNamedCurve(this.curveName),this.setPublicKeyHex(i)},void 0!==e&&void 0!==e.curve&&(this.curveName=e.curve),void 0===this.curveName&&(this.curveName="secp256r1"),this.setNamedCurve(this.curveName),void 0!==e&&(void 0!==e.prv&&this.setPrivateKeyHex(e.prv),void 0!==e.pub&&this.setPublicKeyHex(e.pub))},KJUR.crypto.ECDSA.parseSigHex=function(e){var t=KJUR.crypto.ECDSA.parseSigHexInHexRS(e);return{r:new BigInteger(t.r,16),s:new BigInteger(t.s,16)}},KJUR.crypto.ECDSA.parseSigHexInHexRS=function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV;if(t.checkStrictDER(e,0),"30"!=e.substr(0,2))throw new Error("signature is not a ASN.1 sequence");var i=r(e,0);if(2!=i.length)throw new Error("signature shall have two elements");var o=i[0],s=i[1];if("02"!=e.substr(o,2))throw new Error("1st item not ASN.1 integer");if("02"!=e.substr(s,2))throw new Error("2nd item not ASN.1 integer");return{r:n(e,o),s:n(e,s)}},KJUR.crypto.ECDSA.asn1SigToConcatSig=function(e){var t=KJUR.crypto.ECDSA.parseSigHexInHexRS(e),r=t.r,n=t.s;if(r.length>=130&&r.length<=134){if(r.length%2!=0)throw Error("unknown ECDSA sig r length error");if(n.length%2!=0)throw Error("unknown ECDSA sig s length error");"00"==r.substr(0,2)&&(r=r.substr(2)),"00"==n.substr(0,2)&&(n=n.substr(2));var i=Math.max(r.length,n.length);return(r=("000000"+r).slice(-i))+(n=("000000"+n).slice(-i))}if("00"==r.substr(0,2)&&r.length%32==2&&(r=r.substr(2)),"00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),r.length%32==30&&(r="00"+r),n.length%32==30&&(n="00"+n),r.length%32!=0)throw Error("unknown ECDSA sig r length error");if(n.length%32!=0)throw Error("unknown ECDSA sig s length error");return r+n},KJUR.crypto.ECDSA.concatSigToASN1Sig=function(e){if(e.length%4!=0)throw Error("unknown ECDSA concatinated r-s sig length error");var t=e.substr(0,e.length/2),r=e.substr(e.length/2);return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(t,r)},KJUR.crypto.ECDSA.hexRSSigToASN1Sig=function(e,t){var r=new BigInteger(e,16),n=new BigInteger(t,16);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(r,n)},KJUR.crypto.ECDSA.biRSSigToASN1Sig=function(e,t){var r=KJUR.asn1,n=new r.DERInteger({bigint:e}),i=new r.DERInteger({bigint:t});return new r.DERSequence({array:[n,i]}).tohex()},KJUR.crypto.ECDSA.getName=function(e){return"2b8104001f"===e?"secp192k1":"2a8648ce3d030107"===e?"secp256r1":"2b8104000a"===e?"secp256k1":"2b81040021"===e?"secp224r1":"2b81040022"===e?"secp384r1":"2b81040023"===e?"secp521r1":-1!=="|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(e)?"secp256r1":-1!=="|secp256k1|".indexOf(e)?"secp256k1":-1!=="|secp224r1|NIST P-224|P-224|".indexOf(e)?"secp224r1":-1!=="|secp384r1|NIST P-384|P-384|".indexOf(e)?"secp384r1":-1!=="|secp521r1|NIST P-521|P-521|".indexOf(e)?"secp521r1":null},void 0!==KJUR&&KJUR||(KJUR={}),void 0!==KJUR.crypto&&KJUR.crypto||(KJUR.crypto={}),KJUR.crypto.ECParameterDB=new function(){var e={},t={};function r(e){return new BigInteger(e,16)}this.getByName=function(r){var n=r;if(void 0!==t[n]&&(n=t[r]),void 0!==e[n])return e[n];throw"unregistered EC curve name: "+n},this.regist=function(n,i,o,s,a,c,l,u,d,h,p,g){e[n]={};var m=r(o),f=r(s),y=r(a),$=r(c),b=r(l),v=new ECCurveFp(m,f,y),w=v.decodePointHex("04"+u+d);e[n].name=n,e[n].keylen=i,e[n].keycharlen=2*Math.ceil(i/8),e[n].curve=v,e[n].G=w,e[n].n=$,e[n].h=b,e[n].oid=p,e[n].info=g;for(var S=0;S1?new BigInteger(n,16):null,l=new BigInteger(i,16),this.setPrivate(o,s,a,c,l)},this.setPublic=function(e,t,r,n){this.isPublic=!0,this.p=e,this.q=t,this.g=r,this.y=n,this.x=null},this.setPublicHex=function(e,t,r,n){var i,o,s,a;i=new BigInteger(e,16),o=new BigInteger(t,16),s=new BigInteger(r,16),a=new BigInteger(n,16),this.setPublic(i,o,s,a)},this.signWithMessageHash=function(e){var t=this.p,r=this.q,n=this.g;this.y;var i=this.x,o=KJUR.crypto.Util.getRandomBigIntegerMinToMax(BigInteger.ONE.add(BigInteger.ONE),r.subtract(BigInteger.ONE)),s=new BigInteger(e.substr(0,r.bitLength()/4),16),a=n.modPow(o,t).mod(r),c=o.modInverse(r).multiply(s.add(i.multiply(a))).mod(r);return KJUR.asn1.ASN1Util.jsonToASN1HEX({seq:[{int:{bigint:a}},{int:{bigint:c}}]})},this.verifyWithMessageHash=function(e,t){var r=this.p,n=this.q,i=this.g,o=this.y,s=this.parseASN1Signature(t),a=s[0],c=s[1],l=new BigInteger(e.substr(0,n.bitLength()/4),16);if(BigInteger.ZERO.compareTo(a)>0||a.compareTo(n)>0)throw"invalid DSA signature";if(BigInteger.ZERO.compareTo(c)>=0||c.compareTo(n)>0)throw"invalid DSA signature";var u=c.modInverse(n),d=l.multiply(u).mod(n),h=a.multiply(u).mod(n);return 0==i.modPow(d,r).multiply(o.modPow(h,r)).mod(r).mod(n).compareTo(a)},this.parseASN1Signature=function(e){try{return[new n(t(e,0,[0],"02"),16),new n(t(e,0,[1],"02"),16)]}catch(e){throw new Error("malformed ASN.1 DSA signature")}},this.readPKCS5PrvKeyHex=function(e){var n,i,o,s,a;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1],"02"),i=t(e,0,[2],"02"),o=t(e,0,[3],"02"),s=t(e,0,[4],"02"),a=t(e,0,[5],"02")}catch(e){throw new Error("malformed PKCS#1/5 plain DSA private key")}this.setPrivateHex(n,i,o,s,a)},this.readPKCS8PrvKeyHex=function(e){var n,i,o,s;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[1,1,0],"02"),i=t(e,0,[1,1,1],"02"),o=t(e,0,[1,1,2],"02"),s=t(e,0,[2,0],"02")}catch(e){throw new Error("malformed PKCS#8 plain DSA private key")}this.setPrivateHex(n,i,o,null,s)},this.readPKCS8PubKeyHex=function(e){var n,i,o,s;if(!1===r(e))throw new Error("not ASN.1 hex string");try{n=t(e,0,[0,1,0],"02"),i=t(e,0,[0,1,1],"02"),o=t(e,0,[0,1,2],"02"),s=t(e,0,[1,0],"02")}catch(e){throw new Error("malformed PKCS#8 DSA public key")}this.setPublicHex(n,i,o,s)},this.readCertPubKeyHex=function(e,n){var i,o,s,a;if(!1===r(e))throw new Error("not ASN.1 hex string");try{i=t(e,0,[0,5,0,1,0],"02"),o=t(e,0,[0,5,0,1,1],"02"),s=t(e,0,[0,5,0,1,2],"02"),a=t(e,0,[0,5,1,0],"02")}catch(e){throw new Error("malformed X.509 certificate DSA public key")}this.setPublicHex(i,o,s,a)}};var KEYUTIL=function(){var e=function(e,r,n){return t(CryptoJS.AES,e,r,n)},t=function(e,t,r,n){var i=CryptoJS.enc.Hex.parse(t),o=CryptoJS.enc.Hex.parse(r),s=CryptoJS.enc.Hex.parse(n),a={};a.key=o,a.iv=s,a.ciphertext=i;var c=e.decrypt(a,o,{iv:s});return CryptoJS.enc.Hex.stringify(c)},r=function(e,t,r){return n(CryptoJS.AES,e,t,r)},n=function(e,t,r,n){var i=CryptoJS.enc.Hex.parse(t),o=CryptoJS.enc.Hex.parse(r),s=CryptoJS.enc.Hex.parse(n),a=e.encrypt(i,o,{iv:s}),c=CryptoJS.enc.Hex.parse(a.toString());return CryptoJS.enc.Base64.stringify(c)},i={"AES-256-CBC":{proc:e,eproc:r,keylen:32,ivlen:16},"AES-192-CBC":{proc:e,eproc:r,keylen:24,ivlen:16},"AES-128-CBC":{proc:e,eproc:r,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:function(e,r,n){return t(CryptoJS.TripleDES,e,r,n)},eproc:function(e,t,r){return n(CryptoJS.TripleDES,e,t,r)},keylen:24,ivlen:8},"DES-CBC":{proc:function(e,r,n){return t(CryptoJS.DES,e,r,n)},eproc:function(e,t,r){return n(CryptoJS.DES,e,t,r)},keylen:8,ivlen:8}},o=function(e){var t={},r=e.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));r&&(t.cipher=r[1],t.ivsalt=r[2]);var n=e.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));n&&(t.type=n[1]);var i=-1,o=0;-1!=e.indexOf("\r\n\r\n")&&(i=e.indexOf("\r\n\r\n"),o=2),-1!=e.indexOf("\n\n")&&(i=e.indexOf("\n\n"),o=1);var s=e.indexOf("-----END");if(-1!=i&&-1!=s){var a=e.substring(i+2*o,s-o);a=a.replace(/\s+/g,""),t.data=a}return t},s=function(e,t,r){for(var n=r.substring(0,16),o=CryptoJS.enc.Hex.parse(n),s=CryptoJS.enc.Utf8.parse(t),a=i[e].keylen+i[e].ivlen,c="",l=null;;){var u=CryptoJS.algo.MD5.create();if(null!=l&&u.update(l),u.update(s),u.update(o),l=u.finalize(),(c+=CryptoJS.enc.Hex.stringify(l)).length>=2*a)break}var d={};return d.keyhex=c.substr(0,2*i[e].keylen),d.ivhex=c.substr(2*i[e].keylen,2*i[e].ivlen),d},a=function(e,t,r,n){var o=CryptoJS.enc.Base64.parse(e),s=CryptoJS.enc.Hex.stringify(o);return(0,i[t].proc)(s,r,n)};return{version:"1.0.0",parsePKCS5PEM:function(e){return o(e)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(e,t,r){return s(e,t,r)},decryptKeyB64:function(e,t,r,n){return a(e,t,r,n)},getDecryptedKeyHex:function(e,t){var r=o(e),n=r.cipher,i=r.ivsalt,c=r.data,l=s(n,t,i).keyhex;return a(c,n,l,i)},getEncryptedPKCS5PEMFromPrvKeyHex:function(e,t,r,n,o){var a="";if(void 0!==n&&null!=n||(n="AES-256-CBC"),void 0===i[n])throw new Error("KEYUTIL unsupported algorithm: "+n);if(void 0===o||null==o){var c=function(e){var t=CryptoJS.lib.WordArray.random(e);return CryptoJS.enc.Hex.stringify(t)}(i[n].ivlen);o=c.toUpperCase()}var l=function(e,t,r,n){return(0,i[t].eproc)(e,r,n)}(t,n,s(n,r,o).keyhex,o);a="-----BEGIN "+e+" PRIVATE KEY-----\r\n";return a+="Proc-Type: 4,ENCRYPTED\r\n",a+="DEK-Info: "+n+","+o+"\r\n",a+="\r\n",a+=l.replace(/(.{64})/g,"$1\r\n"),a+="\r\n-----END "+e+" PRIVATE KEY-----\r\n"},getEncryptedPKCS8PEM:function(e,t,r){return hextopem(this.getEncryptedPKCS8Hex(e,t,r),"ENCRYPTED PRIVATE KEY")},getEncryptedPKCS8Hex:function(e,t,r){var n;(n=null==r||null==r?{}:JSON.parse(JSON.stringify(r))).plain=e,this.initPBES2Param(n),this.encryptPBES2Param(n,t);var i=this.generatePBES2ASN1Param(n);return KJUR.asn1.ASN1Util.newObject(i).tohex()},initPBES2Param:function(e){var t;(null==aryval(e,"encalg")&&(e.encalg="aes256-CBC"),null==aryval(e,"iter")&&(e.iter=2048),null==aryval(e,"prf")&&(e.prf="hmacWithSHA256"),null==aryval(e,"salt")&&(e.salt=CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(8))),null==aryval(e,"enciv"))&&("des-EDE3-CBC"==e.encalg&&(t=8),"aes128-CBC"==e.encalg&&(t=16),"aes256-CBC"==e.encalg&&(t=16),e.enciv=CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(t)))},encryptPBES2Param:function(e,t){var r=KEYUTIL.getDKFromPBES2Param(e,t);try{var n=KJUR.crypto.Cipher.encrypt(e.plain,r,e.encalg,{iv:e.enciv})}catch(t){throw new Error("encrypt error: "+e.plain+" "+r+" "+e.encalg+" "+e.enciv)}e.enc=n},generatePBES2ASN1Param:function(e){var t={seq:[{seq:[{oid:"pkcs5PBES2"},{seq:[{seq:[{oid:"pkcs5PBKDF2"},{seq:[{octstr:{hex:e.salt}},{int:{hex:inttohex(e.iter)}}]}]},{seq:[{oid:e.encalg},{octstr:{hex:e.enciv}}]}]}]},{octstr:{hex:e.enc}}]};return"hmacWithSHA1"!=e.prf&&t.seq[0].seq[1].seq[0].seq[1].seq.push({seq:[{oid:e.prf},{null:""}]}),t},parseHexOfEncryptedPKCS8:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={},o=r(e,0);if(2!=o.length)throw new Error("malformed format: SEQUENCE(0).items != 2: "+o.length);i.ciphertext=n(e,o[1]);var s=r(e,o[0]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0).items != 2: "+s.length);if("2a864886f70d01050d"!=n(e,s[0]))throw new Error("this only supports pkcs5PBES2");var a=r(e,s[1]);if(2!=s.length)throw new Error("malformed format: SEQUENCE(0.0.1).items != 2: "+a.length);var c=r(e,a[1]);if(2!=c.length)throw new Error("malformed format: SEQUENCE(0.0.1.1).items != 2: "+c.length);if("2a864886f70d0307"!=n(e,c[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=n(e,c[1]);var l=r(e,a[0]);if(2!=l.length)throw new Error("malformed format: SEQUENCE(0.0.1.0).items != 2: "+l.length);if("2a864886f70d01050c"!=n(e,l[0]))throw new Error("this only supports pkcs5PBKDF2");var u=r(e,l[1]);if(u.length<2)throw new Error("malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+u.length);i.pbkdf2Salt=n(e,u[0]);var d=n(e,u[1]);try{i.pbkdf2Iter=parseInt(d,16)}catch(e){throw new Error("malformed format pbkdf2Iter: "+d)}return i},getPBKDF2KeyHexFromParam:function(e,t){var r=CryptoJS.enc.Hex.parse(e.pbkdf2Salt),n=e.pbkdf2Iter,i=CryptoJS.PBKDF2(t,r,{keySize:6,iterations:n});return CryptoJS.enc.Hex.stringify(i)},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(e,t){var r=pemtohex(e,"ENCRYPTED PRIVATE KEY"),n=this.parseHexOfEncryptedPKCS8(r),i=KEYUTIL.getPBKDF2KeyHexFromParam(n,t),o={};o.ciphertext=CryptoJS.enc.Hex.parse(n.ciphertext);var s=CryptoJS.enc.Hex.parse(i),a=CryptoJS.enc.Hex.parse(n.encryptionSchemeIV),c=CryptoJS.TripleDES.decrypt(o,s,{iv:a});return CryptoJS.enc.Hex.stringify(c)},parsePBES2:function(e){var t=ASN1HEX.parse(e);if("pkcs5PBES2"!=aryval(t,"seq.0.seq.0.oid")||"pkcs5PBKDF2"!=aryval(t,"seq.0.seq.1.seq.0.seq.0.oid"))throw new Error("not pkcs5PBES2 and pkcs5PBKDF2 used");var r=aryval(t,"seq.0.seq.1.seq.0.seq.1.seq");if(null==r)throw new Error("PBKDF2 parameter not found");var n=aryval(r,"0.octstr.hex"),i=aryval(r,"1.int.hex"),o=aryval(r,"2.seq.0.oid","hmacWithSHA1"),s=-1;try{s=parseInt(i,16)}catch(e){throw new Error("iter not proper value")}var a=aryval(t,"seq.0.seq.1.seq.1.seq.0.oid"),c=aryval(t,"seq.0.seq.1.seq.1.seq.1.octstr.hex"),l=aryval(t,"seq.1.octstr.hex");if(null==a||null==c||null==l)throw new Error("encalg, enciv or enc is undefined");return{salt:n,iter:s,prf:o,encalg:a,enciv:c,enc:l}},getDKFromPBES2Param:function(e,t){var r={hmacWithSHA1:CryptoJS.algo.SHA1,hmacWithSHA224:CryptoJS.algo.SHA224,hmacWithSHA256:CryptoJS.algo.SHA256,hmacWithSHA384:CryptoJS.algo.SHA384,hmacWithSHA512:CryptoJS.algo.SHA512}[e.prf];if(null==r)throw new Error("unsupported prf");var n={"des-EDE3-CBC":6,"aes128-CBC":4,"aes256-CBC":8}[e.encalg];if(null==n)throw new Error("unsupported encalg");var i=CryptoJS.enc.Hex.parse(e.salt),o=e.iter;try{var s=CryptoJS.PBKDF2(t,i,{keySize:n,iterations:o,hasher:r});return CryptoJS.enc.Hex.stringify(s)}catch(r){throw new Error("PBKDF2 error: "+r+" "+JSON.stringify(e)+" "+t)}},getPlainHexFromEncryptedPKCS8PEM:function(e,t){if(-1==e.indexOf("BEGIN ENCRYPTED PRIVATE KEY"))throw new Error("not Encrypted PKCS#8 PEM string");var r,n=pemtohex(e);try{r=KEYUTIL.parsePBES2(n)}catch(e){throw new Error("malformed PBES2 format: "+e.message)}var i=KEYUTIL.getDKFromPBES2Param(r,t);return KJUR.crypto.Cipher.decrypt(r.enc,i,r.encalg,{iv:r.enciv})},getKeyFromEncryptedPKCS8PEM:function(e,t){var r=this.getPlainHexFromEncryptedPKCS8PEM(e,t);return this.getKeyFromPlainPrivatePKCS8Hex(r)},parsePlainPrivatePKCS8Hex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={algparam:null};if("30"!=e.substr(0,2))throw new Error("malformed plain PKCS8 private key(code:001)");var o=r(e,0);if(o.length<3)throw new Error("malformed plain PKCS8 private key(code:002)");if("30"!=e.substr(o[1],2))throw new Error("malformed PKCS8 private key(code:003)");var s=r(e,o[1]);if(2!=s.length)throw new Error("malformed PKCS8 private key(code:004)");if("06"!=e.substr(s[0],2))throw new Error("malformed PKCS8 private key(code:005)");if(i.algoid=n(e,s[0]),"06"==e.substr(s[1],2)&&(i.algparam=n(e,s[1])),"04"!=e.substr(o[2],2))throw new Error("malformed PKCS8 private key(code:006)");return i.keyidx=t.getVidx(e,o[2]),i},getKeyFromPlainPrivatePKCS8PEM:function(e){var t=pemtohex(e,"PRIVATE KEY");return this.getKeyFromPlainPrivatePKCS8Hex(t)},getKeyFromPlainPrivatePKCS8Hex:function(e){var t,r=this.parsePlainPrivatePKCS8Hex(e);if("2a864886f70d010101"==r.algoid)t=new RSAKey;else if("2a8648ce380401"==r.algoid)t=new KJUR.crypto.DSA;else{if("2a8648ce3d0201"!=r.algoid)throw new Error("unsupported private key algorithm");t=new KJUR.crypto.ECDSA}return t.readPKCS8PrvKeyHex(e),t},_getKeyFromPublicPKCS8Hex:function(e){var t,r=ASN1HEX.getVbyList(e,0,[0,0],"06");if("2a864886f70d010101"===r)t=new RSAKey;else if("2a8648ce380401"===r)t=new KJUR.crypto.DSA;else{if("2a8648ce3d0201"!==r)throw new Error("unsupported PKCS#8 public key hex");t=new KJUR.crypto.ECDSA}return t.readPKCS8PubKeyHex(e),t},parsePublicRawRSAKeyHex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={};if("30"!=e.substr(0,2))throw new Error("malformed RSA key(code:001)");var o=r(e,0);if(2!=o.length)throw new Error("malformed RSA key(code:002)");if("02"!=e.substr(o[0],2))throw new Error("malformed RSA key(code:003)");if(i.n=n(e,o[0]),"02"!=e.substr(o[1],2))throw new Error("malformed RSA key(code:004)");return i.e=n(e,o[1]),i},parsePublicPKCS8Hex:function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV,i={algparam:null},o=r(e,0);if(2!=o.length)throw new Error("outer DERSequence shall have 2 elements: "+o.length);var s=o[0];if("30"!=e.substr(s,2))throw new Error("malformed PKCS8 public key(code:001)");var a=r(e,s);if(2!=a.length)throw new Error("malformed PKCS8 public key(code:002)");if("06"!=e.substr(a[0],2))throw new Error("malformed PKCS8 public key(code:003)");if(i.algoid=n(e,a[0]),"06"==e.substr(a[1],2)?i.algparam=n(e,a[1]):"30"==e.substr(a[1],2)&&(i.algparam={},i.algparam.p=t.getVbyList(e,a[1],[0],"02"),i.algparam.q=t.getVbyList(e,a[1],[1],"02"),i.algparam.g=t.getVbyList(e,a[1],[2],"02")),"03"!=e.substr(o[1],2))throw new Error("malformed PKCS8 public key(code:004)");return i.key=n(e,o[1]).substr(2),i}}}();function _zeroPaddingOfSignature(e,t){for(var r="",n=t/4-e.length,i=0;i>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return n}function _rsasign_getAlgNameAndHashFromHexDisgestInfo(e){for(var t in KJUR.crypto.Util.DIGESTINFOHEAD){var r=KJUR.crypto.Util.DIGESTINFOHEAD[t],n=r.length;if(e.substring(0,n)==r)return[t,e.substring(n)]}return[]}function X509(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getV;t.dump;var i,o=t.parse,s=t.getTLV,a=t.getVbyList,c=t.getVbyListEx,l=t.getTLVbyList,u=t.getTLVbyListEx,d=t.getIdxbyList,h=t.getIdxbyListEx,p=t.getVidx,g=t.getInt,m=t.oidname,f=t.hextooidstr,y=pemtohex,$=Error;try{i=KJUR.asn1.x509.AlgorithmIdentifier.PSSNAME2ASN1TLV}catch(e){}this.HEX2STAG={"0c":"utf8",13:"prn",16:"ia5","1a":"vis","1e":"bmp"},this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){if(null===this.hex||0!==this.version)return this.version;var e=l(this.hex,0,[0,0]);if("a0"==e.substr(0,2)){var t=l(e,0,[0]),r=g(t,0);if(r<0||20?t:void 0}catch(e){return}},this._asn1ToNoticeRef=function(e){try{for(var t={},r=aryval(e,"seq"),n=0;n0?t:void 0}catch(e){return}},this._asn1ToNoticeNum=function(e){try{for(var t=aryval(e,"seq"),r=[],n=0;n1){var a=s(e,o[1]),c=this.getGeneralName(a);null!=c.uri&&(i.uri=c.uri)}if(o.length>2){var l=s(e,o[2]);"0101ff"==l&&(i.reqauth=!0),"010100"==l&&(i.reqauth=!1)}return i},this.getExtSubjectDirectoryAttributes=function(e,t){if(void 0===e&&void 0===t){var r=this.getExtInfo("subjectDirectoryAttributes");if(void 0===r)return;e=s(this.hex,r.vidx),t=r.critical}var n={extname:"subjectDirectoryAttributes"};t&&(n.critical=!0);try{for(var i=o(e),a=[],c=0;c0&&(t.ext=this.getExtParamArray()),t.sighex=this.getSignatureValueHex(),1==e.tbshex&&(t.tbshex=l(this.hex,0,[0])),1==e.nodnarray&&(delete t.issuer.array,delete t.subject.array),t},this.getExtParamArray=function(e){null==e&&(-1!=h(this.hex,0,[0,"[3]"])&&(e=u(this.hex,0,[0,"[3]",0],"30")));for(var t=[],n=r(e,0),i=0;i2&&"04"===m.substr(g[1],2)))throw new Error("unsupported PKCS#1/5 hexadecimal key");(T=new s).readPKCS5PrvKeyHex(m)}return T}if("pkcs8prv"===r)return T=u.getKeyFromPlainPrivatePKCS8Hex(e);if("pkcs8pub"===r)return u._getKeyFromPublicPKCS8Hex(e);if("x509pub"===r)return X509.getPublicKeyFromCertHex(e);if(-1!=e.indexOf("-END CERTIFICATE-",0)||-1!=e.indexOf("-END X509 CERTIFICATE-",0)||-1!=e.indexOf("-END TRUSTED CERTIFICATE-",0))return X509.getPublicKeyFromCertPEM(e);if(-1!=e.indexOf("-END PUBLIC KEY-")){var y=pemtohex(e,"PUBLIC KEY");return u._getKeyFromPublicPKCS8Hex(y)}if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var $=l(e,"RSA PRIVATE KEY");return u.getKey($,null,"pkcs5prv")}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){var b=i(x=l(e,"DSA PRIVATE KEY"),0,[1],"02"),v=i(x,0,[2],"02"),w=i(x,0,[3],"02"),S=i(x,0,[4],"02"),_=i(x,0,[5],"02");return(T=new a).setPrivate(new BigInteger(b,16),new BigInteger(v,16),new BigInteger(w,16),new BigInteger(S,16),new BigInteger(_,16)),T}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1==e.indexOf("4,ENCRYPTED")){$=l(e,"EC PRIVATE KEY");return u.getKey($,null,"pkcs5prv")}if(-1!=e.indexOf("-END PRIVATE KEY-"))return u.getKeyFromPlainPrivatePKCS8PEM(e);if(-1!=e.indexOf("-END RSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var E=u.getDecryptedKeyHex(e,t),C=new RSAKey;return C.readPKCS5PrvKeyHex(E),C}if(-1!=e.indexOf("-END EC PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var I,T=i(x=u.getDecryptedKeyHex(e,t),0,[1],"04"),A=i(x,0,[2,0],"06"),D=i(x,0,[3,0],"03").substr(2);if(void 0===KJUR.crypto.OID.oidhex2name[A])throw new Error("undefined OID(hex) in KJUR.crypto.OID: "+A);return(I=new s({curve:KJUR.crypto.OID.oidhex2name[A]})).setPublicKeyHex(D),I.setPrivateKeyHex(T),I.isPublic=!1,I}if(-1!=e.indexOf("-END DSA PRIVATE KEY-")&&-1!=e.indexOf("4,ENCRYPTED")){var x;b=i(x=u.getDecryptedKeyHex(e,t),0,[1],"02"),v=i(x,0,[2],"02"),w=i(x,0,[3],"02"),S=i(x,0,[4],"02"),_=i(x,0,[5],"02");return(T=new a).setPrivate(new BigInteger(b,16),new BigInteger(v,16),new BigInteger(w,16),new BigInteger(S,16),new BigInteger(_,16)),T}if(-1!=e.indexOf("-END ENCRYPTED PRIVATE KEY-"))return u.getKeyFromEncryptedPKCS8PEM(e,t);throw new Error("not supported argument")},KEYUTIL.generateKeypair=function(e,t){if("RSA"==e){var r=t;(s=new RSAKey).generate(r,"10001"),s.isPrivate=!0,s.isPublic=!0;var n=new RSAKey,i=s.n.toString(16),o=s.e.toString(16);return n.setPublic(i,o),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}if("EC"==e){var s,a,c=t,l=new KJUR.crypto.ECDSA({curve:c}).generateKeyPairHex();return(s=new KJUR.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),s.setPrivateKeyHex(l.ecprvhex),s.isPrivate=!0,s.isPublic=!1,(n=new KJUR.crypto.ECDSA({curve:c})).setPublicKeyHex(l.ecpubhex),n.isPrivate=!1,n.isPublic=!0,(a={}).prvKeyObj=s,a.pubKeyObj=n,a}throw new Error("unknown algorithm: "+e)},KEYUTIL.getPEM=function(e,t,r,n,i,o){var s=KJUR,a=s.asn1,c=a.DERObjectIdentifier,l=a.DERInteger,u=a.ASN1Util.newObject,d=a.x509.SubjectPublicKeyInfo,h=s.crypto,p=h.DSA,g=h.ECDSA,m=RSAKey;function f(e){return u({seq:[{int:0},{int:{bigint:e.n}},{int:e.e},{int:{bigint:e.d}},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.dmp1}},{int:{bigint:e.dmq1}},{int:{bigint:e.coeff}}]})}function y(e){return u({seq:[{int:1},{octstr:{hex:e.prvKeyHex}},{tag:["a0",!0,{oid:{name:e.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]}]})}function $(e){return u({seq:[{int:0},{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}},{int:{bigint:e.y}},{int:{bigint:e.x}}]})}if((void 0!==m&&e instanceof m||void 0!==p&&e instanceof p||void 0!==g&&e instanceof g)&&1==e.isPublic&&(void 0===t||"PKCS8PUB"==t))return hextopem(S=new d(e).tohex(),"PUBLIC KEY");if("PKCS1PRV"==t&&void 0!==m&&e instanceof m&&(void 0===r||null==r)&&1==e.isPrivate)return hextopem(S=f(e).tohex(),"RSA PRIVATE KEY");if("PKCS1PRV"==t&&void 0!==g&&e instanceof g&&(void 0===r||null==r)&&1==e.isPrivate){var b=new c({name:e.curveName}).tohex(),v=y(e).tohex(),w="";return w+=hextopem(b,"EC PARAMETERS"),w+=hextopem(v,"EC PRIVATE KEY")}if("PKCS1PRV"==t&&void 0!==p&&e instanceof p&&(void 0===r||null==r)&&1==e.isPrivate)return hextopem(S=$(e).tohex(),"DSA PRIVATE KEY");if("PKCS5PRV"==t&&void 0!==m&&e instanceof m&&void 0!==r&&null!=r&&1==e.isPrivate){var S=f(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",S,r,n,o)}if("PKCS5PRV"==t&&void 0!==g&&e instanceof g&&void 0!==r&&null!=r&&1==e.isPrivate){S=y(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",S,r,n,o)}if("PKCS5PRV"==t&&void 0!==p&&e instanceof p&&void 0!==r&&null!=r&&1==e.isPrivate){S=$(e).tohex();return void 0===n&&(n="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",S,r,n,o)}var _=function(e,t){if("string"==typeof t)return KEYUTIL.getEncryptedPKCS8PEM(e,t);if("object"==typeof t&&null!=aryval(t,"passcode")){var r=JSON.parse(JSON.stringify(t)),n=r.passcode;return delete r.passcode,KEYUTIL.getEncryptedPKCS8PEM(e,n,r)}};if("PKCS8PRV"==t&&null!=m&&e instanceof m&&1==e.isPrivate){var E=f(e).tohex();S=u({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:E}}]}).tohex();return void 0===r||null==r?hextopem(S,"PRIVATE KEY"):_(S,r)}if("PKCS8PRV"==t&&void 0!==g&&e instanceof g&&1==e.isPrivate){var C={seq:[{int:1},{octstr:{hex:e.prvKeyHex}}]};"string"==typeof e.pubKeyHex&&C.seq.push({tag:["a1",!0,{bitstr:{hex:"00"+e.pubKeyHex}}]});E=new u(C).tohex(),S=u({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:e.curveName}}]},{octstr:{hex:E}}]}).tohex();return void 0===r||null==r?hextopem(S,"PRIVATE KEY"):_(S,r)}if("PKCS8PRV"==t&&void 0!==p&&e instanceof p&&1==e.isPrivate){E=new l({bigint:e.x}).tohex(),S=u({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:e.p}},{int:{bigint:e.q}},{int:{bigint:e.g}}]}]},{octstr:{hex:E}}]}).tohex();return void 0===r||null==r?hextopem(S,"PRIVATE KEY"):_(S,r)}throw new Error("unsupported object nor format")},KEYUTIL.getKeyFromCSRPEM=function(e){var t=pemtohex(e,"CERTIFICATE REQUEST");return KEYUTIL.getKeyFromCSRHex(t)},KEYUTIL.getKeyFromCSRHex=function(e){var t=KEYUTIL.parseCSRHex(e);return KEYUTIL.getKey(t.p8pubkeyhex,null,"pkcs8pub")},KEYUTIL.parseCSRHex=function(e){var t=ASN1HEX,r=t.getChildIdx,n=t.getTLV,i={},o=e;if("30"!=o.substr(0,2))throw new Error("malformed CSR(code:001)");var s=r(o,0);if(s.length<1)throw new Error("malformed CSR(code:002)");if("30"!=o.substr(s[0],2))throw new Error("malformed CSR(code:003)");var a=r(o,s[0]);if(a.length<3)throw new Error("malformed CSR(code:004)");return i.p8pubkeyhex=n(o,a[2]),i},KEYUTIL.getKeyID=function(e){var t=KEYUTIL,r=ASN1HEX;"string"==typeof e&&-1!=e.indexOf("BEGIN ")&&(e=t.getKey(e));var n=pemtohex(t.getPEM(e)),i=r.getIdxbyList(n,0,[1]),o=r.getV(n,i).substring(2);return KJUR.crypto.Util.hashHex(o,"sha1")},KEYUTIL.getJWK=function(e,t,r,n,i){var o,s,a={},c=KJUR.crypto.Util.hashHex;if("string"==typeof e)o=KEYUTIL.getKey(e),-1!=e.indexOf("CERTIFICATE")&&(s=pemtohex(e));else{if("object"!=typeof e)throw new Error("unsupported keyinfo type");e instanceof X509?(o=e.getPublicKey(),s=e.hex):o=e}if(o instanceof RSAKey&&o.isPrivate)a.kty="RSA",a.n=hextob64u(o.n.toString(16)),a.e=hextob64u(o.e.toString(16)),a.d=hextob64u(o.d.toString(16)),a.p=hextob64u(o.p.toString(16)),a.q=hextob64u(o.q.toString(16)),a.dp=hextob64u(o.dmp1.toString(16)),a.dq=hextob64u(o.dmq1.toString(16)),a.qi=hextob64u(o.coeff.toString(16));else if(o instanceof RSAKey&&o.isPublic)a.kty="RSA",a.n=hextob64u(o.n.toString(16)),a.e=hextob64u(o.e.toString(16));else if(o instanceof KJUR.crypto.ECDSA&&o.isPrivate){if("P-256"!==(u=o.getShortNISTPCurveName())&&"P-384"!==u&&"P-521"!==u)throw new Error("unsupported curve name for JWT: "+u);var l=o.getPublicKeyXYHex();a.kty="EC",a.crv=u,a.x=hextob64u(l.x),a.y=hextob64u(l.y),a.d=hextob64u(o.prvKeyHex)}else if(o instanceof KJUR.crypto.ECDSA&&o.isPublic){var u;if("P-256"!==(u=o.getShortNISTPCurveName())&&"P-384"!==u&&"P-521"!==u)throw new Error("unsupported curve name for JWT: "+u);l=o.getPublicKeyXYHex();a.kty="EC",a.crv=u,a.x=hextob64u(l.x),a.y=hextob64u(l.y)}if(null==a.kty)throw new Error("unsupported keyinfo");return o.isPrivate||1==t||(a.kid=KJUR.jws.JWS.getJWKthumbprint(a)),null!=s&&1!=r&&(a.x5c=[hex2b64(s)]),null!=s&&1!=n&&(a.x5t=b64tob64u(hex2b64(c(s,"sha1")))),null!=s&&1!=i&&(a["x5t#S256"]=b64tob64u(hex2b64(c(s,"sha256")))),a},KEYUTIL.getJWKFromKey=function(e){return KEYUTIL.getJWK(e,!0,!0,!0,!0)},RSAKey.getPosArrayOfChildrenFromHex=function(e){return ASN1HEX.getChildIdx(e,0)},RSAKey.getHexValueArrayOfChildrenFromHex=function(e){var t,r=ASN1HEX.getV,n=r(e,(t=RSAKey.getPosArrayOfChildrenFromHex(e))[0]),i=r(e,t[1]),o=r(e,t[2]),s=r(e,t[3]),a=r(e,t[4]),c=r(e,t[5]),l=r(e,t[6]),u=r(e,t[7]),d=r(e,t[8]);return(t=new Array).push(n,i,o,s,a,c,l,u,d),t},RSAKey.prototype.readPrivateKeyFromPEMString=function(e){var t=pemtohex(e),r=RSAKey.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8])},RSAKey.prototype.readPKCS5PrvKeyHex=function(e){var t=RSAKey.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},RSAKey.prototype.readPKCS8PrvKeyHex=function(e){var t,r,n,i,o,s,a,c,l=ASN1HEX,u=l.getVbyListEx;if(!1===l.isASN1HEX(e))throw new Error("not ASN.1 hex string");try{t=u(e,0,[2,0,1],"02"),r=u(e,0,[2,0,2],"02"),n=u(e,0,[2,0,3],"02"),i=u(e,0,[2,0,4],"02"),o=u(e,0,[2,0,5],"02"),s=u(e,0,[2,0,6],"02"),a=u(e,0,[2,0,7],"02"),c=u(e,0,[2,0,8],"02")}catch(e){throw new Error("malformed PKCS#8 plain RSA private key")}this.setPrivateEx(t,r,n,i,o,s,a,c)},RSAKey.prototype.readPKCS5PubKeyHex=function(e){var t=ASN1HEX,r=t.getV;if(!1===t.isASN1HEX(e))throw new Error("keyHex is not ASN.1 hex string");var n=t.getChildIdx(e,0);if(2!==n.length||"02"!==e.substr(n[0],2)||"02"!==e.substr(n[1],2))throw new Error("wrong hex for PKCS#5 public key");var i=r(e,n[0]),o=r(e,n[1]);this.setPublic(i,o)},RSAKey.prototype.readPKCS8PubKeyHex=function(e){var t=ASN1HEX;if(!1===t.isASN1HEX(e))throw new Error("not ASN.1 hex string");if("06092a864886f70d010101"!==t.getTLVbyListEx(e,0,[0,0]))throw new Error("not PKCS8 RSA public key");var r=t.getTLVbyListEx(e,0,[1,0]);this.readPKCS5PubKeyHex(r)},RSAKey.prototype.readCertPubKeyHex=function(e,t){var r,n;(r=new X509).readCertHex(e),n=r.getPublicKeyHex(),this.readPKCS8PubKeyHex(n)},RSAKey.prototype.sign=function(e,t){var r=function(e){return KJUR.crypto.Util.hashString(e,t)}(e);return this.signWithMessageHash(r,t)},RSAKey.prototype.signWithMessageHash=function(e,t){var r=parseBigInt(KJUR.crypto.Util.getPaddedDigestInfoHex(e,t,this.n.bitLength()),16);return _zeroPaddingOfSignature(this.doPrivate(r).toString(16),this.n.bitLength())},RSAKey.prototype.signPSS=function(e,t,r){var n=function(e){return KJUR.crypto.Util.hashHex(e,t)}(rstrtohex(e));return void 0===r&&(r=-1),this.signWithMessageHashPSS(n,t,r)},RSAKey.prototype.signWithMessageHashPSS=function(e,t,r){var n,i=hextorstr(e),o=i.length,s=this.n.bitLength()-1,a=Math.ceil(s/8),c=function(e){return KJUR.crypto.Util.hashHex(e,t)};if(-1===r||void 0===r)r=o;else if(-2===r)r=a-o-2;else if(r<-2)throw new Error("invalid salt length");if(a0&&(l=new Array(r),(new SecureRandom).nextBytes(l),l=String.fromCharCode.apply(String,l));var u=hextorstr(c(rstrtohex("\0\0\0\0\0\0\0\0"+i+l))),d=[];for(n=0;n>8*a-s&255;for(g[0]&=~m,n=0;nn)return!1;var i=this.doPublic(r).toString(16);if(i.length+3!=n/4)return!1;var o=_rsasign_getAlgNameAndHashFromHexDisgestInfo(i.replace(/^1f+00/,""));if(0==o.length)return!1;var s=o[0],a=o[1],c=function(e){return KJUR.crypto.Util.hashString(e,s)}(e);return a==c},RSAKey.prototype.verifyWithMessageHash=function(e,t){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var r=parseBigInt(t,16);if(r.bitLength()>this.n.bitLength())return 0;var n=_rsasign_getAlgNameAndHashFromHexDisgestInfo(this.doPublic(r).toString(16).replace(/^1f+00/,""));return 0!=n.length&&(n[0],n[1]==e)},RSAKey.prototype.verifyPSS=function(e,t,r,n){var i=function(e){return KJUR.crypto.Util.hashHex(e,r)}(rstrtohex(e));return void 0===n&&(n=-1),this.verifyWithMessageHashPSS(i,t,r,n)},RSAKey.prototype.verifyWithMessageHashPSS=function(e,t,r,n){if(t.length!=Math.ceil(this.n.bitLength()/4))return!1;var i,o=new BigInteger(t,16),s=function(e){return KJUR.crypto.Util.hashHex(e,r)},a=hextorstr(e),c=a.length,l=this.n.bitLength()-1,u=Math.ceil(l/8);if(-1===n||void 0===n)n=c;else if(-2===n)n=u-c-2;else if(n<-2)throw new Error("invalid salt length");if(u>8*u-l&255;if(0!==(h.charCodeAt(0)&g))throw new Error("bits beyond keysize not zero");var m=pss_mgf1_str(p,h.length,s),f=[];for(i=0;i0)&&-1==(":"+r.join(":")+":").indexOf(":"+m+":"))throw"algorithm '"+m+"' not accepted in the list";if("none"!=m&&null===t)throw"key shall be specified to verify.";if("string"==typeof t&&-1!=t.indexOf("-----BEGIN ")&&(t=KEYUTIL.getKey(t)),!("RS"!=f&&"PS"!=f||t instanceof n))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==f&&!(t instanceof c))throw"key shall be a ECDSA obj for ES* algs";var y=null;if(void 0===o.jwsalg2sigalg[g.alg])throw"unsupported alg name: "+m;if("none"==(y=o.jwsalg2sigalg[m]))throw"not supported";if("Hmac"==y.substr(0,4)){if(void 0===t)throw"hexadecimal key shall be specified for HMAC";var $=new l({alg:y,pass:t});return $.updateString(h),p==$.doFinal()}if(-1!=y.indexOf("withECDSA")){var b,v=null;try{v=c.concatSigToASN1Sig(p)}catch(e){return!1}return(b=new u({alg:y})).init(t),b.updateString(h),b.verify(v)}return(b=new u({alg:y})).init(t),b.updateString(h),b.verify(p)},KJUR.jws.JWS.parse=function(e){var t,r,n,i=e.split("."),o={};if(2!=i.length&&3!=i.length)throw"malformed sJWS: wrong number of '.' splitted elements";return t=i[0],r=i[1],3==i.length&&(n=i[2]),o.headerObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(t)),o.payloadObj=KJUR.jws.JWS.readSafeJSONString(b64utoutf8(r)),o.headerPP=JSON.stringify(o.headerObj,null," "),null==o.payloadObj?o.payloadPP=b64utoutf8(r):o.payloadPP=JSON.stringify(o.payloadObj,null," "),void 0!==n&&(o.sigHex=b64utohex(n)),o},KJUR.jws.JWS.verifyJWT=function(e,t,r){var n=KJUR.jws,i=n.JWS,o=i.readSafeJSONString,s=i.inArray,a=i.includedArray;if(!isBase64URLDot(e))return!1;var c=e.split(".");if(3!=c.length)return!1;var l=c[0],u=c[1];b64utohex(c[2]);var d=o(b64utoutf8(l)),h=o(b64utoutf8(u));if(void 0===d.alg)return!1;if(void 0===r.alg)throw"acceptField.alg shall be specified";if(!s(d.alg,r.alg))return!1;if(void 0!==h.iss&&"object"==typeof r.iss&&!s(h.iss,r.iss))return!1;if(void 0!==h.sub&&"object"==typeof r.sub&&!s(h.sub,r.sub))return!1;if(void 0!==h.aud&&"object"==typeof r.aud)if("string"==typeof h.aud){if(!s(h.aud,r.aud))return!1}else if("object"==typeof h.aud&&!a(h.aud,r.aud))return!1;var p=n.IntDate.getNow();return void 0!==r.verifyAt&&"number"==typeof r.verifyAt&&(p=r.verifyAt),void 0!==r.gracePeriod&&"number"==typeof r.gracePeriod||(r.gracePeriod=0),!(void 0!==h.exp&&"number"==typeof h.exp&&h.exp+r.gracePeriodi&&this.aHeader.pop(),this.aSignature.length>i&&this.aSignature.pop(),"addSignature failed: "+e}},this.verifyAll=function(e){if(this.aHeader.length!==e.length||this.aSignature.length!==e.length)return!1;for(var t=0;t0))throw"malformed header";if(this.aHeader=e.headers,"string"!=typeof e.payload)throw"malformed signatures";if(this.sPayload=e.payload,!(e.signatures.length>0))throw"malformed signatures";this.aSignature=e.signatures}catch(e){throw"malformed JWS-JS JSON object: "+e}},this.getJSON=function(){return{headers:this.aHeader,payload:this.sPayload,signatures:this.aSignature}},this.isEmpty=function(){return 0==this.aHeader.length?1:0}};var RSAKey_1=RSAKey;KJUR.crypto.ECDSA,KJUR.crypto.DSA,KJUR.crypto.Signature,KJUR.crypto.MessageDigest,KJUR.crypto.Mac;var KEYUTIL_1=KEYUTIL,b64utoutf8_1=b64utoutf8,KJUR_1=KJUR;async function g$3(e,t,r){let n=await(r?.fetch??globalThis.fetch??fetch)(e.href,{signal:AbortSignal.timeout(t),headers:r?.headers});if(200!==n.status)throw new Error(`Failed to fetch ${e.href}: ${n.statusText}`);try{return await n.json()}catch{throw new Error("Failed to parse response")}}KJUR.crypto,KJUR.asn1,KJUR.jws,KJUR.lang;var x$1="/.well-known/openid-configuration",v$1="/.well-known/oauth-authorization-server";function W$1(e){if(!e.issuer)throw new Error("'issuer' not found is authorization server metadata")}async function $$1(e){let t=e.URL??globalThis.URL??URL,r=new t(e.issuerBaseUri);if(r.pathname.includes("/.well-known/")){let t=await g$3(r,e.timeout,e);return W$1(t),t}let n=[];r.pathname.endsWith("/")?n.push(`${r.pathname}${x$1.substring(1)}`):n.push(`${r.pathname}${x$1}`),r.pathname.endsWith("/")?n.push(`${v$1}`):n.push(`${v$1}${r.pathname}`);for(let i of n)try{let n=new t(i,r),o=await g$3(n,e.timeout,e);return W$1(o),o}catch{}throw new Error("Failed to fetch authorization server metadata")}var V$1=e=>{let t,r=0;return()=>{let n=Date.now();return(!t||n>r+e.cacheMaxAge)&&(r=n,t=$$1(e).catch(e=>{throw t=void 0,e})),t}},c=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}},h$1=class extends c{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},y$1=class extends c{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},l=class extends c{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},w$1=class extends c{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(e="No matching key found in the JSON Web Key Set",t){super(e,t)}},m=class extends c{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(e="request timed out",t){super(e,t)}};function q$1(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new h$1('Unsupported "alg" value for a JSON Web Key Set')}}function z$2(e){return!!e&&"object"==typeof e&&Array.isArray(e.keys)}var R$1=class{#e;#t=new WeakMap;constructor(e){if(!z$2(e))throw new l("JSON Web Key Set malformed");this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:r,kid:n}={...e,...t?.header},i=q$1(r),o=this.#e.keys.filter(e=>{let t=e.kty===i;return t&&"string"==typeof n&&(t=e.kid===n),t&&"string"==typeof e.alg&&(t=e.alg===r),t&&"string"==typeof e.use&&(t="sig"===e.use),t}),{0:s,length:a}=o;if(0===a)throw new w$1;if(1!==a)throw new Error("Multiple matching keys found");return B$1(this.#t,s,r)}};async function B$1(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){let e=KEYUTIL_1.getKey(t);if(!(e instanceof RSAKey_1))throw new Error("RSA key expected!");n[r]=e}return n[r]}function I$1(e){let t=new R$1(e),r=async(e,r)=>await t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}async function Q$1(e,t,r,n){let i=await(n?.fetch??globalThis.fetch??fetch)(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(e=>{throw"TimeoutError"===e.name?new m:e});if(200!==i.status)throw new c(`Expected 200 OK from JSON Web Key Set response, got ${i.status} ${i.statusText}`);try{return await i.json()}catch(e){throw new c(`Failed to parse the JSON Web Key Set response as JSON: ${e instanceof Error?e.message:String(e)}`)}}var S$1=class{#e;#t;#r;#n;#i;#o;#s;#a;constructor(e,t){this.#e=t.fetch,this.#t=new(t.URL??globalThis.URL??URL)(e.href),this.#s=new(t.Headers??globalThis.Headers??Headers)(t.headers),this.#r="number"==typeof t.timeout?t.timeout:5e3,this.#n="number"==typeof t.cacheMaxAge?t.cacheMaxAge:6e5}fresh(){return"number"==typeof this.#i&&Date.now(){this.#a=I$1(e),this.#i=Date.now(),this.#o=void 0}).catch(e=>{throw this.#o=void 0,e}),await this.#o}};function U$1(e,t){let r=new S$1(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(r.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}var T$1=e=>{let t,r,n=e.URL??URL;return i=>((void 0===t||r!==i)&&(r=i,t=U$1(new n(i),e)),t)};function K$1(e){return"string"==typeof e?[e]:Array.isArray(e)?e:void 0}function H(e,t,r){let{headerObj:n,payloadObj:i}=KJUR_1.jws.JWS.parse(e),o={alg:r?.algorithms??[n.alg],aud:K$1(r?.audience),iss:K$1(r?.issuer),sub:K$1(r?.subject),gracePeriod:r?.clockTolerance};if("function"==typeof t)return t(n).then(t=>KJUR_1.jws.JWS.verifyJWT(e,t,o)).then(e=>{if(!e)throw new y$1;return{payload:i,protectedHeader:n}});if(KJUR_1.jws.JWS.verifyJWT(e,t,o))return{payload:i,protectedHeader:n};throw new y$1}var A$1=(e,t,r)=>{for(let[n,i]of Object.entries(r))if(!1!==i){let r="alg"===n||"typ"===n?t[n]:e[n];if(!("string"==typeof i&&r===i||"function"==typeof i&&i(r,e,t)))throw new Error(`Unexpected '${n}' value: ${JSON.stringify(r)}`)}},M$1=(e,t,r,n,i,o,s)=>({alg:e=>"string"==typeof e&&"none"!==e.toLowerCase()&&(void 0===o||o.includes(e))&&(void 0===s||e===s),typ:e=>!i||"string"==typeof e&&"at+jwt"===e.toLowerCase().replace(/^application\//,""),iss:t=>"string"==typeof t&&t===e,aud:e=>(t="string"==typeof t?[t]:t,"string"==typeof e?t.includes(e):!!Array.isArray(e)&&t.some(Set.prototype.has.bind(new Set(e)))),exp:e=>{let t=Math.floor(Date.now()/1e3);return"number"==typeof e&&e>=t-r},iat:e=>{if(void 0===n)return void 0===e&&!i||"number"==typeof e;let t=Math.floor(Date.now()/1e3);return"number"==typeof e&&et-r-n},sub:e=>void 0===e&&!i||"string"==typeof e,jti:e=>void 0===e&&!i||"string"==typeof e}),J$1=class extends Error{},X$1=({issuerBaseUri:e="",jwksUri:t="",issuer:r="",audience:n="",tokenSigningAlg:i,timeout:o=5e3,cacheMaxAge:s=6e5,clockTolerance:a=5,maxTokenAge:c,strict:l=!1,validators:u,fetch:d,URL:h})=>{let p,g;if(!(e||r&&t))throw new Error("Either 'issuerBaseUri' or both 'issuer' and 'jwksUri' must be provided");if(!n)throw new Error("An 'audience' is required to validate the 'aud' claim");let m=V$1({issuerBaseUri:e,timeout:o,cacheMaxAge:s,fetch:d,URL:h}),f=T$1({timeout:o,cacheMaxAge:s,fetch:d,URL:h});return async o=>{try{if(e){let{jwks_uri:e,issuer:n,id_token_signing_alg_values_supported:i}=await m();t=t||e,r=r||n,p=i}g??={...M$1(r,n,a,c,l,p,i),...u};let{payload:s,protectedHeader:d}=await H(o,f(t),{clockTolerance:a});return A$1(s,d,g),{payload:s,header:d,token:o}}catch(e){throw new J$1(`${e instanceof Error?e.message:String(e)}`)}}},Z$1=X$1,Nc=Object.defineProperty,ge=(e,t)=>()=>(e&&(t=e(e=0)),t),Ht=(e,t)=>{for(var r in t)Nc(e,r,{get:t[r],enumerable:!0})},jr={};function qc(e){return"string"==typeof e}function We(e,t){return qc(e)?e===t:"string"==typeof t&&e.test(t)}function Jr(e,t){for(let r of e)if(We(r,t))return!0;return!1}function Lt(e){if("string"==typeof e){let t=Ec.exec(e)?.groups;if(t??=$c.exec(e)?.groups,t?.pattern)return new RegExp(t.pattern,t.flags??"")}return e}Ht(jr,{regexify:()=>Lt,valueMatches:()=>We,valuesMatch:()=>Jr});var $c,Ec,Ft=ge(()=>{$c=/^#(\(\?(?[im]*)\))?(?.*)$/,Ec=/^\/(?(?:[^/\\]|\\.)+)\/(?[gimsuyd]*)$/});function R(e){return v$3(e)}var L=ge(()=>{});function Zi(e,t){return t.reduce((t,r)=>r===e?t:t.concat(r),[])}function nn(e,t){return e[t]?e:produce(e,e=>{e[t]={}})}function $e(e){return e instanceof Set?Array.from(e).map($e):e instanceof Array?e.map($e):e instanceof Map?$e(Object.fromEntries(e)):e instanceof Object?Object.keys(e).reduce((t,r)=>(t[r]=$e(e[r]),t),{}):e}function dd(e){let t=new Map;return function(r,n){let i=t.get(this)+(Array.isArray(this)?`[${r}]`:`.${r}`);return n===Object(n)&&t.set(n,i),n instanceof RegExp&&(n=`#${n.source}`),e.call(this,r,n,i.replace(/undefined\.\.?/,""))}}function rt(...e){return dd((t,r,n)=>-1!==e.indexOf(n)?"******":r)}function nt(e){return JSON.stringify(e,Object.keys(e).sort(ud))}function pe(e){return!!e}var ud,me=ge(()=>{ud=(e,t)=>e.localeCompare(t)});function am(e,t){for(let[r,n]of Object.entries(e)){if(!We(n,t[r]))return!1}return!0}function Ea(e,t){return Jr(e,t)}function Nt(e,t,r){let n=r?.publishers?.reduce((r,n)=>{if(am(n.identity,e)){let e=n.metrics.block??n.metrics.blacklist??[];if(e.length>0&&Ea(e,t))return!1;{let e=n.metrics.allow??n.metrics.whitelist??[];return r||Ea(e,t)}}return r},void 0);if(void 0!==n)return n;let i=r?.non_matched??"allow";return"allow"===i||"whitelist"===i}var ci=ge(()=>{Ft()});function bm(e){if(e&&Object.keys(e).length>0)return e}function Fa(e){return"object"==typeof e?{value:Object.entries(e).reduce((e,[t,r])=>(e[t]=Fa(r),e),{})}:{value:e}}function Rm(e){return{timestamp:e.timestamp??Date.now(),value:Fa(e.value)}}function xm(e,t){return Array.from(e).reduce((e,r)=>{let n=t(r),i=e.get(n)??[];return 0===i.length&&e.set(n,i),i.push(r),e},new Map)}function*Sr(e,t){La.enabledFor("trace")&&La.debug(`conflating ${JSON.stringify(t)}`);let r,n=xm(t,e=>nt(e.identity));for(let[,e]of n){for(let t of e)if(t.status){let{identity:e,status:n,metadata:i}=t;r&&(yield r),yield{identity:e,status:n,metrics:void 0,metadata:bm(i)},r=void 0}else{let{metric:e,identity:n,datapoint:i}=t,o=e?.name;r||(r={identity:n}),r.metrics=r.metrics??{},r.metrics[o]=r.metrics[o]??{definition:{...e},datapoints:[]},delete r.metrics[o].definition.name,r.metrics[o].datapoints.push(Rm(i))}r&&(yield r)}}var La,pi=ge(()=>{L(),me(),La=R("gateway.metrics.common")});async function wm(e,t,r){return Object.entries(t??{}).forEach(([t,r])=>e.searchParams.append(t,r)),new Worker(e,r)}function Wa({url:e,parameters:t,options:r}){return wm(e,t,r)}var Ja=ge(()=>{});async function Im(e,t){try{let e=await import(t);if("function"==typeof e)return await e();if("function"==typeof e.default)return await e.default()}catch(t){e.error("failed to load preload",t)}}async function Tm(e,t,r){e.debug(`loading publisher from ${t}`);let n=await import(t);return"object"==typeof n.default&&(n=n.default),await n.create(r,e.child(`publisher.${n.name??t}`))}var vr,ja$1=ge(()=>{vr=class{#e;#t;#o;constructor(e){this.#e=e}async#r(e){let t,{publishFn:r,cfg:n}=e;if(n?.preload){let e=await Im(this.#e,n.preload);if("object"==typeof e)for(let t in e)n[t]=e[t]}t="function"==typeof r?r:await Tm(this.#e,r,n);let i=await t("start");this.#t=t,this.#o=i}async#s(){let e=await(this.#t?.("stop"));"function"==typeof e&&await e(this.#o)}async#i(e){if(!this.#t)throw new Error("worker not started");await this.#t(e)}async execute(e,t){switch(e){case"start":await this.#r(t);break;case"stop":await this.#s();break;case"update":await this.#i(t)}}}});function mi(e,t,r){let n={identity:e,status:{...t,"updated-at":t.updated,"expires-at":t.expires}};return r&&(n.metadata=r),n}async function Ir(e,t,r){Y.info(`creating publisher with configuration\n${JSON.stringify(e,rt("authentication.password"))}`);try{let n=e?.worker;if(void 0===n)return await Mm(r,e??{},t);{let i=e?Object.fromEntries(Object.entries(e).filter(([e])=>"worker"!==e)):{};return await Pm(r,i,t,n)}}catch(e){throw Y.error("Failed to create basic publisher",e),e}}async function Mm(e,t,r){let n=new fi$1(t),i=e=>{for(let t of r([e]))n.next(t)};return await n.start(e),i.close=async()=>{await n.stop()},i.on=e=>{n.on(e)},i}async function Pm(e,t,r,n){let i=new gi(await Wa(n),t);await i.start(e);let o=e=>{for(let t of r([e]))i.next(t)};return o.close=async()=>{await i.stop()},o.on=e=>{i.on(e)},o}function Tr(e,t){return new yi(e,t)}var Y,li,yi,wr,fi$1,gi,hi=ge(()=>{Ja(),me(),ci(),ja$1(),Y=v$3("gateway.metrics.publisher"),li=class{constructor(e,t,r,n,i){this.publisher=e,this.filters=t,this.repoId=r,this.heartbeatInterval=n,this.metadata=i}running=!0;latestStatus={initial:!0,stopped:!1,status:{state:0,updated:Date.now(),description:"Running"}};heartbeatCleanup;metrics=new Map;start(){Y.info(`starting repository for ${JSON.stringify(this.repoId)} with heartbeat interval ${this.heartbeatInterval}ms`);let e=Date.now();if(this.latestStatus.stopped&&(this.latestStatus.status.state=0,this.latestStatus.status.description="Running",this.latestStatus.status.updated=e,this.latestStatus.initial=!0,this.latestStatus.stopped=!1),this.heartbeatInterval>=0){let t={...this.latestStatus.status,timestamp:e,expires:e+3*this.heartbeatInterval},r=mi(this.repoId,t,this.metadata);this.publisher(r)}this.running=!0,this.heartbeatInterval>0&&(this.heartbeatCleanup=setInterval(()=>{if(!this.running)return;let e=Date.now(),t={...this.latestStatus.status,timestamp:e,expires:e+3*this.heartbeatInterval},r=mi(this.repoId,t,this.metadata);this.publisher(r)},this.heartbeatInterval))}stop(){Y.info(`stopping repository for ${JSON.stringify(this.repoId)}`),this.running=!1,this.heartbeatCleanup&&clearInterval(this.heartbeatCleanup);let e=Date.now();this.latestStatus.stopped=!0,this.status({state:-1,timestamp:e,updated:e,expires:e,description:"Repository Stopped"})}add(e){for(let t of e){let e=t.name;this.metrics.has(e)||void 0!==this.filters&&!Nt(this.repoId,e,this.filters)||this.metrics.set(e,t)}}publish(e){if(this.running&&e.length>0)for(let t of e){let e=this.metrics.get(t.name);if(e){let r={identity:this.repoId,metric:e,datapoint:{...t}};delete r.datapoint.name,this.publisher(r)}}}status(e){let t={...this.latestStatus};Object.assign(t.status,e),t.timestamp=e.timestamp,t.expires=e.expires;let r=t.status.state!==this.latestStatus.status.state;if((this.latestStatus.initial||r)&&(t.status.updated=e.timestamp),t.initial=!1,Object.assign(this.latestStatus,t),this.running||t.stopped){let t=mi(this.repoId,e,this.metadata);this.publisher(t)}}},yi=class{constructor(e,t){this.config=e,this.publisher=t}repository(e,t){let r=t?.metadata,n=this.config?.heartbeats??0;return new li(this.publisher,this.config?.filters,e,n,r)}async shutdown(){await this.publisher.close()}on(e){this.publisher.on(e)}},wr=class{#e;#t;#o;#r;#s;#i;constructor(e){let{buffer_size:t}=e;this.#e=e,this.#t=t??1e3,this.#o=new Map,this.#r=new Map,this.#s=[],this.#i=0}async start(e){try{await this.enqueue("start",{cfg:this.#e,publishFn:e})[1],Y.info(`publisher [${e}] started`)}catch(t){throw Y.error(`error starting publisher [${e}]: ${t}`),t}}next(e){let[t,r]=this.enqueue("update",e);r.catch(e=>{Y.warn(`update [${t}] error`,e)}).finally(()=>{this.#r.delete(t)})}async stop(e=!1,t=1e3){Y.info(`stopping publisher worker rejectProcessing: ${e}, timeout: ${t}, promises: ${this.#r.size}`);let r=e=>{this.#o.forEach(({resolver:t})=>{t.reject(new Error(`reject on stop: ${e}`))})};e&&r("now");let n=Promise.allSettled(this.#r),i=this.enqueue("stop",void 0)[1];await new Promise((e,i)=>{let o=setTimeout(()=>{r("timeout"),i(new Error("timeout"))},t);n.then(t=>{clearTimeout(o);for(let e of t)"rejected"===e.status&&Y.error(`Pending future failed with ${e.reason} on stop`);e()})}),await i,this.#r.size>0&&Y.error(`uncleared promises: ${this.#r.size}`),Y.info("publisher worker stopped")}enqueue(e,t){this.#o.size>=this.#t&&Y.warn(`processing queue is full. dropping cmd: ${JSON.stringify(e)}`);let r=++this.#i;return[r,new Promise((n,i)=>{this.#o.set(r,{resolver:{resolve:n,reject:i}}),this.processRequest(r,e,t)})]}processResult(e,t,r){let n=this.#o.get(e);if(n){let{resolver:i}=n;try{r?i.reject(r):i.resolve(t)}finally{this.#o.delete(e)}}else Y.error(`unknown message id: ${e}`)}emit(e){this.#s.forEach(t=>t(e))}on(e){this.#s.push(e)}},fi$1=class extends wr{#e;constructor(e){super(e),this.#e=new vr(Y)}processRequest(e,t,r){this.#e.execute(t,r).then(()=>{this.processResult(e,"ok")}).catch(t=>{this.processResult(e,"error",t instanceof Error?t:new Error(String(t)))})}},gi=class extends wr{worker;constructor(e,t){super(t),this.worker=e}processRequest(e,t,r){let n={id:e,cmd:t,arg:r};this.worker.postMessage(n)}async stop(e=!1,t=1e3){try{return await super.stop(e,t)}finally{this.worker.terminate()}}async start(e){await new Promise(e=>{this.worker.onerror=e=>{Y.error(`error from worker: ${e.message}`)},this.worker.onmessageerror=e=>{Y.error(`error receiving message: ${e.data}`)},this.worker.onmessage=t=>{if(t.data.ready)e();else if(t.data.id){let{id:e,result:r,error:n}=t.data;super.processResult(e,r,null==n?void 0:deserializeError(n))}else if(t.data.log){let{level:e,time:r,name:n,message:i,data:o}=t.data.log;E$2({level:e,time:new Date(r),name:n,message:i,data:o.map(e=>deserializeError(e))})}else t.data.event&&super.emit(t.data.event)}});try{await super.start(e),Y.info(`publisher worker [${e}] started`)}catch(t){throw Y.error(`error starting publisher worker [${e}]: ${t}`),this.worker.terminate(),t}}}}),za={};async function Va(e){let t=e?.conflation?.["max-datapoints-repo"]??50;return await Ir(e,e=>Sr(t,e),e?.publishFn??"@interopio/gateway/metrics/publisher/rest")}async function Dm(e){return Tr(e,await Va(e))}Ht(za,{restPublisher:()=>Va,restRepositoryFactory:()=>Dm});var Qa=ge(()=>{hi(),pi()}),Oc={};Ht(Oc,{Encoding:()=>Xe,Factory:()=>qi,Filtering:()=>jr,Logging:()=>my});var Xe={};Ht(Xe,{direct:()=>Wr,json:()=>Gr,transit:()=>Fr});var Ur=class{map;reverse=new Map;constructor(e){if(e)for(let[t,r]of e)this.reverse.set(r,t);else e=this.reverse;this.map=e}get(e){return this.map.get(e)}rev(e){return this.reverse.get(e)}};function $i(e,t){let r=e.indexOf("/");if(-1===r)return Ce$1.keyword(e);let n=e.substring(0,r),i=t?.get(n)??n;return Ce$1.keyword(i+e.substring(r))}function Ei(e,t){let r=e.name(),n=e.namespace();return null===n?r:(t.rev(n)??n)+"/"+r}function Hi(e,t,r,n=""){if(e instanceof Array)return e.map(e=>e);if(e instanceof Object){let i=Ce$1.map();for(let o in e){let s=r?.get(n),a=null===s?o:$i(o,t),c=e[o],l=`${n}/${o}`,u=r?.get(l);if(void 0===u||"string"!=typeof c||"*"!==u&&!u?.has(c)){null===s&&!r?.has(l)&&r?.set(l,null);let e=Hi(c,t,r,l);i.set(a,e)}else i.set(a,$i(c,t))}return i}return e}function Hr(e,t){if(Ce$1.isKeyword(e))return Ei(e,t);if(Ce$1.isMap(e)){let r={};for(let[n,i]of e){r[Ce$1.isKeyword(n)?Ei(n,t):n]=Hr(i,t)}return r}if(Ce$1.isList(e)||e instanceof Array){let r=[];for(let n of e)r.push(Hr(n,t));return r}return e}function Fr(e){let t=e?.verbose?"json-verbose":"json",r=new Ur(e?.namespaces);return{encode:n=>{let i=Hi(n,r,e?.keywordize);return Ce$1.writer(t).write(i)},decode:e=>{let n;try{n=Ce$1.reader(t).read(e)}catch(t){throw new Error(`"${e}" is not valid TRANSIT`,{cause:t})}return Hr(n,r)}}}function Gr(){return{encode:JSON.stringify,decode:JSON.parse}}function Ui(e){return e}function Lr(e){return e instanceof Array||Array.isArray(e)?e.map(Lr):e?.constructor===Object?Object.keys(e).reduce((t,r)=>(t[r]=Lr(e[r]),t),{}):void 0===e?null:e}function Wr(e){return{encode:Ui,decode:e?.cljs?Lr:Ui}}Ft(),L();var Se="global",se="context",Ne=`${Se}.errors.failure`;function x(e,t){return{receiver:e,body:t}}function G(e,t){return{...x({type:"cluster"},t),source:e}}function K(e,t,r){return{...x(t,r),source:e}}function Uc(e,t,r,n,i){let o={type:"error",request_id:t,reason_uri:n.uri,reason:n.message};return e&&(o.domain=e),r&&(o.peer_id=r),i&&(o.context=i),o}function h(e,t,r,n,i,o){return x(t,Uc(e,r,n,i,o))}function Hc(e,t,r){return{type:"success",request_id:t,domain:e,peer_id:r}}function I(e,t,r,n){return x(t,Hc(e,r,n))}function T(e){let t=e.type;return t&&"local"===t}function W(e){return!T(e)}function Lc(e,t,r,n){return{domain:e,type:"token",request_id:t,peer_id:r,token:n}}function Gi(e,t,r,n,i){return x(t,Lc(e,r,n,i))}function Fc(e,t,r,n,i){return{domain:e,type:"peer-added",peer_id:t,new_peer_id:r,identity:n,meta:i}}function qe(e,t,r,n,i,o){return x(t,Fc(e,r,n,i,o))}function Gc(e,t,r,n){return{domain:e,type:"peer-removed",peer_id:t,removed_id:r,reason_uri:n.uri,reason:n.message}}function Je(e,t,r,n,i){return x(t,Gc(e,r,n,i))}L();var ve=class extends Error{data;cause;constructor(e,t,r){super(e),this.name="ExceptionInfo",this.data=t,this.cause=r}};function V(e,t,r){return new ve(e,t,r)}function je(e){if(e instanceof ve)return e.data}function Be(e){if(e instanceof Error)return e.message}function S(e,t){return{uri:e,message:t}}function J(e,t){let r=je(e);return{uri:r?.uri??t,message:r?.message??Be(e)??""}}function k(e,t){throw new ve(t,{uri:e,message:t})}function Q(e){return{uri:e.reason_uri,message:e.reason}}var M=class e extends xn$1{static OR=1;static AND=2;static EQ=3;static NEQ=4;static MATCH=5;static LPAREN=6;static RPAREN=7;static DOLLAR=8;static POUND=9;static STR=10;static WORD=11;static NUMBER=12;static WS=13;static EOF=kn$1.EOF;static RULE_parse=0;static RULE_expr=1;static RULE_andOr=2;static RULE_eqNeq=3;static RULE_term=4;static RULE_ident=5;static RULE_ownIdent=6;static RULE_str=7;static RULE_word=8;static RULE_number=9;static literalNames=[null,"'||'","'&&'","'=='","'!='","'?'","'('","')'","'$'","'#'"];static symbolicNames=[null,"OR","AND","EQ","NEQ","MATCH","LPAREN","RPAREN","DOLLAR","POUND","STR","WORD","NUMBER","WS"];static ruleNames=["parse","expr","andOr","eqNeq","term","ident","ownIdent","str","word","number"];get grammarFileName(){return"Restrictions.g4"}get literalNames(){return e.literalNames}get symbolicNames(){return e.symbolicNames}get ruleNames(){return e.ruleNames}get serializedATN(){return e._serializedATN}createFailedPredicateException(e,t){return new sn$1(this,e,t)}constructor(t){super(t),this._interp=new Tn$1(this,e._ATN,e.DecisionsToDFA,new mn$1)}parse(){let t=new Br(this,this._ctx,this.state);this.enterRule(t,0,e.RULE_parse);try{this.enterOuterAlt(t,1),this.state=20,this.expr(),this.state=21,this.match(e.EOF)}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}expr(){let t=new Gt(this,this._ctx,this.state);this.enterRule(t,2,e.RULE_expr);try{this.enterOuterAlt(t,1),this.state=23,this.andOr(0)}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}andOr(t){void 0===t&&(t=0);let r=this._ctx,n=this.state,i=new fe(this,this._ctx,n),o=i;this.enterRecursionRule(i,4,e.RULE_andOr,t);try{let t;for(this.enterOuterAlt(i,1),i=new Kr(this,i),this._ctx=i,o=i,this.state=26,this.eqNeq(0),this._ctx.stop=this._input.LT(-1),this.state=36,this._errHandler.sync(this),t=this._interp.adaptivePredict(this._input,1,this._ctx);2!==t&&t!==Ge$1.INVALID_ALT_NUMBER;){if(1===t)switch(null!=this._parseListeners&&this.triggerExitRuleEvent(),o=i,this.state=34,this._errHandler.sync(this),this._interp.adaptivePredict(this._input,0,this._ctx)){case 1:if(i=new zr(this,new fe(this,r,n)),this.pushNewRecursionContext(i,4,e.RULE_andOr),this.state=28,!this.precpred(this._ctx,2))throw this.createFailedPredicateException("this.precpred(this._ctx, 2)");this.state=29,this.match(e.AND),this.state=30,this.eqNeq(0);break;case 2:if(i=new Vr(this,new fe(this,r,n)),this.pushNewRecursionContext(i,4,e.RULE_andOr),this.state=31,!this.precpred(this._ctx,1))throw this.createFailedPredicateException("this.precpred(this._ctx, 1)");this.state=32,this.match(e.OR),this.state=33,this.eqNeq(0)}this.state=38,this._errHandler.sync(this),t=this._interp.adaptivePredict(this._input,1,this._ctx)}}catch(e){if(!(e instanceof _n$1))throw e;i.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.unrollRecursionContexts(r)}return i}eqNeq(t){void 0===t&&(t=0);let r=this._ctx,n=this.state,i=new Z(this,this._ctx,n),o=i;this.enterRecursionRule(i,6,e.RULE_eqNeq,t);try{let t;for(this.enterOuterAlt(i,1),i=new Xr(this,i),this._ctx=i,o=i,this.state=40,this.term(),this._ctx.stop=this._input.LT(-1),this.state=53,this._errHandler.sync(this),t=this._interp.adaptivePredict(this._input,3,this._ctx);2!==t&&t!==Ge$1.INVALID_ALT_NUMBER;){if(1===t)switch(null!=this._parseListeners&&this.triggerExitRuleEvent(),o=i,this.state=51,this._errHandler.sync(this),this._interp.adaptivePredict(this._input,2,this._ctx)){case 1:if(i=new Zr(this,new Z(this,r,n)),this.pushNewRecursionContext(i,6,e.RULE_eqNeq),this.state=42,!this.precpred(this._ctx,3))throw this.createFailedPredicateException("this.precpred(this._ctx, 3)");this.state=43,this.match(e.EQ),this.state=44,this.term();break;case 2:if(i=new Yr(this,new Z(this,r,n)),this.pushNewRecursionContext(i,6,e.RULE_eqNeq),this.state=45,!this.precpred(this._ctx,2))throw this.createFailedPredicateException("this.precpred(this._ctx, 2)");this.state=46,this.match(e.NEQ),this.state=47,this.term();break;case 3:if(i=new Qr(this,new Z(this,r,n)),this.pushNewRecursionContext(i,6,e.RULE_eqNeq),this.state=48,!this.precpred(this._ctx,1))throw this.createFailedPredicateException("this.precpred(this._ctx, 1)");this.state=49,this.match(e.MATCH),this.state=50,this.term()}this.state=55,this._errHandler.sync(this),t=this._interp.adaptivePredict(this._input,3,this._ctx)}}catch(e){if(!(e instanceof _n$1))throw e;i.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.unrollRecursionContexts(r)}return i}term(){let t=new Ke(this,this._ctx,this.state);this.enterRule(t,8,e.RULE_term);try{switch(this.enterOuterAlt(t,1),this.state=64,this._errHandler.sync(this),this._interp.adaptivePredict(this._input,4,this._ctx)){case 1:this.state=56,this.ident();break;case 2:this.state=57,this.ownIdent();break;case 3:this.state=58,this.number_();break;case 4:this.state=59,this.str();break;case 5:this.state=60,this.match(e.LPAREN),this.state=61,this.andOr(0),this.state=62,this.match(e.RPAREN)}}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}ident(){let t=new Wt(this,this._ctx,this.state);this.enterRule(t,10,e.RULE_ident);try{this.enterOuterAlt(t,1),this.state=66,this.match(e.DOLLAR),this.state=67,this.word()}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}ownIdent(){let t=new Jt(this,this._ctx,this.state);this.enterRule(t,12,e.RULE_ownIdent);try{this.enterOuterAlt(t,1),this.state=69,this.match(e.POUND),this.state=70,this.word()}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}str(){let t,r=new jt(this,this._ctx,this.state);this.enterRule(r,14,e.RULE_str);try{for(this.enterOuterAlt(r,1),this.state=75,this._errHandler.sync(this),t=this._input.LA(1);13===t;)this.state=72,this.match(e.WS),this.state=77,this._errHandler.sync(this),t=this._input.LA(1);this.state=78,this.match(e.STR)}catch(e){if(!(e instanceof _n$1))throw e;r.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return r}word(){let t=new Rt(this,this._ctx,this.state);this.enterRule(t,16,e.RULE_word);try{this.enterOuterAlt(t,1),this.state=80,this.match(e.WORD)}catch(e){if(!(e instanceof _n$1))throw e;t.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return t}number_(){let t,r=new Bt(this,this._ctx,this.state);this.enterRule(r,18,e.RULE_number);try{for(this.enterOuterAlt(r,1),this.state=85,this._errHandler.sync(this),t=this._input.LA(1);13===t;)this.state=82,this.match(e.WS),this.state=87,this._errHandler.sync(this),t=this._input.LA(1);this.state=88,this.match(e.NUMBER)}catch(e){if(!(e instanceof _n$1))throw e;r.exception=e,this._errHandler.reportError(this,e),this._errHandler.recover(this,e)}finally{this.exitRule()}return r}sempred(e,t,r){switch(t){case 2:return this.andOr_sempred(e,r);case 3:return this.eqNeq_sempred(e,r)}return!0}andOr_sempred(e,t){switch(t){case 0:return this.precpred(this._ctx,2);case 1:return this.precpred(this._ctx,1)}return!0}eqNeq_sempred(e,t){switch(t){case 2:return this.precpred(this._ctx,3);case 3:return this.precpred(this._ctx,2);case 4:return this.precpred(this._ctx,1)}return!0}static _serializedATN=[4,1,13,91,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,1,0,1,0,1,0,1,1,1,1,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,5,2,35,8,2,10,2,12,2,38,9,2,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,5,3,52,8,3,10,3,12,3,55,9,3,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,3,4,65,8,4,1,5,1,5,1,5,1,6,1,6,1,6,1,7,5,7,74,8,7,10,7,12,7,77,9,7,1,7,1,7,1,8,1,8,1,9,5,9,84,8,9,10,9,12,9,87,9,9,1,9,1,9,1,9,0,2,4,6,10,0,2,4,6,8,10,12,14,16,18,0,0,91,0,20,1,0,0,0,2,23,1,0,0,0,4,25,1,0,0,0,6,39,1,0,0,0,8,64,1,0,0,0,10,66,1,0,0,0,12,69,1,0,0,0,14,75,1,0,0,0,16,80,1,0,0,0,18,85,1,0,0,0,20,21,3,2,1,0,21,22,5,0,0,1,22,1,1,0,0,0,23,24,3,4,2,0,24,3,1,0,0,0,25,26,6,2,-1,0,26,27,3,6,3,0,27,36,1,0,0,0,28,29,10,2,0,0,29,30,5,2,0,0,30,35,3,6,3,0,31,32,10,1,0,0,32,33,5,1,0,0,33,35,3,6,3,0,34,28,1,0,0,0,34,31,1,0,0,0,35,38,1,0,0,0,36,34,1,0,0,0,36,37,1,0,0,0,37,5,1,0,0,0,38,36,1,0,0,0,39,40,6,3,-1,0,40,41,3,8,4,0,41,53,1,0,0,0,42,43,10,3,0,0,43,44,5,3,0,0,44,52,3,8,4,0,45,46,10,2,0,0,46,47,5,4,0,0,47,52,3,8,4,0,48,49,10,1,0,0,49,50,5,5,0,0,50,52,3,8,4,0,51,42,1,0,0,0,51,45,1,0,0,0,51,48,1,0,0,0,52,55,1,0,0,0,53,51,1,0,0,0,53,54,1,0,0,0,54,7,1,0,0,0,55,53,1,0,0,0,56,65,3,10,5,0,57,65,3,12,6,0,58,65,3,18,9,0,59,65,3,14,7,0,60,61,5,6,0,0,61,62,3,4,2,0,62,63,5,7,0,0,63,65,1,0,0,0,64,56,1,0,0,0,64,57,1,0,0,0,64,58,1,0,0,0,64,59,1,0,0,0,64,60,1,0,0,0,65,9,1,0,0,0,66,67,5,8,0,0,67,68,3,16,8,0,68,11,1,0,0,0,69,70,5,9,0,0,70,71,3,16,8,0,71,13,1,0,0,0,72,74,5,13,0,0,73,72,1,0,0,0,74,77,1,0,0,0,75,73,1,0,0,0,75,76,1,0,0,0,76,78,1,0,0,0,77,75,1,0,0,0,78,79,5,10,0,0,79,15,1,0,0,0,80,81,5,11,0,0,81,17,1,0,0,0,82,84,5,13,0,0,83,82,1,0,0,0,84,87,1,0,0,0,85,83,1,0,0,0,85,86,1,0,0,0,86,88,1,0,0,0,87,85,1,0,0,0,88,89,5,12,0,0,89,19,1,0,0,0,7,34,36,51,53,64,75,85];static __ATN;static get _ATN(){return e.__ATN||(e.__ATN=(new We$1).deserialize(e._serializedATN)),e.__ATN}static DecisionsToDFA=e._ATN.decisionToState.map((e,t)=>new Qe$1(e,t))},Br=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}expr(){return this.getTypedRuleContext(Gt,0)}EOF(){return this.getToken(M.EOF,0)}get ruleIndex(){return M.RULE_parse}enterRule(e){e.enterParse&&e.enterParse(this)}exitRule(e){e.exitParse&&e.exitParse(this)}accept(e){return e.visitParse?e.visitParse(this):e.visitChildren(this)}},Gt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}andOr(){return this.getTypedRuleContext(fe,0)}get ruleIndex(){return M.RULE_expr}enterRule(e){e.enterExpr&&e.enterExpr(this)}exitRule(e){e.exitExpr&&e.exitExpr(this)}accept(e){return e.visitExpr?e.visitExpr(this):e.visitChildren(this)}},fe=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}get ruleIndex(){return M.RULE_andOr}copyFrom(e){super.copyFrom(e)}},Kr=class extends fe{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}eqNeq(){return this.getTypedRuleContext(Z,0)}enterRule(e){e.enterAndOrEqNeq&&e.enterAndOrEqNeq(this)}exitRule(e){e.exitAndOrEqNeq&&e.exitAndOrEqNeq(this)}accept(e){return e.visitAndOrEqNeq?e.visitAndOrEqNeq(this):e.visitChildren(this)}},Vr=class extends fe{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}andOr(){return this.getTypedRuleContext(fe,0)}OR(){return this.getToken(M.OR,0)}eqNeq(){return this.getTypedRuleContext(Z,0)}enterRule(e){e.enterOr&&e.enterOr(this)}exitRule(e){e.exitOr&&e.exitOr(this)}accept(e){return e.visitOr?e.visitOr(this):e.visitChildren(this)}},zr=class extends fe{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}andOr(){return this.getTypedRuleContext(fe,0)}AND(){return this.getToken(M.AND,0)}eqNeq(){return this.getTypedRuleContext(Z,0)}enterRule(e){e.enterAnd&&e.enterAnd(this)}exitRule(e){e.exitAnd&&e.exitAnd(this)}accept(e){return e.visitAnd?e.visitAnd(this):e.visitChildren(this)}},Z=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}get ruleIndex(){return M.RULE_eqNeq}copyFrom(e){super.copyFrom(e)}},Qr=class extends Z{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}eqNeq(){return this.getTypedRuleContext(Z,0)}MATCH(){return this.getToken(M.MATCH,0)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterMatch&&e.enterMatch(this)}exitRule(e){e.exitMatch&&e.exitMatch(this)}accept(e){return e.visitMatch?e.visitMatch(this):e.visitChildren(this)}},Yr=class extends Z{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}eqNeq(){return this.getTypedRuleContext(Z,0)}NEQ(){return this.getToken(M.NEQ,0)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterNeq&&e.enterNeq(this)}exitRule(e){e.exitNeq&&e.exitNeq(this)}accept(e){return e.visitNeq?e.visitNeq(this):e.visitChildren(this)}},Zr=class extends Z{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}eqNeq(){return this.getTypedRuleContext(Z,0)}EQ(){return this.getToken(M.EQ,0)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterEq&&e.enterEq(this)}exitRule(e){e.exitEq&&e.exitEq(this)}accept(e){return e.visitEq?e.visitEq(this):e.visitChildren(this)}},Xr=class extends Z{constructor(e,t){super(e,t.parentCtx,t.invokingState),super.copyFrom(t)}term(){return this.getTypedRuleContext(Ke,0)}enterRule(e){e.enterEqNeqTerm&&e.enterEqNeqTerm(this)}exitRule(e){e.exitEqNeqTerm&&e.exitEqNeqTerm(this)}accept(e){return e.visitEqNeqTerm?e.visitEqNeqTerm(this):e.visitChildren(this)}},Ke=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}ident(){return this.getTypedRuleContext(Wt,0)}ownIdent(){return this.getTypedRuleContext(Jt,0)}number_(){return this.getTypedRuleContext(Bt,0)}str(){return this.getTypedRuleContext(jt,0)}LPAREN(){return this.getToken(M.LPAREN,0)}andOr(){return this.getTypedRuleContext(fe,0)}RPAREN(){return this.getToken(M.RPAREN,0)}get ruleIndex(){return M.RULE_term}enterRule(e){e.enterTerm&&e.enterTerm(this)}exitRule(e){e.exitTerm&&e.exitTerm(this)}accept(e){return e.visitTerm?e.visitTerm(this):e.visitChildren(this)}},Wt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}DOLLAR(){return this.getToken(M.DOLLAR,0)}word(){return this.getTypedRuleContext(Rt,0)}get ruleIndex(){return M.RULE_ident}enterRule(e){e.enterIdent&&e.enterIdent(this)}exitRule(e){e.exitIdent&&e.exitIdent(this)}accept(e){return e.visitIdent?e.visitIdent(this):e.visitChildren(this)}},Jt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}POUND(){return this.getToken(M.POUND,0)}word(){return this.getTypedRuleContext(Rt,0)}get ruleIndex(){return M.RULE_ownIdent}enterRule(e){e.enterOwnIdent&&e.enterOwnIdent(this)}exitRule(e){e.exitOwnIdent&&e.exitOwnIdent(this)}accept(e){return e.visitOwnIdent?e.visitOwnIdent(this):e.visitChildren(this)}},jt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}STR(){return this.getToken(M.STR,0)}WS_list(){return this.getTokens(M.WS)}WS(e){return this.getToken(M.WS,e)}get ruleIndex(){return M.RULE_str}enterRule(e){e.enterStr&&e.enterStr(this)}exitRule(e){e.exitStr&&e.exitStr(this)}accept(e){return e.visitStr?e.visitStr(this):e.visitChildren(this)}},Rt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}WORD(){return this.getToken(M.WORD,0)}get ruleIndex(){return M.RULE_word}enterRule(e){e.enterWord&&e.enterWord(this)}exitRule(e){e.exitWord&&e.exitWord(this)}accept(e){return e.visitWord?e.visitWord(this):e.visitChildren(this)}},Bt=class extends Sn$1{constructor(e,t,r){super(t,r),this.parser=e}NUMBER(){return this.getToken(M.NUMBER,0)}WS_list(){return this.getTokens(M.WS)}WS(e){return this.getToken(M.WS,e)}get ruleIndex(){return M.RULE_number}enterRule(e){e.enterNumber&&e.enterNumber(this)}exitRule(e){e.exitNumber&&e.exitNumber(this)}accept(e){return e.visitNumber?e.visitNumber(this):e.visitChildren(this)}},xt=class e extends cn$1{static OR=1;static AND=2;static EQ=3;static NEQ=4;static MATCH=5;static LPAREN=6;static RPAREN=7;static DOLLAR=8;static POUND=9;static STR=10;static WORD=11;static NUMBER=12;static WS=13;static EOF=kn$1.EOF;static channelNames=["DEFAULT_TOKEN_CHANNEL","HIDDEN"];static literalNames=[null,"'||'","'&&'","'=='","'!='","'?'","'('","')'","'$'","'#'"];static symbolicNames=[null,"OR","AND","EQ","NEQ","MATCH","LPAREN","RPAREN","DOLLAR","POUND","STR","WORD","NUMBER","WS"];static modeNames=["DEFAULT_MODE"];static ruleNames=["OR","AND","EQ","NEQ","MATCH","LPAREN","RPAREN","DOLLAR","POUND","STR","WORD","NUMBER","WS"];constructor(t){super(t),this._interp=new un$1(this,e._ATN,e.DecisionsToDFA,new mn$1)}get grammarFileName(){return"Restrictions.g4"}get literalNames(){return e.literalNames}get symbolicNames(){return e.symbolicNames}get ruleNames(){return e.ruleNames}get serializedATN(){return e._serializedATN}get channelNames(){return e.channelNames}get modeNames(){return e.modeNames}static _serializedATN=[4,0,13,86,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,1,0,1,0,1,0,1,1,1,1,1,1,1,2,1,2,1,2,1,3,1,3,1,3,1,4,1,4,1,5,1,5,1,6,1,6,1,7,1,7,1,8,1,8,1,9,1,9,4,9,52,8,9,11,9,12,9,53,1,9,1,9,1,10,4,10,59,8,10,11,10,12,10,60,1,11,3,11,64,8,11,1,11,5,11,67,8,11,10,11,12,11,70,9,11,1,11,3,11,73,8,11,1,11,4,11,76,8,11,11,11,12,11,77,1,12,4,12,81,8,12,11,12,12,12,82,1,12,1,12,0,0,13,1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,1,0,5,1,0,39,39,4,0,45,45,65,90,95,95,97,122,2,0,43,43,45,45,1,0,48,57,2,0,9,9,32,32,92,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,1,27,1,0,0,0,3,30,1,0,0,0,5,33,1,0,0,0,7,36,1,0,0,0,9,39,1,0,0,0,11,41,1,0,0,0,13,43,1,0,0,0,15,45,1,0,0,0,17,47,1,0,0,0,19,49,1,0,0,0,21,58,1,0,0,0,23,63,1,0,0,0,25,80,1,0,0,0,27,28,5,124,0,0,28,29,5,124,0,0,29,2,1,0,0,0,30,31,5,38,0,0,31,32,5,38,0,0,32,4,1,0,0,0,33,34,5,61,0,0,34,35,5,61,0,0,35,6,1,0,0,0,36,37,5,33,0,0,37,38,5,61,0,0,38,8,1,0,0,0,39,40,5,63,0,0,40,10,1,0,0,0,41,42,5,40,0,0,42,12,1,0,0,0,43,44,5,41,0,0,44,14,1,0,0,0,45,46,5,36,0,0,46,16,1,0,0,0,47,48,5,35,0,0,48,18,1,0,0,0,49,51,7,0,0,0,50,52,8,0,0,0,51,50,1,0,0,0,52,53,1,0,0,0,53,51,1,0,0,0,53,54,1,0,0,0,54,55,1,0,0,0,55,56,7,0,0,0,56,20,1,0,0,0,57,59,7,1,0,0,58,57,1,0,0,0,59,60,1,0,0,0,60,58,1,0,0,0,60,61,1,0,0,0,61,22,1,0,0,0,62,64,7,2,0,0,63,62,1,0,0,0,63,64,1,0,0,0,64,68,1,0,0,0,65,67,7,3,0,0,66,65,1,0,0,0,67,70,1,0,0,0,68,66,1,0,0,0,68,69,1,0,0,0,69,72,1,0,0,0,70,68,1,0,0,0,71,73,9,0,0,0,72,71,1,0,0,0,72,73,1,0,0,0,73,75,1,0,0,0,74,76,7,3,0,0,75,74,1,0,0,0,76,77,1,0,0,0,77,75,1,0,0,0,77,78,1,0,0,0,78,24,1,0,0,0,79,81,7,4,0,0,80,79,1,0,0,0,81,82,1,0,0,0,82,80,1,0,0,0,82,83,1,0,0,0,83,84,1,0,0,0,84,85,6,12,0,0,85,26,1,0,0,0,8,0,53,60,63,68,72,77,82,1,6,0,0];static __ATN;static get _ATN(){return e.__ATN||(e.__ATN=(new We$1).deserialize(e._serializedATN)),e.__ATN}static DecisionsToDFA=e._ATN.decisionToState.map((e,t)=>new Qe$1(e,t))},St=class extends pn$1{visitParse;visitExpr;visitAndOrEqNeq;visitOr;visitAnd;visitMatch;visitNeq;visitEq;visitEqNeqTerm;visitTerm;visitIdent;visitOwnIdent;visitStr;visitWord;visitNumber},N=new St,et=e=>{let t=N.visitChildren(e);return 1==t.length?t[0]:t};N.visitParse=e=>e.expr().accept(N),N.visitExpr=e=>["expr",et(e)],N.visitAndOrEqNeq=et,N.visitEqNeqTerm=et,N.visitTerm=e=>3===e.getChildCount()?N.visit(e.getChild(1)):et(e),N.visitEq=e=>["eq",et(e.eqNeq()),e.term().accept(N)],N.visitNeq=e=>["neq",et(e.eqNeq()),e.term().accept(N)],N.visitMatch=e=>["match",N.visitChildren(e.eqNeq())[0],e.term().accept(N)],N.visitAnd=e=>{let t=N.visitChildren(e.andOr()),r=N.visitChildren(e.eqNeq());return["and",t[0],r[0]]},N.visitIdent=e=>["ident",e.word().accept(N)],N.visitOwnIdent=e=>["own-ident",e.word().accept(N)],N.visitWord=e=>["word",e.WORD().symbol.text],N.visitNumber=e=>["number",e.NUMBER().symbol.text],N.visitStr=e=>["str",e.STR().symbol.text.slice(1,-1)];var ji=N;function Bi(e){let t=Xe$1.fromString(e),r=new xt(t),n=new Ze$1(r);return new M(n).parse().accept(ji)}function en$1(e,t){if(Array.isArray(t)){let[r,...n]=t,i=e[r];if(i){let t=n.map(t=>en$1(e,t));return i.apply(e,t)}let o=n.map(t=>en$1(e,t));return[r].concat(o)}return t}function Ki(e,t,r){return!((e?.length??0)>0)||en$1({and:(e,t)=>e&&t,or:(e,t)=>e||t,eq:(e,t)=>e===t,neq:(e,t)=>e!==t,match:(e,t)=>t&&e?new RegExp(t).test(e):e,str:e=>e,number:e=>JSON.parse(e),expr:e=>e,"own-ident":([e,r])=>t[r],ident:([e,t])=>r[t]},e)}function X(e){return"string"==typeof e?"cluster"===e||"local"===e?e:Bi(e):e}function ee(e,t,r){let[n,i]=t,[o,s]=r;switch(e){case"local":return n?"local"===n.type?"local"===o?.type:"peer"!==n.type||"peer"===o?.type&&o?.node===n?.node:void 0===o||"local"===o.type;case"cluster":return!0;default:return"cluster"===o?.type||!!Ki(e,i,s)}}if(void 0===globalThis.crypto)throw new Error("Crypto API is not available. If Running Node 18, try --experimental-global-webcrypto.");function Me(e=globalThis.crypto){return e.randomUUID().replaceAll("-","")}function A(e){return e?e.nodeId:Me()}function Pe(e){let t=e.currentId??1,r=`r-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function Vi(e){let t=e.currentId??1,r=`i-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function Kt(e){let t=e.currentId??1,r=`c-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function zi(e){let t=e.currentId??1,r=`a-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function Qi(e){let t=e.currentId??1,r=`p-${e.nodeId}-${t}`;return[{...e,currentId:t+1},r]}function zt(e,t){return{ids:{nodeId:e,currentId:1},signatureKey:t??Me()}}function he$1(e,t,r,n){return produce(e,e=>{e.peers[t][r]=n?{restrictions:n}:{},e.domains=e.domains||{},e.domains[r]=e.domains[r]||new Set,e.domains[r].add(t)})}function te(e,t,r){return produce(e,e=>{e.peers&&delete e.peers[t][r],e.domains&&e.domains[r]&&e.domains[r].delete(t)})}function de$1(e,t,r){return!!e.domains?.[r]?.has(t)}function Yi(e,t){return!!e[t]}function rn(e,t,r){return t?produce(e,e=>{e.gatewayRequests=e.gatewayRequests||{},e.gatewayRequests[t]=r}):e}function tt(e,t){return produce({state:e},e=>{e.state.gatewayRequests&&(e.removed=e.state.gatewayRequests[t],delete e.state.gatewayRequests[t],0===Object.keys(e.state.gatewayRequests).length&&delete e.state.gatewayRequests)})}function vt(e,t){return e.registeredDomains?.[t]?.domain}function ue(e,...t){return t.reduce(([e,t],r)=>{let[n,i]=r(e);return[n,t.concat(i)]},[e,[]])}function eo$1(e,t){switch(t.type){case"node":return t.node===e.node;case"peer":return t.node===e.node&&t.peer===e.peer;case"local":return t.receive===e.receive;default:return!1}}function Te(e,t,r){return ne(e,r).filter(e=>eo$1(e.source,t))}function to(e,t){return pd(e).filter(e=>eo$1(e.source,t))}function B(e,t,r){let n=g$2(e,t);if(n?.[r])return n}function g$2(e,t){return t?e.peers?.[t]:void 0}function _(e,t){if(t){let r=g$2(e,t);if(r)return r;throw V(`Unable to find peer ${t}`,{})}throw V("Peer id is missing",{})}function b(e,t,r){if(t){let n=B(e,t,r);if(n)return n;throw V(`Unable to find peer ${t} in domain ${r}`,{})}throw V("Peer id is missing",{})}function q(e){return"local"===e?.source.type}function re(e,t,r){return ee(t?.[e]?.restrictions,[t?.source,t?.identity],[{type:"cluster"},r])}function ro(e,t){let r=nt(t);return e.identities?.get(r)}function pd(e){return Object.values(e.peers||{})}function ne(e,t){return Array.from(e.domains?.[t]??[],r=>B(e,r,t)).filter(pe)}function sn(e,t,r,n,i,o){let s=g$2(e,r);if(s)return[e,s];let a=produce({id:r,identity:n,source:t},e=>{o&&(e.options=o),i&&(e.creationRequest=i)});return[produce(e,e=>{if(e.users=e.users||{},n.user){e.users.byName=e.users.byName||new Map;let t=e.users.byName.get(n.user);t?t.add(r):e.users.byName.set(n.user,new Set([r]))}else e.users.noUser=e.users.noUser||new Set,e.users.noUser.add(r);e.identities=e.identities||new Map,e.identities.set(nt(n),r),e.peers=e.peers||{},e.peers[r]=castDraft(a),o?.service&&(e.services=e.services||new Set,e.services.add(r))}),a]}function no$1(e,t){let r=t.identity,n=t.id,i=r.user;return produce(e,e=>{if(e.identities&&e.identities.delete(nt(r)),e.users)if(i){let t=e.users.byName?.get(i);t&&(t.delete(n),0==t.size&&e.users.byName?.delete(i)),e.users.byName&&0===e.users.byName.size&&delete e.users.byName}else e.users.noUser?.delete(n),0===e.users.noUser?.size&&delete e.users.noUser;e.peers&&delete e.peers[n],e.services=e.services||new Set,e.services&&e.services.delete(n)})}function C(e,t,r){return produce(e,e=>{e.peers=e.peers||castDraft({}),e.peers[t]=castDraft(r)})}function Ee(e,t,r){return produce(e,e=>{e.peers[t]=produce(e.peers[t],r)})}function Qt(e,t){let[r,n,i,o]=e,[s,a,c,l]=t;if(i||c)return ee(i,[r,n],[s,a])&&ee(c,[s,a],[r,n]);{let e=a?.user,t=n?.user;return l||o||e===t}}function it$1(e,t,r){return r.id!==t.id&&Qt([t.source,t.identity,t[e]?.restrictions,t.options?.service],[r.source,r.identity,r[e]?.restrictions,r.options?.service])}function Xi(e,t,r,n=!1){return ne(e,t).concat(Array.from(e.services??[],t=>g$2(e,t)).filter(pe)).filter(e=>n&&r.id===e.id||it$1(t,r,e))}function ie(e,t,r,n){if(r.options?.service)return Xi(e,t,r,n);{let i=r.identity.user;return i?Array.from(e.users?.byName?.get(i)??[]).concat(Array.from(e.services??[])).map(t=>g$2(e,t)).filter(pe).filter(e=>Yi(e,t)&&it$1(t,r,e)||!0===n&&e.id===r.id):Xi(e,t,r,n)}}function md(e,t,r,n,i){let o=i.identity,s=i.id,a=n.id,c=q(n);return produce(t,t=>{c&&t.push(qe(e,r,a,s,o,{local:c})),q(i)&&t.push(qe(e,i.source,s,a,n.identity,{local:c}))})}function Yt(e,t,r,n,i){return ie(r,t,i).reduce((t,r)=>md(e,t,n,i,r),[])}function Zt(e,t,r,n,i,o){let s=n.id;return[te(r,s,t),ie(r,t,n).filter(q).reduce((t,r)=>(t=t.concat(Je(e,r.source,r.id,s,i)),!o&&q(n)&&(t=t.concat(Je(e,n.source,s,r.id,i))),t),[])]}function ld(e,t){if(e===t)return!0;let r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(let n of r)if(e[n]!==t[n])return!1;return!0}function yd(e,t,r){let{peer_id:n}=r,i=g$2(e,n);if(i&&!ld(t,i.source))throw V(`The original source ${JSON.stringify(i.source)} of peer ${n} doesnt match the current source ${JSON.stringify(t)}`,{message:"Bad Source"})}enableMapSet(),me();var ot=R("gateway.node");function fd(e,t){let r=Object.values(t.registeredDomains).filter(e=>e.info.uri!==Se).map(e=>e.domain);return t.registeredDomains[Se]&&r.push(t.registeredDomains[Se].domain),r.reduce(([t,r],n)=>{ot.enabledFor("debug")&&ot.debug(`About to remove source from domain ${JSON.stringify(n.info())}`);let i=n.handleMessage(t,e);if(i){ot.enabledFor("debug")&&ot.debug(`removed source from domain ${JSON.stringify(n.info())}`);let[e,t]=i;return[e,r.concat(t)]}return[t,r]},[t,[]])}function ze(e,t,r){if("commands/source-removed"===t.body.type)return fd(t,e);{let{body:n}=t,{registeredDomains:i}=e,o=n.domain??Se,s=i[o]?.domain;if(s)return ot.enabledFor("debug")&&ot.debug(`Handling message with domain ${JSON.stringify(s.info())} message: \n ${JSON.stringify(t,null,"\t")}`),yd(e,r,n),s.handleMessage(e,t);{let i=n;return[e,[h(i.domain,r,i.request_id,i.peer_id,S(Ne,`Unable to find domain for message ${JSON.stringify(t)}`))]]}}}function Xt(e){return e.reduce((e,t)=>{let r=t.info(),n={};return n[r.uri]={domain:t,info:r},Object.assign(e,n)},{})}L(),me();var an=class{constructor(e){this.handler=e}close(){}message(e){this.handler(e)}addSource(e){}removeSource(e){let t={origin:"local",source:e,body:{type:"commands/source-removed"}};return this.handler(t)}},De=R("gateway.node.local");function gd(e,t){let{source:r,body:n,origin:i}=t;try{return n.dump?(De.info(`state dump:\n${JSON.stringify($e(e),null,"\t")}`),[e,[]]):"cluster"===i?[e,[]]:ze(e,t,r)}catch(i){De.error(`Error handling message ${JSON.stringify(t)}`,i);let o=n;return[e,[h(void 0,r,o.request_id,o.peer_id,J(i,Ne))]]}}function hd(e){return"receive"in e&&e.receive}function bd(e){switch(e.receiver.type){case"cluster":case"node":case"peer":return;case"local":{let{receiver:t,body:r}=e;De.enabledFor("debug")&&De.debug(`Sending message ${JSON.stringify(r,null,"\t")} to ${JSON.stringify(t)}`),hd(t)&&t.receive(r);break}default:De.error(`Unable to process response ${JSON.stringify(e)}`)}}function Rd(e,t){try{De.enabledFor("trace")&&De.debug(`domain handler processing message ${JSON.stringify(t)}`);let[r,n]=gd(e,t);if(n)for(let e of n)bd(e);return r??e}catch(r){return De.error(`error handling message ${JSON.stringify(t)}`,r),e}}function io(e,t){let r,n=e=>{try{r=Rd(r,e)}catch(t){throw De.error(`Error processing internal message ${JSON.stringify(e)}`,t),t}},i=Xt(e);return r=e.reduce((e,t)=>t.init(e),{...zt(t?.nodeId??A(),t?.signingKey),registeredDomains:i,handler:n}),new an(n)}var D=Se,cn=Ne,oo=`${D}.errors.unhandled_message`,dn=`${D}.errors.already_seen`,un=`${D}.errors.invalid_domain`,pn=`${D}.errors.authentication.failure`,mn=`${D}.errors.invalid_peer`;function so(e,t,r,n,i,o){let s={domain:D,type:"welcome",request_id:t,peer_id:r,available_domains:n,resolved_identity:i};return o&&(s.options=o),x(e,s)}function ao(e,t,r,n,i){return x(t,{domain:e,type:"authentication-request",request_id:r,authentication:i})}function st(e,t,r,n,i,o){let s={domain:D,type:"join",request_id:e,peer_id:t,destination:n,identity:i};return r&&(s.restrictions=r),o&&(s.options=o),s}function co(e){return x(e,{type:"ping"})}L();var ln={application:{required:!0},instance:{required:!1},region:{required:!1},environment:{required:!1},machine:{required:!1},user:{required:!1}};function Sd(e){return Object.keys(ln).find(t=>ln[t]&&ln[t].required&&void 0===e[t])}function uo(e){let t=Sd(e);if(t)throw new ve(`Identity ${JSON.stringify(e)} is missing required key: ${t}`,{})}function po(e,t){let r=e;return r&&-1!==r.indexOf(":")&&(r=r.substring(0,r.indexOf(":"))),r&&r.indexOf("127.0.0.1")>=0?t:r??t}function wt(e,t){return KJUR_1.jws.JWS.sign(null,{alg:"HS256",typ:"JWT"},e,t)}function er(e,t,r){let n;if(!KJUR_1.jws.JWS.verifyJWT(e,t,{alg:["HS256"],verifyAt:r?.now}))throw new Error("invalid jwt token");return n=KJUR_1.jws.JWS.parse(e),n.payloadObj}function fn$1(e,t,r,n){return wt({type:"gw-request","impersonate-peer":t,"gw-request":r},e.signatureKey)}function mo(e,t,r){return wt({type:"authentication",user:t.user},e.signatureKey)}function lo(e,t,r){void 0===r&&(r=r??Date.now());let n={};return r&&(n.now=Math.floor(r/1e3)),er(t,e,n)}function w(e,t){return{type:"peer",peer:t,node:e}}function _e(e){return{type:"node",node:e}}function gn(e){return Object.values(e.contexts||{})}L(),L();var vd=R("gateway.action"),yo$1="info";function $(e,t){let r=vd.child(e);if(r.enabledFor(yo$1)){let e=t();r[yo$1](e)}}function It(e){return`${e}.errors.not_authorized`}function fo(e){return`${e}.errors.bad_lifetime`}function go(e){return`${e}.errors.invalid_context`}function ho(e){return`${e}.errors.unhandled_message`}function hn(e){return S(`${e}.destroyed`,"Context destroyed explicitly")}function bo(e){return S(`${e}.peer-left`,"Context destroyed because its owner/last peer left")}function Ue(e){return`${e}.errors.failure`}function Ro(e,t,r,n,i,o){return x(t,{domain:e,type:"subscribed-context",request_id:r,peer_id:n,context_id:i,data:o})}function bn(e,t,r,n,i,o){return x(t,{domain:e,type:"context-added",peer_id:r,creator_id:n,context_id:i,name:o})}function Rn(e,t,r,n,i){return x(t,{domain:e,type:"context-destroyed",peer_id:r,context_id:n,reason_uri:i.uri,reason:i.message})}function xo(e,t,r,n,i){return x(t,{domain:e,type:"context-created",request_id:r,peer_id:n,context_id:i})}function So(e,t,r,n,i,o){return x(t,{domain:e,type:"context-updated",peer_id:r,updater_id:n,context_id:i,delta:o})}function wo(e){return Object.values(e.contexts||{})}function tr$1(e,t){return produce(e,e=>{e.contexts=e.contexts||{},e.contexts[t.id]=castDraft(t)})}function rr(e,t){return produce(e,e=>{e.contexts&&(delete e.contexts[t],0===Object.values(e.contexts).length&&delete e.contexts)})}function Qe(e,t,r){let n,i=r.identity.user,o=r.options?.service,s=Object.values(e.contexts||{});return n=s.find(e=>t===e.name&&e.identity.user===i),n||(n=s.find(e=>t===e.name&&(o||e.options?.service))),n}function He(e,t){if(t)return e.contexts?.[t]}function Tt(e,t,r){let n=t.contexts?.[r];if(n)return n;throw V(`Unable to find context with id ${r}`,{uri:go(e)})}function dt(e,t,r){return t&&r?t.members.has(r)?e:produce(e,e=>{e.contexts=e.contexts||{},e.contexts[t.id]=castDraft(produce(t,e=>{e.members=e.members||new Set,e.members.add(r)}))}):e}function nr(e,t,r){return produce([e,t],([e,n])=>{n.members.delete(r),r===n.owner&&delete n.owner,e.contexts=e.contexts||{},e.contexts[t.id]=n})}function Io(e,t,r){if(!t)return r;if(1===t.length)e[t[0]]=r;else{let n=e[t[0]];(void 0===n||Array.isArray(n)||"number"==typeof n||"boolean"==typeof n)&&(n={}),e[t[0]]=Io(n,t.slice(1),r)}return e}function Id(e,t){return{...e,...t}}function Td(e,t){let[r,n]=t;switch(r){case"removed":n.forEach(t=>{delete e?.[t]});break;case"added":e=Object.entries(n).reduce((e,[t,r])=>(e[t]=r,e),e??{});break;case"updated":e=Object.entries(n).reduce((e,[t,r])=>(Array.isArray(r)&&Array.isArray(e[t])?e[t]=r:r instanceof Object&&e[t]instanceof Object?e[t]=Id(e[t],r):e[t]=r,e),e??{});break;case"reset":n&&(e=n);break;case"commands":e=n.reduce((e,t)=>{switch(t.type){case"set":return Io(e??{},vo(t.path),t.value);case"remove":{let r=vo(t.path);if(!r)return{};{let t=e;for(let n=0;n{e.contexts[t].data=Object.entries(r).reduce((e,[t,r])=>Td(e,[t,r]),e.contexts[t].data),e.contexts[t].version=n})}function vo(e){if(e)return e.split(".")}function ir(e,t,r,n,i,o,s,a,c){let l=e.identity,u=e.options,d={id:a,data:r??{},identity:l,lifetime:n,read_permissions:i,write_permissions:o,permissions:s,members:new Set,version:c,name:t,creator:e.id};return u&&(castDraft(d).options=u),void 0===d.permissions&&delete castDraft(d).permissions,void 0===d.read_permissions&&delete castDraft(d).read_permissions,void 0===d.write_permissions&&delete castDraft(d).write_permissions,d}function Ao(e){let t=e.version?.updates||0;return t++,{updates:t,timestamp:Date.now()}}function or(){return{updates:0,timestamp:Date.now()}}function Le(e){return ee(e.permissions?.read,[{type:e.local?"local":"cluster"},e.identity],[{type:"cluster"},void 0])}function Co(e,t){let r=e.version,n=t.version;return r.updates>n.updates||r.updates===n.updates&&r.timestamp>=n.timestamp}function sr(e,t,r=!1){let n=e.lifetime;return t.id===e.creator||("activity"===n?e.members.has(t.id):t.id===e.creator||t.id===e.owner||(r?!!e.permissions?.write&&ee(e.permissions?.write,[void 0,e.identity],[t.source,t.identity]):ee(e.permissions?.write,[void 0,e.identity],[t.source,t.identity])))}function Mo(e,t,r){"activity"===t.lifetime&&k(It(e),"Activity contexts cannot be explicitly destroyed");let n="ownership"===t.lifetime;n&&t.owner===r.id||!n&&sr(t,r)||k(It(e),"Not authorized to destroy context")}function ar$1(e,t){return t.id===e.creator||t.id===e.owner||ee(e.permissions?.read,[void 0,e.identity],[t.source,t.identity])||sr(e,t,!0)}function Md(e,t){return q(e)&&"activity"!==t.lifetime&&ar$1(t,e)}function cr(e,t,r){ar$1(t,r)||k(It(e),"Not authorized to read context")}function Pd(e){if(!e.local&&!ee(e.permissions?.write,[void 0,e.identity],[{type:"cluster"},void 0]))throw new Error(`cannot create remote context '${e.name}' locally`)}function Dd(e,t,r,n){let{peer_id:i,name:o}=n;try{let r=_(t,i),n=Qe(t,o,r);return n?vn(e,t,r,n):(z$1.enabledFor("debug")&&z$1.debug(`unable to find remote context ${o}`),[t,[]])}catch(e){return z$1.enabledFor("debug")&&z$1.debug(`error processing remote context unsubscribe ${JSON.stringify(n)}`,e),[t,[]]}}function _d(e,t,r,n){let{request_id:i,peer_id:o,context_id:s}=n;try{let a=_(t,o),c=Tt(e,t,s),[l,u]=vn(e,t,a,c),d=u.concat([I(e,r,i,o)]);if(Le(c)){let e={...n,type:"unsubscribe-context",name:c.name};d=d.concat([G(w(A(l.ids),o),e)])}return[l,d]}catch(n){return[t,[h(e,r,i,o,J(n,Ue(e)))]]}}function dr(e,t,r,n){return W(r)?Dd(e,t,r,n):_d(e,t,r,n)}function Po(e,t,r){let{source:n,id:i}=r;return gn(t).filter(e=>Md(r,e)).map(t=>{let{creator:r,id:o,name:s}=t;return bn(e,n,i,r,o,s)})}function At(e){return e.options?.["context-compatibility-mode?"]?Se:se}function xn(e,t,r,n,i,o){let s=t.id,a=To(e,s,n,i);return $(se,()=>`[${t.name}#${t.id}] updated by [${r.identity.application}#${r.id}] (request: ${o})`),[a,Array.from(t.members).filter(e=>e!==r.id).map(e=>g$2(a,e)).filter(pe).filter(e=>q(e)).map(e=>So(At(e),e.source,e.id,r.id,s,n))]}function Od(e,t,r){let{request_id:n,peer_id:i,name:o,delta:s,version:a}=r;try{let e=_(t,i),c=Qe(t,o,e);return c?sr(c,e)&&Co(r,c)?xn(t,c,e,s,a,n):[t,[]]:(z$1.enabledFor("debug")&&z$1.debug(`unable to find remote context ${o}`),[t,[]])}catch(e){return z$1.enabledFor("debug")&&z$1.debug(`error processing remote context update ${JSON.stringify(r)}`,e),[t,[]]}}function kd(e,t,r,n){let{request_id:i,peer_id:o,context_id:s,delta:a}=n;try{let c=_(t,o),l=Tt(e,t,s),u=Ao(l);sr(l,c)||k(It(e),"Not authorized to update context");let d={...n,type:"update-context",version:u,name:l.name,delta:a};return ue(t,e=>xn(e,l,c,a,u,i),t=>[t,[I(e,r,i,o)]],e=>[e,Le(l)?[G(w(A(e.ids),o),d)]:[]])}catch(n){return[t,[h(e,r,i,o,J(n,Ue(e)))]]}}function ut(e,t,r,n){return W(r)?Od(e,t,n):kd(e,t,r,n)}function Do(e,t,r,n){let{name:i,data:o,peer_id:s}=r,a=r.lifetime??n.defaultLifetime,c=!n.isLocal||t.options?.respect_context_lifetime||"retained"!==a&&void 0!==a?a:n.defaultLifetime??"retained",l=r.permissions?.read??n?.defaultPermissions?.("read",i,t.identity),u=r.permissions?.write??n?.defaultPermissions?.("write",i,t.identity),d=l||u?{read:l,write:u}:void 0,[h,p]=Kt(e.ids),g=r.version??or(),m=produce(ir(t,i,o,c,r.read_permissions,r.write_permissions,d,p,g),e=>{e.members=new Set([s]),e.local=n.isLocal,e.lifetime=c,"ownership"===c&&(e.owner=s)});return Pd(m),[tr$1({...e,ids:h},m),m]}function _o(e,t,r,n,i,o){return $(se,()=>`[${i.name}#${i.id}] subscribed by [${o.identity.application}#${o.id}] (request: ${n})`),[dt(t,i,o.id),[Ro(e,r,n,o.id,i.id,i.data)]]}function Nd(e,t,r,n){let{peer_id:i,name:o,request_id:s}=n;try{let r=_(t,i),n=Qe(t,o,r);return n?(cr(e,n,r),$(se,()=>`[${n.name}#${n.id}] subscribed by [${r.identity.application}#${r.id}] (request: ${s})`),[dt(t,n,i),[]]):(z$1.enabledFor("debug")&&z$1.debug(`unable to find remote context ${o}`),[t,[]])}catch(e){return z$1.enabledFor("debug")&&z$1.debug(`error processing remote context subscribe ${JSON.stringify(n)}`,e),[t,[]]}}function qd(e,t,r,n){let{request_id:i,peer_id:o,context_id:s}=n;try{let a=_(t,o),c=Tt(e,t,s);cr(e,c,a);let[l,u]=_o(e,t,r,i,c,a);if(Le(c)){let e={...n,type:"subscribe-context",name:c.name};return[l,u.concat([G(w(A(l.ids),o),e)])]}return[l,u]}catch(n){return[t,[h(e,r,i,o,J(n,Ue(e)))]]}}function ur$1(e,t,r,n){return W(r)?Nd(e,t,r,n):qd(e,t,r,n)}function Oo(e,t,r){let n=t.name,i=t.id,o=r.id;return ie(e,"context-domain",r,!0).filter(e=>q(e)).filter(e=>ar$1(t,e)).map(e=>bn(At(e),e.source,e.id,o,i,n))}function $d(e,t,r){let n=e.id;return t.filter(e=>q(e)).filter(t=>ar$1(e,t)).map(e=>Rn(At(e),e.source,e.id,n,r))}function ko$1(e,t){let r=X(t.read_permissions),n=X(t.write_permissions),i=r||n?{read:r,write:n}:void 0,o=t.lifetime;return o||k(fo(e),`Bad lifetime value ${o}`),{...t,domain:e,lifetime:o,permissions:i}}function Ed(e,t,r,n){let{request_id:i,peer_id:o,name:s}=r;try{let a=b(t,o,"context-domain"),c=Qe(t,s,a);if(c)return cr(e,c,a),Co(r,c)?xn(t,c,a,{reset:r.data},r.version,i):[t,[]];{let o=ko$1(e,r),[s,c]=Do(t,a,o,{isLocal:!1,defaultPermissions:(e,t,r)=>n?.defaultContextRestrictions?.apply(r,[t])});return $(se,()=>`[${c.name}#${c.id}] created for ${c.identity.user??""} by [${c.identity.application}#${c.creator}] (request: ${i}, permissions: ${JSON.stringify(c.permissions)})`),[s,Oo(s,c,a)]}}catch{return z$1.enabledFor("debug")&&z$1.debug(`error processing remote context create ${JSON.stringify(r)}`),[t,[]]}}me();var z$1=R("gateway.contexts");function Ud(e,t,r,n,i){let{request_id:o,peer_id:s,name:a}=n;try{let c=b(t,s,"context-domain"),l=Qe(t,a,c);if(l)return cr(e,l,c),_o(e,t,r,o,l,c);{let a=ko$1(e,n),[l,u]=Do(t,c,a,{isLocal:!0,defaultLifetime:i?.retainedOverride,defaultPermissions:(e,t,r)=>i?.defaultContextRestrictions?.apply(r,[t])});$(se,()=>`[${u.name}#${u.id}] created for ${u.identity.user??""} by [${u.identity.application}#${u.creator}] (request: ${o}, permissions: ${JSON.stringify(u.permissions)})`);let d=Oo(l,u,c);if(d.push(xo(e,r,o,s,u.id)),Le(u)){let e={...n,type:"create-context",version:u.version,lifetime:u.lifetime};d.push(G(w(A(t.ids),s),e))}return[l,d]}}catch(i){return z$1.error(`error creating context from request ${JSON.stringify(n)}`,i),[t,[h(e,r,o,s,J(i,Ue(e)))]]}}function pr(e,t,r,n,i){return W(r)?Ed(e,t,n,i):Ud(e,t,r,n,i)}function Hd(e){switch(e.lifetime){case"ownership":return!e.owner;case"ref-counted":return 0===e.members.size;default:return!1}}function Sn(e,t,r,n){$(se,()=>`[${r.name}#${r.id}] destroyed (reason: ${JSON.stringify(n)})`);let i=r.id,o=r.members;return[rr(t,i),$d(r,ne(t,"context-domain").filter(e=>!o.has(e.id)),n).reduce((e,t)=>e.concat(t),Array.from(o).map(e=>g$2(t,e)).filter(pe).filter(e=>q(e)).map(t=>Rn(e,t.source,t.id,i,n)))]}function Ld(e,t,r,n){let{peer_id:i,name:o}=n;try{let r=_(t,i),n=Qe(t,o,r);return n?(Mo(e,n,r),Sn(e,t,n,hn(e))):(z$1.enabledFor("debug")&&z$1.debug(`unable to find remote context ${o}`),[t,[]])}catch(e){return z$1.enabledFor("debug")&&z$1.debug(`error processing remote destroy ${JSON.stringify(n)}`,e),[t,[]]}}function Fd(e,t,r,n){let{request_id:i,peer_id:o,context_id:s}=n;try{let a=_(t,o),c=Tt(e,t,s);Mo(e,c,a);let l={...n,type:"destroy-context",name:c.name};return ue(t,t=>Sn(e,t,c,hn(e)),t=>[t,[I(e,r,i,o)]],e=>[e,Le(c)?[G(w(A(t.ids),o),l)]:[]])}catch(n){return[t,[h(e,r,i,o,J(n,Ue(e)))]]}}function mr(e,t,r,n){return W(r)?Ld(e,t,r,n):Fd(e,t,r,n)}function Gd(e,t,r){return gn(t).reduce(([t,n],i)=>{let[o,s]=vn(e,t,r,i);return[o,n.concat(s)]},[t,[]])}function vn(e,t,r,n){if(n.members.has(r.id)){let[i,o]=nr(t,n,r.id);return $(se,()=>`[${n.name}#${n.id}] unsubscribed by [${r.identity.application}#${r.id}]`),Hd(o)?Sn(e,i,o,bo(e)):[i,[]]}return[t,[]]}function lr(e,t,r,n,i){let[o,s]=Zt(e,"context-domain",t,r,n,i);$(se,()=>`[${r.identity.application}#${r.id}] removed from context domain (reason: ${JSON.stringify(n)}, source removed: ${i})`);let[a,c]=Gd(e,o,r);return[a,c.concat(s.filter(e=>wn(a,e)))]}function wn(e,t){let r=g$2(e,t.body.peer_id);return!!r&&!r.options?.["context-compatibility-mode?"]}function Jd(e,t,r,n,i){let{request_id:o,identity:s,authentication:a,options:c}=r,l=a?.provider??n.default,u=n.available[l];if(u){let r={requestId:o,remoteIdentity:s,authentication:a,signatureKey:e.signatureKey,clientAuth:t.auth};return u.authenticate(r).then(e=>{let t=e.type;return"success"===e.type?t="internal/authenticated":"continue"===e.type&&(t="internal/authentication-request"),{...e,type:t}}).catch(e=>(ye.debug("authentication request rejected",e),{message:Be(e),...je(e),type:"internal/authentication-failed"})).then(e=>{let r={...e,request_id:o,identity:s};"internal/authenticated"===r.type&&(r.options=c),i({origin:"local",source:t,body:r})}),[e,[]]}return[e,[h(D,t,o,void 0,S(pn,`Requested authentication provider ${l} is not available`))]]}function jd(e,t,r){let{peer_id:n,identity:i,options:o}=r,s=vt(e,r.destination);return s?([e]=sn(e,t,n,i,null,o),ye.enabledFor("info")&&ye.info(`added remote peer ${n} on ${JSON.stringify(t)} with ${JSON.stringify(i)}`),s.handleMessage(e,{origin:"cluster",source:t,body:{...r,type:"domain/join"}})):[e,[]]}function No(e,t,r){let{peer_id:n,request_id:i,destination:o}=r,s=g$2(e,n);if(s?.identity){let a=vt(e,o);if(a){let n={...r,type:"domain/join",identity:s.identity};return a.handleMessage(e,{origin:"local",source:t,body:n})}return[e,[h(D,t,i,n,S(un,`Unable to join missing domain ${o}`))]]}return[e,[h(D,t,i,n,S(mn,`Unable to find peer with id ${n}`))]]}function Bd(e,t,r){return W(t)?jd(e,t,r):No(e,t,r)}function Kd(e,t,r){return No(e,t,r)}function Vd(e,t,r){let{peer_id:n,destination:i}=r;if(g$2(e,n)){let n=vt(e,i);if(n)return n.handleMessage(e,{origin:"local",source:t,body:{...r,type:"domain/leave"}})}return[e,[]]}function zd(e,t,r){let{peer_id:n,request_id:i,destination:o}=r;if(g$2(e,n)){let s=vt(e,o);return s?s.handleMessage(e,{origin:"local",source:t,body:{...r,type:"domain/leave"}}):[e,[h(D,t,i,n,S(un,`Unable to join missing domain ${o}`))]]}return[e,[h(D,t,i,n,S(mn,`Unable to find peer with id ${n}`))]]}function Qd(e,t,r){return W(t)?Vd(e,t,r):zd(e,t,r)}var ye=R("gateway.domains.global");function Yd(e,t,r){ye.enabledFor("debug")&&ye.debug(`removing source ${JSON.stringify(t)} from global domain`);let n=e.ids.nodeId,[i,o]=to(e,t).reduce(([e,i],o)=>(e=no$1(e,o),T(t)&&(ye.enabledFor("info")&&ye.info(`removed peer ${o.id} was on endpoint ${t.endpoint}`),i=i.concat(G(w(n,o.id),r))),[e,i]),[e,[]]);return ye.enabledFor("debug")&&ye.debug(`removed source ${JSON.stringify(t)} from global domain`),[i,o]}function Zd(e,t){return Object.keys(e).filter(t=>"?"===e[t]).reduce((e,r)=>{let n={};return n[r]=t,Object.assign(e,n)},e)}function Xd(e,t){let r=t?.user;return r?{...e,user:r}:e}function eu(e,t,r){let{request_id:n,message:i}=r;return[e,[h(D,t,n,void 0,S(pn,i))]]}function tu(e,t,r){let{request_id:n,authentication:i}=r;return[e,[ao(D,t,n,void 0,i)]]}function ru$1(e,t,r,n){let i=ro(e,r);if(i){let o=g$2(e,i);throw new ve(`peer for ${JSON.stringify(r)} already accepted on source ${JSON.stringify(o?.source)} with id ${i}, ignoring request (with id?: ${n}) on source ${JSON.stringify(t)}`,{uri:dn,message:"Hello already received once",existing:o})}}function nu(e,t,r,n){let{request_id:i,identity:o,user:s,login:a,impersonatePeer:c,gwRequest:l,accessToken:u}=r;l?.id&&(e=tt(e,l.id).state);let d={machine:po(t.host,"127.0.0.1"),...o};if(s&&(d={...d,user:s}),a&&(d={...d,login:a}),c&&(d=Xd(d,c)),!d.instance){let[t,r]=Vi(e.ids);d={...d,instance:r},e={...e,ids:t}}let p={...r.options};"context_compatibility_mode"in p||(p.context_compatibility_mode=n?.contextCompatibility??!0),p["context-compatibility-mode?"]=p.context_compatibility_mode,delete p.context_compatibility_mode;try{ru$1(e,t,d,i),uo(d);let r,[o,s]=Qi(e.ids);d=Zd(d,s),[e,r]=sn({...e,ids:o},t,s,d,l,p),ye.enabledFor("info")&&ye.info(`added local peer ${r.id} on endpoint ${t.endpoint} with ${JSON.stringify(d)}`);let a={};u&&(a.access_token=u),n?.welcomeInfo&&(a.info=n?.welcomeInfo);let c=Object.values(e.registeredDomains??{}).map(e=>e.info),h=so(t,i,r.id,c,d,0===Object.keys(a).length?void 0:a);return ue(e,e=>[e,[h]],e=>p["context-compatibility-mode?"]?Kd(e,t,{request_id:i,peer_id:r.id,identity:d,options:p,destination:se,domain:D}):[e,[]])}catch(r){let n=[],o=je(r);if(ye.warn("authenticated peer not welcomed",r),o?.uri===dn){let e=o.existing;e&&n.push(co(e.source))}return T(t)&&n.push(h(D,t,i,void 0,J(r,cn))),[e,n]}}function iu(e,t,r){return ut(D,e,t,r)}function ou(e,t,r,n){return pr(D,e,t,r,n)}function su(e,t,r){return mr(D,e,t,r)}function au(e,t,r){return ur$1(D,e,t,r)}function cu(e,t,r){return dr(D,e,t,r)}function du(e,t,r,n,i){switch(r.type){case"hello":return Jd(e,t,r,n,e.handler);case"join":return Bd(e,t,r);case"leave":return Qd(e,t,r);case"internal/authenticated":return nu(e,t,r,i);case"internal/authentication-failed":return eu(e,t,r);case"internal/authentication-request":return tu(e,t,r);case"create-context":return ou(e,t,r,i);case"update-context":return iu(e,t,r);case"subscribe-context":return au(e,t,r);case"unsubscribe-context":return cu(e,t,r);case"destroy-context":return su(e,t,r);case"ping":return[e,[]];case"commands/source-removed":return Yd(e,t,r);case"create-token":{let{request_id:n,peer_id:i}=r,o=_(e,i);if(o.identity.user)return[e,[Gi(D,t,n,i,mo(e,{user:o.identity.user}))]];throw V("Cannot create token for peer without user",{})}default:{let n=`Unhandled message ${JSON.stringify(r)}`;return ye.error(n),[e,[h(D,t,r.request_id??-1,r.peer_id,S(oo,n))]]}}}function uu(e,t,r,n){let{source:i,body:o}=t;try{return du(e,i,o,r,n)}catch(t){return[e,[h(D,i,o.request_id??-1,o.peer_id,J(t,cn))]]}}var In=class{constructor(e,t){this.authenticators=e,this.options=t}info(){return{uri:D,description:"",version:2}}init(e){return e}destroy(e){return e}handleMessage(e,t){return uu(e,t,this.authenticators,this.options)}stateToMessages(e,t){return[]}};function qo(e,t){return new In(e,t??{contextCompatibility:!0})}function $o(e,t){let{login:r,secret:n}=e,i=t??r;return i&&(n||""===n)?Promise.resolve({type:"success",user:i,login:r}):Promise.reject(V("Missing login/secret",{type:"failure",message:"Missing login/secret"}))}function Eo(e){if(pu(e))return e.token}function pu(e){return"gateway-token"===e?.method}function Uo(e){return"gateway-client"===e?.method}L();var Ct=class{#e=[];#t;#o=!1;#r=!1;constructor(e=-1){this.#t=e}put(e){return new Promise((t,r)=>{this.#o&&r(new Error("cannot enqueue promise serializer is closed"));let n={action:e,resolve:t,reject:r};this.#t<0||this.#e.lengthnew Promise((t,r)=>{let{authentication:n}=e;Ho.enabledFor("debug")&&Ho.debug(`processing authentication ${JSON.stringify(n,rt("secret","token","providerContext"))}`),this.#o(t,r,e)})),new Promise((e,r)=>{t=setTimeout(()=>{r(new Error("timeout"))},this.#e)})]).finally(()=>clearTimeout(t))}}},Lo={timeout:5e3,max_pending_requests:2e4};function pt$1(e,t){return new Tn(e.timeout??Lo.timeout,e.max_pending_requests??Lo.max_pending_requests,(e,r,n)=>{t.auth(n).then(t=>e(t)).catch(e=>r(e))})}L();var Cn=R("gateway.auth.basic");async function yu({authentication:e},t,r,n,i){switch(e?.method){case"secret":{let o=e.login,s=i?await i(o):o;if(n&&!await n(s,e.secret))throw V("Invalid login/secret",{type:"failure",message:"Invalid login/secret"});let a=await $o(e,s),c=wt({user:a.user,exp:Math.floor((Date.now()+r)/1e3)},t);return{...a,accessToken:c}}case"access-token":try{let r=e.token,n=er(r,t).user;return{type:"success",login:n,user:n,accessToken:r}}catch(e){throw V(`Invalid or expired token:${Be(e)}`,{type:"failure",message:"Invalid or expired token: "+Be(e)},e)}default:{let t=`Unknown authentication method '${e?.method}'`;throw Cn.debug(t),V(t,{type:"failure",message:t})}}}var Mn=class{#e;#t;#o;#r;constructor(e,t,r,n){this.#e=e,this.#t=t,this.#o=r,this.#r=n}auth(e){return yu(e,this.#e,this.#t,this.#o,this.#r)}};function Fo(e){let t=1e3*(e.ttl??6e4),r=e.secretVerifier,n=e.usernameResolver;return Cn.enabledFor("debug")&&Cn.debug(`creating basic authenticator: ttl: ${t}, secret verifier: ${void 0!==r}, username resolver: ${void 0!==n}`),pt$1(e,new Mn(Me(),t,r,n))}var Pn=class{#e;constructor(e,t){this.#e=Z$1({issuerBaseUri:e.issuerBaseURL,audience:e.audience?[e.audience]:[],clockTolerance:3600,timeout:5e3,cacheMaxAge:6e4,...t})}async auth(e){let{method:t,token:r}=e.authentication;if("access-token"!==t)throw new Error("unsupported authentication method");if(!r)throw new Error("missing access token");try{let{payload:e}=await this.#e(r);return{type:"success",user:e.sub}}catch(e){throw new Error("invalid token",{cause:e})}}};function Go(e,t){return pt$1(e,new Pn(e,t))}var Dn=class{authFn;constructor(e){this.authFn=e}async auth(e){return await this.authFn(e)}};function Wo(e,t){return pt$1(e,new Dn(t))}var _n=class{#e;constructor(e){this.#e=e}subscriber(){return(e,t,r)=>{switch(e.type){case"member-added":this.#e?.onMemberAdded?.(t,e.node);break;case"member-removed":this.#e?.onMemberRemoved?.(t,e.node);break;case"message-received":this.#e?.onMessage?.(t,e.message)}}}},On=class{#e;constructor(e){this.#e=e}close(){}register(e,t,r){let n=new _n(r);return this.#e.subscribe(e,n.subscriber())}unregister(e){this.#e.unsubscribe(e)}publish(e,t){let r={type:"publish-message",message:t};this.#e.execute(e,r)}addUsers(e,t){this.#e.execute(e,{type:"add-users",added:t})}removeUsers(e,t){this.#e.execute(e,{type:"remove-users",removed:t})}};function Jo(e){return new On(e)}L();var y="agm",jo=`${y}.errors.failure`,Bo=`${y}.errors.unhandled_message`,Ko=`${y}.errors.unregistration.failure`,mt=`${y}.errors.invocation.failure`,Vo=`${y}.errors.subscription.failure`,Mt=`${y}.errors.subscription.invalid_subscription`,kn=S(`${y}.peer-removed`,"Peer has been removed"),zo=S(`${y}.method-removed`,"Method has been removed"),Qo=S(Mt,"Trying to drop a subscription that wasnt established. Did you mean to return an error instead?");function Ru(e,t,r,n){return{domain:y,type:"methods-added",peer_id:e,source_type:n,server_id:t,methods:r}}function Nn(e,t,r,n,i){return x(e,Ru(t,r,n,i))}function Yo(e,t,r){return{domain:y,type:"register",request_id:e,peer_id:t,methods:r}}function xu(e,t,r){return{domain:y,type:"methods-removed",peer_id:e,server_id:t,methods:r}}function qn(e,t,r,n){return x(e,xu(t,r,n))}function Su(e,t,r,n,i,o,s){return{domain:y,type:"invoke",invocation_id:e,peer_id:t,method_id:r,caller_id:n,arguments:i,arguments_kv:o,context:s}}function Zo(e,t,r,n,i,o,s,a){return x(e,Su(t,r,n,i,o,s,a))}function vu(e,t,r){return{domain:y,type:"result",request_id:e,peer_id:t,result:r}}function Xo(e,t,r,n){return x(e,vu(t,r,n))}function wu(e,t,r,n,i,o,s,a){return{domain:y,type:"add-interest",subscription_id:e,peer_id:t,method_id:r,caller_id:n,arguments:i,arguments_kv:o,flags:s,context:a}}function es$1(e,t,r,n,i,o,s,a,c){return x(e,wu(t,r,n,i,o,s,a,c))}function Iu(e,t,r,n,i){return{domain:y,type:"remove-interest",subscription_id:e,peer_id:t,method_id:r,caller_id:n,reason_uri:i.uri,reason:i.message}}function $n(e,t,r,n,i,o){return x(e,Iu(t,r,n,i,o))}function Tu(e,t,r){return{domain:y,type:"subscribed",request_id:e,peer_id:t,subscription_id:r}}function ts(e,t,r,n){return x(e,Tu(t,r,n))}function Au(e,t,r,n,i,o){return{domain:y,type:"event",peer_id:e,subscription_id:t,oob:r,sequence:n,snapshot:i,data:o}}function En(e,t,r,n,i,o,s){return x(e,Au(t,r,n,i,o,s))}function Cu(e,t,r){return{domain:y,type:"subscription-cancelled",subscription_id:e,peer_id:t,reason_uri:r.uri,reason:r.message}}function Un(e,t,r,n){return x(e,Cu(t,r,n))}function yr(e,t,r){let{server_id:n,method_id:i,arguments:o,arguments_kv:s}=r;e.id!==t.id&&!it$1("agm-domain",e,t)&&k(mt,"Unable to invoke methods across different users"),e["agm-domain"].methods?.[n]?.[i]||k(mt,`Unable to find method with id ${i} on server id ${n} registered with this peer`),o&&s&&k(mt,"Cant use positional and by-name arguments at the same time")}function Mu(e,t,r){let{request_id:n,peer_id:i,server_id:o,invocation_id:s,method_id:a,arguments:c,arguments_kv:l,context:u}=t;r=produce(r,e=>{let t=e["agm-domain"];t.invocations=t.invocations||{},t.invocations[s]={caller:i,method_id:a,request_id:n}});let d=!q(r);return[C(e,o,r),d?[K(w(A(e.ids),i),_e(r.source.node),{domain:y,type:"call",...t})]:[Zo(r.source,s,o,a,i,c,l,u)]]}function ns(e,t,r,n,i){let{request_id:o,peer_id:s,server_id:a,method_id:c}=t;return $(y,()=>{let e=i["agm-domain"]?.methods?.[n.id]?.[c]?.name;return`[${i.identity.application}#${i.id}] called method [${n.identity.application}#${n.id}:${e}#${c}] (request: ${o})`}),i=produce(i,e=>{let t=e["agm-domain"];t.calls=t.calls||{},t.calls[o]={callee:a,method_id:c,invocation_id:r}}),Mu(C(e,s,i),{...t,invocation_id:r},s===a?i:n)}function Pu(e,t,r){let{request_id:n,peer_id:i,server_id:o,invocation_id:s}=r,a=B(e,o,"agm-domain");return q(a)?ns(e,r,s,a,b(e,i,"agm-domain")):[e,[]]}function Du(e,t,r){let{peer_id:n,server_id:i}=r,o=b(e,i,"agm-domain"),s=b(e,n,"agm-domain"),[a,c]=Pe(e.ids);return yr(s,o,r),ns({...e,ids:a},r,c,o,s)}function is$2(e,t,r){return W(t)?Pu(e,t,r):Du(e,t,r)}function os(e,t,r,n){let i=n.id,[o,s]=Object.entries(r["agm-domain"]?.calls??{}).reduce(([e,t],[r,n])=>((n.callee===i?e:t).push([r,n]),[e,t]),[new Array,new Array]);return o.length>0?[Ee(e,r.id,e=>{let t=e["agm-domain"];s.length>0?t.calls=s.reduce((e,[t,r])=>(e=produce(e,e=>{e[t]=r}),e),{}):delete t.calls}),q(r)?o.map(function([e]){return h(y,t,e,r.id,S(mt,"Peer has left while waiting for result"))}):[]]:[e,[]]}function _u(e,t,r,n,i){let{request_id:o,caller:s,method_id:a}=r,c=g$2(e,s);if(c&&(c=produce(c,e=>{e["agm-domain"]&&e["agm-domain"].calls&&(delete e["agm-domain"].calls[o],0===Object.keys(e["agm-domain"].calls).length&&delete e["agm-domain"].calls)})),c){let r=g$2(e=C(e,s,c),t);r?.["agm-domain"]?.methods?.[t][a];let l=i.success,u=i.failure;return q(c)?l?($(y,()=>{let e=c?.["agm-domain"]?.methods?.[t]?.[a]?.name;return`[${c?.identity?.application}#${s}] received success for [${r?.identity.application}#${t}:${e}#${a}] (request: ${o})`}),[e,[Xo(c.source,o,s,l.result)]]):($(y,()=>{let e=c?.["agm-domain"]?.methods?.[t]?.[a]?.name;return`[${c?.identity?.application}#${s}] received failure for [${r?.identity.application}#${t}:${e}#${a}] (request: ${o})`}),[e,[h(y,c.source,o,s,Q(u),u.context)]]):[e,[K(w(A(e.ids),t),_e(c.source.node),n)]]}return[e,[]]}function Hn(e,t,r,n,i){let o=g$2(e,r),s=o?.["agm-domain"]?.invocations?.[t];if(s)return e=C(e,r,produce(o,e=>{e["agm-domain"]?.invocations&&(delete e["agm-domain"].invocations[t],0===Object.keys(e["agm-domain"].invocations).length&&delete e["agm-domain"].invocations)})),_u(e,r,s,n,i)}function ss(e,t,r){let{invocation_id:n,peer_id:i}=r;return b(e,i,"agm-domain"),Hn(e,n,i,r,{success:r})??[e,[]]}function Ou(e,t,r){return ss(e,t,r)}function ku(e,t,r){return ss(e,t,r)}function as(e,t,r){return T(t)?ku(e,t,r):Ou(e,t,r)}function cs$1(e,{parsedRestrictions:t}){return ee(t,[{type:"local"===e.source.type?"local":"cluster"},e.identity],[{type:"cluster"},void 0])}function ds(e,t,r,n,i){let{server:o,stream:s,method_id:a}=r,c=produce(_(e,o),Fn(t,n,s));return e=C(e,o,c),q(c)?[e,[$n(c.source,t,o,a,n,i)]]:[e,[]]}function us(e,t,r){let n=t["agm-domain"]?.subscriptions,i=t.id,[o,s]=Object.entries(n||{}).reduce(([e,t],[n,o])=>{let[s,a]=ds(e,n,o,i,r);return[s,t.concat(a)]},[e,[]]);return[o,s]}function Nu(e,t,r){return Object.entries(e).reduce((e,[n,i])=>(t!==i.server||r&&0!==r.size&&!r.has(i.method_id)?e.remaining[n]=i:e.removed[n]=i,e),{removed:{},remaining:{}})}function fr$1(e,t,r,n,i){let o=r.id,{removed:s,remaining:a}=Nu(t["agm-domain"]?.subscriptions||{},o,n),c=Object.entries(s).reduce((r,[n,o])=>{let s;return[e,s]=ds(e,n,o,t.id,i),e},e);return Object.keys(s).length>0?[Ee(c,t.id,e=>{Object.keys(a).length>0?e["agm-domain"].subscriptions=a:e["agm-domain"]&&delete e["agm-domain"].subscriptions}),T(t.source)?Object.keys(s).map(e=>Un(t.source,e,t.id,i)):[]]:[e,[]]}function qu(e,t,r){let{peer_id:n,server_id:i,subscriptionId:o,method_id:s,arguments:a,arguments_kv:c,context:l,flags:u}=r,d=g$2(t,i);if(d){d=produce(d,e=>{e["agm-domain"].interests=e["agm-domain"].interests||{},e["agm-domain"].interests[o]={subscriber:n,method_id:s}});let e=d.source;return d["agm-domain"].methods[i][s],[C(t,i,d),T(e)?[es$1(e,o,i,s,n,a,c,u,l)]:[K(w(A(t.ids),n),_e(e.node),r)]]}throw V(`unable to find server with id ${i}`,{})}function ps$1(e,t,r){let{request_id:n,peer_id:i,server_id:o,method_id:s}=t,a=produce(b(e,i,"agm-domain"),e=>{e["agm-domain"].subscriptions=e["agm-domain"].subscriptions||{},e["agm-domain"].subscriptions[r]={server:o,method_id:s,request_id:n}}),c=b(e,o,"agm-domain");yr(a,c,t),$(y,()=>`[${a.identity.application}#${a.id}] subscribed for [${c.identity.application}#${c.id}:${c["agm-domain"].methods?.[c.id]?.[s]?.name}#${s}] (subscription: ${r}, request: ${n})`);let l={...t,subscriptionId:r};return qu(a,C(e,i,a),l)}function $u(e,t,r){let[n,i]=Pe(e.ids);return ps$1({...e,ids:n},r,i)}function Eu(e,t){let{subscriptionId:r,server_id:n}=t;return g$2(e,n)?ps$1(e,t,r):[e,[]]}function ms$1(e,t,r){return T(t)?$u(e,t,r):Eu(e,r)}function ls(e,t,r,n,i,o,s){if(t){let a=t["agm-domain"]?.subscriptions?.[n]?.request_id,c=t.source;return $(y,()=>{let e=t["agm-domain"].subscriptions[n];return`[${t.identity.application}#${r}] dropped/rejected [${t["agm-domain"]?.methods?.[e.server][e.method_id].name}] (subscription: ${n}, stream ${e.stream}, request: ${a}, error?: ${s})`}),[C(e,r,produce(t,e=>{let t=e["agm-domain"];t.subscriptions&&(delete t.subscriptions[n],0===Object.keys(t.subscriptions).length&&delete t.subscriptions)})),T(c)?s?[h(y,c,a,r,i,o)]:[Un(c,n,r,i)]:[]]}return[e,[]]}me(),L();var Ln=R("gateway.domains.agm.subscriptions");function Uu(e,t,r,n,i,o){let s=g$2(e,t);if(s){let a=s["agm-domain"]?.subscriptions?.[r]?.request_id;e=C(e,t,produce(s,e=>{e["agm-domain"].subscriptions[r].stream=n}));let c=s.source;return $(y,()=>{let e=s["agm-domain"].subscriptions[r],i=e.method_id,c=s["agm-domain"]?.methods?.[e.server][i].name;return`[${s.identity.application}#${t}] accepted on ${n} for [${o.identity.application}#${e.server}:${c}#${i}] (subscription: ${r}, request: ${a})`}),q(s)?[e,[ts(c,a,t,r)]]:[e,[K(w(A(e.ids),i.peer_id),_e(c.node),i)]]}return[e,[]]}function ys(e,t,r){let{subscription_id:n,peer_id:i,stream_id:o}=r;o||k(Mt,"Invalid or missing stream id");let s=t["agm-domain"].interests?.[n];if(s){let a=s.subscriber;return e=C(e,i,produce(t,e=>{let t=e["agm-domain"];t.interests=t.interests||{},t.interests[n]=t.interests[n]||{},t.interests[n].stream=o,t.streams=t.streams||{},t.streams[o]=t.streams[o]||{},t.streams[o][a]=t.streams[o][a]||new Set,t.streams[o][a].add(n)})),Uu(e,a,n,o,r,t)}return Ln.enabledFor("debug")&&Ln.debug(`Subscription accept response ${JSON.stringify(r)} for missing interest`),[e,[]]}function Hu(e,t){let{subscription_id:r,peer_id:n,subscriber_id:i}=t,o=B(e,n,"agm-domain");return o?ys(e,o,t):(Ln.warn(`Subscription accept response ${JSON.stringify(t)} from missing peer`),ls(e,g$2(e,i),i,r,S(Vo,"Received a response from a missing server"),null,!0))}function Lu(e,t,r){let{subscription_id:n,peer_id:i}=r;return ys(e,b(e,i,"agm-domain"),r)}function fs(e,t,r){return T(t)?Lu(e,t,r):Hu(e,r)}function Fn(e,t,r){return n=>{let i=n["agm-domain"];i&&(i.interests&&(delete i.interests[e],0===Object.keys(i.interests).length&&delete i.interests),r&&i.streams&&(i.streams[r][t].delete(e),0===i.streams[r][t].size&&(delete i.streams[r][t],0===Object.keys(i.streams[r]).length&&(delete i.streams[r],0===Object.keys(i.streams).length&&delete i.streams))))}}function Gn(e,t,r,n){let i=r.peer_id,o=n?r.request_id:r.subscription_id,s=b(e,i,"agm-domain"),a=s["agm-domain"].interests?.[o];if(a){let c=a.subscriber,l=a.stream,u=g$2(e,c),d=u.source;if(l||n){let t;return e=C(e,i,produce(s,Fn(o,c,l))),[e,t]=ls(e,u,c,o,Q(r),r.context,n),u&&!T(d)&&(t=t.concat(K(w(A(e.ids),i),_e(d.node),r))),[e,t]}return[e,[h(y,t,o,i,Qo)]]}return[e,[h(y,t,o,i,S(Mt,"Trying to drop a non-existing subscription"))]]}function Fu(e,t,r,n,i){let o=g$2(e,r);if(o){let s=o["agm-domain"]?.interests?.[n];if(s){let a=t.id,c=o.source;return[e=C(e,r,produce(o,Fn(n,a,s.stream))),[T(c)?$n(c,n,r,s.method_id,a,Q(i)):K(w(A(e.ids),a),_e(c.node),i)]]}}}function gs(e,t,r,n,i){let o=b(e,r,"agm-domain"),s=o["agm-domain"].subscriptions?.[n];return s?.server||k(Mt,`Unable to find subscription with id ${n} on subscriber id ${r}`),$(y,()=>{let e=o["agm-domain"].methods?.[s.server]?.[s.method_id]?.name;return`[${o.identity.application}#${o.id}] unsubscribed [#${s.server}:${e}#${s.method_id}] (subscription: ${n}, request: ${i})`}),e=C(e,r,produce(o,e=>{let t=e["agm-domain"];t.subscriptions&&(delete t.subscriptions[n],0===Object.keys(t.subscriptions).length&&delete t.subscriptions)})),Fu(e,o,s.server,n,t)||[e,[]]}function Gu(e,t){let{request_id:r,peer_id:n,subscription_id:i}=t;return gs(e,t,n,i,r)}function Wu(e,t,r){let n,{request_id:i,peer_id:o,subscription_id:s}=r;return[e,n]=gs(e,r,o,s,i),[e,n.concat(I(y,t,i,o))]}function hs(e,t,r){return T(t)?Wu(e,t,r):Gu(e,r)}function bs(e,t,r){let{peer_id:n,stream_id:i,sequence:o,snapshot:s,data:a}=r,c=B(e,n,"agm-domain")?.["agm-domain"].streams?.[i]||{},l=new Set;return[e,Object.entries(c).flatMap(([t,i])=>{let c=g$2(e,t).source,u=[];if(T(c))u=Array.from(i,e=>En(c,t,e,!1,o,s,a));else{let t=c.node;l.has(t)||(l.add(t),u=[K(w(A(e.ids),n),_e(t),r)])}return u})]}function Rs(e,t,r){let{peer_id:n,subscription_id:i,sequence:o,snapshot:s,data:a}=r,c=B(e,n,"agm-domain")?.["agm-domain"].interests?.[i].subscriber,l=B(e,c,"agm-domain"),u=l?.source;if(u){let t;if(q(l))t=[En(u,c,i,!0,o,s,a)];else{let i={type:"node",node:u.node};t=[K(w(A(e.ids),n),i,r)]}return[e,t]}return[e,[]]}function Ju(e){let t=X(e.restrictions);return t?{...e,parsedRestrictions:t}:e}function ju(e){let t={...e};return delete t.parsedRestrictions,t}function Bu(e,t,r){let n=e.parsedRestrictions;return!n||ee(n,t,r)}function Jn(e,t,r,n,i){let o=t.id,s=n.id,a=n["agm-domain"]?.methods?.[t.id]||{},[c,l]=r.filter(q(t)?e=>!0:_t(n,i?.defaultMethodRestrictions)).filter(e=>Bu(e,[t.source,t.identity],[n.source,n.identity])).reduce(([e,t],r)=>(e=produce(e,e=>{e[r.id]=castDraft(r)}),[e,t.concat(ju(r))]),[a,new Array]);return l.length>0?(n=produce(n,e=>{e["agm-domain"].methods=e["agm-domain"].methods||{},e["agm-domain"].methods[o]=castDraft(c)}),[C(e,s,n),q(n)?Nn(n.source,s,o,l,t.source.type):[]]):[e,[]]}function xs(e,t,r,n){let i=t.id,o=r.map(e=>Ju(e));t=o.reduce((e,t)=>produce(e,e=>{e["agm-domain"].methods=e["agm-domain"].methods||{},e["agm-domain"].methods[i]=e["agm-domain"].methods[i]||{},e["agm-domain"].methods[i][t.id]=castDraft(t)}),t);let s=C(e,i,t);return $(y,()=>`[${t.identity.application}#${t.id}] registered method(s) [${o.map(e=>`${e.name}#${e.id}`).join(", ")}]`),ie(e,"agm-domain",t).reduce(([e,r],i)=>{let[s,a]=Jn(e,t,o,i,n);return[s,r.concat(a)]},[s,[]])}function Ku(e,t,r,n){let{peer_id:i,methods:o}=r,s=B(e,i,"agm-domain");return void 0!==s&&void 0!==o?xs(e,s,o,n):[e,[]]}function _t(e,t){return r=>{if((void 0===r.restrictions||null===r.restrictions)&&void 0!==t){let n=t.call(e.identity,r.name);return cs$1(e,{parsedRestrictions:n})}return!0}}function Vu(e,t,r,n){let{request_id:i,peer_id:o,methods:s}=r,a=b(e,o,"agm-domain"),[c,l]=xs(e,a,s,n);if(l=l.concat([Nn(t,o,o,s,"local"),I(y,t,i,o)]),re("agm-domain",a)){let t=s.filter(_t(a,n?.defaultMethodRestrictions));if(t.length>0){let n={...r,methods:t};l=l.concat([G(w(A(e.ids),o),n)])}}return[c,l]}function Ss(e,t,r,n){return W(t)?Ku(e,t,r,n):Vu(e,t,r,n)}function jn(e,t,r,n){if(!n&&(!(n=Object.keys(r["agm-domain"]?.methods?.[t]??{}))||0==n.length))return[Ee(e,r.id,e=>{let r=e["agm-domain"];r.methods&&(delete r.methods[t],0===Object.keys(r.methods).length&&delete r.methods)}),[]];let i;if([r,i]=n.reduce(([e,r],n)=>(e["agm-domain"]?.methods?.[t]?.[n]&&(e=produce(e,e=>{let r=e["agm-domain"]?.methods;r?.[t]?.[n]&&(delete r[t][n],0===Object.keys(r[t]).length&&delete r[t],0===Object.keys(r).length&&delete e["agm-domain"]?.methods)}),r.add(n)),[e,r]),[r,new Set]),e=C(e,r.id,nn(r,"agm-domain")),0==i.size)return[e,[]];{let n,o=_(e,t);return[e,n]=fr$1(e,r,o,i,zo),q(r)&&(n=n.concat(qn(r.source,r.id,t,Array.from(i)))),[e,n]}}function vs(e,t,r){let n=t.id,i=nn(r.reduce((e,t)=>(e["agm-domain"].methods?.[n][t]?e=produce(e,e=>{e["agm-domain"].methods[n]=e["agm-domain"].methods[n]||{},delete e["agm-domain"].methods[n][t],0===Object.keys(e["agm-domain"].methods[n]).length&&delete e["agm-domain"].methods[n],0===Object.keys(e["agm-domain"].methods).length&&delete e["agm-domain"].methods}):k(Ko,`Unable to unregister missing method ${t}`),e),t),"agm-domain"),[o,s]=[C(e,n,i),new Array];return[o,s]=ie(e,"agm-domain",i).filter(e=>e.id!==n).reduce(([e,t],i)=>{let[o,s]=jn(e,n,i,r);return[o,t.concat(s)]},[o,new Array]),$(y,()=>`[${t.identity.application}#${n}] unregistered method(s) [${r.map(e=>`${t["agm-domain"].methods?.[n]?.[e]?.name}#${e}`).join(", ")}]`),[o,s]}function zu(e,t){let{peer_id:r,methods:n}=t,i=B(e,r,"agm-domain");return i?vs(e,i,n):[e,[]]}function Qu(e,t,r,n){let{request_id:i,peer_id:o,methods:s}=r,a=b(e,o,"agm-domain"),[c,l]=vs(e,a,s);if(l=l.concat([qn(t,o,o,s),I(y,t,i,o)]),re("agm-domain",a)){let t=a["agm-domain"].methods?.[o]??{},i=s.map(e=>t[e]).filter(_t(a,n?.defaultMethodRestrictions)).map(e=>e.id);if(i.length>0){let t={...r,methods:i};l=l.concat([G(w(A(e.ids),o),t)])}}return[c,l]}function ws(e,t,r){return W(t)?zu(e,r):Qu(e,t,r)}var Ot=R("gateway.domains.agm");function Yu(e,t,r,n,i){let o,{identity:s,id:a}=n,c=Object.values(n["agm-domain"]?.methods?.[a]||{}),l=r.id,u=q(r),d=q(n),h=new Array;return u&&h.push(qe(y,t,l,a,s,{local:d})),d&&h.push(qe(y,n.source,a,l,r.identity,{local:u})),[e,o]=Jn(e,n,c,r,i),[e,h.concat(o)]}function Zu(e,t,r,n){return ie(e,"agm-domain",b(e,r,"agm-domain")).reduce(([e,i],o)=>{let[s,a]=Yu(e,t,b(e,r,"agm-domain"),o,n);return[s,i.concat(a)]},[e,[]])}function Is(e,t,r,n,i,o){return $(y,()=>`[${n.application}#${r}](by ${n.user??""}) added to agm domain (restrictions: ${i?JSON.stringify(i):""})`),Zu(e=he$1(e,r,"agm-domain",i),t,r,o)}function Xu(e,t,r,n){let{peer_id:i,identity:o,restrictions:s}=r;return de$1(e,i,"agm-domain")?[e,[]]:Is(e,t,i,o,s)}function ep(e,t,r,n){let{peer_id:i,request_id:o,identity:s,restrictions:a}=r;if(de$1(e,i,"agm-domain"))return[e,[I(y,t,o,i)]];{let c,l=X(a)??n?.defaultPeerRestrictions;[e,c]=Is(e,t,i,s,l,n),c=c.concat([I(y,t,o,i)]);let u=b(e,i,"agm-domain");if(re("agm-domain",u)){let t={...r,type:"join",restrictions:u["agm-domain"].restrictions};u.options&&(t.options=u.options),c=c.concat([G(w(A(e.ids),i),t)])}return[e,c]}}function tp(e,t,r,n){return W(t)?Xu(e,t,r):ep(e,t,r,n)}function rp(e,t,r,n){let i,o=_(e,r),s=o.source;return[e,i]=ue(e,e=>os(e,s,o,t),e=>fr$1(e,o,t,void 0,kn),e=>jn(e,t.id,_(e,o.id))),[e,T(s)?i.concat(Je(y,s,r,t.id,n)):i]}function Kn(e,t,r){let[n,i]=ie(e,"agm-domain",t).map(e=>e.id).reduce(([e,n],i)=>{let[o,s]=rp(e,t,i,r);return[o,n.concat(s)]},us(e,t,r));return $(y,()=>`[${t.identity.application}#${t.id}] removed from agm domain (reason: ${JSON.stringify(r)})`),[te(n,t.id,"agm-domain"),i]}function np(e,t,r){let{peer_id:n}=r,i=B(e,n,"agm-domain");return i?Kn(e,i,Q(r)):[e,[]]}function ip(e,t,r){let{request_id:n,peer_id:i}=r,o=b(e,i,"agm-domain"),[s,a]=Kn(e,o,Q(r)),c=a.concat(I(y,t,n,i));return re("agm-domain",o)&&(c=c.concat([G(w(A(e.ids),i),{...r,type:"leave"})])),[s,c]}function op(e,t,r){return W(t)?np(e,t,r):ip(e,t,r)}function sp(e,t,r){Ot.enabledFor("debug")&&Ot.debug(`removing source ${JSON.stringify(t)} from agm domain`);let n=Te(e,t,"agm-domain"),i=n.map(e=>e.id).reduce((e,t)=>te(e,t,"agm-domain"),e),o=n.reduce(([e,t],r)=>{let[n,i]=Kn(e,r,kn);return[n,t.concat(i)]},[i,[]]);return Ot.enabledFor("debug")&&Ot.debug(`removed source ${JSON.stringify(t)} from agm domain`),o}function ap(e,t,r){let{request_id:n,peer_id:i}=r;return _(e,i),Hn(e,n,i,r,{failure:r})||Gn(e,t,r,!0)}function cp(e,t,r,n){switch(r.type){case"domain/join":return tp(e,t,r,n);case"domain/leave":return op(e,t,r);case"register":return Ss(e,t,r,n);case"unregister":return ws(e,t,r);case"call":return is$2(e,t,r);case"yield":return as(e,t,r);case"subscribe":return ms$1(e,t,r);case"unsubscribe":return hs(e,t,r);case"drop-subscription":return Gn(e,t,r,!1);case"accepted":return fs(e,t,r);case"publish":return bs(e,t,r);case"post":return Rs(e,t,r);case"error":return ap(e,t,r);case"commands/source-removed":return sp(e,t);default:return Ot.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h(y,t,r.request_id??-1,r.peer_id,S(Bo,`Unhandled message ${JSON.stringify(r)}`))]]}}var Bn=class{constructor(e){this.options=e}info(){return{uri:y,description:"",version:1}}init(e){return e}destroy(e){return e}handleMessage(e,t){let{source:r,body:n}=t;try{return cp(e,r,n,this.options)}catch(t){return T(r)?[e,[h(y,r,n.request_id,n.peer_id,J(t,jo))]]:[e,[]]}}stateToMessages(e,t){let r=e.ids.nodeId;return ne(e,"agm-domain").filter(e=>T(e.source)&&re("agm-domain",e)).flatMap(e=>{let n=e.id,i=[st(void 0,n,e["agm-domain"].restrictions,y,e.identity,e.options)],o=Object.values(e["agm-domain"].methods?.[n]??{}).filter(_t(e,this.options?.defaultMethodRestrictions));return o.length>0&&i.push(Yo(void 0,n,o)),i.map(e=>K(w(r,n),t,e))})}};function Ts(e){return new Bn(e)}var v="activity",As=`${v}.errors.failure`,Vn=`${v}.errors.registration.failure`,Cs=`${v}.errors.missing_factory`,Ms=`${v}.errors.factory_already_registered`,Ps=`${v}.errors.owner_creation`,Ds=`${v}.errors.missing_type`,_s=`${v}.errors.invalid_activity`,zn=`${v}.errors.activity_is_child`,Os=`${v}.errors.invalid_peer`,ks=`${v}.errors.not_authorized`,Ns=`${v}.errors.unhandled_message`,qs=S(`${v}.peer-removed`,"Peer has been removed"),$s=S(`${v}.destroyed`,"Activity destroyed");L();var P="activity-domain";function Es(e,t,r){return t.reduce((e,t)=>produce(e,e=>{e.factories||(e.factories={}),e.factories[t]||(e.factories[t]=[]),e.factories[t].push(r)}),e)}function Qn(e,t,r){return t.length>0&&r?t.reduce((e,t)=>produce(e,e=>{e.factories&&(e.factories[t]=Zi(r,e.factories[t]),0==e.factories[t].length&&delete e.factories[t],0===Object.keys(e.factories).length&&delete e.factories)}),e):e}function Us(e){return e.factories}function Hs(e,t){return e.factories?.[t]}function lt(e,t){if(t)return e.activities?.[t]}function yt(e,t,r){return t?produce(e,e=>{e.activities=e.activities||{},e.activities[t]=r}):e}function Ls(e,t){return produce(e,e=>{e.activities&&(delete e.activities[t],0===Object.keys(e.activities).length&&delete e.activities)})}function Fs(e){return Object.values(e.activities??{})}function gr(e,t){if(t)return e.activityTypes?.[t]}function Gs(e,t,r){return r.reduce((e,r)=>produce(e,e=>{e.activityTypes=e.activityTypes||{},e.activityTypes[t]=e.activityTypes[t]||{},e.activityTypes[t][r.name]=castDraft(r)}),e)}function Ws(e,t,r){return Array.from(r).reduce((e,r)=>produce(e,e=>{e.activityTypes&&(e.activityTypes[t]&&(delete e.activityTypes[t][r],0===Object.keys(e.activityTypes[t]).length&&delete e.activityTypes[t]),0===Object.keys(e.activityTypes).length&&delete e.activityTypes)}),e)}function Yn(e,t){let r=new Set;return e.activitySubscribers?.byType?.[t].forEach(r.add),e.activitySubscribers?.all?.forEach(r.add),r}function Js(e,t,r){return produce(e,e=>{e.activitySubscribers=e.activitySubscribers||{},!0===r?(e.activitySubscribers.all=e.activitySubscribers.all||new Set,e.activitySubscribers.all.add(t)):(e.activitySubscribers.byType=e.activitySubscribers.byType||{},e.activitySubscribers.byType[r]=e.activitySubscribers.byType[r]||new Set,e.activitySubscribers.byType[r].add(t))})}function js(e,t,r){return produce(e,e=>{e.activitySubscribers&&(!0===r?e.activitySubscribers.all&&(e.activitySubscribers.all.delete(t),0===e.activitySubscribers.all.size&&delete e.activitySubscribers.all):e.activitySubscribers.byType&&(e.activitySubscribers.byType[r]&&(e.activitySubscribers.byType[r].delete(t),0===e.activitySubscribers.byType[r].size&&delete e.activitySubscribers.byType[r]),0===Object.keys(e.activitySubscribers.byType).length&&delete e.activitySubscribers.byType),0===Object.keys(e.activitySubscribers).length&&delete e.activitySubscribers)})}function ft(e,t){let r=lt(e,t);if(r)return r;k(_s,`Unable to find activity with id ${t}`)}function Bs(e,t){if(t)return ft(e,t)}function mp(e,t,r){return{domain:v,type:"peer-factories-added",peer_id:e,owner_id:t,factories:r}}function Zn(e,t,r,n){return x(e,mp(t,r,n))}function lp(e,t,r){return{domain:v,type:"peer-factories-removed",peer_id:e,owner_id:t,factory_ids:r}}function Vs(e,t,r,n){return x(e,lp(t,r,n))}function yp(e,t,r,n,i,o){return{domain:v,type:"peer-requested",request_id:e,peer_id:t,peer_factory:r,gateway_token:n,configuration:i,...o}}function zs(e,t,r,n,i,o,s){return x(e,yp(t,r,n,i,o,s))}function Xn(e,t,r,n){return x(e,{domain:v,type:"dispose-peer",peer_id:t,requestor_id:r,reason_uri:n.uri,reason:n.message})}function fp(e,t,r){return{domain:v,type:"peer-created",request_id:e,peer_id:t,created_id:r}}function Qs(e,t,r,n){return x(e,fp(t,r,n))}function ei(e,t,r){return x(e,{domain:v,type:"types-added",peer_id:t,types:r})}function Ys(e,t,r){return x(e,{domain:v,type:"types-removed",peer_id:t,types:r})}function Zs(e,t,r,n){return x(e,{domain:v,type:"initiated",request_id:t,peer_id:r,activity_id:n})}function ti(e){return Object.entries(e).reduce((e,[t,r])=>(e[t]=produce(r,e=>{e.context=e.context.data,e.children&&(e.children=ti(e.children))}),e),{})}function hr(e,t){let r=g$2(e,t);return{peer_id:t,name:r?.peerName,type:r?.peerType}}function gp(e,t,r,n){let i=r.children,o=t.peerName,s=t.peerType,a={domain:v,type:"joined",peer_id:t.id,activity_id:r.id,activity_type:r.type,initiator:r.initiator,context_id:r.contextId,owner:hr(e,r.owner),participants:Array.from(r.readyMembers||[]).map(t=>hr(e,t)),context_snapshot:n};return o&&(a.peer_name=o),s&&(a.peer_type=s),i&&(a.children=ti(i)),a}function br(e,t,r,n,i){return x(t,gp(e,r,n,i))}function hp(e,t,r){let n=t.peerName,i={domain:v,type:"activity-joined",peer_id:e,activity_id:r,joined_id:t.id,joined_type:t.peerType};return n&&(i.peer_name=n),i}function Xs(e,t,r,n){return x(e,hp(t,r,n))}function bp(e,t,r){let n=r.children,i={domain:v,type:"created",peer_id:t,activity_id:r.id,context_id:r.contextId,owner:hr(e,r.owner),participants:Array.from(r.readyMembers||[]).concat(Array.from(r.participants||[])).map(t=>hr(e,t)),activity_type:r.type,initiator:r.initiator};return n&&(i.children=ti(n)),i}function ri(e,t,r,n){return x(t,bp(e,r,n))}function ea(e,t,r,n,i){return x(e,{domain:v,type:"left",peer_id:t,activity_id:n,left_id:r,reason_uri:i.uri,reason:i.message})}function Rp(e,t,r){let n=r.peerName,i=r.peerType,o={domain:v,type:"owner-changed",peer_id:e,activity_id:t,owner_id:r.id};return n&&(o.peer_name=n),i&&(o.peer_type=i),o}function ta$1(e,t,r,n){return x(e,Rp(t,r,n))}function Ye(e,t,r){return I(v,e,t,r)}function kt(e,t,r,n,i){return h(v,e,t,r,n,i)}function ra(e,t,r,n){let i={type:"activity",id:e,peer_type:t.type,activity:{id:r.id,"owner?":n}};return t.name&&(i.peer_name=t.name),i}function na(e,t,r,n){let i={type:"create-peer",id:e,peer_type:t,clientRequest:n};return r&&(i.peer_name=r),i}function Sp(e,t,r){let n=r.reduce((e,t)=>(e[t.peer_type]?e[t.peer_type].push(t):e[t.peer_type]=[t],e),{});return e=C(e,t.id,produce(t,e=>{e[P].factories=e[P].factories||{};for(let[t,r]of Object.entries(n))e[P].factories[t]=r[0]})),e=Es(e,Object.keys(n),t.id)}function vp(e,t,r){return ie(e,P,t).map(e=>Zn(e.source,e.id,t.id,r))}function oa(e,t){return Array.from(new Set(Object.values(Us(e)||{}).flat(1))).map(t=>B(e,t,"activity-domain")).filter(e=>!!e).filter(e=>it$1("activity-domain",t,e)).map(e=>{let r=e["activity-domain"].factories;if(r)return Zn(t.source,t.id,e.id,Object.values(r))}).filter(pe)}function wp(e,t){let r=t.peer_type;e[P]?.factories?.[r]&&k(Ms,`Factory for type ${r} is already registered by this peer`)}function sa(e,t,r){let{request_id:n,peer_id:i,factories:o}=r,s=b(e,i,"activity-domain");o.forEach(e=>wp(s,e));let a=Sp(e,s,o);return[a,vp(a,s,o).concat(I(v,t,n,i))]}function aa(e,t,r,n){let i=t.id;return ie(e,P,t).filter(e=>n||i!==e.id).map(e=>Vs(e.source,e.id,t.id,r))}function Ip(e,t){return Object.values(e||{}).find(e=>e.id===t)}function Tp(e,t){let r=e[P]?.factories,[n,i]=t.reduce(([e,t],n)=>{let i=Ip(r,n);return i?[produce(e,e=>{e[P]?.factories&&(delete e[P]?.factories?.[i.peer_type],0===Object.keys(e[P]?.factories).length&&delete e[P]?.factories)}),t.concat(i)]:[e,t]},[e,[]]);return[n,i]}function ca$1(e,t,r){let{request_id:n,peer_id:i,factory_ids:o}=r,s=b(e,i,"activity-domain"),[a,c]=Tp(s,o),l=Qn(C(e,i,a),c.map(e=>e.peer_type),i),u=aa(l,s,c.map(e=>e.id),!0);return u=u.concat([I(v,t,n,i)]),[l,u]}function da$1(e,t,r,n,i,o,s,a,c){let l={};return s&&(l.activity={id:s.id,type:s.type,context_id:a?.id,"initial-context":a?.data}),c&&(l.peer_name=c),zs(t.source,o,t.id,r.id,i,{...r.configuration,...n},l)}function ua$1(e,t){let r=t.creationRequest?.clientRequest;r||k(Os,`Unable to find originating request for a ready message from peer ${t.id}`);let n=r.peer_id;return[e,[Qs(g$2(e,n).source,r.request_id,n,t.id)]]}function pa(e,t){let r=Object.values(t[P]?.factories||{});return r?[Qn(e,r.map(e=>e.peer_type),t.id),aa(e,t,r.map(e=>e.id),!1)]:[e,[]]}function Ap(e,t,r){let n=g$2(e,t?.peer_id);return n?[e,[h(v,n.source,t.request_id,n.id,r)]]:[e,[]]}function ma(e,t,r,n){return Ap(e,r,t)}function la(e,t,r){let n=g$2(e,t??Hs(e,r)?.[0]),i=n?.[P]?.factories?.[r];return i||k(Cs,`Unable to find factory owner for type ${r}`),[n,i]}function ni(e,t,r,n,i,o,s){let[a,c]=la(e,void 0,r.type),l=_(e,t),[u,d]=Pe(e.ids),h=ra(d,r,n,o),p=fn$1(e,l.identity,h);return{state:e=rn({...e,ids:u},d,h),messages:[da$1(e,a,c,s,p,d,n,i,null)],requestId:d}}function Cp(e,t,r,n,i,o,s,a){let[c,l]=la(e,r,n),u=_(e,t),[d,h]=Pe(e.ids),p=na(h,n,i,{request_id:a.request_id,peer_id:a.peer_id}),g=fn$1(e,u.identity,p);return{state:e=rn({...e,ids:d},h,p),messages:[da$1(e,c,l,s,g,h,o,He(e,o?.contextId),i)],requestId:h}}function ya(e,t,r){let{request_id:n,peer_id:i,owner_id:o,peer_type:s,peer_name:a,activity_id:c}=r;b(e,i,"activity-domain");let l=Cp(e,i,o,s,a??s,Bs(e,c),r.configuration,r);return[l.state,l.messages.concat(I(v,t,n,i))]}me(),L(),me();var Rr=R("gateway.domains.activity.activities");function Pp(e,t,r){let[n,i]=Kt(e.ids),o=X(t.read_permissions),s=X(t.write_permissions),a=o||s?{read:o,write:s}:void 0,c=ir(r,i,t.initial_context,"activity",t.read_permissions,t.write_permissions,a,i,or()),[l,u]=zi(n),d={id:u,type:t.activity_type,contextId:i,initiator:t.peer_id};return d.client_request=t,[{...e,ids:l},d,c]}function ga(e,t,r,n){let i=lt(e,t);if(i){let t=r.id,o=n.activity?.["owner?"],s=He(e,i.contextId);e=yt(e,i.id,produce(i,e=>{e.participants||(e.participants=new Set),e.participants.add(t),o&&(e.owner=r.id),e.gatewayRequests&&(e.gatewayRequests.delete(n.id),0===e.gatewayRequests.size&&delete e.gatewayRequests)})),e=C(e,t,produce(r,e=>{e["activity-domain"].member=i.id,e["activity-domain"].reload=n.reload})),e=dt(e,s,t)}return e}function Dp(e,t,r){return ne(e,P).filter(e=>e.identity.user===t).map(e=>ei(e.source,e.id,r))}function _p(e,t,r){return ne(e,P).filter(e=>e.identity.user===t).map(e=>Ys(e.source,e.id,r))}function ha(e,t,r,n,i){let o=b(e,n,"activity-domain"),s=o.identity.user;if(s){let o=Dp(e,s,i);return o=o.concat(Ye(t,r,n)),[Gs(e,s,i),o]}return[e,[kt(t,r,n,S(Vn,`Registering peer is missing an user in its identity ${JSON.stringify(o.identity)}`))]]}function ba(e,t,r){let{request_id:n,peer_id:i,types:o}=r,s=b(e,i,"activity-domain"),a=s.identity.user;if(a){let r=new Set(o),s=Array.from(new Set(Object.keys(gr(e,a)).filter(e=>r.has(e)))),c=_p(e,a,s);return c=c.concat(Ye(t,n,i)),[Ws(e,a,s),c]}return[e,[kt(t,n,i,S(Vn,`Removing peer is missing an user in its identity ${JSON.stringify(s.identity)}`))]]}function Ra(e,t){let r=gr(e,t.identity.user);if(r){let e=Object.values(r);return[ei(t.source,t.id,e)]}return[]}function Op(e,t,r){let n=gr(e,t.identity.user)?.[r];return n||k(Ds,`Unable to find activity type ${r}`),n}function xa(e,t){e.configuration}function kp(e,t,r,n,i){let{state:o,messages:s,requestId:a}=ni(e.state,r,t,e.activity,n,!0,xa(t));return produce(e,e=>{e.state=castDraft(o),e.messages=e.messages.concat(s),e.activity.gatewayRequests=e.activity.gatewayRequests||new Set,e.activity.gatewayRequests.add(a)})}function Np(e,t,r,n,i){return t?t.reduce((t,i)=>{let{state:o,messages:s,requestId:a}=ni(t.state,r,i,t.activity,n,!1,xa(i));return produce(e,e=>{e.state=castDraft(o),e.messages=e.messages.concat(s),e.activity.gatewayRequests=e.activity.gatewayRequests||new Set,e.activity.gatewayRequests.add(a)})},e):e}function Sa(e,t,r,n){let i,o,{request_id:s,peer_id:a}=r,c=b(e,a,"activity-domain"),l=Op(e,c,r.activity_type),u=(n||[]).reduce((e,t)=>(e[`[${t.type},${t.name??""}]`]=t.configuration??null,e),{}),d=r.types_override;d&&0!==Object.keys(u).length&&k(zn,"Cannot specify types override and custom configuration at the same time"),[e,o,i]=Pp(e,r,c);let h=[Zs(t,s,a,o.id)],p={state:e,messages:h,activity:o};return p=kp(p,d?.owner_type??l.owner_type,a,i),p=Np(p,d?.helper_types??l.helper_types,a,i),({state:e,activity:o,messages:h}=p),[e=yt(e=tr$1(e,i),o.id,o),h]}function qp(e,t,r){if(t["ready?"]){return ii(e,r.id,t,r).map(e=>ta$1(e.source,e.id,t.id,r))}return[]}function $p(e,t,r){let n=t.contextId,i=He(e,n)?.data||{},o=r.id,s=r[P]?.reload;t=produce(t,e=>{e.owner=o,e["ready?"]=!0,delete e.clientRequest});let a=[];return s?(a=a.concat(br(e,r.source,r,t,i)),a=a.concat(qp(e,t,r))):(a=a.concat(Lp(e,t,i)),a=a.concat(Gp(e,t))),{state:e,activity:t,messages:a}}function va(e,t,r){let n=r.id;return!(!e.readyMembers?.has(n)&&!e.participants?.has(n)&&e.owner!==n)||Qt([t.source,t.identity,e.read_permissions,t.options?.service],[r.source,r.identity,void 0,r.options?.service])}function Ep(e,t,r,n){return ii(e,t.id,r,n).map(e=>Xs(e.source,e.id,t,r.id))}function Up(e,t,r,n,i){let o=_(e,r.owner);return ii(e,t,r,o).map(e=>ea(e.source,e.id,t,r.id,n))}function Hp(e,t,r){let n=r.id;if(t.readyMembers?.has(n)||t.participants?.has(n)||t.owner===n)return!0;{let n=g$2(e,t.owner);return Qt([n?.source,n?.identity,t.write_permissions,!1],[r.source,r.identity,void 0,!1])}}function Lp(e,t,r){let n=t.owner,i=t.readyMembers;return(n?[n]:[]).concat(Array.from(i||[])).map(t=>g$2(e,t)).filter(e=>!!e).map(n=>br(e,n.source,n,t,r))}function Fp(e,t,r){let n=new Set;return r&&n.add(r),t.participants&&t.participants.forEach(n.add),t.readyMembers&&t.readyMembers.forEach(n.add),n}function ii(e,t,r,n,i){let o=new Set;return Yn(e,r.type).forEach(o.add),Fp(e,r,n?.id),o.delete(t),Array.from(o).map(t=>g$2(e,t)).filter(e=>!!e).filter(e=>va(r,n,e))}function Gp(e,t){let r=t.type,n=g$2(e,t.owner);return Array.from(Yn(e,r)).map(t=>g$2(e,t)).filter(e=>!!e).filter(e=>va(t,n,e)).map(r=>ri(e,r.source,r.id,t))}function Wp(e,t,r){let n=r.id,i=He(e,t.contextId);t=produce(t,e=>{e.readyMembers=e.readyMembers||new Set,e.readyMembers.add(n)});let o=new Array;if(t["ready?"]){let n=_(e,t.owner);o=o.concat(Ep(e,r,t,n)),o=o.concat(br(e,r.source,r,t,i?.data||{}))}return{state:dt(e,i,n),activity:t,messages:o}}function xr(e){return produce(e,e=>{delete e[P]?.member,delete e[P]?.owner})}function wa(e,t,r,n){let i=n.id,o=lt(e,r);if(o){let t=o.owner===i;o=produce(o,e=>{t||(e.readyMembers=e.readyMembers||new Set,e.readyMembers.add(i)),e.participants?.delete(i),0===e.participants?.size&&delete e.participants});let{state:s,activity:a,messages:c}=t?$p(e,o,n):Wp(e,o,n);return[yt(s,r,a),c]}return[C(e,i,xr(n)),[Xn(t,i,void 0,$s)]]}function Jp(e,t,r){return t.reduce(([e,t],n)=>{let i=g$2(e,n);return i?[C(e,n,xr(i)),t.concat(Xn(i.source,n,void 0,r))]:[e,t]},[e,[]])}function jp(e,t){return(t.gatewayRequests?Array.from(t.gatewayRequests):[]).reduce((e,t)=>tt(e,t).state,e)}function Bp(e,t){return e=rr(e=Ls(e=jp(e,t),t.id),t.contextId)}function oi(e,t,r){let n,i=t.clientRequest,o=t.owner;t.id,[e,n]=ue(e,e=>[Bp(e,t),[]],e=>{let n=new Set;return o&&n.add(o),t.participants&&t.participants.forEach(n.add),t.readyMembers&&t.readyMembers.forEach(n.add),Jp(e,Array.from(n),r)});let s=g$2(e,i?.peer_id);return s?[e,n.concat(kt(s.source,i?.request_id,i?.peer_id,r))]:[e,n]}function Ia(e,t,r){let{request_id:n,peer_id:i,activity_id:o}=r,s=_(e,i),a=ft(e,o);return Hp(e,a,s)?ue(e,e=>oi(e,a,Q(r)),e=>[e,[Ye(t,n,i)]]):[e,[kt(t,n,i,S(ks,"Not authorized to destroy activity"))]]}function Kp(e,t){return oi(e,ft(e,t.id),S(Ps,"Activity owner cannot be created"))}function Ta(e,t){return t["owner?"]?Kp(e,t):[e,[]]}function Vp(e,t,r){return{state:e,activity:t,messages:[]}}function Aa(e,t,r){let{request_id:n,peer_id:i,target_id:o,activity_id:s,peer_type:a,peer_name:c}=r;b(e,i,"activity-domain");let l=ft(e,s),u=produce(b(e,o,P),e=>{a&&(e.peerType=a),c&&(e.peerName=c)}),d=u[P]?.member,h=u[P]?.owner,p=lt(e,d??h);if(p?.id===s)return[e,[Ye(t,n,i)]];p&&k(zn,`Peer is already in activity ${p.id}`);let{state:g,messages:m}=Vp(e,l);return[g,m.concat(Ye(t,n,i))]}function zp(e,t){return produce(e,e=>{e.participants&&(e.participants.delete(t),0===e.participants.size&&delete e.participants),e.readyMembers&&(e.readyMembers.delete(t),0===e.readyMembers.size&&delete e.readyMembers)})}function Ca(e,t,r,n){Rr.enabledFor("debug")&&Rr.debug(`a participant ${r.id} of activity ${t.id} has left.`);let i=r.id,o=(t=zp(t,i)).id,s=Up(e,i,t,n);return e=yt(e=C(e,i,xr(r)),o,t),[e]=nr(e,He(e,t.contextId),i),{state:e,activity:t,messages:s}}function Qp(e,t,r,n,i){let o=r.id;if(Rr.enabledFor("debug")&&Rr.debug(`the owner ${o} of activity ${t.id} has left`),i)return oi(C(e,o,xr(r)),t,n);{let{state:i,messages:o}=Ca(e,t,r,n);return[i,o]}}function Ma(e,t,r){let n=t[P]?.member,i=lt(e,n);if(i){let n=i.owner,o=t.id,s=i.reloading&&i.reloading.has(o);if(i=produce(i,e=>{s&&e.reloading&&(e.reloading.delete(o),0===e.reloading.size&&delete e.reloading)}),n===o)return Qp(e,i,t,r,!s);{let{state:n,messages:o}=Ca(e,i,t,r);return[n,o]}}return[e,[]]}function Pa(e,t,r,n,i,o){return e=i?i.filter(e=>!!e).reduce((e,t)=>o(e,n,t),e):o(e,n,!0),[e,[Ye(t,r,n)]]}function Da(e,t,r){let n,{request_id:i,peer_id:o,activity_types:s}=r,a=b(e,o,"activity-domain");[e,n]=Pa(e,t,i,o,s,Js);let c=Fs(e).filter(e=>e["ready?"]);return n=n.concat((s?c.filter(e=>-1!==s.indexOf(e.type)):c).map(t=>ri(e,a.source,a.id,t))),[e,n]}function _a(e,t,r){let{request_id:n,peer_id:i,activity_types:o}=r;return b(e,i,"activity-domain"),Pa(e,t,n,i,o,js)}var gt=R("gateway.domains.activity");function Xp(e,t,r){let{state:n,removed:i}=tt(e,r.request_id);if(i){let e=i.type;switch(e){case"activity":{let e=i.activity;if(e)return Ta(n,e);break}case"create-peer":return ma(n,Q(r),i.clientRequest);default:gt.error("Unable to handle error for an unknown incoming request type "+e)}}return[e,[]]}function em(e,t){let r=t?.creationRequest;if(r){let{peer_name:n,peer_type:i}=r;switch(t=produce(t,e=>{n&&(e.peerName=n),i&&(e.peerType=i)}),r.type){case"activity":return ga(e,r.activity?.id,t,r);case"create-peer":return C(e,t.id,t)}}return e}function tm(e,t,r){let{request_id:n,peer_id:i,restrictions:o}=r;if(de$1(e,i,P))return[e,[I(v,t,n,i)]];let s=X(o),a=b(e=he$1(e,i,P,s),i,"activity-domain");e=em(e,a);let c=new Array;return c=c.concat(Yt(v,P,e,t,a)),c=c.concat(Ra(e,a)),c=c.concat(oa(e,a)),c=c.concat([I(v,t,n,i)]),[e,c]}function Oa(e,t,r,n){return ue(e,e=>Ma(e,t,r),e=>pa(e,t),e=>Zt(v,P,e,t,r,n))}function rm(e,t,r){let{request_id:n,peer_id:i}=r,o=b(e,i,"activity-domain");return ue(e,e=>Oa(e,o,Q(r),!1),e=>[e,[I(v,t,n,i)]])}function nm(e,t,r){let n=_(e,r.peer_id),i=n[P]?.member;return i?wa(e,t,i,n):ua$1(e,n)}function im(e,t){gt.enabledFor("debug")&>.debug(`removing source ${JSON.stringify(t)} from activity domain`);let r=Te(e,t,P),n=r.map(e=>e.id).reduce((e,t)=>te(e,t,P),e),i=r.reduce(([e,t],r)=>{let[n,i]=Oa(e,r,qs,!0);return[n,t.concat(i)]},[n,[]]);return gt.enabledFor("debug")&>.debug(`removed source ${JSON.stringify(t)} from activity domain`),i}function om(e,t,r){switch(r.type){case"domain/join":return tm(e,t,r);case"domain/leave":return rm(e,t,r);case"ready":return nm(e,t,r);case"add-types":{let{request_id:n,peer_id:i,types:o}=r;return ha(e,t,n,i,o)}case"remove-types":return ba(e,t,r);case"create":{let{configuration:n,...i}=r;return Sa(e,t,i,n)}case"destroy":return Ia(e,t,r);case"subscribe":return Da(e,t,r);case"unsubscribe":return _a(e,t,r);case"join-activity":return Aa(e,t,r);case"add-peer-factories":return sa(e,t,r);case"remove-peer-factories":return ca$1(e,t,r);case"create-peer":return ya(e,t,r);case"error":return Xp(e,t,r);case"update-context":return ut(v,e,t,r);case"commands/source-removed":return im(e,t);default:return gt.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h(v,t,r.request_id??-1,r.peer_id,S(Ns,`Unhandled message ${JSON.stringify(r)}`))]]}}var si=class{info(){return{uri:v,description:"",version:2}}init(e){return e}destroy(e){return e}handleMessage(e,t){let{source:r,body:n}=t;try{return om(e,r,n)}catch(t){return T(r)?[e,[h(v,r,n.request_id,n.peer_id,J(t,As))]]:[e,[]]}}stateToMessages(e,t){return[]}};function ka(){return new si}L();var Re="metrics",Na=`${Re}.errors.failure`,qa=`${Re}.errors.unhandled_message`,$a=`${Re}.errors.bad_identity`,ai=S(`${Re}.peer-removed`,"Peer has been removed"),oe="metrics-domain";ci();var Ge=R("gateway.domains.metrics"),cm=["system","service","instance"];function dm(e){let t=cm.find(t=>!(t in e));t&&k($a,`Repository is missing required ${t} property`)}function um(e,t){return{machine:t.machine,system:t.system,service:t.application,"start-time":Date.now()}}function pm$1(e,t,r){let{request_id:n,peer_id:i,identity:o,options:s}=r,a=Object.assign({},um(t,o),s,o);return de$1(e,i,oe)||(dm(a),e=produce(he$1(e,i,oe,void 0),e=>{let t=e.peers?.[i];t[oe]={restrictions:"local",repoId:a}})),[e,[I(Re,t,n,i)]]}function ui(e,t,r){let n=t.id,i=t[oe]?.repos;return i&&(Ge.info(`stopping metrics publishing for peer ${n}, reason: ${JSON.stringify(r)}`),i.forEach(e=>{e.stop()})),te(e,n,oe)}function mm(e,t,r){let{request_id:n,peer_id:i}=r;return[ui(e,_(e,i),Q(r)),[I(Re,t,n,i)]]}function lm(e,t,r,n){let i=produce(e,e=>{let i,o=e.peers?.[r];if(o){let e=o[oe];e&&(i=e.repos,i||(i=e.repos=t.map(e=>{let t=e.repository(n);return t.start(),t}),e.repos=i))}});return[i,i.peers?.[r]?.[oe]?.repos??[]]}function ym(e,t,r,n,i){let{peer_id:o,metrics:s}=r,a=b(e,o,oe),c=a[oe].repoId,l=s.filter(e=>Nt(c,e.name,i));if(l.length>0){Ge.enabledFor("debug")&&Ge.debug(`publisher ${JSON.stringify(c)} adding metrics [${l.map(e=>e.name).join(",")}]`);let[t,r]=lm(e,n,a.id,c);return r.forEach(e=>e.add(l)),[t,[]]}return[e,[]]}function fm(e,t,r,n){let{peer_id:i,values:o}=r,s=b(e,i,oe),a=s[oe].repoId,c=o.filter(e=>Nt(a,e.name,n));if(c.length>0){let e=s[oe].repos;e&&e.forEach(e=>e.publish(c))}return[e,[]]}function gm(e,t){return Ge.enabledFor("debug")&&Ge.debug(`removing source ${JSON.stringify(t)} from metrics domain`),e=Te(e,t,oe).reduce((e,t)=>ui(e,t,ai),e),[e,[]]}function hm(e,t,r,n,i){switch(r.type){case"domain/join":return pm$1(e,t,r);case"domain/leave":return mm(e,t,r);case"commands/source-removed":return gm(e,t);case"define":return ym(e,t,r,n,i);case"publish":return fm(e,t,r,i);default:return Ge.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h(Re,t,r.request_id??-1,r.peer_id,S(qa,`Unhandled message ${JSON.stringify(r)}`))]]}}var di=class{constructor(e,t){this.factories=e,this.filters=t}info(){return{uri:Re,description:"",version:1}}init(e){return e}destroy(e){return e=ne(e,oe).reduce((e,t)=>ui(e,t,ai),e),e}handleMessage(e,t){let{source:r,body:n}=t;try{return hm(e,r,n,this.factories,this.filters)}catch(t){return T(r)?[e,[h(Re,r,n.request_id,n.peer_id,J(t,Na))]]:[e,[]]}}stateToMessages(e,t){return[]}};function Ha(e,t){return Ge.enabledFor("debug")&&Ge.debug(`Initializing metrics domain with filters ${t?JSON.stringify(t):""}`),new di(e,t)}async function Ka(e){return Tr(e,await Ir(e,t=>Sr(e.split_size??1,t),e?.publishFn??"@interopio/gateway/metrics/publisher/custom"))}pi(),hi(),me(),L();var km=R("gateway.metrics");async function Nm(e,t){if("rest"===e){let{restRepositoryFactory:e}=await Promise.resolve().then(()=>(Qa(),za));return await e(t)}if("file"===e)throw new Error("file publisher is supported only in nodejs")}async function Za(e,t){let r=e??{publishers:[]};return Promise.all(r.publishers.map(async e=>{try{if("string"==typeof e)return await Nm(e,r[e]);{let r=produce(e,e=>{t&&(e.context=e.context||{},e.context.gw=e.context.gw||{url:t},e.context.gw.url=t)});return await Ka(r)}}catch(t){return void km.error(`failed to create repository factory ${JSON.stringify(e)}`,t)}})).then(e=>e.filter(pe))}L();var ht="context-domain",E=se,Xa=Ue(E),Ar=S(`${E}.peer-removed`,"Peer has been removed");function ec(e,t,r,n,i,o,s,a){return{domain:E,type:"create-context",request_id:e,peer_id:t,name:r,data:n,lifetime:i,read_permissions:o,write_permissions:s,version:a}}function tc(e,t,r){return{domain:E,type:"subscribe-context",peer_id:t,request_id:e,context_id:r.id,name:r.name}}var qt=R("gateway.domains.context");function $m(e,t){return ec(void 0,e,t.name,t.data,t.lifetime,t.read_permissions,t.write_permissions,t.version)}function Em(e,t,r,n){let i=b(e,r,"context-domain"),o=Yt(E,"context-domain",e,t,i).filter(t=>wn(e,t));n&&(o=o.filter(e=>r!==e.body.new_peer_id));let s=n?[]:Po(At(i),e,i);return o.concat(s)}function rc(e,t,r,n,i,o){let s=he$1(e,r,ht,i);return $(E,()=>`[${n.application}#${r}(by ${n.user??""})] added to context domain (restrictions: ${i?JSON.stringify(i):""})`),o&&(s=Ee(s,r,e=>{e.options&&(delete e.options["context-compatibility-mode?"],0===Object.keys(e.options).length&&delete e.options)})),[s,Em(s,t,r,o)]}function Um(e,t,r){let{request_id:n,peer_id:i,identity:o,restrictions:s}=r,a=r.options?.["context-compatibility-mode?"],c=g$2(e,i)?.options?.["context-compatibility-mode?"],l=de$1(e,i,ht);if(l&&!c)return[e,[I(E,t,n,i)]];{let u=X(s),[d,h]=rc(e,t,i,o,u,l&&c),p=g$2(d,i),g=[];if(a||g.push(I(E,t,n,i)),re("context-domain",p)){let t={...r,domain:D,type:"join",destination:E,identity:o};p?.options&&(t.options=p.options),u&&(t.restrictions=u),g.push(G(w(A(e.ids),i),t))}return[d,h.concat(g)]}}function Hm(e,t,r){let{peer_id:n,identity:i,restrictions:o}=r,s=g$2(e,n)?.options?.["context-compatibility-mode?"];return s&&de$1(e,n,ht)?[e,[]]:rc(e,t,n,i,o,s)}function Lm(e,t,r){return W(t)?Hm(e,t,r):Um(e,t,r)}function Fm(e,t,r){let{peer_id:n}=r,i=B(e,n,"context-domain");return i?lr(E,e,i,Q(r),!1):[e,[]]}function Gm(e,t,r){let{request_id:n,peer_id:i}=r,[o,s]=lr(E,e,b(e,i,"context-domain"),Q(r),!1);return[o,s.concat([I(E,t,n,i),G(w(A(o.ids),i),{...r,type:"leave"})])]}function Wm(e,t,r){return W(t)?Fm(e,t,r):Gm(e,t,r)}function Jm(e){return 1==e.local&&void 0!==e.version&&Le(e)}function jm(e,t){let r=e.ids.nodeId,n=new Set,i=ne(e,"context-domain").filter(e=>T(e.source)&&re("context-domain",e)).map(e=>{let i=e.id;return n.add(i),K(w(r,i),t,st(void 0,i,e["context-domain"].restrictions,E,e.identity,e.options))}),o=wo(e).filter(Jm).flatMap(e=>{let i=Array.from(e.members).filter(e=>n.has(e)),o=e.owner??i[0],s=[K(w(r,o),t,$m(o,e))],a=Array.from(i).map(n=>K(w(r,n),t,tc(void 0,n,e)));return s.concat(a)});return i.concat(o)}function Bm(e,t,r){qt.enabledFor("debug")&&qt.debug(`removing source ${JSON.stringify(t)} from context domain`);let n=Te(e,t,ht),i=n.map(e=>e.id).reduce((e,t)=>te(e,t,ht),e),o={domain:D,type:"leave",destination:E,reason_uri:Ar.uri,reason:Ar.message},s=n.reduce(([t,r],n)=>{let[i,s]=lr(E,t,n,Ar,!0),a=[];if(T(n.source)&&re("context-domain",n)){let t={...o,peer_id:n.id};a.push(G(w(A(e.ids),n.id),t))}return[i,r.concat(s.concat(a))]},[i,[]]);return qt.enabledFor("debug")&&qt.debug(`removed source ${JSON.stringify(t)} from context domain`),s}function Km(e,t,r,n){switch(r.type){case"domain/join":return Lm(e,t,r);case"domain/leave":return Wm(e,t,r);case"create-context":return pr(E,e,t,r,n);case"update-context":return ut(E,e,t,r);case"subscribe-context":return ur$1(E,e,t,r);case"unsubscribe-context":return dr(E,e,t,r);case"destroy-context":return mr(E,e,t,r);case"commands/source-removed":return Bm(e,t);default:return qt.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h(E,t,r.request_id??-1,r.peer_id,S(ho(E),`Unhandled message ${JSON.stringify(r)}`))]]}}var bi=class{constructor(e){this.options=e}destroy(e){return e}handleMessage(e,t){let{source:r,body:n}=t;try{return Km(e,r,n,this.options)}catch(t){return T(r)?[e,[h(E,r,n.request_id,n.peer_id,J(t,Xa))]]:[e,[]]}}info(){return{uri:E,description:"",version:3}}init(e){return e}stateToMessages(e,t){return jm(e,t)}};function nc(e){return new bi(e)}L();var ic="bus.errors.failure",oc="bus.errors.unhandled_message";function sc(e,t,r,n,i){return x(e,{domain:"bus",type:"event",peer_id:t,subscription_id:r,"publisher-identity":n,data:i})}function ac(e,t,r,n){return x(e,{domain:"bus",type:"subscribed",request_id:t,peer_id:r,subscription_id:n})}var Cr=R("gateway.domains.bus");function Vm(e,t,r){let{peer_id:n,restrictions:i}=r;return de$1(e,n,"bus-domain")?[e,[]]:[he$1(e,n,"bus-domain",i),[]]}function zm(e,t,r,n){let{request_id:i,peer_id:o,restrictions:s}=r;if(de$1(e,o,"bus-domain"))return[e,[I("bus",t,i,o)]];let a=b(e=he$1(e,o,"bus-domain",X(s)??n?.defaultPeerRestrictions),o,"bus-domain"),c=[I("bus",t,i,o)];if(re("bus-domain",a)){let t={...r,type:"join",options:a?.options,restrictions:a["bus-domain"].restrictions};c.push(G(w(A(e.ids),o),t))}return[e,c]}function Qm(e,t,r,n){return W(t)?Vm(e,t,r):zm(e,t,r,n)}function Ym(e,t){return Cr.enabledFor("debug")&&Cr.debug(`removing source ${JSON.stringify(t)} from bus domain`),e=Te(e,t,"bus-domain").reduce((e,t)=>te(e,t.id,"bus-domain"),e),[e,[]]}function Zm(e,t,r){let{peer_id:n}=r;return g$2(e,n)?[te(e,n,"bus-domain"),[]]:[e,[]]}function Xm(e,t,r){let{request_id:n,peer_id:i}=r,o=b(e,i,"bus-domain"),s=te(e,i,"bus-domain"),a=[I("bus",t,n,i)];return re("bus-domain",o)&&a.push(G(w(A(e.ids),i),{...r,type:"leave"})),[s,a]}function el(e,t,r){return W(t)?Zm(e,t,r):Xm(e,t,r)}function tl(e){return e.map(e=>[e,Object.entries(e["bus-domain"]?.subscriptions||{})]).flatMap(([e,t])=>t.map(([t,r])=>({peer:e,subscription:[t,r]})))}function rl({topic:e,topicRepattern:t},r){if(t){let e=r.match(t);return null!==e&&r===e[0]}return e===r}function nl$1(e,t){return!e||!t||e===t}function il(e,t,[,r]){return rl(r,e)&&nl$1(r.routingKey,t)}function ol(e,t){if(e){let r=t.identity;for(let[t,n]of Object.entries(e))if(r[t]!==n)return!1}return!0}function dc(e,t,r){let{data:n}=t;if(n){let{topic:i,routing_key:o,peer_id:s,target_identity:a}=t,c=e=>il(i,o,e),l=e=>ol(a,e),u=r.identity,d=new Set,h=tl(ie(e,"bus-domain",r,!0).filter(l)).filter(({subscription:e})=>c(e)).reduce((r,{peer:i,subscription:o})=>{let a=i.source,c=i.id,[l]=o,h=T(a)?sc(a,c,l,u,n):function(){if(s!==c){let r=a.node;if(d.has(r)){d.add(r);let n={type:"node",node:r};return K(w(A(e.ids),s),n,t)}}}();return h?r.concat(h):r},[]);return[e,h]}return[e,[]]}function sl$1(e,t){let{peer_id:r}=t,n=b(e,r,"bus-domain");return n?dc(e,t,n):[e,[]]}function al(e,t){let{peer_id:r}=t,n=B(e,r,"bus-domain");return n?dc(e,t,n):[e,[]]}function cl(e,t,r){return T(t)?sl$1(e,r):al(e,r)}function dl(e){return-1!==e.indexOf(">")||-1!==e.indexOf("*")}function ul(e){return new RegExp(e.replace(/\./g,"\\.").replace(/\*/g,"[a-zA-Z_0-9]+").replace(/>/g,".*"),"g")}function uc(e,t,r,n){let{topic:i,routing_key:o,request_id:s,peer_id:a}=t,c=n.source;n=produce(n,e=>{e["bus-domain"].subscriptions=e["bus-domain"].subscriptions||{},e["bus-domain"].subscriptions[r]={topic:i,routingKey:o},dl(i)&&(e["bus-domain"].subscriptions[r].topicRepattern=ul(i))});let l={...t,subscription_id:r};return[C(e,a,n),T(c)?[ac(c,s,a,r),G(w(A(e.ids),a),l)]:[]]}function pl$1(e,t,r){let[n,i]=Pe(e.ids),o=b(e,r.peer_id,"bus-domain");return uc({...e,ids:n},r,i,o)}function ml(e,t,r){let{subscription_id:n,peer_id:i}=r,o=B(e,i,"bus-domain");return o?uc(e,r,n,o):[e,[]]}function ll(e,t,r){return T(t)?pl$1(e,t,r):ml(e,t,r)}function pc(e,t,r){let{request_id:n,peer_id:i,subscription_id:o}=t,s=r.source;return r=produce(r,e=>{e["bus-domain"].subscriptions&&delete e["bus-domain"].subscriptions[o]}),[C(e,i,r),T(s)?[I("bus",s,n,i),G(w(A(e.ids),i),t)]:[]]}function yl(e,t,r){return pc(e,r,b(e,r.peer_id,"bus-domain"))}function fl(e,t){let r=B(e,t.peer_id,"bus-domain");return r?pc(e,t,r):[e,[]]}function gl(e,t,r){return T(t)?yl(e,t,r):fl(e,r)}function hl(e,t,r,n){switch(r.type){case"domain/join":return Qm(e,t,r,n);case"domain/leave":return el(e,t,r);case"commands/source-removed":return Ym(e,t);case"publish":return cl(e,t,r);case"subscribe":return ll(e,t,r);case"unsubscribe":return gl(e,t,r);default:return Cr.error(`Unhandled message ${JSON.stringify(r)}`),[e,[h("bus",t,r.request_id??-1,r.peer_id,S(oc,`Unhandled message ${JSON.stringify(r)}`))]]}}var Ri=class{constructor(e){this.options=e}info(){return{uri:"bus",description:"",version:1}}init(e){return e}destroy(e){return e}handleMessage(e,t){let{source:r,body:n}=t;try{return hl(e,r,n,this.options)}catch(i){return je(i)||Cr.error(`Error processing message ${JSON.stringify(t)}`,i),[e,[h("bus",r,n.request_id,n.peer_id,J(i,ic))]]}}stateToMessages(e,t){let r=A(e.ids);return ne(e,"bus-domain").filter(e=>T(e.source)&&re("bus-domain",e)).flatMap(e=>{let n=e.id;return[st(void 0,n,e["bus-domain"].restrictions,"bus",e.identity,e.options)].map(e=>K(w(r,n),t,e))})}};function mc(e){return new Ri(e)}L();var Mr=R("gateway.clients");function lc(e,t,r,n,i,o){Mr.info(`adding client for key ${r}`);let s={source:n,lastAccess:Date.now(),onScavenge:i,onStop:o};e.set(r,s);try{t.addSource(n)}catch(e){Mr.error(`Unable to add client for key ${r}`,e)}}function Pr(e,t,r){Mr.info(`removing client for key ${r}`);let n=e.get(r);if(n){e.delete(r);try{t.removeSource(n.source)}catch(e){Mr.error(`Unable to remove client for ${r}`,e)}}}L();var $t=R("gateway.scavenger");function bl(e,t,r){$t.enabledFor("trace")&&$t.debug(`running client scavenger. collecting everything older than ${r}`),e.forEach((n,i)=>{if(n.lastAccess<=r){$t.info(`scavenging client for ${i}. Last access ${new Date(n.lastAccess)} < ${new Date(r)}`);try{Pr(e,t,i),n.onScavenge&&n.onScavenge()}catch(e){$t.warn(`error scavenging client for ${i}`,e)}}})}var Rl=10,yc=1e3,Et=class{constructor(e,t,r){this.clients=e,this.node=t,this.inactiveSeconds=r,r>0&&($t.info(`clients inactive for ${r} seconds will be scavenged`),this.cancel=setInterval(async()=>{this.scavengeClients()},yc))}scavenging=!1;cancel;scavengeClients(){if(!this.scavenging)try{this.scavenging=!0;let e=2*Math.max(this.inactiveSeconds,Rl)*yc,t=Date.now()-e;bl(this.clients,this.node,t)}finally{this.scavenging=!1}}stop(){clearTimeout(this.cancel)}},fc="0.22.2";function Dr(e){return"peer"===e?.type}function gc(e){return"node"===e?.type}function hc(e){return"cluster"===e?.type}me(),L(),me();var xi=class{#e;#t;#o;#r;constructor(e,t,r,n){this.#e=e,this.#t=t,this.#o=r,this.#r=n}init(){void 0!==this.#r&&this.#t.addUsers(this.#o,this.#r)}close(){void 0!==this.#r&&this.#t.removeUsers(this.#o,this.#r),this.#t.unregister(this.#o),this.#t.close()}message(e){this.#e(e)}addSource(e){}removeSource(e){let t={origin:"local",source:e,body:{type:"commands/source-removed"}};return this.#e(t)}},j=R("gateway.node.mesh");function xl(e,t){let{source:r,body:n,origin:i}=t;try{return n.dump?(j.info(`state dump:\n${JSON.stringify($e(e),null,"\t")}`),[e,[]]):"cluster"===i?Sl(e,t):ze(e,t,r)}catch(i){j.error(`Error handling message ${JSON.stringify(t)}`,i);let o=n;return[e,[h(void 0,r,o.request_id,o.peer_id,J(i,Ne))]]}}function bc(e,t,r){j.info(`Node ${t} is sending state to node ${r}`);let n={type:"node",node:r},i=Object.values(e.registeredDomains||[]).map(e=>e.domain).flatMap(t=>t.stateToMessages(e,n)).filter(pe);return[e,i]}function xc(e){return"receive"in e&&e.receive}function Sl(e,t){let r=e.ids.nodeId,{source:n,body:i,origin:o,receiver:s}=t;if(Dr(s)){if(r===s.node){let t=g$2(e,s.peer);t&&xc(t.source)&&t.source.receive(i)}return[e,[]]}return gc(s)?r===s.node?"send-state"===i.type?bc(e,r,n.node):ze(e,t,n):[e,[]]:hc(s)?r!==n.node?"send-state"===i.type?bc(e,r,n.node):ze(e,t,n):[e,[]]:ze(e,t,n)}function vl(e,t,r){switch(r.receiver.type){case"cluster":j.enabledFor("debug")&&j.debug(`broadcasting message ${JSON.stringify(r)}`),t.publish(e,r);break;case"node":j.enabledFor("debug")&&j.debug(`unicasting message ${JSON.stringify(r)}`),t.publish(e,r);break;case"peer":if(j.enabledFor("debug")){let{receiver:e,body:t}=r;j.enabledFor("debug")&&j.debug(`Sending message ${JSON.stringify(t,null,"\t")} to remote peer ${JSON.stringify(e)}`)}t.publish(e,r);break;case"local":{let{receiver:e,body:t}=r;j.enabledFor("debug")&&j.debug(`Sending message ${JSON.stringify(t,null,"\t")} to local peer ${JSON.stringify(e)}`),xc(e)&&e.receive(t);break}default:j.error(`Unable to process response ${JSON.stringify(r)}`)}}function Rc(e){return new Set(e.users?.byName?.keys())}function wl(e,t,r,n){try{j.enabledFor("trace")&&j.debug(`domain handler processing message ${JSON.stringify(n)}`);let i=e.ids.nodeId,[o,s]=xl(e,n);try{for(let e of s){vl(i,r,{...e,source:{...e.source,node:i}})}}catch(e){j.error("error processing responses",e)}if(t){let t=Rc(o),n=Rc(e),s=Array.from(t??[]).filter(e=>!n?.has(e));s&&s.length>0&&r.addUsers(i,s);let a=Array.from(n??[]).filter(e=>!t?.has(e));a&&a.length>0&&r.removeUsers(i,a)}return o??e}catch(t){return j.error(`error handling message ${JSON.stringify(n)}`,t),e}}function _r(e,t,r){let n,i=void 0===r.users,o=t=>{n=wl(n,i,e,t)},s=Xt(t),a={domains:Object.values(s).map(e=>e.info)},c=e.register(r.nodeId,a,{onMessage:(e,t)=>(j.enabledFor("debug")&&j.debug(`Node ${e} received a message from cluster ${JSON.stringify(t)}`),o({...t,origin:"cluster"})),onMemberAdded:(t,r)=>{j.enabledFor("debug")&&j.debug(`Node ${t} received a node ${r} add to cluster.`);let n={origin:"cluster",receiver:{type:"node",node:r},source:{type:"node",node:t},body:{type:"send-state"}};return e.publish(t,n)},onMemberRemoved:(e,t)=>(j.enabledFor("debug")&&j.debug(`Node ${e} received a node ${t} dropped from cluster`),o({origin:"cluster",receiver:{type:"node",node:e},source:{type:"node",node:t},body:{type:"commands/source-removed"}}))});n=t.reduce((e,t)=>t.init(e),{...zt(c,r.signingKey),registeredDomains:s,handler:e=>{o(e)}});let l=new xi(o,e,c,r.users);return l.init(),l}L();var U=R("gateway.ws.common"),vi$1=class{constructor(e,t,r){this.url=e,this.protocols="string"==typeof t?t:[...t],this.dynamicArguments=r.dynamicArguments,this.WebSocket=r.WebSocket,this.URL=r.URL,this.codec=r.codec,this.maxEnqueued=r.maxEnqueued??-1,this.retry=r.retry}dynamicArguments;url;protocols;WebSocket;URL;state="_initial";codec;socket;maxEnqueued;queue=[];retry;reconnectAttempt=0;reconnectTimeout;activeSocketId=0},Il=50,Si={min:1e3+4e3*Math.random(),max:6e4,factor:1.3};function Tl(e,t){let r=Math.max(Il,t?.min??Si.min),n=Math.max(r,t?.max??Si.max),i=Math.max(1,t?.factor??Si.factor);return Math.round(Math.min(n,r*Math.pow(i,e)))}var wi=class e{#e;#t;#o;static#r="interop.io:manual-disconnect";constructor(e){this.#e=e,this.#t="string"==typeof e.url?e.url:e.url.href}get url(){return this.#t}onConnect;onReceive;onError;onDisconnect;onClose;#s(e){let t=++this.#e.activeSocketId;U.enabledFor("debug")&&U.debug(`[${t}]: connecting to ${this.#e.url}`),this.#a(e).then(()=>{let e=new this.#e.WebSocket(this.#t,this.#o);e._internalSocketId=t,this.#i(e)}).catch(e=>{this.onError?this.onError(e instanceof Error?e:new Error(`Failed to create socket: ${e}`)):U.warn(`[${t}]: init socket error: ${e}`,e)})}#i(t){t.onopen=()=>{U.info(`[${t._internalSocketId}]: connection to ${this.#e.url} is up.`);let r="connecting"===this.#e.state;if(this.#e.queue.length>0)for(U.debug(`[${t._internalSocketId}]: flushing ${this.#e.queue.length} pending messages`);this.#e.queue.length>0;){let e=this.#e.queue.shift();e&&(r?t.send(e):U.warn(`[${t._internalSocketId}]: connection to ${this.#e.url} is ${this.#e.state} state, dropping message ${e}`))}return"closing"===this.#e.state?(U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: socket opened but in closing state, closing socket to ${this.#e.url}`),void t.close()):"_disconnecting"===this.#e.state?(U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: socket opened but in disconnecting state, closing socket to ${this.#e.url}`),this.#e.state="_initial",void t.close(1e3,e.#r)):(this.#e.state="connected",this.#e.socket=t,void(this.onConnect&&this.onConnect(t.url,t.protocol)))},t.onerror=e=>{this.onError?this.onError(e.error):U.warn(`[${t._internalSocketId}]: got error: ${JSON.stringify(e)}`,e.error)},t.onmessage=e=>{let r=this.#e.codec.decode(e.data);U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: got message ${JSON.stringify(r)} from ${this.#e.url}`),this.onReceive&&this.onReceive(r)},t.onclose=r=>{let n=!1;if(this.#e.socket?._internalSocketId===t._internalSocketId&&(n=!0,this.#e.socket=void 0),"closing"===this.#e.state)n&&this.onDisconnect&&this.onDisconnect(r.code,r.reason,r.wasClean),this.#e.state="closed",U.enabledFor("info")&&U.info(`[${t._internalSocketId}]: connection to ${this.#e.url} has closed (${r.reason}:${r.code}) (wasOpen: ${n})`),this.onClose&&this.onClose();else{let n="connected"===this.#e.state,i="_disconnecting"===this.#e.state;if(!1===this.#e.retry||r.reason===e.#r){if(U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: will not reconnect to ${this.#e.url} (manual disconnect or retry disabled) (wasConnected: ${n})`),"_initial"!==this.#e.state&&(this.#e.state="_initial"),!i)return}else{"connecting"!==this.#e.state&&(this.#e.reconnectAttempt=0,this.#e.state="connecting");let e=Tl(this.#e.reconnectAttempt,this.#e.retry),n=this.#e.reconnectAttempt++;U.enabledFor("debug")&&U.debug(`[${t._internalSocketId}]: schedule reconnect to ${this.#e.url} in ${e} ms. [attempt: ${n}]`),this.#e.reconnectTimeout=setTimeout(()=>{this.#s(r)},e)}(n||i)&&(U.info(`[${t._internalSocketId}]: connection to ${this.#e.url} has disconnected (${r.reason}:${r.code})`),this.onDisconnect&&this.onDisconnect(r.code,r.reason,r.wasClean))}}}connect(){"_initial"!==this.#e.state&&"_disconnecting"!==this.#e.state||(this.#e.state="connecting",this.#s())}disconnect(){if("closing"===this.#e.state||"closed"===this.#e.state)throw new Error(`connection to ${this.#e.url} is already closing/closed.`);if("_disconnecting"===this.#e.state||"_initial"===this.#e.state)return;let t="connecting"===this.#e.state;this.#e.state="_disconnecting",this.#e.reconnectTimeout&&(clearTimeout(this.#e.reconnectTimeout),this.#e.reconnectTimeout=void 0,this.#e.reconnectAttempt=0);let r=this.#e.socket;U.enabledFor("debug")&&U.debug(`[${r?._internalSocketId}]: disconnecting connection to ${this.#e.url} (opened?: ${void 0!==r})`),r?(this.#e.socket=void 0,r.close(1e3,e.#r)):t||(this.#e.state="_initial",this.onDisconnect&&this.onDisconnect(1e3,e.#r,!0))}close(){if("closed"===this.#e.state||"closing"===this.#e.state)return;let e="connecting"===this.#e.state;this.#e.state="closing",this.#e.reconnectTimeout&&(clearTimeout(this.#e.reconnectTimeout),this.#e.reconnectTimeout=void 0);let t=this.#e.socket;U.enabledFor("debug")&&U.debug(`closing connection to ${this.#e.url} (opened?: ${void 0!==t})`),t?(this.#e.socket=void 0,t.close()):e||(this.#e.state="closed",this.onClose&&this.onClose())}send(e){if("closing"===this.#e.state||"closed"===this.#e.state)throw new Error(`connection to ${this.#e.url} is closed.`);let t=this.#e.socket,r=void 0===t&&this.#e.maxEnqueued>0&&this.#e.queue.length0;){let e=this.#r.pop();void 0!==e&&e.close()}}};function Or(e){let t=e?.codec??Gr(),r=e?.retry,n=e?.WebSocket;return new Ii(t,r,n)}function Sc(e){return Dr(e)?{type:"peer",node:e.node,"peer-id":e.peer}:e}function vc(e){return"peer"===e.type?w(e.node,e["peer-id"]):e}function kr(e){let{receiver:t,body:r,source:n}=e,i=Sc(t),o=Sc(n);return[t.type,{...e,source:o,receiver:i}]}function Nr(e){let{receiver:t,body:r,source:n}=e,i=vc(t),o=vc(n);return{...e,source:o,receiver:i}}function qr(){return Fr({namespaces:new Map([["commands","gateway.common.commands"]]),keywordize:new Map([["/type","*"],["/to",new Set(["all"])],["/message/origin","*"],["/message/receiver/type","*"],["/message/source/type","*"],["/message/body/type","*"],["/data/origin","*"],["/data/receiver/type","*"],["/data/source/type","*"],["/data/body/type","*"]])})}L();var Ze=R("gateway.mesh.ws.broker.client");function Al(e){return void 0!==e&&"node"in e&&void 0!==e.node}function Ic(e,t,r){let{receiver:n,body:i,source:o}=r;Al(n)?e.send({type:"data",from:t,to:n.node,message:r}):Ze.error(`Destination nodeId is missing when sending message ${JSON.stringify(r)}`)}function Cl(e,t,r){let[n,i]=kr(r);switch(n){case"cluster":e.send({type:"data",from:t,to:"all",message:i});break;case"node":case"peer":Ic(e,t,i);break;default:Ze.error(`Unhandled receiver type when publishing ${JSON.stringify(r)}`)}}var Ti=class{constructor(e){this.ch=e}close(){this.ch(void 0)}register(e,t,r){if("all"===e)throw new Error("cannot register with node id 'all'");return e=e??Me(),this.ch({type:"register",nodeId:e,gateway:t,callbacks:r}),e}unregister(e){this.ch({type:"unregister",nodeId:e})}publish(e,t){this.ch({type:"publish",nodeId:e,message:t})}addUsers(e,t){}removeUsers(e,t){}};function Ml(e,t,r){let{nodeId:n,gateway:i,callbacks:o}=e;t.set(n,{gateway:i,callbacks:o}),r.send({type:"hello","node-id":n,gateway:i})}function Pl(e,t,r){let n=e.nodeId;t.delete(n),r.send({type:"bye","node-id":n})}function Dl(e,t){Cl(t,e.nodeId,e.message)}function _l(e,t){Ze.info("connected to mesh broker");for(let[r,{gateway:n}]of e)t.send({type:"hello","node-id":r,gateway:n})}function Ol(e,t){Ze.info("disconnected from mesh broker");let r=new Set(e);e.clear();for(let e of r)for(let[r,{callbacks:n}]of t){let t=n?.onMemberRemoved;t&&t(r,e)}}function kl(e,t,r){let{"node-id":n,"new-node":i}=e;t.add(i);let o=r.get(n)?.callbacks?.onMemberAdded;o&&(Ze.info(`on-msg ${n}, ${i}`),o(n,i))}function Nl(e,t,r){let{"node-id":n,"removed-node":i}=e;t.delete(i);let o=r.get(n)?.callbacks?.onMemberRemoved;o&&o(n,i)}function ql(e,t){let{to:r,from:n}=e;for(let[r,{callbacks:i}]of t)if(r!==n){let t=i?.onMessage;t&&t(r,Nr(e.message))}}function $l(e,t,r,n){switch(e.type){case"register":Ml(e,r,t);break;case"unregister":Pl(e,r,t);break;case"publish":Dl(e,t);break;case"connected":_l(r,t);break;case"disconnected":Ol(n,r);break;case"node-added":kl(e,n,r);break;case"node-removed":Nl(e,n,r);break;case"data":ql(e,r)}}function Tc(e,t){let r=new Map,n=new Set,i=Or({codec:qr(),WebSocket:t?.WebSocket}).create(e,void 0,t),o=e=>{e&&(Ze.enabledFor("debug")&&Ze.debug(`mesh node processing command ${JSON.stringify(e,null,"\t")}`),$l(e,i,r,n))};return i.onConnect=()=>o({type:"connected"}),i.onReceive=e=>o(e),i.onDisconnect=()=>o({type:"disconnected"}),i.connect(),new Ti(o)}function El(e,t,r,n){let i=`${e}:${t}`,o=r.get(i);if(o)return o.connection;let s=new class{close(){n.send({type:"bye",from:t,to:e}),r.delete(i)}send(e){n.send(e)}toJSON(){return{type:"relay",from:e,to:t}}};return r.set(i,{from:e,to:t,connection:s}),s}function Ul(e,t,r,n){switch(n.type){case"hello":{let{from:i,to:o}=n,s=El(i,o,e,r);t.onConnect(o,i,s);break}case"bye":{let{from:e,to:r}=n;t.onDisconnect(r,e);break}case"data":{let{from:e,to:r,data:i}=n;t.onReceive(r,e,i);break}}}function Ac(e,t,r,n){let i=new Map;return{register:(o,s)=>{let a=i.get(o);if(void 0!==a){let e=s[0];if(a.owner===e)return;return a.connection.disconnect(),a.owner=e,a.connection.connect(),void r.onRegister?.(o,e,a.connection.url)}{let a=new Map,c=`${t}?node=${o}`,l=e.create(c,[],{...n,dynamicArguments:e=>{let t=i.get(o)?.owner;return"string"==typeof e?e=`${e}&owner=${t??""}`:e.searchParams.append("owner",t??""),{url:e}}}),u=s[0];l.onConnect=e=>{r.onRegister?.(o,u,l.url),l.send({type:"hello",from:o,to:"all"})},l.onReceive=e=>{Ul(a,r,l,e)},l.onDisconnect=()=>{for(let[,e]of a)e.connection.close(),r.onDisconnect(e.to,e.from)},l.onClose=()=>{r.onUnregister?.(o)},i.set(o,{node:o,owner:u,connected:a,connection:l}),l.connect()}},unregister:e=>{let t=i.get(e);void 0!==t&&t.connection.close(),i.delete(e)},stop:()=>{for(let[,e]of i)e.connection.close();i.clear()}}}L();var Hl=(e,t)=>"object"==typeof(t="string"==typeof t?[t]:t)?Array.isArray(t)?void 0!==e?{headers:{...e},protocols:[...t]}:[...t]:{...t,headers:{...t.headers,...e}}:void 0===t&&void 0!==e?{headers:{...e}}:void 0,Ai=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}create(e,t,r){return this.#e.create(e,t,this.#o(r))}close(){this.#e.close()}#o(e){let t={...e},r=e?.dynamicArguments,n=e?.URL??globalThis.URL??URL;return t.dynamicArguments=this.#r(n,r),t}#r(e,t){return async(r,n)=>{let i=await(t?.(r,n))??{},o={...this.#t.headers},s=this.#t.getHeaders?await this.#t.getHeaders():{};for(let[e,t]of Object.entries(s))o[e]=t;r=new e(i.url??r,i.baseUrl);let a=this.#t.getWebSocketSearchParams?.(o,r.search);if(a)for(let[e,t]of Object.entries(a))void 0===t?r.searchParams.delete(e):r.searchParams.set(e,t);i.url=r;let c=this.#t.getWebSocketProtocols??void 0===this.#t.getWebSocketSearchParams?Hl:void 0;return i.protocols=c?.(o,i.protocols??n),i}}},Cc=(e,t)=>t&&(t.getWebSocketProtocols||t.getWebSocketSearchParams||t.getHeaders||t.headers)?new Ai(e,t):e,F=R("gateway.mesh.ws");function Ll(e,t,r){let{receiver:n,body:i}=e,o=n.node;if(o){let n=r?.connections.get(o);n&&n.send({type:"data",from:t,to:o,data:e})}}function Fl(e,t,r){let[n,i]=kr(e);switch(n){case"cluster":r?.connections.forEach((e,r)=>{e.send({type:"data",from:t,to:r,data:i})});break;case"node":case"peer":Ll(i,t,r);break;default:F.error(`Unhandled receiver type when publishing ${JSON.stringify(e)}`)}}function Mc(e){for(let t of e.values())t.close()}function Gl(e,t,r){let n=t.node,i=t.to.node,o=t.to.endpoint;F.enabledFor("debug")&&F.debug(`directory connect ${n} to ${i} via ${o}`);let s=r.factory.create(o,void 0,{URL:r.URL});s.onConnect=()=>{e({type:"node-connected",from:n,to:i})},s.onReceive=t=>{"data"===t.type&&e({type:"node-data",to:n,from:i,msg:t.data})},s.onDisconnect=()=>{e({type:"node-disconnected",from:n,to:i})},e({type:"connecting-nodes",from:n,to:i,connection:s}),s.connect()}function Wl(e,t){let r=t.node,n=t.from.node;F.enabledFor("debug")&&F.debug(`directory disconnect ${r} to ${n}`),e({type:"disconnecting-nodes",from:r,to:n})}function Jl(e,t,r){F.enabledFor("debug")&&F.debug(`directory replica change for node ${t.node}: ${JSON.stringify(t.replicas)}`),r.register(t.node,t.replicas)}var Ci=class{#e;#t;#o;#r;#s;#i;constructor(e,t,r,n,i,o){this.#e=e,this.#t=t,this.#o=r,this.#r=n,this.#s=i,this.#i=o?.URL}register(e,t,r){return e=e??Me(),F.enabledFor("info")&&F.info(`registering local node ${e}`),this.#e.set(e,{callbacks:r,connections:new Map}),this.#o.add(e,void 0,{replicaChange:e=>{Jl(this.#r,e,this.#t)},connect:e=>{Gl(this.#r,e,{factory:this.#s,URL:this.#i})},disconnect:e=>{Wl(this.#r,e)}}),e}unregister(e){this.#o.remove(e);let t=this.#e.get(e);t&&(F.enabledFor("info")&&F.info(`unregistering local node ${e}`),this.#e.delete(e),Mc(t.connections)),this.#t.unregister(e)}publish(e,t){Fl(t,e,this.#e.get(e))}addUsers(e,t){this.#o.addUsers(e,...t)}removeUsers(e,t){this.#o.removeUsers(e,...t)}close(){this.#o.close();for(let[,e]of this.#e)Mc(e.connections);this.#e.clear(),this.#t.stop(),this.#s.close()}};function jl(e,t){let{from:r,to:n,connection:i}=t,o=e.get(r);o?(F.enabledFor("debug")&&F.debug(`processing connection request from ${n} to ${r}`),o.connections.set(n,i)):(F.warn(`discarding connection request from ${n} to ${r}`),i.close())}function Bl(e,t){let{from:r,to:n}=t,i=e.get(r);if(i){let e=i.connections.get(n);if(e)return F.enabledFor("debug")&&F.debug(`processing disconnection request from ${n} to ${r}`),i.connections.delete(n),void e.close()}F.warn(`discarding disconnection request from ${n} to ${r}`)}function Kl(e,t){let{from:r,to:n}=t,i=e.get(r);if(i){let e=i.connections.get(n);if(e){F.enabledFor("info")&&F.info(`mesh connected ${r} to ${n}, sending hello`),e.send({type:"hello",from:r,to:n});let t=i.callbacks?.onMemberAdded;t&&t(r,n)}}}function Vl(e,t){let{from:r,to:n}=t,i=e.get(r);if(i){F.enabledFor("info")&&F.info(`mesh disconnected ${r} from ${n}`);let e=i.callbacks?.onMemberRemoved;e&&e(r,n)}}function zl(e,t){let{from:r,to:n}=t,i=e.get(n);if(i&&i.connections.get(r)){let e=i.callbacks?.onMessage;e&&e(n,Nr(t.msg))}}function Mi(e,t,r){let n=new Map,i=e=>{if(e)switch(F.enabledFor("debug")&&F.debug(`mesh processing command ${JSON.stringify(e,(e,t)=>{if("connection"!==e)return t},"\t")}`),e.type){case"connecting-nodes":jl(n,e);break;case"disconnecting-nodes":Bl(n,e);break;case"node-connected":Kl(n,e);break;case"node-disconnected":Vl(n,e);break;case"node-data":zl(n,e)}},o=Cc(Or({codec:qr(),WebSocket:r?.WebSocket}),r),s=Ac(o,`${e.relays}`,{onConnect:(e,t,r)=>{F.enabledFor("debug")&&F.debug(`server relay connected ${e} to ${t}`),i({type:"connecting-nodes",from:e,to:t,connection:r}),i({type:"node-connected",from:e,to:t})},onDisconnect:(e,t)=>{i({type:"disconnecting-nodes",from:e,to:t}),i({type:"node-disconnected",from:e,to:t})},onReceive:(e,t,r)=>{i({type:"node-data",from:t,to:e,msg:r})}});return new Ci(n,s,t,i,o,r)}L();var ke=R("gateway.mesh.rest-directory");function Ql(e,t,r,n,i){let o=t?.replicaChange;o&&i&&o({cmd:"replica-change",node:e,replicas:[i]});let s=t?.disconnect;s&&n.forEach(t=>s({cmd:"disconnect",node:e,from:t}));let a=t?.connect;a&&r.forEach(t=>a({cmd:"connect",node:e,to:t}))}var Pi=class{#e;#t;#o;constructor(e,t,r,n){if(this.#e=e,this.#t=t,r>0){let e=async()=>{Di(this.#e,this.#t,n),clearTimeout(this.#o),this.#o=setTimeout(e,r)};this.#o=setTimeout(e,r)}}add(e,t,r){this.#e({command:"add",node:e,callbacks:r,endpoint:t})}remove(e){this.#e({command:"remove",node:e})}addUsers(e,...t){this.#e({command:"add-users",node:e,added:t})}removeUsers(e,...t){this.#e({command:"remove-users",node:e,removed:t})}close(){this.#o&&(clearTimeout(this.#o),this.#o=void 0)}};function Yl(e,t,r){r&&(ke.enabledFor("debug")&&ke.debug(`removing node ${r}`),e(`${t}/api/nodes/${r}`,{method:"delete",credentials:"include"}).catch(e=>{ke.warn("remove node request failed",e)}))}async function Zl(e){if(e.ok)return await e.json();throw new Error(`${e.status} ${e.statusText}`)}function Xl(e,t){return ke.enabledFor("debug")&&ke.debug(`processing response ${JSON.stringify(t)}`),t.reduce((e,t)=>{let r=t.node,n=e.get(r);if(n){let i=n.owner,o=t.owner,s=void 0===i||i!==o?o:void 0,a=n.connected,c=t.connect,l=(a??[]).filter(e=>void 0===c||void 0===c.find(t=>t.node===e.node&&t.endpoint===e.endpoint)),u=(c??[]).filter(e=>void 0===a||void 0===a.find(t=>e.node===t.node&&e.endpoint===t.endpoint));return Ql(r,n.callbacks,u,l,s),n.owner=o,n.connected=c,e}return e},e)}function Di(e,t,r){let n=Array.from(t.values()).map(e=>({node:e.node,endpoint:e.endpoint,users:Array.from(e.users),metadata:r}));n.length>0&&e({command:"announce",nodes:n})}function ey(e,t,r,n){let i=JSON.stringify(n);ke.enabledFor("debug")&&ke.debug(`announcing nodes ${i}`),t(`${r}/api/nodes`,{method:"post",body:i,credentials:"include",headers:[["content-type","application/json"]]}).then(async t=>{let r=await Zl(t);e({command:"response",response:r})}).catch(e=>{ke.warn(`announce node request failed. ${e.message}`,e)})}function ty(e,t,r,n,i,o){switch(n.command){case"add":{let{node:e,callbacks:t,endpoint:i}=n;r.set(e,{node:e,callbacks:t,endpoint:i,users:new Set});break}case"remove":{let{node:e}=n;Yl(i,t,e),r.delete(e);break}case"add-users":{let{node:t,added:i}=n,s=r.get(t);s&&(i.forEach(e=>s.users.add(e)),Di(e,r,o));break}case"remove-users":{let{node:t,removed:i}=n,s=r.get(t);s&&(i.forEach(e=>s.users.delete(e)),Di(e,r,o));break}case"announce":{let{nodes:r}=n;ey(e,i,t,r);break}case"response":{let{response:e}=n;Xl(r,e);break}}}function ry(e,t,r,n,i,o){ty(e,t,r,n,i,o)}function Pc(e,t){let r=e.uri,n=e.announceInterval??1e4,i=new Map,o=e=>{ry(o,r,i,e,ny(t),t?.metadata)};return ke.info(`rest directory with uri '${r}' and announce interval ${n}ms`),new Pi(o,i,n,t?.metadata)}function ny(e){let t=e?.fetch??globalThis.fetch??fetch,r=t;if(e?.getHeaders||e?.headers){let t=e?.Headers??globalThis.Headers??Headers;return async(n,i)=>{let o=new t(i?.headers);return e?.headers&&new t(e.headers).forEach((e,t)=>{o.set(t,e)}),e?.getHeaders&&new t(await e.getHeaders()).forEach((e,t)=>{o.set(t,e)}),await r(n,{...i,headers:o})}}return t}function Ut(e,t){return t?.filter(t=>t.domain===e)?.find(e=>{if(void 0===e.identity)return!0;throw new Error("identity in default restrictions rules set is not allowed")})?.restrictions}function _i(e,t){let r=t?.map(t=>iy(e,t));return function(e){return r?.find(t=>oy(t,this,e))?.restrictions}}function iy(e,t){let r={identity:{},restrictions:t.restrictions};if(t[e]&&(r.name=Lt(t[e])),t.identity)for(let[e,n]of Object.entries(t.identity))r.identity[e]=Lt(n);return r}function oy(e,t,r){for(let[r,n]of Object.entries(e.identity)){if(!We(n,t[r]))return!1}return!(e.name&&!We(e.name,r))}Ft();var Oi=class{#e;constructor(e){this.#e=e}add(e,t,r){if(this.#e.has(e)){this.#e.get(e).callbacks=r;let t=r.replicaChange;t&&t({cmd:"replica-change",node:e,replicas:[]});let n=r.connect,i=this.#e.get(e).memberId;n&&Array.from(this.#e.values()).filter(e=>e.memberId{n({cmd:"connect",node:e,to:t.member})})}}remove(e){if(this.#e.has(e)){let t=this.#e.get(e);delete t.callbacks,Array.from(this.#e.values()).filter(e=>e.memberId>t.memberId).filter(e=>e.callbacks?.disconnect).forEach(e=>{let r=e.callbacks?.disconnect;r&&r({cmd:"disconnect",node:e.member.node,from:t.member})})}}addUsers(){}removeUsers(){}close(){}};function Dc(e){let t=new Map;return e.forEach((e,r)=>{t.set(e.node,{member:{...e},memberId:r})}),new Oi(t)}var ae=R("gateway");function sy(e,t){let r=(e?.available??["basic"]).reduce((r,n)=>{if("basic"===n)return r[n]=Fo(e?.basic??{}),r;if("oauth2"===n)return r[n]=Go(e?.oauth2??{},{...t}),r;let i=e?.[n]??{};if(i.authenticator){let e=i.authenticator,t={...i};return delete t.authenticator,r[n]=Wo(t,e),r}return r},{});return{default:e?.default??"basic",available:r}}function ay(e,t,r,n,i){let o=r??e;if(void 0===r&&o.startsWith("http")&&(o=o.replace("http","ws"),o+=o.endsWith("/")?"":"/",o+="relays"),void 0!==n?.members)return Mi({relays:`${o}`},Dc(n.members),i);{let r=n?.uri??e,s=n?.interval;return Mi({relays:`${o}`},Pc({uri:r,announceInterval:s},{metadata:{...t.gateway,...n?.metadata},...i}),i)}}function cy(e,t,r,n,i,o){if(i){r=i.node??r;let s=null===i.auth.user?void 0:"string"==typeof i.auth.user?[i.auth.user]:i.auth.user,a=i.cluster;if(a){let{endpoint:i,relays:c,directory:l,opts:u}=a;return _r(ay(i,t,c,l,{...o,...u}),e,{nodeId:r,signingKey:n,users:s})}let c=i.channel;if(c){return _r(Jo(c),e,{nodeId:r,signingKey:n,users:s})}let l=i.broker?.endpoint;if(l){return _r(Tc(l,o),e,{nodeId:r,signingKey:n,users:s})}}return io(e,{nodeId:r,signingKey:n})}var _c=Wr({cljs:!0}),dy=100,uy="io.Gateway",ki={version:fc,description:uy},py=rt("token.key","metrics.rest.authentication.password","mesh.cluster.auth.basic.password","mesh.cluster.auth.token.value"),Ni=class{#e;#t;constructor(e){this.#t=e}async doStart(e,t){let r=sy(e.authentication,e.globals),n=e.contexts?.lifetime,i={retainedOverride:"retained"===n?void 0:n??"ref-counted",defaultPeerRestrictions:Ut("context",e.peers?.visibility)??"cluster",defaultContextRestrictions:_i("context",e.contexts?.visibility)},o=await Za(e.metrics,t?.endpoint),s=Ut("interop",e.peers?.visibility)??Ut("agm",e.peers?.visibility)??"local",a=cy([qo(r,{...i,welcomeInfo:ki}),nc(i),Ts({defaultPeerRestrictions:s,defaultMethodRestrictions:_i("method",e.methods?.visibility)}),ka(),mc({defaultPeerRestrictions:Ut("bus",e.peers?.visibility)}),Ha(o,e.metrics?.filters)],{gateway:ki,...t},e.node,e.token?.key,e.mesh,e.globals),c=new Map;return{config:e,auth:r,factories:o,node:a,clients:c,scavenger:new Et(c,a,e.clients?.inactive_seconds??0),environment:t}}async startGateway(e,t){return await this.doStart(e,t)}async start(e){let t=this.#t;return ae.info(`starting gateway with environment:\n${JSON.stringify(e)}\nconfiguration:${JSON.stringify(t,py,"\t")}`),this.#e=await this.startGateway(t,e),this}async doStop(e){ae.info(`stopping gateway [${JSON.stringify({environment:e.environment,clients:[...e.clients.keys()]})}]`),Object.values(e.clients).forEach(e=>{e.onStop&&e.onStop()}),e.scavenger.stop(),e.node.close();for(let t of e.factories)await t.shutdown();Object.values(e.auth.available).forEach(e=>e.stop())}async stop(){return this.#e&&(await this.doStop(this.#e),this.#e=void 0),this}info(){return{...ki,endpoint:this.#e?.environment?.endpoint}}cnt=0;async connect(e){if(!this.#e)throw new Error("(no gateway) did you call start?");let t=this.#e,r=this.#e?.config.clients?.buffer_size??dy;ae.info(`local client connected, buffer-size: ${r}`);let n="local:"+ ++this.cnt;return new $r(e,t,{key:n,codec:_c})}client(e,t){if(!this.#e)throw new Error("(no gateway) did you call start() and waited for completion?");if(1!==e.length)throw new Error("expecting function with one arg");let r="local:"+ ++this.cnt,n=this.#e;return new $r(e,n,{key:r,codec:_c,...t})}},$r=class{constructor(e,t,r){this.gw=t,this.receive=1===e.length?e:function(t){e(this,t)}.bind(this),this.key=r.key,this.codec=r.codec,this.host=r.host,this.ping=r.onPing?.bind(this),this.auth=r.onAuthenticate?.bind(this);let n={type:"local",receive:e=>{let t;try{"ping"===e.type&&this.ping?(ae.enabledFor("info")&&ae.info(`checking ${this.key}`),this.ping()):(t=this.codec.encode(e),ae.enabledFor("trace")&&ae.debug(`sending message ${t} to ${this.key}`),Promise.resolve().then(()=>{try{this.receive(t)}catch(e){ae.error(`custom client error, that we're looking for ${t}`,e)}}))}catch(e){ae.error(`unable to send message ${t}`,e)}},endpoint:this.key,host:this.host,auth:this.auth},i=r.onDisconnect?.bind(this);lc(this.gw.clients,this.gw.node,this.key,n,i?()=>{i("inactive")}:void 0,i?()=>{i("shutdown")}:void 0)}receive;key;codec;host;ping;auth;close(){Pr(this.gw.clients,this.gw.node,this.key)}async disconnect(){return this.close(),!0}send(e){try{let t=this.codec.decode(e);ae.enabledFor("debug")&&ae.debug(`processing incoming message from client [${this.key}]`);let r=this.gw.clients.get(this.key);if(r?.source)if("ping"===t.type){let e=Date.now();ae.enabledFor("debug")&&ae.debug(`received ping from ${this.key} at ${e}`),r.lastAccess=e}else this.gw.node.message({origin:"local",source:r.source,body:t});else ae.warn(`cannot process message from non-registered client key ${this.key}`)}catch(e){this.receive(e?.message)}}},qi=e=>new Ni(e),mv=qi,toStr$5=Object.prototype.toString,isArguments$3=function(e){var t=toStr$5.call(e),r="[object Arguments]"===t;return r||(r="[object Array]"!==t&&null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Function]"===toStr$5.call(e.callee)),r},implementation$a,hasRequiredImplementation$1;function requireImplementation$1(){if(hasRequiredImplementation$1)return implementation$a;var e;if(hasRequiredImplementation$1=1,!Object.keys){var t=Object.prototype.hasOwnProperty,r=Object.prototype.toString,n=isArguments$3,i=Object.prototype.propertyIsEnumerable,o=!i.call({toString:null},"toString"),s=i.call(function(){},"prototype"),a=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],c=function(e){var t=e.constructor;return t&&t.prototype===e},l={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},u=function(){if("undefined"==typeof window)return!1;for(var e in window)try{if(!l["$"+e]&&t.call(window,e)&&null!==window[e]&&"object"==typeof window[e])try{c(window[e])}catch(e){return!0}}catch(e){return!0}return!1}();e=function(e){var i=null!==e&&"object"==typeof e,l="[object Function]"===r.call(e),d=n(e),h=i&&"[object String]"===r.call(e),p=[];if(!i&&!l&&!d)throw new TypeError("Object.keys called on a non-object");var g=s&&l;if(h&&e.length>0&&!t.call(e,0))for(var m=0;m0)for(var f=0;f3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new $TypeError$b("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new $TypeError$b("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new $TypeError$b("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new $TypeError$b("`loose`, if provided, must be a boolean");var n=arguments.length>3?arguments[3]:null,i=arguments.length>4?arguments[4]:null,o=arguments.length>5?arguments[5]:null,s=arguments.length>6&&arguments[6],a=!!gopd&&gopd(e,t);if($defineProperty$2)$defineProperty$2(e,t,{configurable:null===o&&a?a.configurable:!o,enumerable:null===n&&a?a.enumerable:!n,value:r,writable:null===i&&a?a.writable:!i});else{if(!s&&(n||i||o))throw new $SyntaxError$2("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[t]=r}},$defineProperty$1=esDefineProperty,hasPropertyDescriptors=function(){return!!$defineProperty$1};hasPropertyDescriptors.hasArrayLengthDefineBug=function(){if(!$defineProperty$1)return null;try{return 1!==$defineProperty$1([],"length",{value:1}).length}catch(e){return!0}};var hasPropertyDescriptors_1=hasPropertyDescriptors,keys=objectKeys$2,hasSymbols$4="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),toStr$4=Object.prototype.toString,concat=Array.prototype.concat,defineDataProperty=defineDataProperty$1,isFunction$2=function(e){return"function"==typeof e&&"[object Function]"===toStr$4.call(e)},supportsDescriptors$2=hasPropertyDescriptors_1(),defineProperty$1=function(e,t,r,n){if(t in e)if(!0===n){if(e[t]===r)return}else if(!isFunction$2(n)||!n())return;supportsDescriptors$2?defineDataProperty(e,t,r,!0):defineDataProperty(e,t,r)},defineProperties$1=function(e,t){var r=arguments.length>2?arguments[2]:{},n=keys(t);hasSymbols$4&&(n=concat.call(n,Object.getOwnPropertySymbols(t)));for(var i=0;i1&&"boolean"!=typeof t)throw new $TypeError$9('"allowMissing" argument must be a boolean');if(null===$exec$1(/^%?[^%]*%?$/,e))throw new $SyntaxError$1("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=stringToPath(e),n=r.length>0?r[0]:"",i=getBaseIntrinsic("%"+n+"%",t),o=i.name,s=i.value,a=!1,c=i.alias;c&&(n=c[0],$spliceApply(r,$concat$1([0,1],c)));for(var l=1,u=!0;l=r.length){var g=$gOPD$1(s,d);s=(u=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:s[d]}else u=hasOwn$3(s,d),s=s[d];u&&!a&&(INTRINSICS[o]=s)}}return s},GetIntrinsic$8=getIntrinsic,define$5=defineDataProperty$1,hasDescriptors$1=hasPropertyDescriptors_1(),gOPD$4=gopd$1,$TypeError$8=type,$floor$1=GetIntrinsic$8("%Math.floor%"),setFunctionLength=function(e,t){if("function"!=typeof e)throw new $TypeError$8("`fn` is not a function");if("number"!=typeof t||t<0||t>4294967295||$floor$1(t)!==t)throw new $TypeError$8("`length` must be a positive 32-bit integer");var r=arguments.length>2&&!!arguments[2],n=!0,i=!0;if("length"in e&&gOPD$4){var o=gOPD$4(e,"length");o&&!o.configurable&&(n=!1),o&&!o.writable&&(i=!1)}return(n||i||!r)&&(hasDescriptors$1?define$5(e,"length",t,!0,!0):define$5(e,"length",t)),e},bind$1=requireFunctionBind(),$apply=requireFunctionApply(),actualApply=actualApply$1,applyBind=function(){return actualApply(bind$1,$apply,arguments)};!function(e){var t=setFunctionLength,r=esDefineProperty,n=callBindApplyHelpers,i=applyBind;e.exports=function(e){var r=n(arguments),i=e.length-(arguments.length-1);return t(r,1+(i>0?i:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(callBind$6);var callBindExports=callBind$6.exports,GetIntrinsic$7=getIntrinsic,callBindBasic=callBindApplyHelpers,$indexOf$2=callBindBasic([GetIntrinsic$7("%String.prototype.indexOf%")]),callBound$h=function(e,t){var r=GetIntrinsic$7(e,!!t);return"function"==typeof r&&$indexOf$2(e,".prototype.")>-1?callBindBasic([r]):r},objectKeys$1=objectKeys$2,hasSymbols$1=requireShams$1()(),callBound$g=callBound$h,$Object$1=esObjectAtoms,$push=callBound$g("Array.prototype.push"),$propIsEnumerable=callBound$g("Object.prototype.propertyIsEnumerable"),originalGetSymbols=hasSymbols$1?$Object$1.getOwnPropertySymbols:null,implementation$8=function(e,t){if(null==e)throw new TypeError("target must be an object");var r=$Object$1(e);if(1===arguments.length)return r;for(var n=1;n-1?callBind$4(r):r},functionsHaveNames=function(){return"string"==typeof function(){}.name},gOPD$3=Object.getOwnPropertyDescriptor;if(gOPD$3)try{gOPD$3([],"length")}catch(e){gOPD$3=null}functionsHaveNames.functionsHaveConfigurableNames=function(){if(!functionsHaveNames()||!gOPD$3)return!1;var e=gOPD$3(function(){},"name");return!!e&&!!e.configurable};var $bind=Function.prototype.bind;functionsHaveNames.boundFunctionsHaveNames=function(){return functionsHaveNames()&&"function"==typeof $bind&&""!==function(){}.bind().name};var functionsHaveNames_1=functionsHaveNames,define$3=defineDataProperty$1,hasDescriptors=hasPropertyDescriptors_1(),functionsHaveConfigurableNames=functionsHaveNames_1.functionsHaveConfigurableNames(),$TypeError$7=type,setFunctionName$1=function(e,t){if("function"!=typeof e)throw new $TypeError$7("`fn` is not a function");return arguments.length>2&&!!arguments[2]&&!functionsHaveConfigurableNames||(hasDescriptors?define$3(e,"name",t,!0,!0):define$3(e,"name",t)),e},setFunctionName=setFunctionName$1,$TypeError$6=type,$Object=Object,implementation$5=setFunctionName(function(){if(null==this||this!==$Object(this))throw new $TypeError$6("RegExp.prototype.flags getter called on non-object");var e="";return this.hasIndices&&(e+="d"),this.global&&(e+="g"),this.ignoreCase&&(e+="i"),this.multiline&&(e+="m"),this.dotAll&&(e+="s"),this.unicode&&(e+="u"),this.unicodeSets&&(e+="v"),this.sticky&&(e+="y"),e},"get flags",!0),implementation$4=implementation$5,supportsDescriptors$1=defineProperties_1.supportsDescriptors,$gOPD=Object.getOwnPropertyDescriptor,polyfill$2=function(){if(supportsDescriptors$1&&"gim"===/a/gim.flags){var e=$gOPD(RegExp.prototype,"flags");if(e&&"function"==typeof e.get&&"dotAll"in RegExp.prototype&&"hasIndices"in RegExp.prototype){var t="",r={};if(Object.defineProperty(r,"hasIndices",{get:function(){t+="d"}}),Object.defineProperty(r,"sticky",{get:function(){t+="y"}}),e.get.call(r),"dy"===t)return e.get}}return implementation$4},supportsDescriptors=defineProperties_1.supportsDescriptors,getPolyfill$3=polyfill$2,gOPD$2=gopd$1,defineProperty=Object.defineProperty,$TypeError$5=esErrors,getProto$1=requireGetProto(),regex=/a/,shim$3=function(){if(!supportsDescriptors||!getProto$1)throw new $TypeError$5("RegExp.prototype.flags requires a true ES5 environment that supports property descriptors");var e=getPolyfill$3(),t=getProto$1(regex),r=gOPD$2(t,"flags");return r&&r.get===e||defineProperty(t,"flags",{configurable:!0,enumerable:!1,get:e}),e},define$2=defineProperties_1,callBind$3=callBindExports,implementation$3=implementation$5,getPolyfill$2=polyfill$2,shim$2=shim$3,flagsBound=callBind$3(getPolyfill$2());define$2(flagsBound,{getPolyfill:getPolyfill$2,implementation:implementation$3,shim:shim$2});var regexp_prototype_flags=flagsBound,esGetIterator={exports:{}},shams,hasRequiredShams;function requireShams(){if(hasRequiredShams)return shams;hasRequiredShams=1;var e=requireShams$1();return shams=function(){return e()&&!!Symbol.toStringTag}}var hasToStringTag$6=requireShams()(),callBound$e=callBound$h,$toString$6=callBound$e("Object.prototype.toString"),isStandardArguments=function(e){return!(hasToStringTag$6&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===$toString$6(e)},isLegacyArguments=function(e){return!!isStandardArguments(e)||null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==$toString$6(e)&&"callee"in e&&"[object Function]"===$toString$6(e.callee)},supportsStandardArguments=function(){return isStandardArguments(arguments)}();isStandardArguments.isLegacyArguments=isLegacyArguments;var isArguments$2=supportsStandardArguments?isStandardArguments:isLegacyArguments,_nodeResolve_empty={},_nodeResolve_empty$1=Object.freeze({__proto__:null,default:_nodeResolve_empty}),require$$0=getAugmentedNamespace(_nodeResolve_empty$1),hasMap="function"==typeof Map&&Map.prototype,mapSizeDescriptor=Object.getOwnPropertyDescriptor&&hasMap?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,mapSize=hasMap&&mapSizeDescriptor&&"function"==typeof mapSizeDescriptor.get?mapSizeDescriptor.get:null,mapForEach=hasMap&&Map.prototype.forEach,hasSet="function"==typeof Set&&Set.prototype,setSizeDescriptor=Object.getOwnPropertyDescriptor&&hasSet?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,setSize=hasSet&&setSizeDescriptor&&"function"==typeof setSizeDescriptor.get?setSizeDescriptor.get:null,setForEach=hasSet&&Set.prototype.forEach,hasWeakMap="function"==typeof WeakMap&&WeakMap.prototype,weakMapHas=hasWeakMap?WeakMap.prototype.has:null,hasWeakSet="function"==typeof WeakSet&&WeakSet.prototype,weakSetHas=hasWeakSet?WeakSet.prototype.has:null,hasWeakRef="function"==typeof WeakRef&&WeakRef.prototype,weakRefDeref=hasWeakRef?WeakRef.prototype.deref:null,booleanValueOf=Boolean.prototype.valueOf,objectToString=Object.prototype.toString,functionToString=Function.prototype.toString,$match=String.prototype.match,$slice$1=String.prototype.slice,$replace=String.prototype.replace,$toUpperCase=String.prototype.toUpperCase,$toLowerCase=String.prototype.toLowerCase,$test=RegExp.prototype.test,$concat=Array.prototype.concat,$join=Array.prototype.join,$arrSlice=Array.prototype.slice,$floor=Math.floor,bigIntValueOf$1="function"==typeof BigInt?BigInt.prototype.valueOf:null,gOPS=Object.getOwnPropertySymbols,symToString="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,hasShammedSymbols="function"==typeof Symbol&&"object"==typeof Symbol.iterator,toStringTag$1="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===hasShammedSymbols||"symbol")?Symbol.toStringTag:null,isEnumerable=Object.prototype.propertyIsEnumerable,gPO$1=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function addNumericSeparator(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||$test.call(/e/,t))return t;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var n=e<0?-$floor(-e):$floor(e);if(n!==e){var i=String(n),o=$slice$1.call(t,i.length+1);return $replace.call(i,r,"$&_")+"."+$replace.call($replace.call(o,/([0-9]{3})/g,"$&_"),/_$/,"")}}return $replace.call(t,r,"$&_")}var utilInspect=require$$0,inspectCustom=utilInspect.custom,inspectSymbol=isSymbol$2(inspectCustom)?inspectCustom:null,quotes={__proto__:null,double:'"',single:"'"},quoteREs={__proto__:null,double:/(["\\])/g,single:/(['\\])/g},objectInspect=function e(t,r,n,i){var o=r||{};if(has(o,"quoteStyle")&&!has(quotes,o.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(has(o,"maxStringLength")&&("number"==typeof o.maxStringLength?o.maxStringLength<0&&o.maxStringLength!==1/0:null!==o.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var s=!has(o,"customInspect")||o.customInspect;if("boolean"!=typeof s&&"symbol"!==s)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(has(o,"indent")&&null!==o.indent&&"\t"!==o.indent&&!(parseInt(o.indent,10)===o.indent&&o.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(has(o,"numericSeparator")&&"boolean"!=typeof o.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var a=o.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return inspectString(t,o);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var c=String(t);return a?addNumericSeparator(t,c):c}if("bigint"==typeof t){var l=String(t)+"n";return a?addNumericSeparator(t,l):l}var u=void 0===o.depth?5:o.depth;if(void 0===n&&(n=0),n>=u&&u>0&&"object"==typeof t)return isArray$4(t)?"[Array]":"[Object]";var d=getIndent(o,n);if(void 0===i)i=[];else if(indexOf(i,t)>=0)return"[Circular]";function h(t,r,s){if(r&&(i=$arrSlice.call(i)).push(r),s){var a={depth:o.depth};return has(o,"quoteStyle")&&(a.quoteStyle=o.quoteStyle),e(t,a,n+1,i)}return e(t,o,n+1,i)}if("function"==typeof t&&!isRegExp$1(t)){var p=nameOf(t),g=arrObjKeys(t,h);return"[Function"+(p?": "+p:" (anonymous)")+"]"+(g.length>0?" { "+$join.call(g,", ")+" }":"")}if(isSymbol$2(t)){var m=hasShammedSymbols?$replace.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):symToString.call(t);return"object"!=typeof t||hasShammedSymbols?m:markBoxed(m)}if(isElement(t)){for(var f="<"+$toLowerCase.call(String(t.nodeName)),y=t.attributes||[],$=0;$"}if(isArray$4(t)){if(0===t.length)return"[]";var b=arrObjKeys(t,h);return d&&!singleLineValues(b)?"["+indentedJoin(b,d)+"]":"[ "+$join.call(b,", ")+" ]"}if(isError(t)){var v=arrObjKeys(t,h);return"cause"in Error.prototype||!("cause"in t)||isEnumerable.call(t,"cause")?0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+$join.call(v,", ")+" }":"{ ["+String(t)+"] "+$join.call($concat.call("[cause]: "+h(t.cause),v),", ")+" }"}if("object"==typeof t&&s){if(inspectSymbol&&"function"==typeof t[inspectSymbol]&&utilInspect)return utilInspect(t,{depth:u-n});if("symbol"!==s&&"function"==typeof t.inspect)return t.inspect()}if(isMap$3(t)){var w=[];return mapForEach&&mapForEach.call(t,function(e,r){w.push(h(r,t,!0)+" => "+h(e,t))}),collectionOf("Map",mapSize.call(t),w,d)}if(isSet$3(t)){var S=[];return setForEach&&setForEach.call(t,function(e){S.push(h(e,t))}),collectionOf("Set",setSize.call(t),S,d)}if(isWeakMap$1(t))return weakCollectionOf("WeakMap");if(isWeakSet$1(t))return weakCollectionOf("WeakSet");if(isWeakRef(t))return weakCollectionOf("WeakRef");if(isNumber$2(t))return markBoxed(h(Number(t)));if(isBigInt$1(t))return markBoxed(h(bigIntValueOf$1.call(t)));if(isBoolean$2(t))return markBoxed(booleanValueOf.call(t));if(isString$4(t))return markBoxed(h(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&t===globalThis||void 0!==commonjsGlobal$1&&t===commonjsGlobal$1)return"{ [object globalThis] }";if(!isDate$2(t)&&!isRegExp$1(t)){var _=arrObjKeys(t,h),E=gPO$1?gPO$1(t)===Object.prototype:t instanceof Object||t.constructor===Object,C=t instanceof Object?"":"null prototype",I=!E&&toStringTag$1&&Object(t)===t&&toStringTag$1 in t?$slice$1.call(toStr$3(t),8,-1):C?"Object":"",T=(E||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(I||C?"["+$join.call($concat.call([],I||[],C||[]),": ")+"] ":"");return 0===_.length?T+"{}":d?T+"{"+indentedJoin(_,d)+"}":T+"{ "+$join.call(_,", ")+" }"}return String(t)};function wrapQuotes(e,t,r){var n=r.quoteStyle||t,i=quotes[n];return i+e+i}function quote(e){return $replace.call(String(e),/"/g,""")}function canTrustToString(e){return!toStringTag$1||!("object"==typeof e&&(toStringTag$1 in e||void 0!==e[toStringTag$1]))}function isArray$4(e){return"[object Array]"===toStr$3(e)&&canTrustToString(e)}function isDate$2(e){return"[object Date]"===toStr$3(e)&&canTrustToString(e)}function isRegExp$1(e){return"[object RegExp]"===toStr$3(e)&&canTrustToString(e)}function isError(e){return"[object Error]"===toStr$3(e)&&canTrustToString(e)}function isString$4(e){return"[object String]"===toStr$3(e)&&canTrustToString(e)}function isNumber$2(e){return"[object Number]"===toStr$3(e)&&canTrustToString(e)}function isBoolean$2(e){return"[object Boolean]"===toStr$3(e)&&canTrustToString(e)}function isSymbol$2(e){if(hasShammedSymbols)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!symToString)return!1;try{return symToString.call(e),!0}catch(e){}return!1}function isBigInt$1(e){if(!e||"object"!=typeof e||!bigIntValueOf$1)return!1;try{return bigIntValueOf$1.call(e),!0}catch(e){}return!1}var hasOwn$2=Object.prototype.hasOwnProperty||function(e){return e in this};function has(e,t){return hasOwn$2.call(e,t)}function toStr$3(e){return objectToString.call(e)}function nameOf(e){if(e.name)return e.name;var t=$match.call(functionToString.call(e),/^function\s*([\w$]+)/);return t?t[1]:null}function indexOf(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,n=e.length;rt.maxStringLength){var r=e.length-t.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return inspectString($slice$1.call(e,0,t.maxStringLength),t)+n}var i=quoteREs[t.quoteStyle||"single"];return i.lastIndex=0,wrapQuotes($replace.call($replace.call(e,i,"\\$1"),/[\x00-\x1f]/g,lowbyte),"single",t)}function lowbyte(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+$toUpperCase.call(t.toString(16))}function markBoxed(e){return"Object("+e+")"}function weakCollectionOf(e){return e+" { ? }"}function collectionOf(e,t,r,n){return e+" ("+t+") {"+(n?indentedJoin(r,n):$join.call(r,", "))+"}"}function singleLineValues(e){for(var t=0;t=0)return!1;return!0}function getIndent(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=$join.call(Array(e.indent+1)," ")}return{base:r,prev:$join.call(Array(t+1),r)}}function indentedJoin(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+$join.call(e,","+r)+"\n"+t.prev}function arrObjKeys(e,t){var r=isArray$4(e),n=[];if(r){n.length=e.length;for(var i=0;i=e.length)return t+1;var r=$charCodeAt(e,t);if(r<55296||r>56319)return t+1;var n=$charCodeAt(e,t+1);return n<56320||n>57343?t+1:t+2},getArrayIterator=function(e){var t=0;return{next:function(){var r,n=t>=e.length;return n||(r=e[t],t+=1),{done:n,value:r}}}},getNonCollectionIterator=function(e,t){if(isArray$3(e)||isArguments$1(e))return getArrayIterator(e);if(isString$2(e)){var r=0;return{next:function(){var t=advanceStringIndex(e,r),n=$stringSlice(e,r,t);return r=t,{done:t>e.length,value:n}}}}return t&&void 0!==e["_es6-shim iterator_"]?e["_es6-shim iterator_"]():void 0};if($Map||$Set$1){var isMap$1=isMap$2,isSet$1=isSet$2,$mapForEach=callBound$b("Map.prototype.forEach",!0),$setForEach=callBound$b("Set.prototype.forEach",!0),$mapIterator=callBound$b("Map.prototype.iterator",!0),$setIterator=callBound$b("Set.prototype.iterator",!0),$mapAtAtIterator=callBound$b("Map.prototype.@@iterator",!0)||callBound$b("Map.prototype._es6-shim iterator_",!0),$setAtAtIterator=callBound$b("Set.prototype.@@iterator",!0)||callBound$b("Set.prototype._es6-shim iterator_",!0),getCollectionIterator=function(e){if(isMap$1(e)){if($mapIterator)return getStopIterationIterator($mapIterator(e));if($mapAtAtIterator)return $mapAtAtIterator(e);if($mapForEach){var t=[];return $mapForEach(e,function(e,r){$arrayPush(t,[r,e])}),getArrayIterator(t)}}if(isSet$1(e)){if($setIterator)return getStopIterationIterator($setIterator(e));if($setAtAtIterator)return $setAtAtIterator(e);if($setForEach){var r=[];return $setForEach(e,function(e){$arrayPush(r,e)}),getArrayIterator(r)}}};esGetIterator.exports=function(e){return getCollectionIterator(e)||getNonCollectionIterator(e)}}else esGetIterator.exports=function(e){if(null!=e)return getNonCollectionIterator(e,!0)}}var esGetIteratorExports=esGetIterator.exports,numberIsNaN=function(e){return e!=e},implementation$2=function(e,t){return 0===e&&0===t?1/e==1/t:e===t||!(!numberIsNaN(e)||!numberIsNaN(t))},implementation$1=implementation$2,polyfill$1=function(){return"function"==typeof Object.is?Object.is:implementation$1},getPolyfill$1=polyfill$1,define$1=defineProperties_1,shim$1=function(){var e=getPolyfill$1();return define$1(Object,{is:e},{is:function(){return Object.is!==e}}),e},define=defineProperties_1,callBind$2=callBindExports,implementation=implementation$2,getPolyfill=polyfill$1,shim=shim$1,polyfill=callBind$2(getPolyfill(),Object);define(polyfill,{getPolyfill:getPolyfill,implementation:implementation,shim:shim});var objectIs=polyfill,callBind$1=callBindExports,callBound$a=callBound$h,GetIntrinsic$2=getIntrinsic,$ArrayBuffer=GetIntrinsic$2("%ArrayBuffer%",!0),$byteLength$2=callBound$a("ArrayBuffer.prototype.byteLength",!0),$toString$5=callBound$a("Object.prototype.toString"),abSlice=!!$ArrayBuffer&&!$byteLength$2&&new $ArrayBuffer(0).slice,$abSlice=!!abSlice&&callBind$1(abSlice),isArrayBuffer$3=$byteLength$2||$abSlice?function(e){if(!e||"object"!=typeof e)return!1;try{return $byteLength$2?$byteLength$2(e):$abSlice(e,0),!0}catch(e){return!1}}:$ArrayBuffer?function(e){return"[object ArrayBuffer]"===$toString$5(e)}:function(e){return!1},callBound$9=callBound$h,getDay=callBound$9("Date.prototype.getDay"),tryDateObject=function(e){try{return getDay(e),!0}catch(e){return!1}},toStr$2=callBound$9("Object.prototype.toString"),dateClass="[object Date]",hasToStringTag$5=requireShams()(),isDateObject=function(e){return"object"==typeof e&&null!==e&&(hasToStringTag$5?tryDateObject(e):toStr$2(e)===dateClass)},callBound$8=callBound$h,hasToStringTag$4=requireShams()(),hasOwn=requireHasown(),gOPD$1=gopd$1,fn;if(hasToStringTag$4){var $exec=callBound$8("RegExp.prototype.exec"),isRegexMarker={},throwRegexMarker=function(){throw isRegexMarker},badStringifier={toString:throwRegexMarker,valueOf:throwRegexMarker};"symbol"==typeof Symbol.toPrimitive&&(badStringifier[Symbol.toPrimitive]=throwRegexMarker),fn=function(e){if(!e||"object"!=typeof e)return!1;var t=gOPD$1(e,"lastIndex");if(!(t&&hasOwn(t,"value")))return!1;try{$exec(e,badStringifier)}catch(e){return e===isRegexMarker}}}else{var $toString$4=callBound$8("Object.prototype.toString"),regexClass="[object RegExp]";fn=function(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&$toString$4(e)===regexClass}}var isRegex$1=fn,callBound$7=callBound$h,$byteLength$1=callBound$7("SharedArrayBuffer.prototype.byteLength",!0),isSharedArrayBuffer$1=$byteLength$1?function(e){if(!e||"object"!=typeof e)return!1;try{return $byteLength$1(e),!0}catch(e){return!1}}:function(e){return!1},callBound$6=callBound$h,$numToStr=callBound$6("Number.prototype.toString"),tryNumberObject=function(e){try{return $numToStr(e),!0}catch(e){return!1}},$toString$3=callBound$6("Object.prototype.toString"),numClass="[object Number]",hasToStringTag$3=requireShams()(),isNumberObject=function(e){return"number"==typeof e||!(!e||"object"!=typeof e)&&(hasToStringTag$3?tryNumberObject(e):$toString$3(e)===numClass)},callBound$5=callBound$h,$boolToStr=callBound$5("Boolean.prototype.toString"),$toString$2=callBound$5("Object.prototype.toString"),tryBooleanObject=function(e){try{return $boolToStr(e),!0}catch(e){return!1}},boolClass="[object Boolean]",hasToStringTag$2=requireShams()(),isBooleanObject=function(e){return"boolean"==typeof e||null!==e&&"object"==typeof e&&(hasToStringTag$2?tryBooleanObject(e):$toString$2(e)===boolClass)},isSymbol$1={exports:{}},safeRegexTest$1,hasRequiredSafeRegexTest;function requireSafeRegexTest(){if(hasRequiredSafeRegexTest)return safeRegexTest$1;hasRequiredSafeRegexTest=1;var e=isRegex$1,t=callBound$h("RegExp.prototype.exec"),r=type;return safeRegexTest$1=function(n){if(!e(n))throw new r("`regex` must be a RegExp");return function(e){return null!==t(n,e)}},safeRegexTest$1}var callBound$4=callBound$h,$toString$1=callBound$4("Object.prototype.toString"),hasSymbols=hasSymbols$3(),safeRegexTest=requireSafeRegexTest();if(hasSymbols){var $symToStr=callBound$4("Symbol.prototype.toString"),isSymString=safeRegexTest(/^Symbol\(.*\)$/),isSymbolObject=function(e){return"symbol"==typeof e.valueOf()&&isSymString($symToStr(e))};isSymbol$1.exports=function(e){if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||"[object Symbol]"!==$toString$1(e))return!1;try{return isSymbolObject(e)}catch(e){return!1}}}else isSymbol$1.exports=function(e){return!1};var isSymbolExports=isSymbol$1.exports,isBigint={exports:{}},$BigInt="undefined"!=typeof BigInt&&BigInt,hasBigints=function(){return"function"==typeof $BigInt&&"function"==typeof BigInt&&"bigint"==typeof $BigInt(42)&&"bigint"==typeof BigInt(42)},hasBigInts=hasBigints();if(hasBigInts){var bigIntValueOf=BigInt.prototype.valueOf,tryBigInt=function(e){try{return bigIntValueOf.call(e),!0}catch(e){}return!1};isBigint.exports=function(e){return null!=e&&"boolean"!=typeof e&&"string"!=typeof e&&"number"!=typeof e&&"symbol"!=typeof e&&"function"!=typeof e&&("bigint"==typeof e||tryBigInt(e))}}else isBigint.exports=function(e){return!1};var isBigintExports=isBigint.exports,isString$1=requireIsString(),isNumber$1=isNumberObject,isBoolean$1=isBooleanObject,isSymbol=isSymbolExports,isBigInt=isBigintExports,whichBoxedPrimitive$1=function(e){return null==e||"object"!=typeof e&&"function"!=typeof e?null:isString$1(e)?"String":isNumber$1(e)?"Number":isBoolean$1(e)?"Boolean":isSymbol(e)?"Symbol":isBigInt(e)?"BigInt":void 0},$WeakMap="function"==typeof WeakMap&&WeakMap.prototype?WeakMap:null,$WeakSet$1="function"==typeof WeakSet&&WeakSet.prototype?WeakSet:null,exported;$WeakMap||(exported=function(e){return!1});var $mapHas$2=$WeakMap?$WeakMap.prototype.has:null,$setHas$2=$WeakSet$1?$WeakSet$1.prototype.has:null;exported||$mapHas$2||(exported=function(e){return!1});var isWeakmap=exported||function(e){if(!e||"object"!=typeof e)return!1;try{if($mapHas$2.call(e,$mapHas$2),$setHas$2)try{$setHas$2.call(e,$setHas$2)}catch(e){return!0}return e instanceof $WeakMap}catch(e){}return!1},isWeakset={exports:{}},GetIntrinsic$1=getIntrinsic,callBound$3=callBound$h,$WeakSet=GetIntrinsic$1("%WeakSet%",!0),$setHas$1=callBound$3("WeakSet.prototype.has",!0);if($setHas$1){var $mapHas$1=callBound$3("WeakMap.prototype.has",!0);isWeakset.exports=function(e){if(!e||"object"!=typeof e)return!1;try{if($setHas$1(e,$setHas$1),$mapHas$1)try{$mapHas$1(e,$mapHas$1)}catch(e){return!0}return e instanceof $WeakSet}catch(e){}return!1}}else isWeakset.exports=function(e){return!1};var isWeaksetExports=isWeakset.exports,isMap=isMap$2,isSet=isSet$2,isWeakMap=isWeakmap,isWeakSet=isWeaksetExports,whichCollection$1=function(e){if(e&&"object"==typeof e){if(isMap(e))return"Map";if(isSet(e))return"Set";if(isWeakMap(e))return"WeakMap";if(isWeakSet(e))return"WeakSet"}return!1},fnToStr=Function.prototype.toString,reflectApply="object"==typeof Reflect&&null!==Reflect&&Reflect.apply,badArrayLike,isCallableMarker;if("function"==typeof reflectApply&&"function"==typeof Object.defineProperty)try{badArrayLike=Object.defineProperty({},"length",{get:function(){throw isCallableMarker}}),isCallableMarker={},reflectApply(function(){throw 42},null,badArrayLike)}catch(_){_!==isCallableMarker&&(reflectApply=null)}else reflectApply=null;var constructorRegex=/^\s*class\b/,isES6ClassFn=function(e){try{var t=fnToStr.call(e);return constructorRegex.test(t)}catch(e){return!1}},tryFunctionObject=function(e){try{return!isES6ClassFn(e)&&(fnToStr.call(e),!0)}catch(e){return!1}},toStr$1=Object.prototype.toString,objectClass="[object Object]",fnClass="[object Function]",genClass="[object GeneratorFunction]",ddaClass="[object HTMLAllCollection]",ddaClass2="[object HTML document.all class]",ddaClass3="[object HTMLCollection]",hasToStringTag$1="function"==typeof Symbol&&!!Symbol.toStringTag,isIE68=!(0 in[,]),isDDA=function(){return!1};if("object"==typeof document){var all$1=document.all;toStr$1.call(all$1)===toStr$1.call(document.all)&&(isDDA=function(e){if((isIE68||!e)&&(void 0===e||"object"==typeof e))try{var t=toStr$1.call(e);return(t===ddaClass||t===ddaClass2||t===ddaClass3||t===objectClass)&&null==e("")}catch(e){}return!1})}var isCallable$1=reflectApply?function(e){if(isDDA(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;try{reflectApply(e,null,badArrayLike)}catch(e){if(e!==isCallableMarker)return!1}return!isES6ClassFn(e)&&tryFunctionObject(e)}:function(e){if(isDDA(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(hasToStringTag$1)return tryFunctionObject(e);if(isES6ClassFn(e))return!1;var t=toStr$1.call(e);return!(t!==fnClass&&t!==genClass&&!/^\[object HTML/.test(t))&&tryFunctionObject(e)},isCallable=isCallable$1,toStr=Object.prototype.toString,hasOwnProperty$1=Object.prototype.hasOwnProperty,forEachArray=function(e,t,r){for(var n=0,i=e.length;n=3&&(n=r),isArray$2(e)?forEachArray(e,t,n):"string"==typeof e?forEachString(e,t,n):forEachObject(e,t,n)},possibleTypedArrayNames=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],possibleNames=possibleTypedArrayNames,g$1="undefined"==typeof globalThis?commonjsGlobal$1:globalThis,availableTypedArrays$1=function(){for(var e=[],t=0;t-1?t:"Object"===t&&trySlices(e)}return gOPD?tryTypedArrays(e):null},callBound$1=callBound$h,$byteLength=callBound$1("ArrayBuffer.prototype.byteLength",!0),isArrayBuffer$2=isArrayBuffer$3,arrayBufferByteLength=function(e){return isArrayBuffer$2(e)?$byteLength?$byteLength(e):e.byteLength:NaN},assign=object_assign,callBound=callBound$f,flags=regexp_prototype_flags,GetIntrinsic=getIntrinsic,getIterator=esGetIteratorExports,getSideChannel=sideChannel,is$1=objectIs,isArguments=isArguments$2,isArray$1=isarray,isArrayBuffer$1=isArrayBuffer$3,isDate$1=isDateObject,isRegex=isRegex$1,isSharedArrayBuffer=isSharedArrayBuffer$1,objectKeys=objectKeys$2,whichBoxedPrimitive=whichBoxedPrimitive$1,whichCollection=whichCollection$1,whichTypedArray=whichTypedArray$1,byteLength=arrayBufferByteLength,sabByteLength=callBound("SharedArrayBuffer.prototype.byteLength",!0),$getTime=callBound("Date.prototype.getTime"),gPO=Object.getPrototypeOf,$objToString=callBound("Object.prototype.toString"),$Set=GetIntrinsic("%Set%",!0),$mapHas=callBound("Map.prototype.has",!0),$mapGet=callBound("Map.prototype.get",!0),$mapSize=callBound("Map.prototype.size",!0),$setAdd=callBound("Set.prototype.add",!0),$setDelete=callBound("Set.prototype.delete",!0),$setHas=callBound("Set.prototype.has",!0),$setSize=callBound("Set.prototype.size",!0);function setHasEqualElement(e,t,r,n){for(var i,o=getIterator(e);(i=o.next())&&!i.done;)if(internalDeepEqual(t,i.value,r,n))return $setDelete(e,i.value),!0;return!1}function findLooseMatchingPrimitives(e){return void 0===e?null:"object"!=typeof e?"symbol"!=typeof e&&("string"!=typeof e&&"number"!=typeof e||+e==+e):void 0}function mapMightHaveLoosePrim(e,t,r,n,i,o){var s=findLooseMatchingPrimitives(r);if(null!=s)return s;var a=$mapGet(t,s),c=assign({},i,{strict:!1});return!(void 0===a&&!$mapHas(t,s)||!internalDeepEqual(n,a,c,o))&&(!$mapHas(e,s)&&internalDeepEqual(n,a,c,o))}function setMightHaveLoosePrim(e,t,r){var n=findLooseMatchingPrimitives(r);return null!=n?n:$setHas(t,n)&&!$setHas(e,n)}function mapHasEqualEntry(e,t,r,n,i,o){for(var s,a,c=getIterator(e);(s=c.next())&&!s.done;)if(internalDeepEqual(r,a=s.value,i,o)&&internalDeepEqual(n,$mapGet(t,a),i,o))return $setDelete(e,a),!0;return!1}function internalDeepEqual(e,t,r,n){var i=r||{};if(i.strict?is$1(e,t):e===t)return!0;if(whichBoxedPrimitive(e)!==whichBoxedPrimitive(t))return!1;if(!e||!t||"object"!=typeof e&&"object"!=typeof t)return i.strict?is$1(e,t):e==t;var o,s=n.has(e),a=n.has(t);if(s&&a){if(n.get(e)===n.get(t))return!0}else o={};return s||n.set(e,o),a||n.set(t,o),objEquiv(e,t,i,n)}function isBuffer$1(e){return!(!e||"object"!=typeof e||"number"!=typeof e.length)&&("function"==typeof e.copy&&"function"==typeof e.slice&&(!(e.length>0&&"number"!=typeof e[0])&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))))}function setEquiv(e,t,r,n){if($setSize(e)!==$setSize(t))return!1;for(var i,o,s,a=getIterator(e),c=getIterator(t);(i=a.next())&&!i.done;)if(i.value&&"object"==typeof i.value)s||(s=new $Set),$setAdd(s,i.value);else if(!$setHas(t,i.value)){if(r.strict)return!1;if(!setMightHaveLoosePrim(e,t,i.value))return!1;s||(s=new $Set),$setAdd(s,i.value)}if(s){for(;(o=c.next())&&!o.done;)if(o.value&&"object"==typeof o.value){if(!setHasEqualElement(s,o.value,r.strict,n))return!1}else if(!r.strict&&!$setHas(e,o.value)&&!setHasEqualElement(s,o.value,r.strict,n))return!1;return 0===$setSize(s)}return!0}function mapEquiv(e,t,r,n){if($mapSize(e)!==$mapSize(t))return!1;for(var i,o,s,a,c,l,u=getIterator(e),d=getIterator(t);(i=u.next())&&!i.done;)if(a=i.value[0],c=i.value[1],a&&"object"==typeof a)s||(s=new $Set),$setAdd(s,a);else if(void 0===(l=$mapGet(t,a))&&!$mapHas(t,a)||!internalDeepEqual(c,l,r,n)){if(r.strict)return!1;if(!mapMightHaveLoosePrim(e,t,a,c,r,n))return!1;s||(s=new $Set),$setAdd(s,a)}if(s){for(;(o=d.next())&&!o.done;)if(a=o.value[0],l=o.value[1],a&&"object"==typeof a){if(!mapHasEqualEntry(s,e,a,l,r,n))return!1}else if(!(r.strict||e.has(a)&&internalDeepEqual($mapGet(e,a),l,r,n)||mapHasEqualEntry(s,e,a,l,assign({},r,{strict:!1}),n)))return!1;return 0===$setSize(s)}return!0}function objEquiv(e,t,r,n){var i,o;if(typeof e!=typeof t)return!1;if(null==e||null==t)return!1;if($objToString(e)!==$objToString(t))return!1;if(isArguments(e)!==isArguments(t))return!1;if(isArray$1(e)!==isArray$1(t))return!1;var s=e instanceof Error,a=t instanceof Error;if(s!==a)return!1;if((s||a)&&(e.name!==t.name||e.message!==t.message))return!1;var c=isRegex(e),l=isRegex(t);if(c!==l)return!1;if((c||l)&&(e.source!==t.source||flags(e)!==flags(t)))return!1;var u=isDate$1(e),d=isDate$1(t);if(u!==d)return!1;if((u||d)&&$getTime(e)!==$getTime(t))return!1;if(r.strict&&gPO&&gPO(e)!==gPO(t))return!1;var h=whichTypedArray(e),p=whichTypedArray(t);if(h!==p)return!1;if(h||p){if(e.length!==t.length)return!1;for(i=0;i=0;i--)if(v[i]!=w[i])return!1;for(i=v.length-1;i>=0;i--)if(!internalDeepEqual(e[o=v[i]],t[o],r,n))return!1;var S=whichCollection(e),_=whichCollection(t);return S===_&&("Set"===S||"Set"===_?setEquiv(e,t,r,n):"Map"!==S||mapEquiv(e,t,r,n))}var deepEqual$1=function(e,t,r){return internalDeepEqual(e,t,r,getSideChannel())},deepEqual$2=getDefaultExportFromCjs$2(deepEqual$1),fastDeepEqual=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,i,o;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(i=n;0!==i--;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(o=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(i=n;0!==i--;)if(!Object.prototype.hasOwnProperty.call(r,o[i]))return!1;for(i=n;0!==i--;){var s=o[i];if(!e(t[s],r[s]))return!1}return!0}return t!=t&&r!=r},equal=getDefaultExportFromCjs$2(fastDeepEqual);let urlAlphabet$3="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$5=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$3[64*Math.random()|0];return t};class IOError{extractErrorMsg(e){return"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e)}raiseError(e,t){const r=this.extractErrorMsg(e);if(errorChannel.port1.postMessage(r),t)throw e;throw new Error(r)}}const ioError=new IOError;var utils$6={};const WIN_SLASH="\\\\/",WIN_NO_SLASH=`[^${WIN_SLASH}]`,DOT_LITERAL="\\.",PLUS_LITERAL="\\+",QMARK_LITERAL="\\?",SLASH_LITERAL="\\/",ONE_CHAR="(?=.)",QMARK="[^/]",END_ANCHOR=`(?:${SLASH_LITERAL}|$)`,START_ANCHOR=`(?:^|${SLASH_LITERAL})`,DOTS_SLASH=`${DOT_LITERAL}{1,2}${END_ANCHOR}`,NO_DOT=`(?!${DOT_LITERAL})`,NO_DOTS=`(?!${START_ANCHOR}${DOTS_SLASH})`,NO_DOT_SLASH=`(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`,NO_DOTS_SLASH=`(?!${DOTS_SLASH})`,QMARK_NO_DOT=`[^.${SLASH_LITERAL}]`,STAR=`${QMARK}*?`,SEP="/",POSIX_CHARS={DOT_LITERAL:DOT_LITERAL,PLUS_LITERAL:PLUS_LITERAL,QMARK_LITERAL:QMARK_LITERAL,SLASH_LITERAL:SLASH_LITERAL,ONE_CHAR:ONE_CHAR,QMARK:QMARK,END_ANCHOR:END_ANCHOR,DOTS_SLASH:DOTS_SLASH,NO_DOT:NO_DOT,NO_DOTS:NO_DOTS,NO_DOT_SLASH:NO_DOT_SLASH,NO_DOTS_SLASH:NO_DOTS_SLASH,QMARK_NO_DOT:QMARK_NO_DOT,STAR:STAR,START_ANCHOR:START_ANCHOR,SEP:SEP},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:`[${WIN_SLASH}]`,QMARK:WIN_NO_SLASH,STAR:`${WIN_NO_SLASH}*?`,DOTS_SLASH:`${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,NO_DOT:`(?!${DOT_LITERAL})`,NO_DOTS:`(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,NO_DOT_SLASH:`(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,NO_DOTS_SLASH:`(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,QMARK_NO_DOT:`[^.${WIN_SLASH}]`,START_ANCHOR:`(?:^|[${WIN_SLASH}])`,END_ANCHOR:`(?:[${WIN_SLASH}]|$)`,SEP:"\\"},POSIX_REGEX_SOURCE$1={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};var constants$2={MAX_LENGTH:65536,POSIX_REGEX_SOURCE:POSIX_REGEX_SOURCE$1,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars:e=>({"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}),globChars:e=>!0===e?WINDOWS_CHARS:POSIX_CHARS};!function(e){const{REGEX_BACKSLASH:t,REGEX_REMOVE_BACKSLASH:r,REGEX_SPECIAL_CHARS:n,REGEX_SPECIAL_CHARS_GLOBAL:i}=constants$2;e.isObject=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),e.hasRegexChars=e=>n.test(e),e.isRegexChar=t=>1===t.length&&e.hasRegexChars(t),e.escapeRegex=e=>e.replace(i,"\\$1"),e.toPosixSlashes=e=>e.replace(t,"/"),e.isWindows=()=>{if("undefined"!=typeof navigator&&navigator.platform){const e=navigator.platform.toLowerCase();return"win32"===e||"windows"===e}return!1},e.removeBackslashes=e=>e.replace(r,e=>"\\"===e?"":e),e.escapeLast=(t,r,n)=>{const i=t.lastIndexOf(r,n);return-1===i?t:"\\"===t[i-1]?e.escapeLast(t,r,i-1):`${t.slice(0,i)}\\${t.slice(i)}`},e.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r},e.wrapOutput=(e,t={},r={})=>{let n=`${r.contains?"":"^"}(?:${e})${r.contains?"":"$"}`;return!0===t.negated&&(n=`(?:^(?!${n}).*$)`),n},e.basename=(e,{windows:t}={})=>{const r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return""===n?r[r.length-2]:n}}(utils$6);const utils$5=utils$6,{CHAR_ASTERISK:CHAR_ASTERISK,CHAR_AT:CHAR_AT,CHAR_BACKWARD_SLASH:CHAR_BACKWARD_SLASH,CHAR_COMMA:CHAR_COMMA,CHAR_DOT:CHAR_DOT,CHAR_EXCLAMATION_MARK:CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH:CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE:CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES:CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET:CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS:CHAR_PLUS,CHAR_QUESTION_MARK:CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE:CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES:CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET:CHAR_RIGHT_SQUARE_BRACKET}=constants$2,isPathSeparator=e=>e===CHAR_FORWARD_SLASH||e===CHAR_BACKWARD_SLASH,depth=e=>{!0!==e.isPrefix&&(e.depth=e.isGlobstar?1/0:1)},scan$1=(e,t)=>{const r=t||{},n=e.length-1,i=!0===r.parts||!0===r.scanToEnd,o=[],s=[],a=[];let c,l,u=e,d=-1,h=0,p=0,g=!1,m=!1,f=!1,y=!1,$=!1,b=!1,v=!1,w=!1,S=!1,_=!1,E=0,C={value:"",depth:0,isGlob:!1};const I=()=>d>=n,T=()=>u.charCodeAt(d+1),A=()=>(c=l,u.charCodeAt(++d));for(;d0&&(x=u.slice(0,h),u=u.slice(h),p-=h),D&&!0===f&&p>0?(D=u.slice(0,p),R=u.slice(p)):!0===f?(D="",R=u):D=u,D&&""!==D&&"/"!==D&&D!==u&&isPathSeparator(D.charCodeAt(D.length-1))&&(D=D.slice(0,-1)),!0===r.unescape&&(R&&(R=utils$5.removeBackslashes(R)),D&&!0===v&&(D=utils$5.removeBackslashes(D)));const O={prefix:x,input:e,start:h,base:D,glob:R,isBrace:g,isBracket:m,isGlob:f,isExtglob:y,isGlobstar:$,negated:w,negatedExtglob:S};if(!0===r.tokens&&(O.maxDepth=0,isPathSeparator(l)||s.push(C),O.tokens=s),!0===r.parts||!0===r.tokens){let t;for(let n=0;n{if("function"==typeof t.expandRange)return t.expandRange(...e,t);e.sort();const r=`[${e.join("-")}]`;try{new RegExp(r)}catch(t){return e.map(e=>utils$4.escapeRegex(e)).join("..")}return r},syntaxError=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,parse$3=(e,t)=>{if("string"!=typeof e)throw new TypeError("Expected a string");e=REPLACEMENTS[e]||e;const r={...t},n="number"==typeof r.maxLength?Math.min(MAX_LENGTH,r.maxLength):MAX_LENGTH;let i=e.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);const o={type:"bos",value:"",output:r.prepend||""},s=[o],a=r.capture?"":"?:",c=constants$1.globChars(r.windows),l=constants$1.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:h,ONE_CHAR:p,DOTS_SLASH:g,NO_DOT:m,NO_DOT_SLASH:f,NO_DOTS_SLASH:y,QMARK:$,QMARK_NO_DOT:b,STAR:v,START_ANCHOR:w}=c,S=e=>`(${a}(?:(?!${w}${e.dot?g:u}).)*?)`,_=r.dot?"":m,E=r.dot?$:b;let C=!0===r.bash?S(r):v;r.capture&&(C=`(${C})`),"boolean"==typeof r.noext&&(r.noextglob=r.noext);const I={input:e,index:-1,start:0,dot:!0===r.dot,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:s};e=utils$4.removePrefix(e,I),i=e.length;const T=[],A=[],D=[];let x,R=o;const O=()=>I.index===i-1,N=I.peek=(t=1)=>e[I.index+t],P=I.advance=()=>e[++I.index]||"",k=()=>e.slice(I.index+1),M=(e="",t=0)=>{I.consumed+=e,I.index+=t},L=e=>{I.output+=null!=e.output?e.output:e.value,M(e.value)},F=()=>{let e=1;for(;"!"===N()&&("("!==N(2)||"?"===N(3));)P(),I.start++,e++;return e%2!=0&&(I.negated=!0,I.start++,!0)},j=e=>{I[e]++,D.push(e)},U=e=>{I[e]--,D.pop()},B=e=>{if("globstar"===R.type){const t=I.braces>0&&("comma"===e.type||"brace"===e.type),r=!0===e.extglob||T.length&&("pipe"===e.type||"paren"===e.type);"slash"===e.type||"paren"===e.type||t||r||(I.output=I.output.slice(0,-R.output.length),R.type="star",R.value="*",R.output=C,I.output+=R.output)}if(T.length&&"paren"!==e.type&&(T[T.length-1].inner+=e.value),(e.value||e.output)&&L(e),R&&"text"===R.type&&"text"===e.type)return R.output=(R.output||R.value)+e.value,void(R.value+=e.value);e.prev=R,s.push(e),R=e},H=(e,t)=>{const n={...l[t],conditions:1,inner:""};n.prev=R,n.parens=I.parens,n.output=I.output;const i=(r.capture?"(":"")+n.open;j("parens"),B({type:e,value:t,output:I.output?"":p}),B({type:"paren",extglob:!0,value:P(),output:i}),T.push(n)},q=e=>{let n,i=e.close+(r.capture?")":"");if("negate"===e.type){let o=C;if(e.inner&&e.inner.length>1&&e.inner.includes("/")&&(o=S(r)),(o!==C||O()||/^\)+$/.test(k()))&&(i=e.close=`)$))${o}`),e.inner.includes("*")&&(n=k())&&/^\.[^\\/.]+$/.test(n)){const r=parse$3(n,{...t,fastpaths:!1}).output;i=e.close=`)${r})${o})`}"bos"===e.prev.type&&(I.negatedExtglob=!0)}B({type:"paren",extglob:!0,value:x,output:i}),U("parens")};if(!1!==r.fastpaths&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=!1,i=e.replace(REGEX_SPECIAL_CHARS_BACKREF,(e,t,r,i,o,s)=>"\\"===i?(n=!0,e):"?"===i?t?t+i+(o?$.repeat(o.length):""):0===s?E+(o?$.repeat(o.length):""):$.repeat(r.length):"."===i?u.repeat(r.length):"*"===i?t?t+i+(o?C:""):C:t?e:`\\${e}`);return!0===n&&(i=!0===r.unescape?i.replace(/\\/g,""):i.replace(/\\+/g,e=>e.length%2==0?"\\\\":e?"\\":"")),i===e&&!0===r.contains?(I.output=e,I):(I.output=utils$4.wrapOutput(i,I,t),I)}for(;!O();){if(x=P(),"\0"===x)continue;if("\\"===x){const e=N();if("/"===e&&!0!==r.bash)continue;if("."===e||";"===e)continue;if(!e){x+="\\",B({type:"text",value:x});continue}const t=/^\\+/.exec(k());let n=0;if(t&&t[0].length>2&&(n=t[0].length,I.index+=n,n%2!=0&&(x+="\\")),!0===r.unescape?x=P():x+=P(),0===I.brackets){B({type:"text",value:x});continue}}if(I.brackets>0&&("]"!==x||"["===R.value||"[^"===R.value)){if(!1!==r.posix&&":"===x){const e=R.value.slice(1);if(e.includes("[")&&(R.posix=!0,e.includes(":"))){const e=R.value.lastIndexOf("["),t=R.value.slice(0,e),r=R.value.slice(e+2),n=POSIX_REGEX_SOURCE[r];if(n){R.value=t+n,I.backtrack=!0,P(),o.output||1!==s.indexOf(R)||(o.output=p);continue}}}("["===x&&":"!==N()||"-"===x&&"]"===N())&&(x=`\\${x}`),"]"!==x||"["!==R.value&&"[^"!==R.value||(x=`\\${x}`),!0===r.posix&&"!"===x&&"["===R.value&&(x="^"),R.value+=x,L({value:x});continue}if(1===I.quotes&&'"'!==x){x=utils$4.escapeRegex(x),R.value+=x,L({value:x});continue}if('"'===x){I.quotes=1===I.quotes?0:1,!0===r.keepQuotes&&B({type:"text",value:x});continue}if("("===x){j("parens"),B({type:"paren",value:x});continue}if(")"===x){if(0===I.parens&&!0===r.strictBrackets)throw new SyntaxError(syntaxError("opening","("));const e=T[T.length-1];if(e&&I.parens===e.parens+1){q(T.pop());continue}B({type:"paren",value:x,output:I.parens?")":"\\)"}),U("parens");continue}if("["===x){if(!0!==r.nobracket&&k().includes("]"))j("brackets");else{if(!0!==r.nobracket&&!0===r.strictBrackets)throw new SyntaxError(syntaxError("closing","]"));x=`\\${x}`}B({type:"bracket",value:x});continue}if("]"===x){if(!0===r.nobracket||R&&"bracket"===R.type&&1===R.value.length){B({type:"text",value:x,output:`\\${x}`});continue}if(0===I.brackets){if(!0===r.strictBrackets)throw new SyntaxError(syntaxError("opening","["));B({type:"text",value:x,output:`\\${x}`});continue}U("brackets");const e=R.value.slice(1);if(!0===R.posix||"^"!==e[0]||e.includes("/")||(x=`/${x}`),R.value+=x,L({value:x}),!1===r.literalBrackets||utils$4.hasRegexChars(e))continue;const t=utils$4.escapeRegex(R.value);if(I.output=I.output.slice(0,-R.value.length),!0===r.literalBrackets){I.output+=t,R.value=t;continue}R.value=`(${a}${t}|${R.value})`,I.output+=R.value;continue}if("{"===x&&!0!==r.nobrace){j("braces");const e={type:"brace",value:x,output:"(",outputIndex:I.output.length,tokensIndex:I.tokens.length};A.push(e),B(e);continue}if("}"===x){const e=A[A.length-1];if(!0===r.nobrace||!e){B({type:"text",value:x,output:x});continue}let t=")";if(!0===e.dots){const e=s.slice(),n=[];for(let t=e.length-1;t>=0&&(s.pop(),"brace"!==e[t].type);t--)"dots"!==e[t].type&&n.unshift(e[t].value);t=expandRange(n,r),I.backtrack=!0}if(!0!==e.comma&&!0!==e.dots){const r=I.output.slice(0,e.outputIndex),n=I.tokens.slice(e.tokensIndex);e.value=e.output="\\{",x=t="\\}",I.output=r;for(const e of n)I.output+=e.output||e.value}B({type:"brace",value:x,output:t}),U("braces"),A.pop();continue}if("|"===x){T.length>0&&T[T.length-1].conditions++,B({type:"text",value:x});continue}if(","===x){let e=x;const t=A[A.length-1];t&&"braces"===D[D.length-1]&&(t.comma=!0,e="|"),B({type:"comma",value:x,output:e});continue}if("/"===x){if("dot"===R.type&&I.index===I.start+1){I.start=I.index+1,I.consumed="",I.output="",s.pop(),R=o;continue}B({type:"slash",value:x,output:h});continue}if("."===x){if(I.braces>0&&"dot"===R.type){"."===R.value&&(R.output=u);const e=A[A.length-1];R.type="dots",R.output+=x,R.value+=x,e.dots=!0;continue}if(I.braces+I.parens===0&&"bos"!==R.type&&"slash"!==R.type){B({type:"text",value:x,output:u});continue}B({type:"dot",value:x,output:u});continue}if("?"===x){if(!(R&&"("===R.value)&&!0!==r.noextglob&&"("===N()&&"?"!==N(2)){H("qmark",x);continue}if(R&&"paren"===R.type){const e=N();let t=x;("("===R.value&&!/[!=<:]/.test(e)||"<"===e&&!/<([!=]|\w+>)/.test(k()))&&(t=`\\${x}`),B({type:"text",value:x,output:t});continue}if(!0!==r.dot&&("slash"===R.type||"bos"===R.type)){B({type:"qmark",value:x,output:b});continue}B({type:"qmark",value:x,output:$});continue}if("!"===x){if(!0!==r.noextglob&&"("===N()&&("?"!==N(2)||!/[!=<:]/.test(N(3)))){H("negate",x);continue}if(!0!==r.nonegate&&0===I.index){F();continue}}if("+"===x){if(!0!==r.noextglob&&"("===N()&&"?"!==N(2)){H("plus",x);continue}if(R&&"("===R.value||!1===r.regex){B({type:"plus",value:x,output:d});continue}if(R&&("bracket"===R.type||"paren"===R.type||"brace"===R.type)||I.parens>0){B({type:"plus",value:x});continue}B({type:"plus",value:d});continue}if("@"===x){if(!0!==r.noextglob&&"("===N()&&"?"!==N(2)){B({type:"at",extglob:!0,value:x,output:""});continue}B({type:"text",value:x});continue}if("*"!==x){"$"!==x&&"^"!==x||(x=`\\${x}`);const e=REGEX_NON_SPECIAL_CHARS.exec(k());e&&(x+=e[0],I.index+=e[0].length),B({type:"text",value:x});continue}if(R&&("globstar"===R.type||!0===R.star)){R.type="star",R.star=!0,R.value+=x,R.output=C,I.backtrack=!0,I.globstar=!0,M(x);continue}let t=k();if(!0!==r.noextglob&&/^\([^?]/.test(t)){H("star",x);continue}if("star"===R.type){if(!0===r.noglobstar){M(x);continue}const n=R.prev,i=n.prev,o="slash"===n.type||"bos"===n.type,s=i&&("star"===i.type||"globstar"===i.type);if(!0===r.bash&&(!o||t[0]&&"/"!==t[0])){B({type:"star",value:x,output:""});continue}const a=I.braces>0&&("comma"===n.type||"brace"===n.type),c=T.length&&("pipe"===n.type||"paren"===n.type);if(!o&&"paren"!==n.type&&!a&&!c){B({type:"star",value:x,output:""});continue}for(;"/**"===t.slice(0,3);){const r=e[I.index+4];if(r&&"/"!==r)break;t=t.slice(3),M("/**",3)}if("bos"===n.type&&O()){R.type="globstar",R.value+=x,R.output=S(r),I.output=R.output,I.globstar=!0,M(x);continue}if("slash"===n.type&&"bos"!==n.prev.type&&!s&&O()){I.output=I.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type="globstar",R.output=S(r)+(r.strictSlashes?")":"|$)"),R.value+=x,I.globstar=!0,I.output+=n.output+R.output,M(x);continue}if("slash"===n.type&&"bos"!==n.prev.type&&"/"===t[0]){const e=void 0!==t[1]?"|$":"";I.output=I.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type="globstar",R.output=`${S(r)}${h}|${h}${e})`,R.value+=x,I.output+=n.output+R.output,I.globstar=!0,M(x+P()),B({type:"slash",value:"/",output:""});continue}if("bos"===n.type&&"/"===t[0]){R.type="globstar",R.value+=x,R.output=`(?:^|${h}|${S(r)}${h})`,I.output=R.output,I.globstar=!0,M(x+P()),B({type:"slash",value:"/",output:""});continue}I.output=I.output.slice(0,-R.output.length),R.type="globstar",R.output=S(r),R.value+=x,I.output+=R.output,I.globstar=!0,M(x);continue}const n={type:"star",value:x,output:C};!0!==r.bash?!R||"bracket"!==R.type&&"paren"!==R.type||!0!==r.regex?(I.index!==I.start&&"slash"!==R.type&&"dot"!==R.type||("dot"===R.type?(I.output+=f,R.output+=f):!0===r.dot?(I.output+=y,R.output+=y):(I.output+=_,R.output+=_),"*"!==N()&&(I.output+=p,R.output+=p)),B(n)):(n.output=x,B(n)):(n.output=".*?","bos"!==R.type&&"slash"!==R.type||(n.output=_+n.output),B(n))}for(;I.brackets>0;){if(!0===r.strictBrackets)throw new SyntaxError(syntaxError("closing","]"));I.output=utils$4.escapeLast(I.output,"["),U("brackets")}for(;I.parens>0;){if(!0===r.strictBrackets)throw new SyntaxError(syntaxError("closing",")"));I.output=utils$4.escapeLast(I.output,"("),U("parens")}for(;I.braces>0;){if(!0===r.strictBrackets)throw new SyntaxError(syntaxError("closing","}"));I.output=utils$4.escapeLast(I.output,"{"),U("braces")}if(!0===r.strictSlashes||"star"!==R.type&&"bracket"!==R.type||B({type:"maybe_slash",value:"",output:`${h}?`}),!0===I.backtrack){I.output="";for(const e of I.tokens)I.output+=null!=e.output?e.output:e.value,e.suffix&&(I.output+=e.suffix)}return I};parse$3.fastpaths=(e,t)=>{const r={...t},n="number"==typeof r.maxLength?Math.min(MAX_LENGTH,r.maxLength):MAX_LENGTH,i=e.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);e=REPLACEMENTS[e]||e;const{DOT_LITERAL:o,SLASH_LITERAL:s,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:h,START_ANCHOR:p}=constants$1.globChars(r.windows),g=r.dot?u:l,m=r.dot?d:l,f=r.capture?"":"?:";let y=!0===r.bash?".*?":h;r.capture&&(y=`(${y})`);const $=e=>!0===e.noglobstar?y:`(${f}(?:(?!${p}${e.dot?c:o}).)*?)`,b=e=>{switch(e){case"*":return`${g}${a}${y}`;case".*":return`${o}${a}${y}`;case"*.*":return`${g}${y}${o}${a}${y}`;case"*/*":return`${g}${y}${s}${a}${m}${y}`;case"**":return g+$(r);case"**/*":return`(?:${g}${$(r)}${s})?${m}${a}${y}`;case"**/*.*":return`(?:${g}${$(r)}${s})?${m}${y}${o}${a}${y}`;case"**/.*":return`(?:${g}${$(r)}${s})?${o}${a}${y}`;default:{const t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;const r=b(t[1]);if(!r)return;return r+o+t[2]}}},v=utils$4.removePrefix(e,{negated:!1,prefix:""});let w=b(v);return w&&!0!==r.strictSlashes&&(w+=`${s}?`),w};var parse_1=parse$3;const scan=scan_1,parse$2=parse_1,utils$3=utils$6,constants=constants$2,isObject$2=e=>e&&"object"==typeof e&&!Array.isArray(e),picomatch$1=(e,t,r=!1)=>{if(Array.isArray(e)){const n=e.map(e=>picomatch$1(e,t,r)),i=e=>{for(const t of n){const r=t(e);if(r)return r}return!1};return i}const n=isObject$2(e)&&e.tokens&&e.input;if(""===e||"string"!=typeof e&&!n)throw new TypeError("Expected pattern to be a non-empty string");const i=t||{},o=i.windows,s=n?picomatch$1.compileRe(e,t):picomatch$1.makeRe(e,t,!1,!0),a=s.state;delete s.state;let c=()=>!1;if(i.ignore){const e={...t,ignore:null,onMatch:null,onResult:null};c=picomatch$1(i.ignore,e,r)}const l=(r,n=!1)=>{const{isMatch:l,match:u,output:d}=picomatch$1.test(r,s,t,{glob:e,posix:o}),h={glob:e,state:a,regex:s,posix:o,input:r,output:d,match:u,isMatch:l};return"function"==typeof i.onResult&&i.onResult(h),!1===l?(h.isMatch=!1,!!n&&h):c(r)?("function"==typeof i.onIgnore&&i.onIgnore(h),h.isMatch=!1,!!n&&h):("function"==typeof i.onMatch&&i.onMatch(h),!n||h)};return r&&(l.state=a),l};picomatch$1.test=(e,t,r,{glob:n,posix:i}={})=>{if("string"!=typeof e)throw new TypeError("Expected input to be a string");if(""===e)return{isMatch:!1,output:""};const o=r||{},s=o.format||(i?utils$3.toPosixSlashes:null);let a=e===n,c=a&&s?s(e):e;return!1===a&&(c=s?s(e):e,a=c===n),!1!==a&&!0!==o.capture||(a=!0===o.matchBase||!0===o.basename?picomatch$1.matchBase(e,t,r,i):t.exec(c)),{isMatch:Boolean(a),match:a,output:c}},picomatch$1.matchBase=(e,t,r)=>(t instanceof RegExp?t:picomatch$1.makeRe(t,r)).test(utils$3.basename(e)),picomatch$1.isMatch=(e,t,r)=>picomatch$1(t,r)(e),picomatch$1.parse=(e,t)=>Array.isArray(e)?e.map(e=>picomatch$1.parse(e,t)):parse$2(e,{...t,fastpaths:!1}),picomatch$1.scan=(e,t)=>scan(e,t),picomatch$1.compileRe=(e,t,r=!1,n=!1)=>{if(!0===r)return e.output;const i=t||{},o=i.contains?"":"^",s=i.contains?"":"$";let a=`${o}(?:${e.output})${s}`;e&&!0===e.negated&&(a=`^(?!${a}).*$`);const c=picomatch$1.toRegex(a,t);return!0===n&&(c.state=e),c},picomatch$1.makeRe=(e,t={},r=!1,n=!1)=>{if(!e||"string"!=typeof e)throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return!1===t.fastpaths||"."!==e[0]&&"*"!==e[0]||(i.output=parse$2.fastpaths(e,t)),i.output||(i=parse$2(e,t)),picomatch$1.compileRe(i,t,r,n)},picomatch$1.toRegex=(e,t)=>{try{const r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(e){if(t&&!0===t.debug)throw e;return/$^/}},picomatch$1.constants=constants;var picomatch_1$1=picomatch$1;const pico=picomatch_1$1,utils$2=utils$6;function picomatch(e,t,r=!1){return!t||null!==t.windows&&void 0!==t.windows||(t={...t,windows:utils$2.isWindows()}),pico(e,t,r)}Object.assign(picomatch,pico);var picomatch_1=picomatch,pm=getDefaultExportFromCjs$2(picomatch_1);const getRelativeBounds=(e,t,r)=>"bottom"===r?{left:t.left,top:t.top+t.height+0,width:t.width,height:e.height}:"top"===r?{left:t.left,top:t.top-e.height-0,width:t.width,height:e.height}:"right"===r?{left:t.left+t.width+0,top:t.top,width:e.width,height:t.height}:"left"===r?{left:t.left-e.width-0,top:t.top,width:e.width,height:t.height}:ioError.raiseError("invalid relativeDirection"),objEqual=(e,t)=>deepEqual$2(e,t,{strict:!0}),objEqualFast=(e,t)=>equal(e,t),waitFor=(e,t)=>{let r=e;return()=>{r--,0===r&&t()}},wait=e=>new Promise(t=>setTimeout(()=>t(),e)),extractErrorMsg$1=e=>"string"==typeof e?e:e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):JSON.stringify(e),checkMatch=(e,t)=>{if(!e.count)return!1;const r=t();return r&&(e.count=--e.count<0?0:e.count),r},clearNullUndefined=e=>{Object.keys(e).forEach(t=>{null!==e[t]&&void 0!==e[t]||delete e[t]})},runDecoderWithIOError=(e,t)=>{try{return e.runWithException(t)}catch(e){return ioError.raiseError(e,!0)}},checkIsOriginBlocked=(e,t=[])=>{const r=new URL(e);if(!t.length)return!1;if(t.includes("*"))return!0;return t.some(e=>pm(e)(r.origin))},getSafeTimeoutDelay=e=>Math.min(e,MAX_SET_TIMEOUT_DELAY);function generateLayoutToken(){return nanoid$5(10)}const getLastUpdateTimestamp=()=>(new Date).toISOString(),escapeRegex$1=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");class Gateway{_gatewayInstance;configureLogging=Oc.Logging.configure;create=mv;async start(e,t){if(e?.logging){const t=e.logging.appender;this.configureLogging({level:e.logging.level||"error",appender:e=>{if(t){const r={time:e.time,output:e.message,level:e.level,line:-1,message:e.message,namespace:e.name,stacktrace:""};t(r)}}})}const r=this.getGatewayConfig(e,t);this._gatewayInstance=this.create(r),await this._gatewayInstance.start()}async connectClient(e){return this._gatewayInstance.connect((t,r)=>e.postMessage(r))}async connectExtClient(e,t){const r=await this._gatewayInstance.connect((t,r)=>e.postMessage({glue42ExtInc:r}));e.onMessage.addListener(n=>{const i=n?.glue42ExtOut?.glue42core;if(i&&i.type===Glue42CoreMessageTypes.clientUnload.name)return r.close(),e.disconnect(),void(t&&t(i.data.clientId,!0));if(n.glue42ExtOut&&!i){const e=n.glue42ExtOut;return void r.send(e)}})}async setupInternalClient(e){let t;e.onmessage=async r=>{const n=r.data?.glue42core;if(n&&n.type===Glue42CoreMessageTypes.gatewayInternalConnect.name)t=await this.handleInternalGatewayConnectionRequest(e);else if(t&&!e.closed)return n&&n.type===Glue42CoreMessageTypes.gatewayDisconnect.name?(e.closed=!0,void t?.close()):void t?.send(r.data)}}async handleInternalGatewayConnectionRequest(e){e.closed=!1;try{const t=await this._gatewayInstance.connect((t,r)=>e.postMessage(r));return e.postMessage({glue42core:{type:Glue42CoreMessageTypes.gatewayInternalConnect.name,success:!0}}),t}catch(t){const r="string"==typeof t?t:JSON.stringify(t.message);return void e.postMessage({glue42core:{type:Glue42CoreMessageTypes.gatewayInternalConnect.name,error:r}})}}getGatewayConfig(e,t){const r={clients:{inactive_seconds:0,buffer_size:"number"==typeof e?.clients?.buffer_size?e.clients.buffer_size:1e3},contexts:{lifetime:"retained"}};if(!e?.bridge)return r;if(!t)return ioError.raiseError("Platform initialization failed due to missing user details. Providing configuration settings for connecting to io.Bridge also requires providing user details via the `user` property.");const n=t.id;return r.authentication={basic:{usernameResolver:()=>n}},r.mesh={auth:{user:n},cluster:{endpoint:e.bridge.url,directory:{interval:6e4,metadata:{type:"io.Connect Browser"}},opts:{headers:e.bridge.headers,getHeaders:e.bridge.getHeaders,getWebSocketSearchParams:e.bridge.getWebSocketSearchParams}}},r.contexts={...r.contexts,visibility:[{context:new RegExp(/^___instance___.+/),restrictions:"local"},{context:new RegExp(/^___window___.+/),restrictions:"local"},{context:new RegExp(/^___window-hibernation___.+/),restrictions:"local"},{context:new RegExp(/^___workspace___.+/),restrictions:"local"},{context:new RegExp(`^${escapeRegex$1(ChannelContextPrefix)}.+`),restrictions:e.bridge.channels?.enabled??1?"cluster":"local"},...e.bridge.contexts?.visibility??[],{context:new RegExp(/[\s\S]*/),restrictions:e.bridge.contexts?.enabled??1?"cluster":"local"}]},r.methods={visibility:[{method:new RegExp(`^${escapeRegex$1(GlueWebIntentsPrefix)}.+`),restrictions:e.bridge.intents?.enabled??1?"cluster":"local"},{method:/^T42\.Search\.(Client|Provider)$/,restrictions:e.bridge.search?.enabled??1?"cluster":"local"},{method:/^T42\..+/,restrictions:"local"},...e.bridge.interop?.visibility??[],{method:new RegExp(/[\s\S]*/),restrictions:e.bridge.interop?.enabled??1?"cluster":"local"}]},r.peers={visibility:[{domain:"context",restrictions:"cluster"},{domain:"interop",restrictions:"cluster"}]},r}}function createRegistry$2(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;ir(e)).catch(e=>n(e))}async handlePluginMessage(e,t){return this.processControllerCommand(e,"plugin",t)}async processControllerCommand(e,t,r){try{this.domainsController.validateDomain(e.domain)}catch(e){const n=extractErrorMsg$1(e);return this.logger?.trace(`rejecting execution of a command issued by a ${t}: ${r}, because of a domain validation error: ${n}`),ioError.raiseError(`Cannot execute this platform control, because of domain validation error: ${n}`)}const n=Object.assign({},e,{commandId:nanoid$5(10),callerId:r,callerType:t});this.logger?.trace(`[${n.commandId}] received a command for a valid domain: ${e.domain} from ${t}: ${r}, forwarding to the appropriate controller`);try{const e=await this.executeCommand(n);return this.logger?.trace(`[${n.commandId}] this command was executed successfully, sending the result to the caller.`),e}catch(t){const r="string"==typeof t?t:t.message?JSON.stringify(t.message):JSON.stringify(t);throw this.logger?.trace(`[${n.commandId}] this command's execution was rejected, reason: ${r}`),new Error(`The platform rejected operation ${n.operation} for domain: ${e.domain} with reason: ${r}`)}}handleClientUnloaded(e){this.domainsController.notifyDomainsClientUnloaded(e)}executeCommand(e){const t=this.interceptionController.getOperationInterceptor({domain:e.domain,operation:e.operation});return t&&!e.settings?.skipInterception?(this.logger?.trace(`[${e.commandId}] The operation is being intercepted and executed by: ${t.name}`),t.intercept(e)):this.domainsController.executeControlMessage(e)}buildPlatformApi(){return{version:this.glueController.platformVersion,contextTrackGlue:this.ctxTrackingGlue,systemGlue:this.systemGlue,connectExtClient:(e,t)=>this.connectExtClient(e,t),onSystemReconnect:e=>this.onSystemReconnect(e),system:{shutdown:this.shutDown.bind(this),cache:{clear:this.idbCacheController.clear.bind(this.idbCacheController),deleteOtherDBs:this.idbCacheController.deleteOtherDBs.bind(this.idbCacheController)},connection:{switchGW:this.preferredConnectionController.connectPreferred.bind(this.preferredConnectionController),switchToInternal:this.preferredConnectionController.revertToDefault.bind(this.preferredConnectionController)}}}}async connectExtClient(e,t){await this.portsBridge.handleExtConnectionRequest(e,t)}onSystemReconnect(e){return this.preferredConnectionController.onReconnect(e)}async shutDown(){this.restScheduler.stop(),await this.glueController.sendShutDownSignals(),this.stateController.cancel(),this.portsBridge.shutdown(),this.domainsController.shutdown(),this.serviceWorkerController.shutdown(),await this.pluginsController.shutdown(),this.interceptionController.shutdown(),this.preferredConnectionController.shutdown(),this.glueController.shutdown(),this.sessionController.shutdown(),this.localStorageController.stop(),this.idbController.stop(),this.idbCacheController.stop();const e=window.iobrowser?.system;window.iobrowser={webStarted:!1,system:e}}verifyLicense(e){if(!e||"string"!=typeof e||!e.length)return ioError.raiseError("The provided license key is not a valid string");if(!this.licenseController.verifyLicense(e).valid)return this.logExpirationErrors(),ioError.raiseError("io.Connect Browser cannot initialize, because there was no license token provided or it was invalid.");const t=this.licenseController.getLicensePayload(e),r=window.location;return this.licenseController.isPlatformOriginAllowed(r,t.platformAllowOrigins)?"trial"===t.type&&this.licenseController.checkExpired(t.expiration)?(this.logExpirationErrors(),ioError.raiseError("io.Connect Browser cannot initialize, because the provided trial license has expired.")):(this.licenseController.checkExpired(t.expiration)&&this.logExpirationErrors(),void console.info(`This io.Connect Browser is running with a ${t.type} license, which expires on: ${new Date(t.expiration).toString()}`)):ioError.raiseError("io.Connect Browser cannot initialize, because the platform origin is not allowed by the provided license.")}logExpirationErrors(){console.error("***********************************************************************************************************"),console.error("***********************************************************************************************************"),console.error("********************** This io.Connect Browser has an expired or invalid license **************************"),console.error("***********************************************************************************************************"),console.error("***********************************************************************************************************")}getProfileData(e,t){const r=this.licenseController.getLicensePayload(e),n={license:{type:r.type,expiration:r.expiration},productsInfo:{platform:{apiVersion:this.glueController.platformVersion},client:{apiVersion:this.glueController.clientGlue.version}},plugins:this.pluginsController.registeredPlugins.map(e=>({name:e.name,version:e.version}))};return t&&(n.user={id:t.id,username:t.username,email:t.email,firstName:t.firstName,lastName:t.lastName,type:t.type,role:t.role,meta:t.meta}),this.glueController.clientGlue.workspaces&&(n.productsInfo.workspaces={apiVersion:this.glueController.clientGlue.workspaces.version,container:window.ioworkspaces?{type:window.ioworkspaces.type,version:window.ioworkspaces.version}:void 0}),this.glueController.clientGlue.search&&(n.productsInfo.search={apiVersion:this.glueController.clientGlue.search.version}),this.glueController.clientGlue.modals&&(n.productsInfo.modals={apiVersion:this.glueController.clientGlue.modals.version}),window.iohome&&(n.productsInfo.home={version:window.iohome.version}),n}async startCacheIdb(e){const t=e.applicationPreferences?.store?.rest?.cache?.enabled,r=e.layouts?.rest?.cache?.enabled,n=e.applications?.remote?.cache?.enabled;(t||r||n)&&(this.logger?.info("Starting IDB cache..."),await this.idbCacheController.start(e.user))}}const connectBrowserAppProps=["name","title","version","customProperties","icon","caption","type"],fdc3v2AppProps=["appId","name","type","details","version","title","tooltip","lang","description","categories","icons","screenshots","contactEmail","moreInfo","publisher","customConfig","hostManifests","interop","localizedVersions"];var ok$3=function(e){return{ok:!0,result:e}},err$3=function(e){return{ok:!1,error:e}},asPromise$3=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$3=function(e,t){return!0===t.ok?t.result:e},withException$3=function(e){if(!0===e.ok)return e.result;throw e.error},map$4=function(e,t){return!0===t.ok?ok$3(e(t.result)):t},map2$3=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$3(e(t.result,r.result))},mapError$3=function(e,t){return!0===t.ok?t:err$3(e(t.error))},andThen$3=function(e,t){return!0===t.ok?e(t.result):t},__assign$3=function(){return __assign$3=Object.assign||function(e){for(var t,r=1,n=arguments.length;re.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$3=number$6().where(e=>e>=0,"Expected a non-negative number"),regexDecoder$1=anyJson$3().andThen(e=>e instanceof RegExp?anyJson$3():fail("expected a regex, got a "+typeof e)),intentDefinitionDecoder$1=object$4({name:nonEmptyStringDecoder$4,displayName:optional$4(string$6()),contexts:optional$4(array$4(string$6())),customConfig:optional$4(object$4())}),v2TypeDecoder=oneOf$2(constant$3("web"),constant$3("native"),constant$3("citrix"),constant$3("onlineNative"),constant$3("other")),v2DetailsDecoder=object$4({url:nonEmptyStringDecoder$4}),v2IconDecoder=object$4({src:nonEmptyStringDecoder$4,size:optional$4(nonEmptyStringDecoder$4),type:optional$4(nonEmptyStringDecoder$4)}),v2ScreenshotDecoder=object$4({src:nonEmptyStringDecoder$4,size:optional$4(nonEmptyStringDecoder$4),type:optional$4(nonEmptyStringDecoder$4),label:optional$4(nonEmptyStringDecoder$4)}),v2ListensForIntentDecoder=object$4({contexts:array$4(nonEmptyStringDecoder$4),displayName:optional$4(nonEmptyStringDecoder$4),resultType:optional$4(nonEmptyStringDecoder$4),customConfig:optional$4(anyJson$3())}),v2IntentsDecoder=object$4({listensFor:optional$4(dict(v2ListensForIntentDecoder)),raises:optional$4(dict(array$4(nonEmptyStringDecoder$4)))}),v2UserChannelDecoder=object$4({broadcasts:optional$4(array$4(nonEmptyStringDecoder$4)),listensFor:optional$4(array$4(nonEmptyStringDecoder$4))}),v2AppChannelDecoder=object$4({name:nonEmptyStringDecoder$4,description:optional$4(nonEmptyStringDecoder$4),broadcasts:optional$4(array$4(nonEmptyStringDecoder$4)),listensFor:optional$4(array$4(nonEmptyStringDecoder$4))}),v2InteropDecoder=object$4({intents:optional$4(v2IntentsDecoder),userChannels:optional$4(v2UserChannelDecoder),appChannels:optional$4(array$4(v2AppChannelDecoder))}),glue42ApplicationDetailsDecoder=object$4({url:optional$4(nonEmptyStringDecoder$4),top:optional$4(number$6()),left:optional$4(number$6()),width:optional$4(nonNegativeNumberDecoder$3),height:optional$4(nonNegativeNumberDecoder$3)}),glue42HostManifestsBrowserDecoder=object$4({name:optional$4(nonEmptyStringDecoder$4),type:optional$4(nonEmptyStringDecoder$4.where(e=>"window"===e,"Expected a value of window")),title:optional$4(nonEmptyStringDecoder$4),version:optional$4(nonEmptyStringDecoder$4),customProperties:optional$4(anyJson$3()),icon:optional$4(string$6()),caption:optional$4(string$6()),details:optional$4(glue42ApplicationDetailsDecoder),intents:optional$4(array$4(intentDefinitionDecoder$1)),hidden:optional$4(boolean$5())}),v1DefinitionDecoder=object$4({name:nonEmptyStringDecoder$4,appId:nonEmptyStringDecoder$4,title:optional$4(nonEmptyStringDecoder$4),version:optional$4(nonEmptyStringDecoder$4),manifest:nonEmptyStringDecoder$4,manifestType:nonEmptyStringDecoder$4,tooltip:optional$4(nonEmptyStringDecoder$4),description:optional$4(nonEmptyStringDecoder$4),contactEmail:optional$4(nonEmptyStringDecoder$4),supportEmail:optional$4(nonEmptyStringDecoder$4),publisher:optional$4(nonEmptyStringDecoder$4),images:optional$4(array$4(object$4({url:optional$4(nonEmptyStringDecoder$4)}))),icons:optional$4(array$4(object$4({icon:optional$4(nonEmptyStringDecoder$4)}))),customConfig:anyJson$3(),intents:optional$4(array$4(intentDefinitionDecoder$1))}),v2LocalizedDefinitionDecoder=object$4({appId:optional$4(nonEmptyStringDecoder$4),name:optional$4(nonEmptyStringDecoder$4),details:optional$4(v2DetailsDecoder),version:optional$4(nonEmptyStringDecoder$4),title:optional$4(nonEmptyStringDecoder$4),tooltip:optional$4(nonEmptyStringDecoder$4),lang:optional$4(nonEmptyStringDecoder$4),description:optional$4(nonEmptyStringDecoder$4),categories:optional$4(array$4(nonEmptyStringDecoder$4)),icons:optional$4(array$4(v2IconDecoder)),screenshots:optional$4(array$4(v2ScreenshotDecoder)),contactEmail:optional$4(nonEmptyStringDecoder$4),supportEmail:optional$4(nonEmptyStringDecoder$4),moreInfo:optional$4(nonEmptyStringDecoder$4),publisher:optional$4(nonEmptyStringDecoder$4),customConfig:optional$4(array$4(anyJson$3())),hostManifests:optional$4(anyJson$3()),interop:optional$4(v2InteropDecoder)}),v2DefinitionDecoder=object$4({appId:nonEmptyStringDecoder$4,name:optional$4(nonEmptyStringDecoder$4),type:v2TypeDecoder,details:v2DetailsDecoder,version:optional$4(nonEmptyStringDecoder$4),title:optional$4(nonEmptyStringDecoder$4),tooltip:optional$4(nonEmptyStringDecoder$4),lang:optional$4(nonEmptyStringDecoder$4),description:optional$4(nonEmptyStringDecoder$4),categories:optional$4(array$4(nonEmptyStringDecoder$4)),icons:optional$4(array$4(v2IconDecoder)),screenshots:optional$4(array$4(v2ScreenshotDecoder)),contactEmail:optional$4(nonEmptyStringDecoder$4),supportEmail:optional$4(nonEmptyStringDecoder$4),moreInfo:optional$4(nonEmptyStringDecoder$4),publisher:optional$4(nonEmptyStringDecoder$4),customConfig:optional$4(array$4(anyJson$3())),hostManifests:optional$4(anyJson$3()),interop:optional$4(v2InteropDecoder),localizedVersions:optional$4(dict(v2LocalizedDefinitionDecoder))}),allDefinitionsDecoder=oneOf$2(v1DefinitionDecoder,v2DefinitionDecoder),parseDecoderErrorToStringMessage=e=>`${e.kind} at ${e.at}: ${JSON.stringify(e.input)}. Reason - ${e.message}`;class FDC3Service{fdc3ToDesktopDefinitionType={web:"window",native:"exe",citrix:"citrix",onlineNative:"clickonce",other:"window"};toApi(){return{isFdc3Definition:this.isFdc3Definition.bind(this),parseToBrowserBaseAppData:this.parseToBrowserBaseAppData.bind(this),parseToDesktopAppConfig:this.parseToDesktopAppConfig.bind(this)}}isFdc3Definition(e){const t=allDefinitionsDecoder.run(e);return t.ok?e.appId&&e.details?{isFdc3:!0,version:"2.0"}:e.manifest?{isFdc3:!0,version:"1.2"}:{isFdc3:!1,reason:"The passed definition is not FDC3"}:{isFdc3:!1,reason:parseDecoderErrorToStringMessage(t.error)}}parseToBrowserBaseAppData(e){const{isFdc3:t,version:r}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const n=allDefinitionsDecoder.run(e);if(!n.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage(n.error)}`);const i=this.getUserPropertiesFromDefinition(e,r),o={url:this.getUrl(e,r)},s={name:e.appId,type:"window",createOptions:o,userProperties:{...i,intents:"1.2"===r?i.intents:this.getIntentsFromV2AppDefinition(e),details:o},title:e.title,version:e.version,icon:this.getIconFromDefinition(e,r),caption:e.description,fdc3:"2.0"===r?{...e,definitionVersion:"2.0"}:void 0},a=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!a)return s;const c=glue42HostManifestsBrowserDecoder.run(a);if(!c.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage(c.error)}`);return Object.keys(c.result).length?this.mergeBaseAppDataWithGlueManifest(s,c.result):s}parseToDesktopAppConfig(e){const{isFdc3:t,version:r}=this.isFdc3Definition(e);if(!t)throw new Error("The passed definition is not FDC3");const n=allDefinitionsDecoder.run(e);if(!n.ok)throw new Error(`Invalid FDC3 ${r} definition. Error: ${parseDecoderErrorToStringMessage(n.error)}`);if("1.2"===r){const t=e;return{name:t.appId,type:"window",details:{url:this.getUrl(e,r)},version:t.version,title:t.title,tooltip:t.tooltip,caption:t.description,icon:t.icons?.[0].icon,intents:t.intents,customProperties:{manifestType:t.manifestType,images:t.images,contactEmail:t.contactEmail,supportEmail:t.supportEmail,publisher:t.publisher,icons:t.icons,customConfig:t.customConfig}}}const i=e,o={name:i.appId,type:this.fdc3ToDesktopDefinitionType[i.type],details:i.details,version:i.version,title:i.title,tooltip:i.tooltip,caption:i.description,icon:this.getIconFromDefinition(i,"2.0"),intents:this.getIntentsFromV2AppDefinition(i),fdc3:{...i,definitionVersion:"2.0"}},s=e.hostManifests?.ioConnect||e.hostManifests?.Glue42;if(!s)return o;if("object"!=typeof s||Array.isArray(s))throw new Error(`Invalid '${e.hostManifests.ioConnect?"hostManifests.ioConnect":"hostManifests['Glue42']"}' key`);return this.mergeDesktopConfigWithGlueManifest(o,s)}getUserPropertiesFromDefinition(e,t){return"1.2"===t?Object.fromEntries(Object.entries(e).filter(([e])=>!connectBrowserAppProps.includes(e))):Object.fromEntries(Object.entries(e).filter(([e])=>!connectBrowserAppProps.includes(e)&&!fdc3v2AppProps.includes(e)))}getUrl(e,t){let r;if("1.2"===t){const t=JSON.parse(e.manifest);r=t.details?.url||t.url}else r=e.details?.url;if(!r||"string"!=typeof r)throw new Error(`Invalid FDC3 ${t} definition. Provide valid 'url' under '${"1.2"===t?"manifest":"details"}' key`);return r}getIntentsFromV2AppDefinition(e){const t=e.interop?.intents?.listensFor;if(!t)return;return Object.entries(t).map(e=>{const[t,r]=e;return{name:t,...r}})}getIconFromDefinition(e,t){return"1.2"===t?e.icons?.find(e=>e.icon)?.icon||void 0:e.icons?.find(e=>e.src)?.src||void 0}mergeBaseAppDataWithGlueManifest(e,t){let r=e;if(t.customProperties&&(r.userProperties={...e.userProperties,...t.customProperties}),t.details){const n={...e.createOptions,...t.details};r.createOptions=n,r.userProperties.details=n}return Array.isArray(t.intents)&&(r.userProperties.intents=(r.userProperties.intents||[]).concat(t.intents)),r={...r,...t},delete r.details,delete r.intents,r}mergeDesktopConfigWithGlueManifest(e,t){const r=Object.assign({},e,t,{details:{...e.details,...t.details}});return Array.isArray(t.intents)&&(r.intents=(e.intents||[]).concat(t.intents)),r}}const decoders$1={common:{nonEmptyStringDecoder:nonEmptyStringDecoder$4,nonNegativeNumberDecoder:nonNegativeNumberDecoder$3,regexDecoder:regexDecoder$1},fdc3:{allDefinitionsDecoder:allDefinitionsDecoder,v1DefinitionDecoder:v1DefinitionDecoder,v2DefinitionDecoder:v2DefinitionDecoder}};var INTENTS_ERRORS;!function(e){e.USER_CANCELLED="User Closed Intents Resolver UI without choosing a handler",e.CALLER_NOT_DEFINED="Caller Id is not defined",e.TIMEOUT_HIT="Timeout hit",e.INTENT_NOT_FOUND="Cannot find Intent",e.HANDLER_NOT_FOUND="Cannot find Intent Handler",e.TARGET_INSTANCE_UNAVAILABLE="Cannot start Target Instance",e.INTENT_DELIVERY_FAILED="Target Instance did not add a listener",e.RESOLVER_UNAVAILABLE="Intents Resolver UI unavailable",e.RESOLVER_TIMEOUT="User did not choose a handler",e.INVALID_RESOLVER_RESPONSE="Intents Resolver UI returned invalid response",e.INTENT_HANDLER_REJECTION="Intent Handler function processing the raised intent threw an error or rejected the promise it returned"}(INTENTS_ERRORS||(INTENTS_ERRORS={}));let IoC$2=class{_fdc3;_decoders=decoders$1;_errors={intents:INTENTS_ERRORS};get fdc3(){return this._fdc3||(this._fdc3=(new FDC3Service).toApi()),this._fdc3}get decoders(){return this._decoders}get errors(){return this._errors}};const ioc=new IoC$2,fdc3=ioc.fdc3,decoders=ioc.decoders,errors=ioc.errors;var ok$2=function(e){return{ok:!0,result:e}},err$2=function(e){return{ok:!1,error:e}},asPromise$2=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault$2=function(e,t){return!0===t.ok?t.result:e},withException$2=function(e){if(!0===e.ok)return e.result;throw e.error},map$3=function(e,t){return!0===t.ok?ok$2(e(t.result)):t},map2$2=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok$2(e(t.result,r.result))},mapError$2=function(e,t){return!0===t.ok?t:err$2(e(t.error))},andThen$2=function(e,t){return!0===t.ok?e(t.result):t},__assign$2=function(){return __assign$2=Object.assign||function(e){for(var t,r=1,n=arguments.length;r"string"==typeof e.color&&e.color.length>0,"Expected color to be a non-empty string"),layoutTypeDecoder=oneOf$1(constant$2("Global"),constant$2("Activity"),constant$2("ApplicationDefault"),constant$2("Swimlane"),constant$2("Workspace")),componentTypeDecoder=oneOf$1(constant$2("application"),constant$2("activity")),functionCheck$1=(e,t)=>{const r=typeof e;return"function"===r?anyJson$2():fail$2(`The provided argument as ${t} should be of type function, provided: ${typeof r}`)},operationCheckConfigDecoder=object$3({operation:nonEmptyStringDecoder$2}),operationCheckResultDecoder=object$3({isSupported:boolean$4()}),layoutSummaryDecoder$1=object$3({name:nonEmptyStringDecoder$2,type:layoutTypeDecoder,context:optional$3(anyJson$2()),metadata:optional$3(anyJson$2())}),windowComponentStateDecoder=object$3({context:optional$3(anyJson$2()),bounds:windowBoundsDecoder,createArgs:object$3({name:optional$3(nonEmptyStringDecoder$2),url:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),windowState:optional$3(nonEmptyStringDecoder$2),restoreState:optional$3(nonEmptyStringDecoder$2),instanceId:nonEmptyStringDecoder$2,isCollapsed:optional$3(boolean$4()),isSticky:optional$3(boolean$4()),restoreSettings:object$3({groupId:optional$3(nonEmptyStringDecoder$2),groupZOrder:optional$3(number$5())}),channelId:optional$3(nonEmptyStringDecoder$2)}),windowLayoutComponentDecoder=object$3({type:constant$2("window"),componentType:optional$3(componentTypeDecoder),application:nonEmptyStringDecoder$2,state:windowComponentStateDecoder}),libDomainDecoder=oneOf$1(constant$2("system"),constant$2("windows"),constant$2("appManager"),constant$2("layouts"),constant$2("workspaces"),constant$2("intents"),constant$2("notifications"),constant$2("extension"),constant$2("channels"),constant$2("search"),constant$2("themes"),constant$2("manager"),constant$2("prefs"),constant$2("ui")),systemOperationTypesDecoder=oneOf$1(constant$2("getEnvironment"),constant$2("getBase"),constant$2("operationCheck"),constant$2("workspacesInitCheck"),constant$2("clientError"),constant$2("systemHello"),constant$2("getProfileData")),windowLayoutItemDecoder=object$3({type:constant$2("window"),config:object$3({appName:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),url:optional$3(nonEmptyStringDecoder$2),title:optional$3(string$5()),showCloseButton:optional$3(boolean$4()),allowExtract:optional$3(boolean$4()),allowReorder:optional$3(boolean$4()),isMaximized:optional$3(boolean$4())})}),groupLayoutItemDecoder$1=object$3({type:constant$2("group"),config:anyJson$2(),children:array$3(oneOf$1(windowLayoutItemDecoder))}),columnLayoutItemDecoder$1=object$3({type:constant$2("column"),config:anyJson$2(),children:array$3(oneOf$1(groupLayoutItemDecoder$1,windowLayoutItemDecoder,lazy$1(()=>columnLayoutItemDecoder$1),lazy$1(()=>rowLayoutItemDecoder$1)))}),rowLayoutItemDecoder$1=object$3({type:constant$2("row"),config:anyJson$2(),children:array$3(oneOf$1(columnLayoutItemDecoder$1,groupLayoutItemDecoder$1,windowLayoutItemDecoder,lazy$1(()=>rowLayoutItemDecoder$1)))}),workspaceLayoutComponentStateDecoder=object$3({config:anyJson$2(),context:anyJson$2(),children:array$3(oneOf$1(rowLayoutItemDecoder$1,columnLayoutItemDecoder$1,groupLayoutItemDecoder$1,windowLayoutItemDecoder))}),workspaceLayoutComponentDecoder=object$3({type:constant$2("Workspace"),application:optional$3(string$5()),state:workspaceLayoutComponentStateDecoder}),workspaceFrameComponentStateDecoder=object$3({bounds:windowBoundsDecoder,instanceId:nonEmptyStringDecoder$2,selectedWorkspace:nonNegativeNumberDecoder$2,workspaces:array$3(workspaceLayoutComponentStateDecoder),windowState:optional$3(nonEmptyStringDecoder$2),restoreState:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),workspaceFrameComponentDecoder=object$3({type:constant$2("workspaceFrame"),application:nonEmptyStringDecoder$2,componentType:optional$3(componentTypeDecoder),state:workspaceFrameComponentStateDecoder}),glueLayoutDecoder=object$3({name:nonEmptyStringDecoder$2,type:layoutTypeDecoder,token:optional$3(nonEmptyStringDecoder$2),components:array$3(oneOf$1(windowLayoutComponentDecoder,workspaceLayoutComponentDecoder,workspaceFrameComponentDecoder)),context:optional$3(anyJson$2()),metadata:optional$3(anyJson$2()),version:optional$3(number$5())}),iframePermissionsPolicyConfigDecoder=object$3({flags:string$5()}),workspacesSandboxDecoder=object$3({flags:string$5()}),channelSelectorDecoder=object$3({enabled:boolean$4()}),applicationDetailsDecoder=object$3({url:nonEmptyStringDecoder$2,top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),workspacesSandbox:optional$3(workspacesSandboxDecoder),channelSelector:optional$3(channelSelectorDecoder),iframePermissionsPolicy:optional$3(iframePermissionsPolicyConfigDecoder)}),intentDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,displayName:optional$3(string$5()),contexts:optional$3(array$3(string$5())),customConfig:optional$3(object$3()),resultType:optional$3(nonEmptyStringDecoder$2)}),glueCoreAppDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,type:nonEmptyStringDecoder$2.where(e=>"window"===e,"Expected a value of window"),title:optional$3(nonEmptyStringDecoder$2),version:optional$3(nonEmptyStringDecoder$2),customProperties:optional$3(anyJson$2()),icon:optional$3(string$5()),caption:optional$3(string$5()),details:applicationDetailsDecoder,intents:optional$3(array$3(intentDefinitionDecoder)),hidden:optional$3(boolean$4()),fdc3:optional$3(decoders.fdc3.v2DefinitionDecoder)}),remoteStoreCacheConfigDecoder=object$3({enabled:optional$3(boolean$4())}),remoteStoreDecoder=object$3({url:nonEmptyStringDecoder$2,pollingInterval:optional$3(nonNegativeNumberDecoder$2),requestTimeout:optional$3(nonNegativeNumberDecoder$2),customHeaders:optional$3(anyJson$2()),getRequestInit:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"remote store getRequestInit"))),waitInitialResponse:optional$3(boolean$4()),cache:optional$3(remoteStoreCacheConfigDecoder)}),channelDefinitionDecoder$1=object$3({name:nonEmptyStringDecoder$2,meta:channelMetaDecoder$1,data:optional$3(anyJson$2())}),pluginDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,start:anyJson$2(),stop:optional$3(anyJson$2()),version:optional$3(nonEmptyStringDecoder$2),config:optional$3(anyJson$2()),critical:optional$3(boolean$4())}),allApplicationDefinitionsDecoder=anyJson$2().andThen(e=>{const t=fdc3.isFdc3Definition(e),{isFdc3:r}=t;return r?"2.0"===t.version?decoders.fdc3.v2DefinitionDecoder:decoders.fdc3.v1DefinitionDecoder:glueCoreAppDefinitionDecoder});array$3(allApplicationDefinitionsDecoder);const applicationsConfigDecoder=object$3({local:optional$3(array$3(allApplicationDefinitionsDecoder)),remote:optional$3(remoteStoreDecoder)}),layoutsConfigDecoder=object$3({mode:optional$3(oneOf$1(constant$2("idb"),constant$2("session"),constant$2("rest"),constant$2("manager"))),local:optional$3(array$3(glueLayoutDecoder)),rest:optional$3(remoteStoreDecoder)}),channelsModeDecoder=oneOf$1(constant$2("single"),constant$2("multi")),channelsConfigDecoder=object$3({definitions:array$3(channelDefinitionDecoder$1),mode:optional$3(channelsModeDecoder)}),pluginsConfigDecoder=object$3({definitions:array$3(pluginDefinitionDecoder)}),gatewayVisibilityRestrictionsDecoder=oneOf$1(constant$2("local"),constant$2("cluster")),gatewayConfigDecoder=object$3({logging:optional$3(object$3({level:optional$3(logLevelDecoder),appender:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"gateway log appender")))})),clients:optional$3(object$3({buffer_size:optional$3(number$5())})),bridge:optional$3(object$3({url:nonEmptyStringDecoder$2,headers:optional$3(anyJson$2()),getHeaders:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"getHeaders function"))),getWebSocketSearchParams:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"getWebSocketSearchParams function"))),channels:optional$3(object$3({enabled:optional$3(boolean$4())})),contexts:optional$3(object$3({enabled:optional$3(boolean$4()),visibility:optional$3(array$3(object$3({context:oneOf$1(nonEmptyStringDecoder$2,regexDecoder),restrictions:gatewayVisibilityRestrictionsDecoder})))})),intents:optional$3(object$3({enabled:optional$3(boolean$4())})),interop:optional$3(object$3({enabled:optional$3(boolean$4()),visibility:optional$3(array$3(object$3({method:oneOf$1(nonEmptyStringDecoder$2,regexDecoder),restrictions:gatewayVisibilityRestrictionsDecoder})))})),search:optional$3(object$3({enabled:optional$3(boolean$4())}))}))}),glueConfigDecoder=anyJson$2(),maximumActiveWorkspacesDecoder=object$3({threshold:number$5().where(e=>e>1,"Expected a number larger than 1")}),idleWorkspacesDecoder=object$3({idleMSThreshold:number$5().where(e=>e>100,"Expected a number larger than 100")}),hibernationConfigDecoder=object$3({maximumActiveWorkspaces:optional$3(maximumActiveWorkspacesDecoder),idleWorkspaces:optional$3(idleWorkspacesDecoder)}),loadingConfigDecoder=object$3({delayed:optional$3(object$3({batch:optional$3(number$5()),initialOffsetInterval:optional$3(number$5()),interval:optional$3(number$5())})),defaultStrategy:optional$3(oneOf$1(constant$2("direct"),constant$2("delayed"),constant$2("lazy"))),showDelayedIndicator:optional$3(boolean$4())}),iframeSandBoxConfigDecoder=object$3({flags:string$5()}),workspacesConfigDecoder=object$3({src:nonEmptyStringDecoder$2,hibernation:optional$3(hibernationConfigDecoder),loadingStrategy:optional$3(loadingConfigDecoder),isFrame:optional$3(boolean$4()),initAsEmpty:optional$3(boolean$4()),frameCache:optional$3(boolean$4()),iframeSandbox:optional$3(iframeSandBoxConfigDecoder),iframePermissionsPolicy:optional$3(iframePermissionsPolicyConfigDecoder)}),preferredConnectionSettingsDecoder=object$3({url:nonEmptyStringDecoder$2,auth:optional$3(object$3({username:optional$3(nonEmptyStringDecoder$2),password:optional$3(nonEmptyStringDecoder$2),sessionId:optional$3(nonEmptyStringDecoder$2),provider:optional$3(nonEmptyStringDecoder$2),providerContext:optional$3(anyJson$2()),token:optional$3(nonEmptyStringDecoder$2),gatewayToken:optional$3(nonEmptyStringDecoder$2),flowName:optional$3(constant$2("sspi")),flowCallback:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"flowCallback function")))})),forceIncompleteSwitch:optional$3(boolean$4()),discoveryIntervalMS:optional$3(nonNegativeNumberDecoder$2)}),connectionConfigDecoder=object$3({preferred:optional$3(preferredConnectionSettingsDecoder),enableManualSwitching:optional$3(boolean$4()),alwaysPlatform:optional$3(boolean$4()),allowedClientFallbackOrigin:optional$3(nonEmptyStringDecoder$2),blockList:optional$3(array$3(nonEmptyStringDecoder$2))}),windowsConfigDecoder=object$3({windowResponseTimeoutMs:optional$3(nonNegativeNumberDecoder$2),defaultWindowOpenBounds:optional$3(windowBoundsDecoder)}),serviceWorkerConfigDecoder=object$3({url:optional$3(nonEmptyStringDecoder$2),registrationPromise:optional$3(anyJson$2())}),notificationFilterDecoder=object$3({allowed:optional$3(array$3(nonEmptyStringDecoder$2)),blocked:optional$3(array$3(nonEmptyStringDecoder$2))}),notificationsConfigDecoder=object$3({enabled:optional$3(boolean$4()),enableToasts:optional$3(boolean$4()),sourceFilter:optional$3(notificationFilterDecoder),clearNotificationOnClick:optional$3(boolean$4())}),themesConfigDecoder=object$3({defaultTheme:optional$3(oneOf$1(constant$2("os"),constant$2("light"),constant$2("dark")))}),userConfigDecoder=object$3({id:nonEmptyStringDecoder$2,username:optional$3(nonEmptyStringDecoder$2),firstName:optional$3(nonEmptyStringDecoder$2),lastName:optional$3(nonEmptyStringDecoder$2),email:optional$3(nonEmptyStringDecoder$2),type:optional$3(nonEmptyStringDecoder$2),role:optional$3(nonEmptyStringDecoder$2),meta:optional$3(anyJson$2())}),managerAuthConfig=object$3({basic:optional$3(object$3({username:nonEmptyStringDecoder$2,password:nonEmptyStringDecoder$2})),username:optional$3(nonEmptyStringDecoder$2),token:optional$3(object$3({bearer:optional$3(nonEmptyStringDecoder$2)})),includeCredentials:optional$3(boolean$4())}),managerConfigDecoder=object$3({url:nonEmptyStringDecoder$2,auth:managerAuthConfig,critical:optional$3(boolean$4()),headers:optional$3(anyJson$2()),fetchIntervalMS:optional$3(nonNegativeNumberDecoder$2),tokenRefreshIntervalMS:optional$3(nonNegativeNumberDecoder$2),responseTimeoutMS:optional$3(nonNegativeNumberDecoder$2),requests:optional$3(object$3({timeout:optional$3(nonNegativeNumberDecoder$2),openSessionTimeout:optional$3(nonNegativeNumberDecoder$2),closeSessionTimeout:optional$3(nonNegativeNumberDecoder$2)})),cache:optional$3(object$3({enabled:optional$3(boolean$4()),clearOld:optional$3(boolean$4())})),getHeaders:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"dynamic headers function"))),features:optional$3(object$3({applicationsStore:optional$3(boolean$4()),layoutsStore:optional$3(boolean$4()),preferencesStore:optional$3(boolean$4())}))}),applicationPreferencesStoreDecoder=object$3({type:optional$3(oneOf$1(constant$2("local"),constant$2("manager"),constant$2("rest"))),rest:optional$3(remoteStoreDecoder)}),applicationPreferencesConfigDecoder=object$3({store:optional$3(applicationPreferencesStoreDecoder),validNonExistentApps:optional$3(array$3(nonEmptyStringDecoder$2))}),otelMetricTypeDecoder=oneOf$1(constant$2("app_started"),constant$2("app_stopped"),constant$2("app_startup"),constant$2("app_count"),constant$2("app_duration"),constant$2("app_error"),constant$2("layout_startup"),constant$2("workspace_startup"),constant$2("workspace_stopped"),constant$2("workspace_count"),constant$2("platform_startup"),constant$2("platform_error")),otelMetricDefinitionDecoder=object$3({enabled:optional$3(boolean$4()),name:optional$3(nonEmptyStringDecoder$2),description:optional$3(nonEmptyStringDecoder$2),buckets:optional$3(array$3(number$5())),type:otelMetricTypeDecoder}),otelMetricsDefinitionDecoder=object$3({url:nonEmptyStringDecoder$2,publishInterval:optional$3(nonNegativeNumberDecoder$2),metrics:optional$3(array$3(otelMetricDefinitionDecoder)),additionalResourceAttributes:optional$3(object$3()),getAdditionalAttributes:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"getAdditionalAttributes function"))),headers:optional$3(anyJson$2())}),otelConfigDecoder=object$3({additionalResourceAttributes:optional$3(object$3()),getAdditionalAttributes:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"getAdditionalAttributes function"))),headers:optional$3(anyJson$2()),metrics:optional$3(otelMetricsDefinitionDecoder)}),platformConfigDecoder=object$3({licenseKey:nonEmptyStringDecoder$2,windows:optional$3(windowsConfigDecoder),applications:optional$3(applicationsConfigDecoder),notifications:optional$3(notificationsConfigDecoder),layouts:optional$3(layoutsConfigDecoder),channels:optional$3(channelsConfigDecoder),plugins:optional$3(pluginsConfigDecoder),serviceWorker:optional$3(serviceWorkerConfigDecoder),gateway:optional$3(gatewayConfigDecoder),connection:optional$3(connectionConfigDecoder),browser:optional$3(glueConfigDecoder),workspaces:optional$3(workspacesConfigDecoder),environment:optional$3(anyJson$2()),themes:optional$3(themesConfigDecoder),manager:optional$3(managerConfigDecoder),user:optional$3(userConfigDecoder),browserFactory:optional$3(anyJson$2().andThen(e=>functionCheck$1(e,"glueFactory"))),applicationPreferences:optional$3(applicationPreferencesConfigDecoder),otel:optional$3(otelConfigDecoder),widget:optional$3(widgetConfigDecoder),modals:optional$3(modalsConfigDecoder),intentResolver:optional$3(intentResolverConfigDecoder)}),windowOpenSettingsDecoder=object$3({top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),context:optional$3(anyJson$2()),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(windowRelativeDirectionDecoder),windowId:optional$3(nonEmptyStringDecoder$2),layoutComponentId:optional$3(nonEmptyStringDecoder$2)}),interceptorRegistrationRequestDecoder=object$3({callInterceptor:anyJson$2().andThen(e=>functionCheck$1(e,"callInterceptor")),interceptions:array$3(object$3({domain:libDomainDecoder,operation:nonEmptyStringDecoder$2}))}),focusEventDataDecoder=object$3({windowId:nonEmptyStringDecoder$2,hasFocus:boolean$4()}),bringBackToWorkspaceDataDecoder=object$3({windowId:nonEmptyStringDecoder$2}),workspacesInitCheckResultDecoder=object$3({initialized:boolean$4()}),clientErrorDataDecoder=object$3({message:nonEmptyStringDecoder$2}),systemHelloSuccessDecoder=object$3({isClientErrorOperationSupported:boolean$4()});var isMergeableObject=function(e){return isNonNullObject(e)&&!isSpecial(e)};function isNonNullObject(e){return!!e&&"object"==typeof e}function isSpecial(e){var t=Object.prototype.toString.call(e);return"[object RegExp]"===t||"[object Date]"===t||isReactElement(e)}var canUseSymbol="function"==typeof Symbol&&Symbol.for,REACT_ELEMENT_TYPE=canUseSymbol?Symbol.for("react.element"):60103;function isReactElement(e){return e.$$typeof===REACT_ELEMENT_TYPE}function emptyTarget(e){return Array.isArray(e)?[]:{}}function cloneUnlessOtherwiseSpecified(e,t){return!1!==t.clone&&t.isMergeableObject(e)?deepmerge(emptyTarget(e),e,t):e}function defaultArrayMerge(e,t,r){return e.concat(t).map(function(e){return cloneUnlessOtherwiseSpecified(e,r)})}function getMergeFunction(e,t){if(!t.customMerge)return deepmerge;var r=t.customMerge(e);return"function"==typeof r?r:deepmerge}function getEnumerableOwnPropertySymbols(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}function getKeys(e){return Object.keys(e).concat(getEnumerableOwnPropertySymbols(e))}function propertyIsOnObject(e,t){try{return t in e}catch(e){return!1}}function propertyIsUnsafe(e,t){return propertyIsOnObject(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}function mergeObject(e,t,r){var n={};return r.isMergeableObject(e)&&getKeys(e).forEach(function(t){n[t]=cloneUnlessOtherwiseSpecified(e[t],r)}),getKeys(t).forEach(function(i){propertyIsUnsafe(e,i)||(propertyIsOnObject(e,i)&&r.isMergeableObject(t[i])?n[i]=getMergeFunction(i,r)(e[i],t[i],r):n[i]=cloneUnlessOtherwiseSpecified(t[i],r))}),n}function deepmerge(e,t,r){(r=r||{}).arrayMerge=r.arrayMerge||defaultArrayMerge,r.isMergeableObject=r.isMergeableObject||isMergeableObject,r.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified;var n=Array.isArray(t);return n===Array.isArray(e)?n?r.arrayMerge(e,t,r):mergeObject(e,t,r):cloneUnlessOtherwiseSpecified(t,r)}deepmerge.all=function(e,t){if(!Array.isArray(e))throw new Error("first argument should be an array");return e.reduce(function(e,r){return deepmerge(e,r,t)},{})};var deepmerge_1=deepmerge,cjs=deepmerge_1,deepMerge=getDefaultExportFromCjs$2(cjs);let urlAlphabet$2="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$4=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$2[64*Math.random()|0];return t};function getDefaultExportFromCjs$1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createRegistry$1(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;ie.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder$1=number$4().where(e=>e>=0,"Expected a non-negative number"),searchTypeDecoder=object$2({name:nonEmptyStringDecoder$1,displayName:optional$2(nonEmptyStringDecoder$1)}),providerData=object$2({id:nonEmptyStringDecoder$1,interopId:nonEmptyStringDecoder$1,name:nonEmptyStringDecoder$1,appName:optional$2(nonEmptyStringDecoder$1),types:optional$2(array$2(searchTypeDecoder))}),providerLimitsDecoder=object$2({maxResults:optional$2(nonNegativeNumberDecoder$1),maxResultsPerType:optional$2(nonNegativeNumberDecoder$1)}),queryConfigDecoder=object$2({search:nonEmptyStringDecoder$1,providers:optional$2(array$2(providerData)),types:optional$2(array$2(searchTypeDecoder)),providerLimits:optional$2(providerLimitsDecoder)}),providerRegistrationConfig=object$2({name:nonEmptyStringDecoder$1,types:optional$2(array$2(searchTypeDecoder))}),operationDecoder=oneOf(constant$1("cancel"),constant$1("info"),constant$1("search")),queryStatusDecoder=oneOf(constant$1("done"),constant$1("in-progress"),constant$1("error")),searchCancelRequestDecoder=object$2({id:nonEmptyStringDecoder$1}),mainActionDecoder=object$2({method:nonEmptyStringDecoder$1,target:optional$2(oneOf(object$2({instance:nonEmptyStringDecoder$1}),constant$1("all"))),params:optional$2(anyJson$1())}),secondaryActionDecoder=object$2({name:nonEmptyStringDecoder$1,method:nonEmptyStringDecoder$1,target:optional$2(oneOf(object$2({instance:nonEmptyStringDecoder$1}),constant$1("all"))),params:optional$2(anyJson$1())}),queryResultDecoder=object$2({type:searchTypeDecoder,id:optional$2(nonEmptyStringDecoder$1),displayName:optional$2(nonEmptyStringDecoder$1),description:optional$2(nonEmptyStringDecoder$1),iconURL:optional$2(nonEmptyStringDecoder$1),metadata:optional$2(anyJson$1()),action:optional$2(mainActionDecoder),secondaryActions:optional$2(array$2(secondaryActionDecoder))}),legacySearchResultItemDecoder=object$2({type:string$4(),category:optional$2(string$4()),id:optional$2(string$4()),displayName:optional$2(string$4()),description:optional$2(string$4()),iconURL:optional$2(string$4()),action:optional$2(mainActionDecoder)}),protocolSearchResultsBatchDecoder=object$2({items:array$2(oneOf(queryResultDecoder,legacySearchResultItemDecoder)),provider:optional$2(providerData),queryId:nonEmptyStringDecoder$1,status:constant$1("in-progress")}),protocolSearchCompletedDecoder=object$2({items:array$2(oneOf(queryResultDecoder,legacySearchResultItemDecoder)),queryId:nonEmptyStringDecoder$1,status:constant$1("done")}),protocolProviderErrorDecoder=object$2({items:array$2(oneOf(queryResultDecoder,legacySearchResultItemDecoder)),provider:optional$2(providerData),queryId:nonEmptyStringDecoder$1,errorMessage:nonEmptyStringDecoder$1,status:constant$1("error")});class ClientController{logger;glueController;modelFactory;registry=CallbackRegistryFactory$1();activeQueryLookup={};queryIdToMasterIdLookup={};pendingDebounce=[];debounceTimer;debounceMS=0;constructor(e,t,r){this.logger=e,this.glueController=t,this.modelFactory=r}setDebounceMS(e){this.logger.info(`[${e.commandId}] Setting the debounceMS to: ${e.milliseconds}`),this.debounceMS=e.milliseconds,this.logger.info(`[${e.commandId}] debounceMS set to: ${e.milliseconds}`)}getDebounceMS(e){return this.logger.info(`[${e.commandId}] Getting the debounceMS`),this.debounceMS}async query(e,t){if(this.debounceMS&&!t)return this.debounceQuery(e);await this.glueController.registerMainClientMethod(this.handleProviderCall.bind(this));const{queryConfig:r,commandId:n}=e;this.logger.info(`[${n}] Initiating a query request`);let i=await this.glueController.getAllProvidersInfo();this.logger.trace(`[${n}] Got all available providers: ${JSON.stringify(i)}`),r.providers&&(this.logger.info(`[${n}] Filtering providers by explicitly allowed providers.`),i=this.filterProvidersByAllowList(i,r.providers)),r.types&&(this.logger.info(`[${n}] Filtering providers by explicitly allowed types.`),i=this.filterProvidersByAllowedTypes(i,r.types)),i.length||this.logger.warn(`[${n}] There are no providers that can handle the query for ${e.queryConfig.search}`),this.logger.info(`[${n}] Sending query request to providers: ${JSON.stringify(i)}`);const o=await this.glueController.sendQueryRequest(r,i);this.logger.info(`[${n}] Received responses from the providers: ${JSON.stringify(o)}`);const s=this.generateMasterQueryId(),a=this.modelFactory.buildClientQueryModel(s,this);return this.logger.info(`[${n}] The query is in progress with master id: ${s}`),this.activeQueryLookup[s]={servers:o,model:a},o.forEach(e=>{this.queryIdToMasterIdLookup[e.queryId]=s}),o.length||setTimeout(()=>{this.registry.execute(`on-query-completed-${s}`),this.cleanUpQuery(s)},0),a.exposeFacade()}async cancelQuery(e,t){const r=this.activeQueryLookup[e];if(!r)throw new Error(`[${t}] Cannot cancel query: ${e}, because this query does not exist`);const n=r.servers;this.logger.info(`[${t}] Sending cancel query requests`),await Promise.all(n.map(e=>(this.logger.trace(`[${t}] Sending cancel query request to ${e.interopId} with queryId: ${e.queryId}`),this.glueController.sendQueryCancelRequest({id:e.queryId},{instance:e.interopId})))),this.logger.info(`[${t}] The query was cancelled`)}processClientOnResults(e){return this.registry.add(`on-query-results-${e.masterQueryId}`,e.callback)}processClientOnCompleted(e){return this.registry.add(`on-query-completed-${e.masterQueryId}`,e.callback)}processClientOnError(e){return this.registry.add(`on-query-error-${e.masterQueryId}`,e.callback)}async handleProviderCall(e){const{status:t}=e,r=queryStatusDecoder.runWithException(t),n=nanoid$4(10);switch(r){case SEARCH_QUERY_STATUSES.done:return this.handleQueryCompleted({completedConfig:e,commandId:n});case SEARCH_QUERY_STATUSES.inProgress:return this.handleQueryResults({resultsBatch:e,commandId:n});case SEARCH_QUERY_STATUSES.error:return this.handleQueryError({error:e,commandId:n});default:throw new Error(`Unrecognized status: ${t}`)}}handleQueryResults(e){const{resultsBatch:t,commandId:r}=e;this.logger.trace(`[${r}] Processing a results batch from provider: ${t.provider?.name} with id: ${t.provider?.id}`);const n=protocolSearchResultsBatchDecoder.runWithException(t),i=this.queryIdToMasterIdLookup[n.queryId];if(!i)return void this.logger.warn(`[${r}] Received results for an unknown query. Provider ${JSON.stringify(n.provider)}, items: ${JSON.stringify(n.items)}`);this.logger.trace(`[${r}] The results batch is validated, forwarding to the callbacks`);const o=this.checkTransformLegacyResults(n.items),s={provider:n.provider,results:o};this.registry.execute(`on-query-results-${i}`,s)}handleQueryCompleted(e){const{completedConfig:t,commandId:r}=e;this.logger.trace(`[${r}] Processing a query completed message from query id: ${t.queryId}`);const n=protocolSearchCompletedDecoder.runWithException(t),i=this.queryIdToMasterIdLookup[n.queryId];if(!i)return void this.logger.warn(`[${r}] Received completed message for an unknown query. Provider query id: ${JSON.stringify(n.queryId)}`);if(n.items.length){const e={results:this.checkTransformLegacyResults(n.items)};this.registry.execute(`on-query-results-${i}`,e)}delete this.queryIdToMasterIdLookup[n.queryId];const o=this.activeQueryLookup[i];o.servers=o.servers.filter(e=>e.queryId!==n.queryId),o.servers.length?this.logger.trace(`[${r}] Waiting for more providers to complete`):(this.logger.trace(`[${r}] All providers are done, marking this query as completed`),this.registry.execute(`on-query-completed-${i}`),this.cleanUpQuery(i))}handleQueryError(e){const{error:t,commandId:r}=e;this.logger.trace(`[${r}] Processing an error message from query: ${t.queryId}`);const n=protocolProviderErrorDecoder.runWithException(t),i=this.queryIdToMasterIdLookup[n.queryId];if(!i)return void this.logger.warn(`[${r}] Received error message for an unknown query. Provider query id: ${JSON.stringify(n.queryId)} and message: ${JSON.stringify(n.errorMessage)}`);const o={error:n.errorMessage,provider:n.provider};this.registry.execute(`on-query-error-${i}`,o)}filterProvidersByAllowList(e,t){const r=t.reduce((e,t)=>(e[t.id]=!0,e),{});return e.filter(e=>e.info.providers.some(e=>r[e.id]))}filterProvidersByAllowedTypes(e,t){const r=t.reduce((e,t)=>(e[t.name]=!0,e),{});return e.filter(e=>{const t=e.info.supportedTypes;return!!t.some(e=>"*"===e)||(!t||!t.length||t.some(e=>r[e]))})}generateMasterQueryId(){const e=nanoid$4(10);return this.activeQueryLookup[e]?this.generateMasterQueryId():e}cleanUpQuery(e){this.registry.clearKey(`on-query-results-${e}`),this.registry.clearKey(`on-query-completed-${e}`),this.registry.clearKey(`on-query-error-${e}`),delete this.activeQueryLookup[e]}debounceQuery(e){return new Promise((t,r)=>{clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{const t=[...this.pendingDebounce];this.pendingDebounce=[],this.query(e,!0).then(e=>t.forEach(({resolve:t})=>t(e))).catch(e=>t.forEach(({reject:t})=>t(e)))},this.debounceMS),this.pendingDebounce.push({resolve:t,reject:r})})}checkTransformLegacyResults(e){if(!e.length)return[];const t=e[0];return t&&"object"!=typeof t.type?e.map(e=>({type:{name:e.type,displayName:e.category},id:e.id,displayName:e.displayName,description:e.description,iconURL:e.iconURL,action:e.action})):e}}const MAIN_PROVIDER_METHOD_NAME="T42.Search.Provider",MAIN_CLIENT_METHOD_NAME="T42.Search.Client",SEQUELIZER_INTERVAL_MS=10,FLUSH_SEQUELIZER_INTERVAL_MS=10,FLUSH_TIMEOUT_MS=100,STALE_QUERY_TIMEOUT_MS=9e5;let GlueController$1=class{glue;constructor(e){this.glue=e}get myAppName(){return this.glue.interop.instance.applicationName}get myInteropId(){return this.glue.interop.instance.instance}async registerMainProviderMethod(e){this.checkMyMethodExists(MAIN_PROVIDER_METHOD_NAME).exists||await this.glue.interop.register(MAIN_PROVIDER_METHOD_NAME,e)}async registerMainClientMethod(e){this.checkMyMethodExists(MAIN_CLIENT_METHOD_NAME).exists||await this.glue.interop.register(MAIN_CLIENT_METHOD_NAME,e)}async clearMainProviderMethod(){await this.glue.interop.unregister(MAIN_PROVIDER_METHOD_NAME)}async sendClientResultsBatch(e,t,r){const n={items:e.results,provider:e.provider,queryId:r,status:SEARCH_QUERY_STATUSES.inProgress};await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME,n,{instance:t})}async sendClientQueueCompleted(e,t){const r={items:[],queryId:t,status:SEARCH_QUERY_STATUSES.done};await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME,r,{instance:e})}async sendClientErrorMessage(e,t,r,n){const i={items:[],provider:n,errorMessage:e,queryId:r,status:SEARCH_QUERY_STATUSES.error};await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME,i,{instance:t})}async sendQueryRequest(e,t){if(!t.length)return[];const r=t.map(e=>({instance:e.interopId})),n={operation:CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search,apiVersion:"1",...e};return((await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME,n,r)).all_return_values||[]).map(e=>({interopId:e.executed_by?.instance,queryId:e.returned.id}))}async sendQueryCancelRequest(e,t){const r={operation:CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel,id:e.id};await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME,r,t)}async getAllProvidersInfo(){if(this.glue.interop.methods().every(e=>e.name!==MAIN_PROVIDER_METHOD_NAME))return[];const e={operation:CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info},t=await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME,e,"all");return(t.all_return_values||[]).map(e=>{const r=void 0===e.returned.apiVersion?{supportedTypes:e.returned.supportedTypes,apiVersion:e.returned.apiVersion,providers:[{interopId:e.executed_by?.instance,id:e.executed_by?.instance,name:e.executed_by?.instance,appName:t.executed_by?.application,types:e.returned.supportedTypes.map(e=>({name:e}))}]}:e.returned;return{interopId:e.executed_by?.instance,info:r}})}checkMyMethodExists(e){return{exists:this.glue.interop.methodsForInstance({instance:this.glue.interop.instance.instance}).some(t=>t.name===e)}}};class MainController{logger;glueController;clientController;providerController;constructor(e,t,r,n){this.logger=e,this.glueController=t,this.clientController=r,this.providerController=n}setDebounceMS(e){this.logger.info(`[${e.commandId}] Starting setDebounceMS operation with duration ${e.milliseconds}`),this.clientController.setDebounceMS(e),this.logger.info(`[${e.commandId}] Operation setDebounceMS with duration ${e.milliseconds} completed`)}getDebounceMS(e){return this.logger.info(`[${e.commandId}] Starting getDebounceMS operation.`),this.clientController.getDebounceMS(e)}async query(e){if(this.logger.info(`[${e.commandId}] Starting query operation with config ${JSON.stringify(e.queryConfig)}`),Array.isArray(e.queryConfig.providers)&&!e.queryConfig.providers.length)throw new Error("Cannot sent a query with a defined empty array of providers, because this is an impossible query for complete.");if(Array.isArray(e.queryConfig.types)&&!e.queryConfig.types.length)throw new Error("Cannot sent a query with a defined empty array of types, because this is an impossible query for complete.");const t=await this.clientController.query(e);return this.logger.info(`[${e.commandId}] Operation query with config ${JSON.stringify(e.queryConfig)} completed.`),t}async registerProvider(e){this.logger.info(`[${e.commandId}] Starting registerProvider operation with config ${JSON.stringify(e.config)}`);const t=await this.providerController.processRegisterProvider(e);return this.logger.info(`[${e.commandId}] Operation registerProvider with config ${JSON.stringify(e.config)} completed.`),t}async providers(e){this.logger.info(`[${e.commandId}] Starting providers operation.`);const t=(await this.glueController.getAllProvidersInfo()).flatMap(e=>e.info.providers);return this.logger.info(`[${e.commandId}] Operation providers completed.`),t}async types(e){this.logger.info(`[${e.commandId}] Starting types operation.`);const t=(await this.glueController.getAllProvidersInfo()).flatMap(e=>e.info.providers).filter(e=>!!e.types).flatMap(e=>e.types),r=[...new Set(t)];return this.logger.info(`[${e.commandId}] Operation types completed.`),r}}const extractErrorMsg=e=>"string"==typeof e?e:e.message?JSON.stringify(e.message):JSON.stringify(e);class ProviderController{logger;glueController;sequelizer;limitsTracker;modelsFactory;registry=CallbackRegistryFactory$1();providersModels={};activeQueries={};constructor(e,t,r,n,i){this.logger=e,this.glueController=t,this.sequelizer=r,this.limitsTracker=n,this.modelsFactory=i}async processRegisterProvider(e){const{config:t,commandId:r}=e;this.logger.info(`[${r}] enqueueing the provider registration process with config: ${JSON.stringify(t)}`);const n=await this.sequelizer.enqueue(async()=>{if((await this.glueController.getAllProvidersInfo()).flatMap(e=>e.info.providers).some(e=>e&&e.name===t.name))throw new Error(`Cannot register a new provider with name: ${t.name}, because there already is a provider with this name`);await this.glueController.registerMainProviderMethod(this.handleSearchQueryRequest.bind(this));const e={id:nanoid$4(10),name:t.name,interopId:this.glueController.myInteropId,appName:this.glueController.myAppName,types:t.types},r=this.modelsFactory.buildProviderModel(e,this);return this.providersModels[e.id]=r,r.exposeFacade()});return this.logger.info(`[${r}] the provider with name: ${t.name} has been registered.`),n}processProviderOnQuery(e){return this.registry.add(`on-search-query-${e.id}`,e.callback)}processProviderOnQueryCancel(e){return this.registry.add(`on-cancel-query-${e.id}`,e.callback)}async processProviderUnregister(e){this.logger.info(`[${e.commandId}] enqueueing the provider un-registration with id: ${e.id}`),await this.sequelizer.enqueue(async()=>{this.cleanUpProvider(e.id,e.commandId),Object.keys(this.providersModels).length||await this.glueController.clearMainProviderMethod()}),this.logger.info(`[${e.commandId}] the provider un-registration with id: ${e.id} completed`)}async processProviderQueryDone(e){const{commandId:t,identification:r}=e;this.activeQueries[r.queryId]?.publisher.syncSuspendProvider(r.providerId,t),await this.sequelizer.enqueue(async()=>{this.logger.trace(`[${t}] Processing a query done command with identification: ${JSON.stringify(r)}`);const e=this.activeQueries[r.queryId];e?(await this.cleanUpProviderQuery(r.queryId,r.providerId,t),e.providersAtWork.length?this.logger.trace(`[${t}] Query done command completed, but there are more providers still at work.`):(this.cleanUpQuery(r.queryId,t),this.logger.trace(`[${t}] Query is completed, signalling.`))):this.logger.warn(`[${t}] Cannot mark provider: ${r.providerId} done with query ${r.queryId}, because there is no active query with this id`)})}processProviderQueryError(e){const{commandId:t,identification:r,error:n}=e;return this.logger.warn(`[${t}] Processing an error sent by provider: ${r.providerId} for query id: ${r.queryId} -> ${n}`),this.activeQueries[r.queryId]?.publisher.markProviderError(e),this.processProviderQueryDone(e)}processProviderQueryResult(e){const{commandId:t,identification:r}=e,n=this.activeQueries[r.queryId];if(!n){const t=`Will not send this result to the client, because there is no active query with id ${r.queryId}. Most likely this query was cancelled.`;throw this.logger.warn(`[${e}] ${t}`),new Error(t)}if(n.publisher.checkProviderSuspended(r.providerId)){const t=`Will not send this result to the client, because there is no info about this provider in the active query with id ${r.queryId}. Most likely this query was marked as done by this provider already.`;throw this.logger.warn(`[${e}] ${t}`),new Error(t)}const i=n.requestedTypes;if(i&&i.every(t=>t.name!==e.result.type.name)){const t=`Will not send this result to the client, because this result has a defined type: ${e.result.type.name} which is not in the explicitly requested list of types by the client.`;throw this.logger.warn(`[${e}] ${t}`),new Error(t)}const o=this.limitsTracker.testResultLimit(e);if(o?.maxLimitHit){const t=`Will not process this result from provider ${e.identification.providerId}, because this provider has reached the max results limit set by the client. This provider cannot send more result, marking it as done.`;throw this.logger.info(t),setTimeout(()=>this.processProviderQueryDone(e),0),new Error(t)}if(o?.maxLimitPerTypeHit){const t=`Will not process this result from provider ${e.identification.providerId}, because this provider has reached the max results limit per type as set by the client.`;throw this.logger.info(t),new Error(t)}this.logger.trace(`[${t}] An active query for query ${r.queryId} was found and the provider is within limits, queueing the result`),this.limitsTracker.update(e),n.publisher.queueResult(e),this.logger.trace(`[${t}] The query result was queued successfully.`)}async handleSearchQueryRequest(e,t){const{operation:r}=e,n=operationDecoder.runWithException(r),i=nanoid$4(10);switch(n){case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info:return this.handleInfoOperation({commandId:i});case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search:return this.handleSearchOperation({args:e,commandId:i},t);case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel:return this.handleCancelOperation({args:e,commandId:i});default:throw new Error(`Unrecognized operation: ${r}`)}}async handleInfoOperation(e){this.logger.info(`[${e.commandId}] handling an info operation`);const t=Object.values(this.providersModels).flatMap(e=>e.myProviderData.types||[]),r=[...new Set(t)];Object.values(this.providersModels).some(e=>!e.myProviderData.types)&&r.push({name:"*"});const n=Object.values(this.providersModels).map(e=>e.myProviderData),i={supportedTypes:r.map(e=>e.name),providers:n,apiVersion:"1"};return this.logger.info(`[${e.commandId}] responding to an info operation with: ${JSON.stringify(i)}`),i}async handleSearchOperation(e,t){const r=e.commandId,n=this.generateQueryId();this.logger.info(`[${r}] Processing search operation with queryId: ${n} request details: ${JSON.stringify(e.args)}`);const i=this.checkRequestLegacy(e.args),o=this.prepareRequest(e.args,i,r);return this.logger.info(`[${r}] Search operation with queryId: ${n} is validated. Creating an active query and enqueueing calling the providers.`),this.activeQueries[n]={queryId:n,callerInstanceId:t.instance,providersAtWork:[],requestedTypes:o.types,publisher:this.modelsFactory.buildPublisher(t.instance,n,i),staleTimer:this.setClearStaleQueryTimer(n)},o.providerLimits&&this.limitsTracker.enableTracking(o.providerLimits,n),setTimeout(()=>{this.sequelizer.enqueue(async()=>{try{this.logger.info(`[${r}] Calling the providers.`),this.callProviders(o,n,r)}catch(e){this.logger.error(`[${r}] Error calling the providers: ${extractErrorMsg(e)}`)}})},0),this.logger.info(`[${r}] Search operation with queryID: ${n} processed successfully.`),{id:n}}async handleCancelOperation(e){await this.sequelizer.enqueue(async()=>{const t=searchCancelRequestDecoder.run(e.args);if(!t.ok){const r=`Cannot process a cancel request, because of validation error: ${JSON.stringify(t.error)}`;throw this.logger.warn(`[${e.commandId}] ${r}`),new Error(r)}const r=t.result,n=this.activeQueries[r.id];n&&(clearTimeout(n.staleTimer),n.publisher.cancel(e.commandId),delete this.activeQueries[r.id],n.providersAtWork.forEach(e=>this.registry.execute(`on-cancel-query-${e.myProviderData.id}`,{id:r.id})))})}generateQueryId(){const e=nanoid$4(10);return this.activeQueries[e]?this.generateQueryId():e}translateLegacySearchRequest(e){return{search:e.search,types:e.types?.map(e=>({name:e})),providerLimits:{maxResults:e.limit,maxResultsPerType:e.categoryLimit}}}checkRequestLegacy(e){return void 0===e.apiVersion}callProviders(e,t,r){let n=e.providers?this.getFilteredProviderModels(e.providers):Object.values(this.providersModels);this.logger.trace(`[${r}] initial providers filtration yielded: ${JSON.stringify(n.map(e=>e.myProviderData.name).join(", "))}`),n=e.types?this.getFilteredProvidersBySearchTypes(n,e.types):n,this.logger.trace(`[${r}] search type providers filtration yielded: ${JSON.stringify(n.map(e=>e.myProviderData.name).join(", "))}`),this.activeQueries[t].publisher.configureProviders(n),this.activeQueries[t].providersAtWork.push(...n),n.forEach(n=>this.callProvider(n,e,t,r))}callProvider(e,t,r,n){const i=this.modelsFactory.buildProviderQueryModel(t,{queryId:r,providerId:e.myProviderData.id},this).exposeFacade();this.logger.info(`[${n}] The query facade for provider: ${e.myProviderData.id} with name ${e.myProviderData.name} is ready, raising the event for query ID: ${r}.`),this.registry.execute(`on-search-query-${e.myProviderData.id}`,i)}getFilteredProviderModels(e){const t=e.reduce((e,t)=>(this.providersModels[t.id]&&e.push(this.providersModels[t.id]),e),[]);return t}getFilteredProvidersBySearchTypes(e,t){return e.filter(e=>!e.myProviderData.types||!e.myProviderData.types.length||e.myProviderData.types?.some(e=>t.some(t=>t.name===e.name)))}setClearStaleQueryTimer(e){return setTimeout(()=>{const t=nanoid$4(10);this.logger.info(`[${t}] Stale query timer is activated for queryId: ${e}`);this.activeQueries[e]?(this.logger.info(`[${t}] force-marking the query as done`),this.cleanUpQuery(e,t),this.logger.info(`[${t}] the stale query was cleared.`)):this.logger.info(`[${t}] No active query was found, this was a false activation.`)},STALE_QUERY_TIMEOUT_MS)}prepareRequest(e,t,r){const n=t?this.translateLegacySearchRequest(e):e,i=queryConfigDecoder.run(n);if(!i.ok){const e=`Cannot process a search request, because of validation error: ${JSON.stringify(i.error)}`;throw this.logger.warn(`[${r}] ${e}`),new Error(e)}return i.result}cleanUpQuery(e,t){const r=this.activeQueries[e];clearTimeout(r.staleTimer),r.publisher.cleanPublisher(t),delete this.activeQueries[e],this.limitsTracker.cleanTracking(e)}cleanUpProvider(e,t){this.registry.clearKey(`on-search-query-${e}`),this.registry.clearKey(`on-cancel-query-${e}`),delete this.providersModels[e];Object.values(this.activeQueries).filter(t=>!t.publisher.checkProviderSuspended(e)).forEach(r=>{this.processProviderQueryDone({identification:{queryId:r.queryId,providerId:e},commandId:t})})}async cleanUpProviderQuery(e,t,r){const n=this.activeQueries[e];n?(n.providersAtWork=n.providersAtWork.filter(e=>e.myProviderData.id!==t),await n.publisher.markProviderDone(t,r)):this.logger.warn(`[${r}] Cannot clean up a provider query ${e} for provider ${t} because there is no such active query`)}}var version$3="3.2.1";class SearchFacade{main;constructor(e){this.main=e}exposeApi(){const e={version:version$3,setDebounceMS:this.setDebounceMS.bind(this),getDebounceMS:this.getDebounceMS.bind(this),listProviders:this.providers.bind(this),listTypes:this.types.bind(this),query:this.query.bind(this),registerProvider:this.registerProvider.bind(this)};return Object.freeze(e)}setDebounceMS(e){nonNegativeNumberDecoder$1.runWithException(e);const t=nanoid$4(10);return this.main.setDebounceMS({milliseconds:e,commandId:t})}getDebounceMS(){const e=nanoid$4(10);return this.main.getDebounceMS({commandId:e})}async providers(){const e=nanoid$4(10);return this.main.providers({commandId:e})}async types(){const e=nanoid$4(10);return this.main.types({commandId:e})}async query(e){const t=queryConfigDecoder.runWithException(e),r=nanoid$4(10);return this.main.query({queryConfig:t,commandId:r})}async registerProvider(e){const t=providerRegistrationConfig.runWithException(e),r=nanoid$4(10);return this.main.registerProvider({config:t,commandId:r})}}let AsyncSequelizer$2=class{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}};class LimitsTracker{limitsLookup={};limitsData={};enableTracking(e,t){this.limitsLookup[t]={},this.limitsData[t]={maxResults:e.maxResults?e.maxResults:Number.MAX_SAFE_INTEGER,maxResultsPerType:e.maxResultsPerType?e.maxResultsPerType:Number.MAX_SAFE_INTEGER}}testResultLimit(e){const t=this.limitsLookup[e.identification.queryId],r=this.limitsData[e.identification.queryId];if(!t||!r)return;let n=t[e.identification.providerId];if(n||(n={total:0},t[e.identification.providerId]=n),n.total+1>r.maxResults)return{maxLimitHit:!0};const i=e.result.type.name;if(!i)return;return(n[i]||0)+1>r.maxResultsPerType?{maxLimitPerTypeHit:!0}:void 0}update(e){const t=this.limitsLookup[e.identification.queryId],r=this.limitsData[e.identification.queryId];if(!t||!r)return;const n=t[e.identification.providerId];n.total+=1;const i=e.result.type.name;i&&(n[i]=n[i]?n[i]+1:1)}cleanTracking(e){delete this.limitsLookup[e],delete this.limitsData[e]}}class ClientQuery{controller;logger;masterQueryId;constructor(e,t,r){this.controller=e,this.logger=t,this.masterQueryId=r}exposeFacade(){const e={cancel:this.cancel.bind(this),onResults:this.onResults.bind(this),onCompleted:this.onCompleted.bind(this),onError:this.onError.bind(this)};return Object.freeze(e)}async cancel(){const e=nanoid$4(10);this.logger.info(`[${e}] received a valid query cancel request, forwarding to the controller.`),await this.controller.cancelQuery(this.masterQueryId,e),this.logger.info(`[${e}] the cancel request was completed.`)}onResults(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid query onResults request, forwarding to the controller.`);const r=this.controller.processClientOnResults({callback:e,masterQueryId:this.masterQueryId,commandId:t});return this.logger.info(`[${t}] the onResults request was completed.`),r}onCompleted(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid query onCompleted request, forwarding to the controller.`);const r=this.controller.processClientOnCompleted({callback:e,masterQueryId:this.masterQueryId,commandId:t});return this.logger.info(`[${t}] the onCompleted request was completed.`),r}onError(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid query onError request, forwarding to the controller.`);const r=this.controller.processClientOnError({callback:e,masterQueryId:this.masterQueryId,commandId:t});return this.logger.info(`[${t}] the onError request was completed.`),r}}class ProviderModel{myData;controller;logger;constructor(e,t,r){this.myData=e,this.controller=t,this.logger=r}get id(){return this.myData.id}get name(){return this.myData.name}get appName(){return this.myData.appName}get types(){return this.myData.types}get myProviderData(){return Object.assign({},this.myData)}exposeFacade(){const e={interopId:this.myData.interopId,id:this.id,name:this.name,appName:this.appName,types:this.types,onQuery:this.onQuery.bind(this),onQueryCancel:this.onQueryCancel.bind(this),unregister:this.unregister.bind(this)};return Object.freeze(e)}onQuery(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid onQuery request, forwarding to the controller.`);const r=this.controller.processProviderOnQuery({callback:e,id:this.id,commandId:t});return this.logger.info(`[${t}] the onQuery request was completed.`),r}onQueryCancel(e){if("function"!=typeof e)throw new Error("onQuery requires a callback of type function");const t=nanoid$4(10);this.logger.info(`[${t}] received a valid onQueryCancel request, forwarding to the controller.`);const r=this.controller.processProviderOnQueryCancel({callback:e,id:this.id,commandId:t});return this.logger.info(`[${t}] the onQueryCancel request was completed.`),r}async unregister(){const e=nanoid$4(10);this.logger.info(`[${e}] received a valid unregister request, forwarding to the controller.`),await this.controller.processProviderUnregister({id:this.id,commandId:e}),this.logger.info(`[${e}] the unregister request was completed.`)}}class ProviderQueryModel{myData;controller;logger;identification;constructor(e,t,r,n){this.myData=e,this.controller=t,this.logger=r,this.identification=n}get id(){return this.identification.queryId}get search(){return this.myData.search}get providers(){return this.myData.providers}get types(){return this.myData.types}get providerLimits(){return this.myData.providerLimits}get myQueryData(){return Object.assign({},this.myData)}exposeFacade(){const e={id:this.id,search:this.search,providers:this.providers,types:this.types,providerLimits:this.providerLimits,sendResult:this.sendResult.bind(this),error:this.error.bind(this),done:this.done.bind(this)};return Object.freeze(e)}sendResult(e){queryResultDecoder.runWithException(e);const t=nanoid$4(10);return this.logger.trace(`[${t}] Received a valid result, forwarding to the controller`),this.controller.processProviderQueryResult({identification:this.identification,result:e,commandId:t})}error(e){const t=nanoid$4(10);nonEmptyStringDecoder$1.runWithException(e),this.logger.trace(`[${t}] Received a valid error, forwarding to the controller`),this.controller.processProviderQueryError({identification:this.identification,error:e,commandId:t}).catch(e=>this.logger.warn(`Error processing the error signal for this provider: ${this.id}, error: ${extractErrorMsg(e)}`))}done(){const e=nanoid$4(10);this.logger.trace(`[${e}] Received a valid done, forwarding to the controller`),this.controller.processProviderQueryDone({identification:this.identification,commandId:e}).catch(e=>this.logger.warn(`Error processing the done signal for this provider: ${this.identification.providerId}, error: ${extractErrorMsg(e)}`))}}class QueryResultsPublisher{sequelizer;glueController;logger;clientInstanceId;queryId;isLegacy;queues={};constructor(e,t,r,n,i,o){this.sequelizer=e,this.glueController=t,this.logger=r,this.clientInstanceId=n,this.queryId=i,this.isLegacy=o}checkProviderSuspended(e){return!!this.queues[e]&&!!this.queues[e].suspended}syncSuspendProvider(e,t){const r=this.queues[e];r?r.suspended=!0:this.logger.warn(`[${t}] Cannot suspend provider: ${e}, because there is no provider queue. This happens when the provider queue was already cancelled or completed`)}configureProviders(e){e.forEach(e=>{this.queues[e.myProviderData.id]={providerData:e,pendingResults:[]}})}queueResult(e){const{commandId:t,identification:r}=e;this.logger.trace(`[${t}] Queuing a new result from provider: ${r.providerId}`);const n=this.queues[r.providerId];if(!n)return void this.logger.warn(`[${t}] Cannot queue this result, because there is no provider queue. This happens when the provider queue was already cancelled or completed`);const i=this.isLegacy?this.translateLegacySearchItem(e.result):e.result;if(n.pendingResults.push(i),clearTimeout(n.flushTimer),10===n.pendingResults.length)return this.logger.trace(`[${t}] Reached the limit in the queue buffer, flushing to the client.`),void this.flushProviderQueue(r.providerId,t);this.logger.trace(`[${t}] The limit in the queue buffer is not reached yet, setting a flush timer.`),n.flushTimer=setTimeout(()=>{this.logger.trace(`[${t}] Reached the time limit in the queue buffer, flushing to the client.`),this.flushProviderQueue(r.providerId,t)},FLUSH_TIMEOUT_MS)}cancel(e){this.logger.trace(`[${e}] Cancelling queue ${this.queryId}.`),Object.values(this.queues).forEach(e=>clearTimeout(e.flushTimer)),this.queues={},this.logger.trace(`[${e}] Queue ${this.queryId} publisher cancelled.`)}async markProviderDone(e,t){this.logger.trace(`[${t}] Marking provider ${e} as done.`);const r=this.queues[e];r?(clearTimeout(r.flushTimer),await this.flushProviderQueue(e,t),delete this.queues[e],this.logger.trace(`[${t}] Provider ${e} marked as done.`)):this.logger.info(`[${t}] Cannot mark this queue as done, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent an error`)}markProviderError(e){const t=this.queues[e.identification.providerId];t?this.glueController.sendClientErrorMessage(e.error,this.clientInstanceId,this.queryId,t.providerData.myProviderData).catch(t=>this.logger.warn(`[${e.commandId}] The client errored when handling error message for query: ${this.queryId} -> ${extractErrorMsg(t)}`)):this.logger.warn(`[${e.commandId}] Cannot mark this provider as errored, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`)}cleanPublisher(e){Object.values(this.queues).forEach(e=>clearTimeout(e.flushTimer)),this.queues={},this.glueController.sendClientQueueCompleted(this.clientInstanceId,this.queryId).catch(t=>this.logger.warn(`[${e}] The client errored when handling search end message for query: ${this.queryId} -> ${extractErrorMsg(t)}`))}async flushProviderQueue(e,t){await this.sequelizer.enqueue(async()=>{const r=this.queues[e];if(!r)return void this.logger.warn(`[${t}] Cannot flush this queue, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`);if(!r.pendingResults.length)return void this.logger.info(`[${t}] This provider does not have any pending results to flush.`);const n={results:r.pendingResults,provider:r.providerData.myProviderData};r.pendingResults=[];try{await this.glueController.sendClientResultsBatch(n,this.clientInstanceId,this.queryId)}catch(e){this.logger.warn(`[${t}] The client errored when handling search results for query: ${this.queryId} -> ${extractErrorMsg(e)}`)}})}translateLegacySearchItem(e){return{type:e.type.name,category:e.type.displayName,id:e.id,displayName:e.displayName,description:e.description,iconURL:e.iconURL,action:e.action}}}class ModelFactory{glueController;glue;flushSequelizer;constructor(e,t,r){this.glueController=e,this.glue=t,this.flushSequelizer=r}buildProviderModel(e,t){return new ProviderModel(e,t,this.glue.logger.subLogger(`search.provider.model.${e.name}`))}buildProviderQueryModel(e,t,r){return new ProviderQueryModel(e,r,this.glue.logger.subLogger(`search.provider.${t.providerId}.query.${t.queryId}`),t)}buildPublisher(e,t,r){return new QueryResultsPublisher(this.flushSequelizer,this.glueController,this.glue.logger.subLogger(`search.results.publisher.${t}`),e,t,r)}buildClientQueryModel(e,t){return new ClientQuery(t,this.glue.logger.subLogger(`search.provider.model.${e}`),e)}}let IoC$1=class{glue;config;_glueController;_facade;_mainController;_providerController;_clientController;_asyncSequelizer;_flushSequelizer;_limitsTracker;_modelFactory;constructor(e,t){this.glue=e,this.config=t}get glueController(){return this._glueController||(this._glueController=new GlueController$1(this.glue)),this._glueController}get main(){return this._mainController||(this._mainController=new MainController(this.glue.logger.subLogger("search.main.controller"),this.glueController,this.clientController,this.providerController)),this._mainController}get clientController(){return this._clientController||(this._clientController=new ClientController(this.glue.logger.subLogger("search.client.controller"),this.glueController,this.modelFactory)),this._clientController}get providerController(){return this._providerController||(this._providerController=new ProviderController(this.glue.logger.subLogger("search.provider.controller"),this.glueController,this.sequelizer,this.limitsTracker,this.modelFactory)),this._providerController}get facade(){return this._facade||(this._facade=new SearchFacade(this.main)),this._facade}get sequelizer(){return this._asyncSequelizer||(this._asyncSequelizer=new AsyncSequelizer$2(SEQUELIZER_INTERVAL_MS)),this._asyncSequelizer}get flushSequelizer(){return this._flushSequelizer||(this._flushSequelizer=new AsyncSequelizer$2(FLUSH_SEQUELIZER_INTERVAL_MS)),this._flushSequelizer}get limitsTracker(){return this._limitsTracker||(this._limitsTracker=new LimitsTracker),this._limitsTracker}get modelFactory(){return this._modelFactory||(this._modelFactory=new ModelFactory(this.glueController,this.glue,this.flushSequelizer)),this._modelFactory}};const factoryFunction=async(e,t)=>{const r=new IoC$1(e,t);e.search=r.facade.exposeApi()};"undefined"!=typeof window&&(window.IOSearch=factoryFunction);class Platform{controller;session;localStorage;config;platformConfig;constructor(e,t,r,n){this.controller=e,this.session=t,this.localStorage=r,this.config=n}async ready(){this.session.start(),this.processConfig(this.config),await this.controller.start(this.platformConfig)}getClientGlue(){return this.controller.getClientGlue()}getPlatformApi(){return this.controller.platformApi}processConfig(e){if(!e)return ioError.raiseError("Cannot start the IoConnect Browser Platform without a config object.");const t=runDecoderWithIOError(platformConfigDecoder,e);if(t.gateway?.bridge&&!t.user)return ioError.raiseError("Platform initialization failed due to missing user details. Providing configuration settings for connecting to io.Bridge also requires providing user details via the `user` property.");this.addSearch(t),this.validatePlugins(t),this.platformConfig=deepMerge(defaultPlatformConfig,t),this.platformConfig.manager&&(this.platformConfig.manager.features=deepMerge(defaultManagerFeatures,this.platformConfig.manager.features||{})),this.platformConfig.manager&&!e?.layouts?.mode&&(this.platformConfig.layouts.mode="manager");const r=deepMerge(defaultNotificationsConfig,t.notifications||{}),n=this.session.getSystemSettings()||{systemInstanceId:nanoid$5(),ctxTrackInstanceId:nanoid$5()};this.session.setSystemSettings(n),this.localStorage.start(this.platformConfig.user);const i=this.localStorage.getNotificationsConfig()||r;void 0===i.showNotificationBadge&&(i.showNotificationBadge=!0),this.localStorage.setNotificationsConfig(i),this.platformConfig.workspacesFrameCache="boolean"!=typeof t.workspaces?.frameCache||t.workspaces?.frameCache,this.transferPromiseObjects(t);const o=window.iobrowser?.system,s={system:o,isPlatformFrame:!!t.workspaces?.isFrame,initAsEmptyFrame:!!t.workspaces?.initAsEmpty,workspacesFrameCache:this.platformConfig.workspacesFrameCache,platformStarted:!0,environment:Object.assign({},this.platformConfig.environment,{extension:void 0}),communicationId:n.systemInstanceId,workspaces:{frameCache:this.platformConfig.workspacesFrameCache,isPlatform:!!t.workspaces?.isFrame,initAsEmpty:!!t.workspaces?.initAsEmpty}};window.iobrowser=s}transferPromiseObjects(e){if(void 0!==e.serviceWorker?.registrationPromise&&(this.platformConfig.serviceWorker.registrationPromise=e.serviceWorker.registrationPromise),e.plugins&&e.plugins.definitions.length){e.plugins.definitions.forEach(e=>{const t=this.platformConfig.plugins?.definitions.find(t=>t.name===e.name);t&&(t.config=e.config)})}}validatePlugins(e){if(!e.plugins?.definitions)return;const t=e.plugins.definitions.reduce((e,t)=>{const r=typeof t.start,n=typeof t.stop,i=t.name;return("function"!==r||t.stop&&"function"!==n)&&e.push({name:i,startType:r,stopType:n}),e},[]);if(t.length){const e=t.map(e=>`The start and stop functions for plugin ${e.name} were expected to be of type function, but was provided start: ${e.startType} and stop: ${e.stopType}`).join("\n");return ioError.raiseError(e)}}addSearch(e){e.browser?e.browser.libraries?e.browser.libraries.push(factoryFunction):e.browser.libraries||(e.browser.libraries=[factoryFunction]):e.browser={libraries:[factoryFunction]}}}var MetricTypes={STRING:1,NUMBER:2,TIMESTAMP:3,OBJECT:4};function getMetricTypeByValue(e){return e.type===MetricTypes.TIMESTAMP?"timestamp":e.type===MetricTypes.NUMBER?"number":e.type===MetricTypes.STRING?"string":e.type===MetricTypes.OBJECT?"object":"unknown"}function getTypeByValue(e){return e.constructor===Date?"timestamp":"number"==typeof e?"number":"string"==typeof e?"string":"object"==typeof e?"object":"string"}function serializeMetric(e){const t={},r=getMetricTypeByValue(e);if("object"===r){const r=Object.keys(e.value).reduce((t,r)=>{const n=getTypeByValue(e.value[r]);if("object"===n){const n=defineNestedComposite(e.value[r]);t[r]={type:"object",description:"",context:{},composite:n}}else t[r]={type:n,description:"",context:{}};return t},{});t.composite=r}return t.name=normalizeMetricName(e.path.join("/")+"/"+e.name),t.type=r,t.description=e.description,t.context={},t}function defineNestedComposite(e){return Object.keys(e).reduce((t,r)=>{const n=getTypeByValue(e[r]);return t[r]="object"===n?{type:"object",description:"",context:{},composite:defineNestedComposite(e[r])}:{type:n,description:"",context:{}},t},{})}function normalizeMetricName(e){return void 0!==e&&e.length>0&&"/"!==e[0]?"/"+e:e}function getMetricValueByType(e){return"timestamp"===getMetricTypeByValue(e)?Date.now():publishNestedComposite(e.value)}function publishNestedComposite(e){return"object"!=typeof e?e:Object.keys(e).reduce((t,r)=>{const n=e[r];return"object"==typeof n&&n.constructor!==Date?t[r]=publishNestedComposite(n):n.constructor===Date?t[r]=new Date(n).getTime():n.constructor===Boolean?t[r]=n.toString():t[r]=n,t},{})}function flatten(e){return e.reduce((e,t)=>e.concat(Array.isArray(t)?flatten(t):t),[])}function getHighestState(e){return e.sort((e,t)=>e.state?t.state?t.state-e.state:-1:1)[0]}function aggregateDescription(e){let t="";return e.forEach((e,r,n)=>{const i=e.path.join(".");r===n.length-1?t+=i+"."+e.name+": "+e.description:t+=i+"."+e.name+": "+e.description+","}),t.length>100?t.slice(0,100)+"...":t}function composeMsgForRootStateMetric(e){const t=flatten(e.root.getAggregateState()),r=getHighestState(t);return{description:aggregateDescription(t),value:r.state}}function gw3(e,t){if(!e||"object"!=typeof e)throw new Error("Connection is required parameter");let r,n;const i=e=>{o(e.root)},o=e=>{s(e),e.metrics.forEach(e=>{a(e)}),e.subSystems.forEach(e=>{o(e)})},s=async e=>{if(void 0===e.parent)return;await r;const i={type:"define",metrics:[{name:normalizeMetricName(e.path.join("/")+"/"+e.name+"/State"),type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};n.sendFireAndForget(i).catch(r=>{t.logger.warn(`Failed to send define for system state metric of ${e.name}: ${JSON.stringify(r)}`)})},a=async e=>{const i=l(e);await r;const o={type:"define",metrics:[serializeMetric(i)]};n.sendFireAndForget(o).catch(r=>{t.logger.warn(`Failed to send define for metric ${e.name}: ${JSON.stringify(r)}`)}),void 0!==i.value&&c(i)},c=e=>{if(u()){const r=getMetricValueByType(e),i={type:"publish",values:[{name:normalizeMetricName(e.path.join("/")+"/"+e.name),value:r,timestamp:Date.now()}]};return n.sendFireAndForget(i).catch(r=>{t.logger.warn(`Failed to publish metric ${e.name}: ${JSON.stringify(r)}`)})}return Promise.resolve()},l=e=>{const t={...e};return"object"==typeof e.value&&null!==e.value&&(t.value={...e.value}),t},u=()=>{try{return(t.canUpdateMetric??(()=>!0))()}catch{return!0}};return{init:o=>{let s;r=new Promise(e=>{s=e}),n=e.domain("metrics"),n.onJoined(e=>{!e&&s&&(s(),s=void 0);const r={type:"define",metrics:[{name:"/State",type:"object",composite:{Description:{type:"string",description:""},Value:{type:"number",description:""}},description:"System state",context:{}}]};n.sendFireAndForget(r).catch(e=>{t.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(e)}`)}),e&&i(o)}),n.join({system:t.system,service:t.service,instance:t.instance})},createSystem:s,updateSystem:async(i,o)=>{await r;const s={type:"publish",values:[{name:normalizeMetricName(i.path.join("/")+"/"+i.name+"/State"),value:{Description:o.description,Value:o.state},timestamp:Date.now()}]};n.sendFireAndForget(s).catch(e=>{t.logger.warn(`Failed to send update for system state metric of ${i.name}: ${JSON.stringify(e)}`)});const a=composeMsgForRootStateMetric(i),c={type:"publish",peer_id:e.peerId,values:[{name:"/State",value:{Description:a.description,Value:a.value},timestamp:Date.now()}]};n.sendFireAndForget(c).catch(e=>{t.logger.warn(`Failed to send update for root state metric of ${i.name}: ${JSON.stringify(e)}`)})},createMetric:a,updateMetric:async e=>{const t=l(e);await r,c(t)}}}var Helpers={validate:(e,t,r)=>{if(null===e||"object"!=typeof e)throw new Error("Missing definition");if(null===t||"object"!=typeof t)throw new Error("Missing parent");if(null===r||"object"!=typeof r)throw new Error("Missing transport")}};class BaseMetric{definition;system;transport;value;type;path=[];name;description;get repo(){return this.system?.repo}get id(){return`${this.system.path}/${name}`}constructor(e,t,r,n,i){this.definition=e,this.system=t,this.transport=r,this.value=n,this.type=i,Helpers.validate(e,t,r),this.path=t.path.slice(0),this.path.push(t.name),this.name=e.name,this.description=e.description,r.createMetric(this)}update(e){return this.value=e,this.transport.updateMetric(this)}}class NumberMetric extends BaseMetric{constructor(e,t,r,n){super(e,t,r,n,MetricTypes.NUMBER)}incrementBy(e){this.update(this.value+e)}increment(){this.incrementBy(1)}decrement(){this.incrementBy(-1)}decrementBy(e){this.incrementBy(-1*e)}}class ObjectMetric extends BaseMetric{constructor(e,t,r,n){super(e,t,r,n,MetricTypes.OBJECT)}update(e){return this.mergeValues(e),this.transport.updateMetric(this)}mergeValues(e){return Object.keys(this.value).forEach(t=>{void 0!==e[t]&&(this.value[t]=e[t])})}}class StringMetric extends BaseMetric{constructor(e,t,r,n){super(e,t,r,n,MetricTypes.STRING)}}class TimestampMetric extends BaseMetric{constructor(e,t,r,n){super(e,t,r,n,MetricTypes.TIMESTAMP)}now(){this.update(new Date)}}function system(e,t,r,n,i){if(!t)throw new Error("Repository is required");if(!r)throw new Error("Transport is required");const o=r,s=e,a=i||"",c=t,l=n,u=function e(t){if(!t||!t.parent)return[];const r=e(t.parent);return r.push(t.name),r}(n);let d={};const h=(g="/",((p=u)&&p.length>0?p.join(g):"")+e);var p,g;const m=t.root,f=[],y=[];function $(e,t,r,n){let i={name:""};i="string"==typeof e?{name:e}:e;const o=y.filter(e=>e.name===i.name);if(o.length>0){const e=o[0];if(e.type!==t)throw new Error(`A metric named ${i.name} is already defined with different type.`);return void 0!==r&&e.update(r).catch(()=>{}),e}const s=n(i);return y.push(s),s}const b={get name(){return s},get description(){return a},get repo(){return c},get parent(){return l},path:u,id:h,root:m,get subSystems(){return f},get metrics(){return y},subSystem:function(e,t){if(!e||0===e.length)throw new Error("name is required");const r=f.filter(t=>t.name===e);if(r.length>0)return r[0];const n=system(e,c,o,b,t);return f.push(n),n},getState:()=>d,setState:function(e,t){d={state:e,description:t},o.updateSystem(b,d)},stringMetric:function(e,t){return $(e,MetricTypes.STRING,t,e=>new StringMetric(e,b,o,t))},timestampMetric:function(e,t){return $(e,MetricTypes.TIMESTAMP,t,e=>new TimestampMetric(e,b,o,t))},objectMetric:function(e,t){return $(e,MetricTypes.OBJECT,t,e=>new ObjectMetric(e,b,o,t))},numberMetric:function(e,t){return $(e,MetricTypes.NUMBER,t,e=>new NumberMetric(e,b,o,t))},getAggregateState:function(){const e=[];return Object.keys(d).length>0&&e.push({name:s,path:u,state:d.state,description:d.description}),f.forEach(t=>{const r=t.getAggregateState();r.length>0&&e.push(...r)}),e}};return o.createSystem(b),b}class Repository{root;constructor(e,t){t.init(this),this.root=system("",this,t),this.addSystemMetrics(this.root,e.clickStream||void 0===e.clickStream)}addSystemMetrics(e,t){if("undefined"!=typeof navigator&&e.stringMetric("UserAgent",navigator.userAgent),t&&"undefined"!=typeof document){const t=e.subSystem("ClickStream"),r=e=>{if(!e.target)return;const r=e.target,n=r?r.getAttribute("class")??"":"";t.objectMetric("LastBrowserEvent",{type:"click",timestamp:new Date,target:{className:n,id:r.id,type:"<"+r.tagName.toLowerCase()+">",href:r.href||""}})};t.objectMetric("Page",{title:document.title,page:window.location.href}),document.addEventListener?document.addEventListener("click",r):document.attachEvent("onclick",r)}e.stringMetric("StartTime",(new Date).toString());const r=e.stringMetric("StartURL",""),n=e.stringMetric("AppName","");if("undefined"!=typeof window){if(void 0!==window.location){const e=window.location.href;r.update(e)}void 0!==window.glue42gd&&n.update(window.glue42gd.appName)}}}class NullProtocol{init(e){}createSystem(e){return Promise.resolve()}updateSystem(e,t){return Promise.resolve()}createMetric(e){return Promise.resolve()}updateMetric(e){return Promise.resolve()}}class PerfTracker{api;lastCount=0;initialPublishTimeout=1e4;publishInterval=6e4;system;constructor(e,t,r){this.api=e,this.initialPublishTimeout=t??this.initialPublishTimeout,this.publishInterval=r??this.publishInterval,this.scheduleCollection(),this.system=this.api.subSystem("performance","Performance data published by the web application")}scheduleCollection(){setTimeout(()=>{this.collect(),setInterval(()=>{this.collect()},this.publishInterval)},this.initialPublishTimeout)}collect(){try{this.collectMemory(),this.collectEntries()}catch{}}collectMemory(){const e=window.performance.memory;this.system.stringMetric("memory",JSON.stringify({totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}))}collectEntries(){const e=window.performance.getEntries();if(e.length<=this.lastCount)return;this.lastCount=e.length;const t=e.map(e=>e.toJSON());this.system.stringMetric("entries",JSON.stringify(t))}}var metrics=e=>{let t;t=e.connection&&"object"==typeof e.connection?gw3(e.connection,e):new NullProtocol;let r=new Repository(e,t).root;e.disableAutoAppSystem||(r=r.subSystem("App"));const n=addFAVSupport(r);return initPerf(n,e.pagePerformanceMetrics),n};function initPerf(e,t){if("undefined"==typeof window)return;const r=window?.glue42gd?.metrics?.pagePerformanceMetrics;r&&(t=r),t?.enabled&&new PerfTracker(e,t.initialPublishTimeout,t.publishInterval)}function addFAVSupport(e){const t=e.subSystem("reporting"),r={name:"features"};let n;return e.featureMetric=(e,i,o)=>{if(void 0===e||""===e)throw new Error("name is mandatory");if(void 0===i||""===i)throw new Error("action is mandatory");if(void 0===o||""===o)throw new Error("payload is mandatory");n?n.update({name:e,action:i,payload:o}):n=t.objectMetric(r,{name:e,action:i,payload:o})},e}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function createRegistry(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var t=e&&"function"==typeof e.errorHandling&&e.errorHandling,r={};function n(r,n){var i=r instanceof Error?r:new Error(r);if(t)t(i);else{var o='[ERROR] callback-registry: User callback for key "'+n+'" failed: '+i.stack;if(e)switch(e.errorHandling){case"log":return console.error(o);case"silent":return;case"throw":throw new Error(o)}console.error(o)}}return{add:function(e,t,i){var o=r[e];return o||(o=[],r[e]=o),o.push(t),i&&setTimeout(function(){i.forEach(function(i){var o;if(null===(o=r[e])||void 0===o?void 0:o.includes(t))try{Array.isArray(i)?t.apply(void 0,i):t.apply(void 0,[i])}catch(t){n(t,e)}})},0),function(){var n=r[e];n&&(n=n.reduce(function(e,r,n){return r===t&&e.length===n||e.push(r),e},[]),0===n.length?delete r[e]:r[e]=n)}},execute:function(e){for(var t=[],i=1;i{this.messageHandler(t)}).then(e=>{this.client=e})}get isObjectBasedTransport(){return!0}sendObject(e){return this.client?(this.client.send(e),Promise.resolve(void 0)):Promise.reject("not connected")}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"in-memory"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class SharedWorkerTransport{logger;worker;registry=CallbackRegistryFactory();constructor(e,t){this.logger=t,this.worker=new SharedWorker(e),this.worker.port.onmessage=e=>{this.messageHandler(e.data)}}get isObjectBasedTransport(){return!0}sendObject(e){return this.worker.port.postMessage(e),Promise.resolve()}send(e){return Promise.reject("not supported")}onMessage(e){return this.registry.add("onMessage",e)}onConnectedChanged(e){return e(!0),()=>{}}close(){return Promise.resolve()}open(){return Promise.resolve()}name(){return"shared-worker"}reconnect(){return Promise.resolve()}messageHandler(e){this.registry.execute("onMessage",e)}}class Utils{static isNode(){if(void 0!==Utils._isNode)return Utils._isNode;if("undefined"!=typeof window)return Utils._isNode=!1,!1;try{Utils._isNode="[object process]"===Object.prototype.toString.call(global.process)}catch(e){Utils._isNode=!1}return Utils._isNode}static _isNode}let PromiseWrapper$1=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve;reject;promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};const timers={};function getAllTimers(){return timers}function timer(e){const t=timers[e];if(t)return t;const r=[];function n(){return(new Date).getTime()}const i=n();let o,s;function a(e,t){const i=t??n();let o=0;r.length>0&&(o=i-r[r.length-1].time),r.push({name:e,time:i,diff:o})}a("start",i);const c={get startTime(){return i},get endTime(){return o},get period(){return s},stop:function(){return o=n(),a("end",o),s=o-i,s},mark:a,marks:r};return timers[e]=c,c}const WebSocketConstructor=Utils.isNode()?null:window.WebSocket;class WS{ws;logger;settings;startupTimer=timer("connection");_running=!0;_registry=CallbackRegistryFactory();wsRequests=[];constructor(e,t){if(this.settings=e,this.logger=t,!this.settings.ws)throw new Error("ws is missing")}onMessage(e){return this._registry.add("onMessage",e)}send(e,t){return new Promise((t,r)=>{this.waitForSocketConnection(()=>{try{this.ws?.send(e),t()}catch(e){r(e)}},r)})}open(){return this.logger.info("opening ws..."),this._running=!0,new Promise((e,t)=>{this.waitForSocketConnection(e,t)})}close(){return this._running=!1,this.ws&&this.ws.close(),Promise.resolve()}onConnectedChanged(e){return this._registry.add("onConnectedChanged",e)}name(){return this.settings.ws}reconnect(){this.ws?.close();const e=new PromiseWrapper$1;return this.waitForSocketConnection(()=>{e.resolve()}),e.promise}waitForSocketConnection(e,t){t=t??(()=>{}),this._running?1!==this.ws?.readyState?(this.wsRequests.push({callback:e,failed:t}),this.wsRequests.length>1||this.openSocket()):e():t(`wait for socket on ${this.settings.ws} failed - socket closed by user`)}async openSocket(e,t){if(this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${e}, retriesLeft: ${t}...`),this.startupTimer.mark("opening-socket"),void 0===e&&(e=this.settings.reconnectInterval),void 0===t&&(t=this.settings.reconnectAttempts),void 0!==t){if(0===t)return void this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`);this.logger.debug(`will retry ${t} more times (every ${e} ms)`)}try{await this.initiateSocket(),this.startupTimer.mark("socket-initiated"),this.notifyForSocketState()}catch{setTimeout(()=>{const r=void 0===t?void 0:t-1;this.openSocket(e,r)},e)}}initiateSocket(){const e=new PromiseWrapper$1;this.logger.debug(`initiating ws to ${this.settings.ws}...`),this.ws=new WebSocketConstructor(this.settings.ws??"");let t=!1;return this.ws.onerror=r=>{let n;try{n=JSON.stringify(r)}catch(e){const t=new WeakSet,i=(e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r instanceof Error?{message:r.message,name:r.name,stack:r.stack}:r};n=JSON.stringify(r,i)}this.logger.info(`ws error - reason: ${n}`),e.reject("error"),t&&(t=!1,this.notifyForSocketState("error")),this.notifyStatusChanged(!1,n)},this.ws.onclose=r=>{this.logger.info(`ws closed - code: ${r?.code} reason: ${r?.reason}`),e.reject("closed"),t&&(t=!1,this.notifyForSocketState("closed")),this.notifyStatusChanged(!1)},this.ws.onopen=()=>{this.startupTimer.mark("ws-opened"),this.logger.info(`ws opened ${this.settings.identity?.application}`),e.resolve(),t=!0,this.notifyStatusChanged(!0)},this.ws.onmessage=e=>{this._registry.execute("onMessage",e.data)},e.promise}notifyForSocketState(e){this.wsRequests.forEach(t=>{e?t.failed&&t.failed(e):t.callback()}),this.wsRequests=[]}notifyStatusChanged(e,t){this._registry.execute("onConnectedChanged",e,t)}}class MessageReplayerImpl{specs;specsNames=[];messages={};isDone;subs={};subsRefCount={};connection;constructor(e){this.specs={};for(const t of e)this.specs[t.name]=t,this.specsNames.push(t.name)}init(e){this.connection=e;for(const t of this.specsNames)for(const r of this.specs[t].types){let t=this.subsRefCount[r];if(t||(t=0),t+=1,this.subsRefCount[r]=t,t>1)continue;const n=e.on(r,e=>this.processMessage(r,e));this.subs[r]=n}}processMessage(e,t){if(!this.isDone&&t)for(const r of this.specsNames)if(-1!==this.specs[r].types.indexOf(e)){const e=this.messages[r]||[];this.messages[r]=e,e.push(t)}}drain(e,t){t&&(this.messages[e]||[]).forEach(t),delete this.messages[e];for(const t of this.specs[e].types)this.subsRefCount[t]-=1,this.subsRefCount[t]<=0&&(this.connection?.off(this.subs[t]),delete this.subs[t],delete this.subsRefCount[t]);delete this.specs[e],this.specs.length||(this.isDone=!0)}}let urlAlphabet$1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",nanoid$3=(e=21)=>{let t="",r=0|e;for(;r--;)t+=urlAlphabet$1[64*Math.random()|0];return t};const PromisePlus$1=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});class WebPlatformTransport{settings;logger;identity;isPreferredActivated;_connectionProtocolVersion;_communicationId;publicWindowId;selfAssignedWindowId;iAmConnected=!1;parentReady=!1;rejected=!1;parentPingResolve;parentPingInterval;connectionResolve;extConnectionResolve;extConnectionReject;connectionReject;port;myClientId;extContentAvailable=!1;extContentConnecting=!1;extContentConnected=!1;parentWindowId;parentInExtMode=!1;webNamespace="g42_core_web";parent;parentType;parentPingTimeout=5e3;connectionRequestTimeout=7e3;defaultTargetString="*";registry=CallbackRegistryFactory();messages={connectionAccepted:{name:"connectionAccepted",handle:this.handleConnectionAccepted.bind(this)},connectionRejected:{name:"connectionRejected",handle:this.handleConnectionRejected.bind(this)},connectionRequest:{name:"connectionRequest",handle:this.handleConnectionRequest.bind(this)},parentReady:{name:"parentReady",handle:()=>{}},parentPing:{name:"parentPing",handle:this.handleParentPing.bind(this)},platformPing:{name:"platformPing",handle:this.handlePlatformPing.bind(this)},platformReady:{name:"platformReady",handle:this.handlePlatformReady.bind(this)},clientUnload:{name:"clientUnload",handle:()=>{}},manualUnload:{name:"manualUnload",handle:this.handleManualUnload.bind(this)},extConnectionResponse:{name:"extConnectionResponse",handle:this.handleExtConnectionResponse.bind(this)},extSetupRequest:{name:"extSetupRequest",handle:this.handleExtSetupRequest.bind(this)},gatewayDisconnect:{name:"gatewayDisconnect",handle:this.handleGatewayDisconnect.bind(this)},gatewayInternalConnect:{name:"gatewayInternalConnect",handle:this.handleGatewayInternalConnect.bind(this)}};constructor(e,t,r){this.settings=e,this.logger=t,this.identity=r,this.extContentAvailable=!!window.glue42ext,this.setUpMessageListener(),this.setUpUnload(),this.setupPlatformUnloadListener(),this.parentType=window.name.includes("#wsp")?"workspace":void 0}manualSetReadyState(){this.iAmConnected=!0,this.parentReady=!0}get transportWindowId(){return this.publicWindowId}get communicationId(){return this._communicationId}async sendObject(e){if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);if(!this.port)throw new Error("Cannot send message, because the port was not opened yet");this.port.postMessage(e)}get isObjectBasedTransport(){return!0}onMessage(e){return this.registry.add("onMessage",e)}send(){return Promise.reject("not supported")}onConnectedChanged(e){return this.registry.add("onConnectedChanged",e)}async open(){this.logger.debug("opening a connection to the web platform gateway."),await this.connect(),this.notifyStatusChanged(!0)}close(){this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId||"unknown"}, client connected: ${this.iAmConnected}`);const e={glue42core:{type:this.messages.gatewayDisconnect.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};return this.port?.postMessage(e),this.parentReady=!1,this.notifyStatusChanged(!1,"manual reconnection"),Promise.resolve()}name(){return"web-platform"}async reconnect(){return await this.close(),Promise.resolve()}initiateInternalConnection(){return new Promise((e,t)=>{this.logger.debug("opening an internal web platform connection"),this.port=this.settings.port,this.iAmConnected?this.logger.warn("cannot open a new connection, because this client is currently connected"):(this.port.onmessage=r=>{if(this.iAmConnected&&!r.data?.glue42core)return void this.registry.execute("onMessage",r.data);const n=r.data?.glue42core;n&&(n.type===this.messages.gatewayInternalConnect.name&&n.success&&(this.publicWindowId=this.settings.windowId,this.identity&&this.publicWindowId&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.publicWindowId),e()),n.type===this.messages.gatewayInternalConnect.name&&n.error&&t(n.error))},this.port.postMessage({glue42core:{type:this.messages.gatewayInternalConnect.name}}))})}initiateRemoteConnection(e){return PromisePlus$1((t,r)=>{this.connectionResolve=t,this.connectionReject=r,this.myClientId=this.myClientId??nanoid$3(10);const n=this.getMyWindowId()||nanoid$3(10),i={glue42core:{type:this.messages.connectionRequest.name,clientId:this.myClientId,clientType:"child",bridgeInstanceId:n,selfAssignedWindowId:this.selfAssignedWindowId}};if(this.logger.debug(`sending connection request - clientId: ${this.myClientId}`),this.extContentConnecting)return i.glue42core.clientType="child",i.glue42core.bridgeInstanceId=this.myClientId,i.glue42core.parentWindowId=this.parentWindowId,window.postMessage(i,window.origin);if(!e)throw new Error("Cannot send a connection request, because no glue target was specified!");e.postMessage(i,this.defaultTargetString)},this.connectionRequestTimeout,"The connection to the target glue window timed out")}async isParentCheckSuccess(e){try{return await e,{success:!0}}catch(e){return{success:!1}}}setUpMessageListener(){this.settings.port?this.logger.debug("skipping generic message listener, because this is an internal client"):(this.logger.debug("setting up window message listener"),window.addEventListener("message",e=>{const t=e.data?.glue42core;if(!t||this.rejected)return;const r=this.settings.allowedOrigins||[];if(r.length&&!r.includes(e.origin))return void this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`);if(!this.checkMessageTypeValid(t.type))return void this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${t.type}`);const n=t.type;this.logger.debug(`received valid glue42core message of type: ${n}`),this.messages[n].handle(e)}))}setUpUnload(){this.settings.port?this.logger.debug("skipping unload event listener, because this is an internal client"):(this.logger.debug("setting up unload event listeners"),window.addEventListener("beforeunload",()=>{this._connectionProtocolVersion||this.signalClientDisappearing()}),window.addEventListener("pagehide",()=>{this._connectionProtocolVersion&&this.signalClientDisappearing()}))}signalClientDisappearing(){if(this.extContentConnected)return;this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`);const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};this.parent?.postMessage(e,this.defaultTargetString),this.port?.postMessage(e)}handlePlatformReady(e){this.logger.debug("the web platform gave the ready signal"),this.parentReady=!0,this.parentPingResolve&&(this.parentPingResolve(),delete this.parentPingResolve),this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval),this.parent=e.source,this.parentType=window.name.includes("#wsp")?"workspace":"window"}handleConnectionAccepted(e){const t=e.data?.glue42core;return this.myClientId!==t.clientId?this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${t.clientId}`):this.handleAcceptanceOfMyRequest(t)}handleAcceptanceOfMyRequest(e){if(this.logger.debug("handling a connection accepted signal targeted at me."),this.isPreferredActivated=e.isPreferredActivated,this.extContentConnecting)return this.processExtContentConnection(e);if(e.port){if(this._connectionProtocolVersion=e.connectionProtocolVersion,this.publicWindowId=this.getMyWindowId(),this.identity&&(this.identity.windowId=this.publicWindowId,this.identity.instance=this.identity.instance?this.identity.instance:this.publicWindowId||nanoid$3(10)),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),this._communicationId=e.communicationId,this.port=e.port,this.port.onmessage=e=>this.registry.execute("onMessage",e.data),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve;this.logger.error("unable to call the connection resolve, because no connection promise was found")}else this.logger.error("cannot set up my connection, because I was not provided with a port")}processExtContentConnection(e){if(this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."),this.extContentConnecting=!1,this.extContentConnected=!0,this.publicWindowId=this.parentWindowId||this.myClientId,this.extContentConnecting&&this.identity&&(this.identity.windowId=this.publicWindowId),this.identity&&e.appName&&(this.identity.application=e.appName,this.identity.applicationName=e.appName),window.addEventListener("message",e=>{const t=e.data?.glue42ExtInc;if(!t)return;const r=this.settings.allowedOrigins||[];!r.length||r.includes(e.origin)?this.registry.execute("onMessage",t):this.logger.warn(`received a message from an origin which is not in the allowed list: ${e.origin}`)}),this.connectionResolve)return this.logger.debug("my connection is set up, calling the connection resolve."),this.connectionResolve(),void delete this.connectionResolve}handleConnectionRejected(e){if(this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"),!this.connectionReject)return;const t="string"==typeof e.data.glue42core?.error?`Connection was rejected. ${e.data.glue42core?.error}`:"The platform connection was rejected. Most likely because this window was not created by a glue API call";this.connectionReject(t),delete this.connectionReject}handleConnectionRequest(){this.extContentConnecting&&this.logger.debug("This connection request event is targeted at the extension content")}handleParentPing(e){if(!this.parentReady)return void this.logger.debug("my parent is not ready, I am ignoring the parent ping");if(!this.iAmConnected)return void this.logger.debug("i am not fully connected yet, I am ignoring the parent ping");const t={glue42core:{type:this.messages.parentReady.name}};this.extContentConnected&&(t.glue42core.extMode={windowId:this.myClientId});const r=e.source;this.logger.debug("responding to a parent ping with a ready message"),r.postMessage(t,e.origin)}setupPlatformUnloadListener(){this.logger.debug("setting up platform unload listener"),this.onMessage(e=>{"platformUnload"===e.type&&(this.logger.debug("detected a web platform unload"),this.parentReady=!1,this.notifyStatusChanged(!1,"Gateway unloaded"))})}handleManualUnload(){this.logger.debug("handling manual unload");const e={glue42core:{type:this.messages.clientUnload.name,data:{clientId:this.myClientId,ownWindowId:this.identity?.windowId}}};if(this.extContentConnected)return window.postMessage({glue42ExtOut:e},window.origin);this.port?.postMessage(e)}handlePlatformPing(){}notifyStatusChanged(e,t){this.logger.debug(`status changed - connected: ${e}, reason: ${t||"none"}`),this.iAmConnected=e,this.registry.execute("onConnectedChanged",e,t)}checkMessageTypeValid(e){return"string"==typeof e&&!!this.messages[e]}requestConnectionPermissionFromExt(){return this.waitForContentScript().then(()=>PromisePlus$1((e,t)=>{this.extConnectionResolve=e,this.extConnectionReject=t;this.logger.debug("permission request to the extension content script was sent"),window.postMessage({glue42core:{type:"extSetupRequest"}},window.origin)},this.parentPingTimeout,"Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out"))}handleExtConnectionResponse(e){const t=e.data?.glue42core;if(!t.approved)return this.extConnectionReject?this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected"):void 0;this.extConnectionResolve&&(this.extConnectionResolve(),delete this.extConnectionResolve),this.extContentConnecting=!0,this.parentType="extension",this.logger.debug("The extension connection was approved, proceeding.")}handleExtSetupRequest(){}handleGatewayDisconnect(){}handleGatewayInternalConnect(){}waitForContentScript(){return!!window.glue42ext?.content?Promise.resolve():PromisePlus$1(e=>{window.addEventListener("Glue42EXTReady",()=>{e()})},this.connectionRequestTimeout,"The content script was available, but was never heard to be ready")}async connect(){if(this.settings.port)return await this.initiateInternalConnection(),void this.logger.debug("internal web platform connection completed");this.logger.debug("opening a client web platform connection"),await this.findParent(),await this.initiateRemoteConnection(this.parent),this.logger.debug("the client is connected")}async findParent(){const e="Cannot initiate glue, because this window was not opened or created by a glue client",t=this.getPossibleParentsInWindow(window),r=this.getPossibleParentsOutsideWindow(window.top?.opener,window.top),n=new Set([...t,...r]);if(!n.size&&!this.extContentAvailable)throw new Error(e);if(!n.size&&this.extContentAvailable)return void await this.requestConnectionPermissionFromExt();if((await this.isParentCheckSuccess(this.confirmParent(Array.from(n)))).success)this.logger.debug("The default parent was found!");else{if(!this.extContentAvailable)throw new Error(e);await this.requestConnectionPermissionFromExt()}}getPossibleParentsInWindow(e){return e?.parent&&e!==e.parent?[e.parent,...this.getPossibleParentsInWindow(e.parent)]:[]}getPossibleParentsOutsideWindow(e,t){return e&&t&&e!==t?[e,...this.getPossibleParentsInWindow(e),...this.getPossibleParentsOutsideWindow(e.opener,e)]:[]}confirmParent(e){const t=PromisePlus$1(t=>{this.parentPingResolve=t;const r={glue42core:{type:this.messages.platformPing.name}};this.parentPingInterval=setInterval(()=>{e.forEach(e=>{e.postMessage(r,this.defaultTargetString)})},1e3)},this.parentPingTimeout,"Cannot initiate glue, because this window was not opened or created by a glue client");return t.catch(()=>{this.parentPingInterval&&(clearInterval(this.parentPingInterval),delete this.parentPingInterval)}),t}getMyWindowId(){return"workspace"===this.parentType?window.name.substring(0,window.name.indexOf("#wsp")):window===window.top?window.name?.includes("g42")?window.name:(this.selfAssignedWindowId=this.selfAssignedWindowId||`g42-${nanoid$3(10)}`,this.selfAssignedWindowId):void 0}}const waitForInvocations=(e,t)=>{let r=e;return()=>{r--,0===r&&t()}};let AsyncSequelizer$1=class{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}};function domainSession(e,t,r,n,i){null==e&&(e="global"),n=n??["success"],i=i??["error"];let o,s="global"===e,a=!1,c=!1;const l=CallbackRegistryFactory();t.disconnected(function(){r.debug("connection is down"),c=!1,s=!1,a=!0,Object.keys(u).forEach(e=>{const t=u[e];t&&(r.trace(`failing pending request ${e} due to connection lost`),t.error({err:"Connection lost - gateway connection was disconnected"}))}),l.execute("onLeft",{disconnected:!0})}),t.loggedIn(async function(){if(c=!0,a){r.debug("connection is now up - trying to reconnect...");try{await d(o)}catch{r.trace("failed to reconnect")}}}),t.on("success",e=>g(e)),t.on("error",e=>p(e)),t.on("result",e=>g(e)),n&&n.forEach(e=>{t.on(e,e=>g(e))}),i&&i.forEach(e=>{t.on(e,e=>p(e))});const u={};function d(t){return o=t,new Promise((n,i)=>{if(s)return void n({});let o;if("global"===e)o=c?Promise.resolve({}):Promise.reject("not connected to gateway");else{r.debug(`joining domain ${e}`);o=y({type:"join",destination:e,domain:"global",options:t})}o.then(()=>{!function(){r.debug("did join "+e),s=!0;const t=a;a=!1,l.execute("onJoined",t)}(),n({})}).catch(t=>{r.debug("error joining "+e+" domain: "+JSON.stringify(t)),i(t)})})}function h(e){return s&&e(!1),l.add("onJoined",e)}function p(t){if(e!==t.domain)return;const r=t.request_id;if(!r)return;const n=u[r];n&&n.error(t)}function g(t){if(t.domain!==e)return;const r=t.request_id;if(!r)return;const n=u[r];n&&n.success(t)}function m(){return nanoid$3(10)}let f=[];function y(n,i,o){if(n.type&&-1===["hello","join"].indexOf(n.type)&&!s){console.warn(`trying to send a message (${n.domain} ${n.type}) but not connected, will queue`);const e=new PromiseWrapper$1;if(f.push({msg:n,tag:i,options:o,pw:e}),1===f.length){const e=h(()=>{r.info(`joined - will now send queued messages (${f.length} -> [${f.map(e=>e.msg.type)}])`),f.forEach(e=>{y(e.msg,e.tag,e.options).then(t=>e.pw.resolve(t)).catch(t=>e.pw.reject(t))}),f=[],e()})}return e.promise}o=o??{},n.request_id=n.request_id??m(),n.domain=n.domain??e,o.skipPeerId||(n.peer_id=t.peerId);const a=n.request_id;return new Promise((e,r)=>{u[a]={success:t=>{delete u[a],t._tag=i,e(t)},error:e=>{console.warn(`Gateway error - ${JSON.stringify(e)}`),delete u[a],e._tag=i,r(e)}},t.send(n,o).catch(e=>{u[a]?.error({err:e})})})}return{join:d,leave:function(){return"global"===e?Promise.resolve():(r.debug("stopping session "+e+"..."),a=!1,y({type:"leave",destination:e,domain:"global"}).then(()=>{s=!1,l.execute("onLeft")}).catch(()=>{s=!1,l.execute("onLeft")}))},onJoined:h,onLeft:function(e){return s||e(),l.add("onLeft",e)},send:y,sendFireAndForget:function(r){return r.request_id=r.request_id?r.request_id:m(),r.domain=r.domain??e,r.peer_id=t.peerId,t.send(r)},on:(n,i)=>{t.on(n,t=>{if(t.domain===e)try{i(t)}catch(e){r.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(t)}`,e)}})},loggedIn:e=>t.loggedIn(e),connected:e=>t.connected(e),disconnected:e=>t.disconnected(e),get peerId(){return t.peerId},get domain(){return e}}}class Connection{settings;logger;protocolVersion=3;peerId;token;info;resolvedIdentity;availableDomains;gatewayToken;replayer;messageHandlers={};ids=1;registry=CallbackRegistryFactory();_connected=!1;isTrace=!1;transport;_defaultTransport;_defaultAuth;_targetTransport;_targetAuth;_swapTransport=!1;_switchInProgress=!1;_transportSubscriptions=[];datePrefix="#T42_DATE#";datePrefixLen=this.datePrefix.length;dateMinLen=this.datePrefixLen+1;datePrefixFirstChar=this.datePrefix[0];_sequelizer=new AsyncSequelizer$1;_isLoggedIn=!1;shouldTryLogin=!0;pingTimer;sessions=[];globalDomain;initialLogin=!0;initialLoginAttempts=3;loginConfig;loginRetryInProgress=!1;constructor(e,t){if(this.settings=e,this.logger=t,(e=e||{}).reconnectAttempts=e.reconnectAttempts??10,e.reconnectInterval=e.reconnectInterval??1e3,e.inproc)this.transport=new InProcTransport(e.inproc,t.subLogger("inMemory"));else if(e.sharedWorker)this.transport=new SharedWorkerTransport(e.sharedWorker,t.subLogger("shared-worker"));else if(e.webPlatform)this.transport=new WebPlatformTransport(e.webPlatform,t.subLogger("web-platform"),e.identity);else{if(void 0===e.ws)throw new Error("No connection information specified");this.transport=new WS(e,t.subLogger("ws"))}this.isTrace=t.canPublish("trace"),t.debug(`starting with ${this.transport.name()} transport`);const r=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),n=this.transport.onMessage(this.handleTransportMessage.bind(this));this._transportSubscriptions.push(r),this._transportSubscriptions.push(n),this._defaultTransport=this.transport,this.ping()}async switchTransport(e){return this._sequelizer.enqueue(async()=>{if(!e||"object"!=typeof e)throw new Error("Cannot switch transports, because the settings are missing or invalid.");if(void 0===e.type)throw new Error("Cannot switch the transport, because the type is not defined");this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(e)}`);const t="secondary"===e.type?this.getNewSecondaryTransport(e):this._defaultTransport;this._targetTransport=t,this._targetAuth="secondary"===e.type?this.getNewSecondaryAuth(e):this._defaultAuth;const r=this.verifyConnection();this._swapTransport=!0,this._switchInProgress=!0,this.logger.trace("The new transport has been set, closing the current transport"),await this.transport.close();try{await r;const e=this.transport===t;return this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${e}`),this._switchInProgress=!1,{success:e}}catch(e){return this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."),this.switchTransport({type:"default"}),this._switchInProgress=!1,{success:!1}}})}onLibReAnnounced(e){return this.registry.add("libReAnnounced",e)}setLibReAnnounced(e){this.registry.execute("libReAnnounced",e)}send(e,t){if(this.transport.sendObject&&this.transport.isObjectBasedTransport){const r=this.createObjectMessage(e);return this.isTrace&&this.logger.trace(`>> ${JSON.stringify(r)}`),this.transport.sendObject(r,t)}{const r=this.createStringMessage(e);return this.isTrace&&this.logger.trace(`>> ${r}`),this.transport.send(r,t)}}on(e,t){e=e.toLowerCase(),void 0===this.messageHandlers[e]&&(this.messageHandlers[e]={});const r=this.ids++;return this.messageHandlers[e][r]=t,{type:e,id:r}}off(e){delete this.messageHandlers[e.type.toLowerCase()][e.id]}get isConnected(){return this._isLoggedIn}connected(e){return this.loggedIn(()=>{const t=this.transport.name();e(t)})}disconnected(e){return this.registry.add("disconnected",e)}async login(e,t){if(this.logger.debug(`Login initiated - reconnect: ${t}, transport: ${this.transport.name()}`),this._defaultAuth||(this._defaultAuth=e),this._swapTransport){this.logger.trace("Detected a transport swap, swapping transports");e=this.transportSwap()??e}try{await this.transport.open(),this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`),timer("connection").mark("transport-opened");const r=await this.loginCore(e,t);return this.logger.debug(`Logged in with identity: ${JSON.stringify(r)}`),timer("connection").mark("protocol-logged-in"),r}catch(e){throw this._switchInProgress&&(this.logger.debug("An error while logging in after a transport swap, preparing a default swap."),this.prepareDefaultSwap()),new Error(e)}}async logout(){await this.logoutCore(),await this.transport.close()}loggedIn(e){return this._isLoggedIn&&e(),this.registry.add("onLoggedIn",e)}domain(e,t,r){let n=this.sessions.find(t=>t.domain===e);return n||(n=domainSession(e,this,this.logger.subLogger(`domain=${e}`),t,r),this.sessions.push(n)),n}authToken(){return this.globalDomain?this.globalDomain.send({domain:"global",type:"create-token"}).then(e=>e.token):Promise.reject(new Error("no global domain session"))}reconnect(){return this.transport.reconnect()}setLoggedIn(e){this._isLoggedIn=e,this._isLoggedIn&&(this.initialLogin=!1,this.registry.execute("onLoggedIn"))}distributeMessage(e,t){const r=this.messageHandlers[t.toLowerCase()];void 0!==r&&Object.keys(r).forEach(t=>{const n=r[t];if(void 0!==n)try{n(e)}catch(e){try{this.logger.error(`Message handler failed with ${e.stack}`,e)}catch(t){console.log("Message handler failed",e)}}})}handleConnectionChanged(e){this._connected!==e?(this.logger.info("connection state changed to "+(e?"connected":"disconnected")),this._connected=e,e?(this.settings?.replaySpecs?.length&&(this.replayer=new MessageReplayerImpl(this.settings.replaySpecs),this.replayer.init(this)),this.registry.execute("connected")):(this.setLoggedIn(!1),this.shouldTryLogin&&this.attemptLoginWithRetry(),this.registry.execute("disconnected"))):this.logger.trace("connection state unchanged, skipping")}async attemptLoginWithRetry(){if(!this.loginConfig)throw new Error("no login info");if(this.loginRetryInProgress)this.logger.debug("login attempt already in progress, ignoring request...");else if(this._isLoggedIn)this.logger.debug("already logged in, ignoring request...");else{if(this.initialLogin){if(this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`),this.initialLoginAttempts<=0)return void this.logger.info("maximum initial login attempts reached, will not try to login again");this.initialLoginAttempts--}try{this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`),this.loginRetryInProgress=!0,await this.login(this.loginConfig,!0)}catch(e){this.logger.error(`error trying to login: ${e?.message}`,e),setTimeout(this.attemptLoginWithRetry.bind(this),this.settings.reconnectInterval??1e3)}finally{this.loginRetryInProgress=!1}}}handleTransportMessage(e){let t;t="string"==typeof e?this.processStringMessage(e):this.processObjectMessage(e),this.isTrace&&this.logger.trace(`<< ${JSON.stringify(t)}`),this.distributeMessage(t.msg,t.msgType)}verifyConnection(){return PromisePlus$1(e=>{let t;const r=waitForInvocations(2,()=>{t&&t(),e()});t=this.onLibReAnnounced(e=>"interop"===e.name||"contexts"===e.name?r():void 0)},1e4,"Transport switch timed out waiting for all libraries to be re-announced")}getNewSecondaryTransport(e){if(!e.transportConfig?.url)throw new Error("Missing secondary transport URL.");return new WS(Object.assign({},this.settings,{ws:e.transportConfig.url,reconnectAttempts:1}),this.logger.subLogger("ws-secondary"))}getNewSecondaryAuth(e){if(!e.transportConfig?.auth)throw new Error("Missing secondary transport auth information.");return e.transportConfig.auth}transportSwap(){if(this._swapTransport=!1,!this._targetTransport||!this._targetAuth)return void this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`);this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport=this._targetTransport;const e=this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)),t=this.transport.onMessage(this.handleTransportMessage.bind(this));return this._transportSubscriptions.push(e),this._transportSubscriptions.push(t),this._targetAuth}prepareDefaultSwap(){this._transportSubscriptions.forEach(e=>e()),this._transportSubscriptions=[],this.transport.close().catch(e=>this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(e)}`)),this._targetTransport=this._defaultTransport,this._targetAuth=this._defaultAuth,this._swapTransport=!0}processStringMessage(e){const t=JSON.parse(e,(e,t)=>{if("string"!=typeof t)return t;if(t.lengthe.leave());await Promise.all(e)}getNewGWToken(){if("undefined"!=typeof window){const e=window.glue42gd;if(e)return e.getGWToken()}return Promise.reject(new Error("not running in GD"))}ping(){this.shouldTryLogin&&(this._isLoggedIn&&this.send({type:"ping"}),this.pingTimer=setTimeout(()=>{this.ping()},3e4))}}const order=["trace","debug","info","warn","error","off"];class Logger{name;parent;static Interop;static InteropMethodName="T42.AppLogger.Log";static Instance;path;subLoggers=[];_consoleLevel;_publishLevel;loggerFullName;includeTimeAndLevel;logFn=console;customLogFn=!1;constructor(e,t,r){this.name=e,this.parent=t,this.name=e,this.path=t?`${t.path}.${e}`:e,this.loggerFullName=`[${this.path}]`,this.includeTimeAndLevel=!r,r&&(this.logFn=r,this.customLogFn=!0)}subLogger(e){const t=this.subLoggers.filter(t=>t.name===e)[0];if(void 0!==t)return t;Object.keys(this).forEach(t=>{if(t===e)throw new Error("This sub logger name is not allowed.")});const r=new Logger(e,this,this.customLogFn?this.logFn:void 0);return this.subLoggers.push(r),r}publishLevel(e){return e&&(this._publishLevel=e),this._publishLevel||this.parent?.publishLevel()}consoleLevel(e){return e&&(this._consoleLevel=e),this._consoleLevel||this.parent?.consoleLevel()}log(e,t,r){this.publishMessage(t||"info",e,r)}trace(e){this.log(e,"trace")}debug(e){this.log(e,"debug")}info(e){this.log(e,"info")}warn(e){this.log(e,"warn")}error(e,t){this.log(e,"error",t)}canPublish(e,t){return order.indexOf(e)>=order.indexOf(t||this.consoleLevel()||"trace")}publishMessage(e,t,r){const n=this.loggerFullName;if("error"===e&&!r){const e=new Error;e.stack&&(t=t+"\n"+e.stack.split("\n").slice(4).join("\n"))}if(this.canPublish(e,this.publishLevel())){const i=Logger.Interop;if(i)try{if(i.methods({name:Logger.InteropMethodName}).length>0){const o={msg:t,logger:n,level:e};r&&r instanceof Error&&(o.error={message:r.message,stack:r.stack??""}),i.invoke(Logger.InteropMethodName,o).catch(e=>{this.logFn.error(`Unable to send log message to the platform: ${e.message}`,e)})}}catch{}}if(this.canPublish(e)){let i="";if(this.includeTimeAndLevel){const t=new Date;i=`[${`${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}:${t.getMilliseconds()}`}] [${e}] `}const o=`${i}${n}: ${t}`;switch(e){case"trace":this.logFn.debug(o);break;case"debug":this.logFn.debug?this.logFn.debug(o):this.logFn.log(o);break;case"info":this.logFn.info(o);break;case"warn":this.logFn.warn(o);break;case"error":r?this.logFn.error(o,r):this.logFn.error(o)}}}}const GW_MESSAGE_CREATE_CONTEXT="create-context",GW_MESSAGE_ACTIVITY_CREATED="created",GW_MESSAGE_ACTIVITY_DESTROYED="destroyed",GW_MESSAGE_CONTEXT_CREATED="context-created",GW_MESSAGE_CONTEXT_ADDED="context-added",GW_MESSAGE_SUBSCRIBE_CONTEXT="subscribe-context",GW_MESSAGE_SUBSCRIBED_CONTEXT="subscribed-context",GW_MESSAGE_UNSUBSCRIBE_CONTEXT="unsubscribe-context",GW_MESSAGE_DESTROY_CONTEXT="destroy-context",GW_MESSAGE_CONTEXT_DESTROYED="context-destroyed",GW_MESSAGE_UPDATE_CONTEXT="update-context",GW_MESSAGE_CONTEXT_UPDATED="context-updated",GW_MESSAGE_JOINED_ACTIVITY="joined",ContextMessageReplaySpec={get name(){return"context"},get types(){return[GW_MESSAGE_CREATE_CONTEXT,GW_MESSAGE_ACTIVITY_CREATED,GW_MESSAGE_ACTIVITY_DESTROYED,GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_CONTEXT_ADDED,GW_MESSAGE_SUBSCRIBE_CONTEXT,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_UNSUBSCRIBE_CONTEXT,GW_MESSAGE_DESTROY_CONTEXT,GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_UPDATE_CONTEXT,GW_MESSAGE_CONTEXT_UPDATED,GW_MESSAGE_JOINED_ACTIVITY]}};var version$2="6.8.1";function prepareConfig(e,t,r){let n;if(Utils.isNode()){const e=process.env._GD_STARTING_CONTEXT_;if(e)try{n=JSON.parse(e)}catch{}}function i(){if(e.application)return e.application;if(r)return r.applicationName;if("undefined"!=typeof window&&void 0!==window.glue42electron)return window.glue42electron.application;const t=nanoid$3(10);return Utils.isNode()?n?n.applicationConfig.name:"NodeJS"+t:"undefined"!=typeof window&&"undefined"!=typeof document?document.title+` (${t})`:t}const o=function(){const o=e.gateway,s=o?.protocolVersion??3,a=o?.reconnectInterval,c=o?.reconnectAttempts;let l=o?.ws;const u=o?.sharedWorker,d=o?.inproc,h=o?.webPlatform??void 0;let p,g,m,f,y;r&&(l=r.gwURL),Utils.isNode()&&n&&n.gwURL&&(l=n.gwURL),l||u||d||(l="ws://localhost:8385");const $=i();let b=$;void 0!==r?(g=r.windowId,m=r.pid,r.env&&(f=r.env.env,y=r.env.region),b=r.application??"glue-app",p=r.appInstanceId):Utils.isNode()?(m=process.pid,n&&(f=n.env,y=n.region,p=n.instanceId)):void 0!==window?.glue42electron&&(g=window?.glue42electron.instanceId,m=window?.glue42electron.pid,f=window?.glue42electron.env,y=window?.glue42electron.region,b=window?.glue42electron.application??"glue-app",p=window?.glue42electron.instanceId);const v=e.gateway?.replaySpecs??[];v.push(ContextMessageReplaySpec);let w={application:b,applicationName:$,windowId:g,instance:p,process:m,region:y,environment:f,api:t.version||version$2};return e.identity&&(w=Object.assign(w,e.identity)),{identity:w,reconnectInterval:a,ws:l,sharedWorker:u,webPlatform:h,inproc:d,protocolVersion:s,reconnectAttempts:c,replaySpecs:v}}();let s=i();if("undefined"!=typeof window){const e=window,t=e.htmlContainer?`${e.htmlContainer.containerName}.${e.htmlContainer.application}`:e?.glue42gd?.application;t&&(s=t)}return{bus:e.bus??!1,application:s,auth:"string"==typeof e.auth?{token:e.auth}:e.auth?e.auth:Utils.isNode()&&n&&n.gwToken?{gatewayToken:n.gwToken}:e.gateway?.webPlatform?{username:"glue42",password:""}:void 0,logger:function(){let t=e.logger;const n="warn";let i;return t||(t=n),r&&(i=r.consoleLogLevel),"string"==typeof t?{console:i??t,publish:n}:{console:i??t.console??n,publish:t.publish??n}}(),connection:o,metrics:e.metrics??!0,contexts:function(){const t={reAnnounceKnownContexts:!0,subscribeOnUpdate:!0,subscribeOnGet:!0,onlyReAnnounceSubscribedContexts:!0};return void 0===e.contexts||"boolean"==typeof e.contexts&&e.contexts?t:"object"==typeof e.contexts&&{...t,...e.contexts}}(),version:t.version||version$2,libs:t.libs??[],customLogger:e.customLogger}}class GW3ContextData{name;contextId;context;isAnnounced;createdByUs;joinedActivity;updateCallbacks={};activityId;sentExplicitSubscription;get hasReceivedSnapshot(){return this.snapshotPromiseWrapper.resolved}set hasReceivedSnapshot(e){e?this.snapshotPromiseWrapper.resolve():this.snapshotPromiseWrapper=new PromiseWrapper$1}get snapshotPromise(){return this.snapshotPromiseWrapper.promise}snapshotPromiseWrapper;constructor(e,t,r,n){this.contextId=e,this.name=t,this.isAnnounced=r,this.activityId=n,this.context={},this.snapshotPromiseWrapper=new PromiseWrapper$1}hasCallbacks(){return Object.keys(this.updateCallbacks).length>0}getState(){return this.isAnnounced&&this.hasCallbacks()?3:this.isAnnounced?2:this.hasCallbacks()?1:0}}var lodash_clonedeep={exports:{}};lodash_clonedeep.exports,function(e,t){var r="__lodash_hash_undefined__",n=9007199254740991,i="[object Arguments]",o="[object Boolean]",s="[object Date]",a="[object Function]",c="[object GeneratorFunction]",l="[object Map]",u="[object Number]",d="[object Object]",h="[object Promise]",p="[object RegExp]",g="[object Set]",m="[object String]",f="[object Symbol]",y="[object WeakMap]",$="[object ArrayBuffer]",b="[object DataView]",v="[object Float32Array]",w="[object Float64Array]",S="[object Int8Array]",_="[object Int16Array]",E="[object Int32Array]",C="[object Uint8Array]",I="[object Uint8ClampedArray]",T="[object Uint16Array]",A="[object Uint32Array]",D=/\w*$/,x=/^\[object .+?Constructor\]$/,R=/^(?:0|[1-9]\d*)$/,O={};O[i]=O["[object Array]"]=O[$]=O[b]=O[o]=O[s]=O[v]=O[w]=O[S]=O[_]=O[E]=O[l]=O[u]=O[d]=O[p]=O[g]=O[m]=O[f]=O[C]=O[I]=O[T]=O[A]=!0,O["[object Error]"]=O[a]=O[y]=!1;var N="object"==typeof commonjsGlobal&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,P="object"==typeof self&&self&&self.Object===Object&&self,k=N||P||Function("return this")(),M=t&&!t.nodeType&&t,L=M&&e&&!e.nodeType&&e,F=L&&L.exports===M;function j(e,t){return e.set(t[0],t[1]),e}function U(e,t){return e.add(t),e}function B(e,t,r,n){for(var i=-1,o=e?e.length:0;++i-1},Ie.prototype.set=function(e,t){var r=this.__data__,n=Re(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},Te.prototype.clear=function(){this.__data__={hash:new Ce,map:new(pe||Ie),string:new Ce}},Te.prototype.delete=function(e){return Me(this,e).delete(e)},Te.prototype.get=function(e){return Me(this,e).get(e)},Te.prototype.has=function(e){return Me(this,e).has(e)},Te.prototype.set=function(e,t){return Me(this,e).set(e,t),this},Ae.prototype.clear=function(){this.__data__=new Ie},Ae.prototype.delete=function(e){return this.__data__.delete(e)},Ae.prototype.get=function(e){return this.__data__.get(e)},Ae.prototype.has=function(e){return this.__data__.has(e)},Ae.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Ie){var n=r.__data__;if(!pe||n.length<199)return n.push([e,t]),this;r=this.__data__=new Te(n)}return r.set(e,t),this};var Fe=le?z(le,Object):function(){return[]},je=function(e){return ee.call(e)};function Ue(e,t){return!!(t=null==t?n:t)&&("number"==typeof e||R.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=n}(e.length)&&!Je(e)}var Ge=ue||function(){return!1};function Je(e){var t=Ke(e)?ee.call(e):"";return t==a||t==c}function Ke(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ve(e){return We(e)?De(e):function(e){if(!Be(e))return de(e);var t=[];for(var r in Object(e))Q.call(e,r)&&"constructor"!=r&&t.push(r);return t}(e)}e.exports=function(e){return Oe(e,!0,!0)}}(lodash_clonedeep,lodash_clonedeep.exports);var lodash_clonedeepExports=lodash_clonedeep.exports,cloneDeep=getDefaultExportFromCjs(lodash_clonedeepExports);function applyContextDelta(e,t,r){try{if(r?.canPublish("trace")&&r?.trace(`applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`),!t)return e;if(t.reset)return e={...t.reset};if(e=deepClone(e,void 0),t.commands){for(const r of t.commands)"remove"===r.type?deletePath(e,r.path):"set"===r.type&&setValueToPath(e,r.value,r.path);return e}const n=t.added,i=t.updated,o=t.removed;return n&&Object.keys(n).forEach(t=>{e[t]=n[t]}),i&&Object.keys(i).forEach(t=>{mergeObjectsProperties(t,e,i)}),o&&o.forEach(t=>{delete e[t]}),e}catch(n){return r?.error(`error applying context delta ${JSON.stringify(t)} on context ${JSON.stringify(e)}`,n),e}}function deepClone(e,t){return cloneDeep(e)}const mergeObjectsProperties=(e,t,r)=>{const n=r[e];if(void 0===n)return t;const i=t[e];return i&&n?"string"==typeof i||"number"==typeof i||"boolean"==typeof i||"string"==typeof n||"number"==typeof n||"boolean"==typeof n||Array.isArray(i)||Array.isArray(n)?(t[e]=n,t):(t[e]=Object.assign({},i,n),t):(t[e]=n,t)};function deepEqual(e,t){if(e===t)return!0;if(!(e instanceof Object&&t instanceof Object))return!1;if(e.constructor!==t.constructor)return!1;for(const r in e)if(e.hasOwnProperty(r)){if(!t.hasOwnProperty(r))return!1;if(e[r]!==t[r]){if("object"!=typeof e[r])return!1;if(!deepEqual(e[r],t[r]))return!1}}for(const r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}function setValueToPath(e,t,r){const n=r.split("."),i=["__proto__","constructor","prototype"];let o;for(o=0;o"object"==typeof t[r]?isSubset(e?.[r]||{},t[r]||{}):t[r]===e?.[r])}function deletePath(e,t){const r=t.split(".");let n;for(n=0;n"context"===e.uri);this._protocolVersion=e?.version??1}return this._protocolVersion}get setPathSupported(){return this.protocolVersion>=2}constructor(e){this._connection=e.connection,this._logger=e.logger,this._trackAllContexts=e.trackAllContexts,this._reAnnounceKnownContexts=e.reAnnounceKnownContexts,this._subscribeOnUpdate=e.subscribeOnUpdate??!0,this._subscribeOnGet=e.subscribeOnGet??!0,this._onlyReAnnounceSubscribedContexts=e.onlyReAnnounceSubscribedContexts??!0,this._gw3Session=this._connection.domain("global",[GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_CONTEXT_UPDATED]),this._gw3Session.disconnected(this.resetState.bind(this)),this._gw3Session.onJoined(e=>{if(e)return this._reAnnounceKnownContexts?void this.reInitiateState().then(()=>this._connection.setLibReAnnounced({name:"contexts"})).catch(e=>{this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(e)}`)}):(this._contextsTempCache={},this._connection.setLibReAnnounced({name:"contexts"}))}),this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED||t===GW_MESSAGE_CONTEXT_ADDED||t===GW_MESSAGE_ACTIVITY_CREATED?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT||t===GW_MESSAGE_CONTEXT_UPDATED||t===GW_MESSAGE_JOINED_ACTIVITY?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED&&t!==GW_MESSAGE_ACTIVITY_DESTROYED||this.handleContextDestroyedMessage(e))})}dispose(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._gw3Subscriptions.length=0;for(const e in this._contextNameToData)this._contextNameToId.hasOwnProperty(e)&&delete this._contextNameToData[e]}createContext(e,t){return e in this._creationPromises||(this._creationPromises[e]=this._gw3Session.send({type:GW_MESSAGE_CREATE_CONTEXT,domain:"global",name:e,data:t,lifetime:"retained"}).then(r=>{this._contextNameToId[e]=r.context_id,this._contextIdToName[r.context_id]=e;const n=this._contextNameToData[e]||new GW3ContextData(r.context_id,e,!0,void 0);return n.isAnnounced=!0,n.name=e,n.contextId=r.context_id,n.context=r.data||deepClone(t),n.hasReceivedSnapshot=!0,this._contextNameToData[e]=n,delete this._creationPromises[e],n.sentExplicitSubscription=!0,n.createdByUs=!0,this.subscribe(e,()=>{}),r.context_id})),this._creationPromises[e]}all(){return Object.keys(this._contextNameToData).filter(e=>this._contextNameToData[e].isAnnounced)}async update(e,t){t&&(t=deepClone(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return void await this.createContext(e,t);const n=await this.get(r.name),i=this.setPathSupported?this.calculateContextDeltaV2(n,t):this.calculateContextDeltaV1(n,t);if(!(Object.keys(i.added).length||Object.keys(i.updated).length||i.removed.length||i.commands?.length))return Promise.resolve();const o=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:r.contextId,delta:i},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&(await r.snapshotPromise,this.handleUpdated(r,i,{updaterId:o.peer_id}))}async set(e,t){t&&(t=deepClone(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced)return this.createContext(e,t);const n=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:r.contextId,delta:{reset:t}},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&this.handleUpdated(r,{reset:t,added:{},removed:[],updated:{}},{updaterId:n.peer_id})}setPath(e,t,r){return this.setPathSupported?this.setPaths(e,[{path:t,value:r}]):Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later")}async setPaths(e,t){if(!this.setPathSupported)return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");t&&(t=deepClone(t)),e in this._creationPromises&&await this._creationPromises[e];const r=this._contextNameToData[e];if(!r||!r.isAnnounced){const r={};for(const e of t)setValueToPath(r,e.value,e.path);return this.createContext(e,r)}const n=[];for(const e of t)null===e.value?n.push({type:"remove",path:e.path}):n.push({type:"set",path:e.path,value:e.value});const i=await this._gw3Session.send({type:GW_MESSAGE_UPDATE_CONTEXT,domain:"global",context_id:r.contextId,delta:{commands:n}},{},{skipPeerId:!1});!this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId||this.subscribe(e,()=>{}),(this._subscribeOnUpdate||r.sentExplicitSubscription||r.activityId)&&(await r.snapshotPromise,this.handleUpdated(r,{added:{},removed:[],updated:{},commands:n},{updaterId:i.peer_id}))}async get(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e];if(!t||!t.isAnnounced)return!t&&this._subscribeOnGet&&this.subscribe(e,()=>{}),Promise.resolve({});if(t&&!t.sentExplicitSubscription)return new Promise((t,r)=>{this.subscribe(e,(e,r,n,i)=>{this._subscribeOnGet||this.unsubscribe(i),t(e)}).catch(e=>{this.isInvalidContextError(e)?t({}):r(e)})});await t.snapshotPromise;const r=t?.context??{};return Promise.resolve(deepClone(r))}isInvalidContextError(e){return e.reason_uri===this.ERROR_URI_INVALID_CONTEXT||e.reason_uri===this.ERROR_URI_FAILURE&&e.reason?.startsWith("Unable to find context with id")}async subscribe(e,t,r){e in this._creationPromises&&await this._creationPromises[e];const n=void 0===r?this._nextCallbackSubscriptionNumber:r;void 0===r&&(this._nextCallbackSubscriptionNumber+=1,this._contextsSubscriptionsCache.push({contextName:e,subKey:n,callback:t}));let i=this._contextNameToData[e];if(!i||!i.isAnnounced)return i=i||new GW3ContextData(void 0,e,!1,void 0),this._contextNameToData[e]=i,i.updateCallbacks[n]=t,Promise.resolve(n);const o=i.hasCallbacks();if(i.updateCallbacks[n]=t,o){if(i.hasReceivedSnapshot&&!r){const e=deepClone(i.context);t(e,e,[],n)}return Promise.resolve(n)}if(i.joinedActivity||i.createdByUs){if(i.hasReceivedSnapshot&&!r){const e=deepClone(i.context);t(e,e,[],n)}return Promise.resolve(n)}if(i.context&&i.sentExplicitSubscription){if(i.hasReceivedSnapshot&&!r){const e=deepClone(i.context);t(e,e,[],n)}return Promise.resolve(n)}return this.sendSubscribe(i).then(()=>n,()=>(this.unsubscribe(n,!0),n))}unsubscribe(e,t){t||(this._contextsSubscriptionsCache=this._contextsSubscriptionsCache.filter(t=>t.subKey!==e));for(const t of Object.keys(this._contextNameToData)){const r=this._contextNameToData[t];if(!r)continue;const n=r.hasCallbacks();delete r.updateCallbacks[e],r.isAnnounced&&n&&!r.hasCallbacks()&&r.sentExplicitSubscription&&(r.hasReceivedSnapshot=!1,r.context={},this.sendUnsubscribe(r).catch(()=>{})),r.isAnnounced||r.hasCallbacks()||(delete this._contextNameToData[t],delete this._contextNameToId[t],r.contextId&&delete this._contextIdToName[r.contextId])}}async destroy(e){e in this._creationPromises&&await this._creationPromises[e];const t=this._contextNameToData[e],r=t?.contextId;return t&&r?this._gw3Session.send({type:GW_MESSAGE_DESTROY_CONTEXT,domain:"global",context_id:t.contextId}).then(()=>{}):Promise.reject(`context with ${e} does not exist`)}handleUpdated(e,t,r){const n=e.context;e.context=applyContextDelta(e.context,t,this._logger),this._contextNameToData[e.name]!==e||deepEqual(n,e.context)||this.invokeUpdateCallbacks(e,t,r)}subscribeToContextCreatedMessages(){const e=[GW_MESSAGE_CONTEXT_ADDED,GW_MESSAGE_CONTEXT_CREATED,GW_MESSAGE_ACTIVITY_CREATED];for(const t of e){const e=this._connection.on(t,this.handleContextCreatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextCreatedMessage(e){const t=e.type;t===GW_MESSAGE_ACTIVITY_CREATED?(this._contextNameToId[e.activity_id]=e.context_id,this._contextIdToName[e.context_id]=e.activity_id):t===GW_MESSAGE_CONTEXT_ADDED&&(this._contextNameToId[e.name]=e.context_id,this._contextIdToName[e.context_id]=e.name);const r=this._contextIdToName[e.context_id];if(!r)throw new Error("Received created event for context with unknown name: "+e.context_id);if(!this._contextNameToId[r])throw new Error("Received created event for context with unknown id: "+e.context_id);let n=this._contextNameToData[r];if(n){if(n.isAnnounced)return;if(!n.hasCallbacks())throw new Error("Assertion failure: contextData.hasCallbacks()");n.isAnnounced=!0,n.contextId=e.context_id,n.activityId=e.activity_id,n.sentExplicitSubscription||this.sendSubscribe(n).catch(()=>{})}else this._contextNameToData[r]=n=new GW3ContextData(e.context_id,r,!0,e.activity_id),this._trackAllContexts&&this.subscribe(r,()=>{}).then(e=>this._systemContextsSubKey=e)}subscribeToContextUpdatedMessages(){const e=[GW_MESSAGE_CONTEXT_UPDATED,GW_MESSAGE_SUBSCRIBED_CONTEXT,GW_MESSAGE_JOINED_ACTIVITY];for(const t of e){const e=this._connection.on(t,this.handleContextUpdatedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextUpdatedMessage(e){const t=e.type,r=e.context_id;let n=this._contextNameToData[this._contextIdToName[r]];const i=!n||!n.isAnnounced;if(t===GW_MESSAGE_JOINED_ACTIVITY)n||(n=this._contextNameToData[e.activity_id]||new GW3ContextData(r,e.activity_id,!0,e.activity_id)),this._contextNameToData[e.activity_id]=n,this._contextIdToName[r]=e.activity_id,this._contextNameToId[e.activity_id]=r,n.contextId=r,n.isAnnounced=!0,n.activityId=e.activity_id,n.joinedActivity=!0;else if(!n||!n.isAnnounced)return void(t===GW_MESSAGE_SUBSCRIBED_CONTEXT?(n=n||new GW3ContextData(r,e.name,!0,void 0),n.sentExplicitSubscription=!0,this._contextNameToData[e.name]=n,this._contextIdToName[r]=e.name,this._contextNameToId[e.name]=r):this._logger.error(`Received 'update' for unknown context: ${r}`));const o=n.context;if(n.hasReceivedSnapshot=!0,t===GW_MESSAGE_SUBSCRIBED_CONTEXT)n.context=e.data??{};else if(t===GW_MESSAGE_JOINED_ACTIVITY)n.context=e.context_snapshot??{};else{if(t!==GW_MESSAGE_CONTEXT_UPDATED)throw new Error("Unrecognized context update message "+t);n.context=applyContextDelta(n.context,e.delta,this._logger)}!i&&deepEqual(n.context,o)&&t!==GW_MESSAGE_SUBSCRIBED_CONTEXT||this.invokeUpdateCallbacks(n,e.delta,{updaterId:e.updater_id})}invokeUpdateCallbacks(e,t,r){if((t=t||{added:{},updated:{},reset:{},removed:[]}).commands){t.added=t.updated=t.reset={},t.removed=[];for(const e of t.commands)"remove"===e.type?(-1===e.path.indexOf(".")&&t.removed.push(e.path),setValueToPath(t.updated,null,e.path)):"set"===e.type&&setValueToPath(t.updated,e.value,e.path)}for(const n in e.updateCallbacks)if(e.updateCallbacks.hasOwnProperty(n))try{(0,e.updateCallbacks[n])(deepClone(e.context),deepClone(Object.assign({},t.added||{},t.updated||{},t.reset||{})),t.removed,parseInt(n,10),r)}catch(e){this._logger.debug("callback error: "+JSON.stringify(e))}}subscribeToContextDestroyedMessages(){const e=[GW_MESSAGE_CONTEXT_DESTROYED,GW_MESSAGE_ACTIVITY_DESTROYED];for(const t of e){const e=this._connection.on(t,this.handleContextDestroyedMessage.bind(this));this._gw3Subscriptions.push(e)}}handleContextDestroyedMessage(e){let t,r;if(e.type===GW_MESSAGE_ACTIVITY_DESTROYED){if(r=e.activity_id,t=this._contextNameToId[r],!t)return void this._logger.error(`Received 'destroyed' for unknown activity: ${e.activity_id}`)}else if(t=e.context_id,r=this._contextIdToName[t],!r)return void this._logger.error(`Received 'destroyed' for unknown context: ${e.context_id}`);delete this._contextIdToName[t],delete this._contextNameToId[r];const n=this._contextNameToData[r];delete this._contextNameToData[r],n&&n.isAnnounced||this._logger.error(`Received 'destroyed' for unknown context: ${t}`)}async sendSubscribe(e){e.sentExplicitSubscription=!0;try{return void await this._gw3Session.send({type:GW_MESSAGE_SUBSCRIBE_CONTEXT,domain:"global",context_id:e.contextId})}catch(t){throw e.sentExplicitSubscription=!1,t}}async sendUnsubscribe(e){const t=e.sentExplicitSubscription;e.sentExplicitSubscription=!1;try{return void await this._gw3Session.send({type:GW_MESSAGE_UNSUBSCRIBE_CONTEXT,domain:"global",context_id:e.contextId})}catch(r){throw e.sentExplicitSubscription=t,r}}calculateContextDeltaV1(e,t){const r={added:{},updated:{},removed:[],reset:void 0};if(e)for(const n of Object.keys(e))-1===Object.keys(t).indexOf(n)||null===t[n]||deepEqual(e[n],t[n])||(r.updated[n]=t[n]);for(const n of Object.keys(t))e&&-1!==Object.keys(e).indexOf(n)?null===t[n]&&r.removed.push(n):null!==t[n]&&(r.added[n]=t[n]);return r}calculateContextDeltaV2(e,t){const r={added:{},updated:{},removed:[],reset:void 0,commands:[]};for(const n of Object.keys(t))if(null!==t[n]){deepEqual(e?e[n]:null,t[n])||r.commands?.push({type:"set",path:n,value:t[n]})}else r.commands?.push({type:"remove",path:n});return r}resetState(){for(const e of this._gw3Subscriptions)this._connection.off(e);this._systemContextsSubKey&&(this.unsubscribe(this._systemContextsSubKey,!0),delete this._systemContextsSubKey),this._gw3Subscriptions=[],this._contextNameToId={},this._contextIdToName={},delete this._protocolVersion,this._contextsTempCache=Object.keys(this._contextNameToData).reduce((e,t)=>{const r=this._contextNameToData[t];return(!this._onlyReAnnounceSubscribedContexts||r.hasReceivedSnapshot)&&(e[t]=this._contextNameToData[t].context),e},{}),this._contextNameToData={}}async reInitiateState(){this.subscribeToContextCreatedMessages(),this.subscribeToContextUpdatedMessages(),this.subscribeToContextDestroyedMessages(),this._connection.replayer?.drain(ContextMessageReplaySpec.name,e=>{const t=e.type;t&&(t===GW_MESSAGE_CONTEXT_CREATED||t===GW_MESSAGE_CONTEXT_ADDED||t===GW_MESSAGE_ACTIVITY_CREATED?this.handleContextCreatedMessage(e):t===GW_MESSAGE_SUBSCRIBED_CONTEXT||t===GW_MESSAGE_CONTEXT_UPDATED||t===GW_MESSAGE_JOINED_ACTIVITY?this.handleContextUpdatedMessage(e):t!==GW_MESSAGE_CONTEXT_DESTROYED&&t!==GW_MESSAGE_ACTIVITY_DESTROYED||this.handleContextDestroyedMessage(e))}),await Promise.all(this._contextsSubscriptionsCache.map(e=>this.subscribe(e.contextName,e.callback,e.subKey))),await this.flushQueue();for(const e in this._contextsTempCache){if("object"!=typeof this._contextsTempCache[e]||0===Object.keys(this._contextsTempCache[e]).length)continue;const t=this._contextsTempCache[e];this._logger.info(`Re-announcing known context: ${e}`),await this.flushQueue(),await this.update(e,t)}this._contextsTempCache={},this._logger.info("Contexts are re-announced")}flushQueue(){return new Promise(e=>setTimeout(()=>e(),0))}}class ContextsModule{initTime;initStartTime;initEndTime;_bridge;constructor(e){this._bridge=new GW3Bridge(e)}all(){return this._bridge.all()}update(e,t){return this.checkName(e),this.checkData(t),this._bridge.update(e,t)}set(e,t){return this.checkName(e),this.checkData(t),this._bridge.set(e,t)}setPath(e,t,r){this.checkName(e),this.checkPath(t);return""===t?(this.checkData(r),this.set(e,r)):this._bridge.setPath(e,t,r)}setPaths(e,t){if(this.checkName(e),!Array.isArray(t))throw new Error("Please provide the paths as an array of PathValues!");for(const{path:e,value:r}of t){this.checkPath(e);""===e&&this.checkData(r)}return this._bridge.setPaths(e,t)}subscribe(e,t){if(this.checkName(e),"function"!=typeof t)throw new Error("Please provide the callback as a function!");return this._bridge.subscribe(e,(e,r,n,i,o)=>t(e,r,n,()=>this._bridge.unsubscribe(i),o)).then(e=>()=>{this._bridge.unsubscribe(e)})}get(e){return this.checkName(e),this._bridge.get(e)}ready(){return Promise.resolve(this)}destroy(e){return this.checkName(e),this._bridge.destroy(e)}get setPathSupported(){return this._bridge.setPathSupported}checkName(e){if("string"!=typeof e||""===e)throw new Error("Please provide the name as a non-empty string!")}checkPath(e){if("string"!=typeof e)throw new Error("Please provide the path as a dot delimited string!")}checkData(e){if("object"!=typeof e)throw new Error("Please provide the data as an object!")}}function promisify(e,t,r){return"function"!=typeof t&&"function"!=typeof r?e:("function"!=typeof t?t=()=>{}:"function"!=typeof r&&(r=()=>{}),e.then(t,r))}function rejectAfter(e=0,t,r){let n;const i=()=>{n&&clearTimeout(n)};return t.then(()=>{i()}).catch(()=>{i()}),new Promise((t,i)=>{n=setTimeout(()=>i(r),e)})}var ok=function(e){return{ok:!0,result:e}},err=function(e){return{ok:!1,error:e}},asPromise=function(e){return!0===e.ok?Promise.resolve(e.result):Promise.reject(e.error)},withDefault=function(e,t){return!0===t.ok?t.result:e},withException=function(e){if(!0===e.ok)return e.result;throw e.error},map$1=function(e,t){return!0===t.ok?ok(e(t.result)):t},map2=function(e,t,r){return!1===t.ok?t:!1===r.ok?r:ok(e(t.result,r.result))},mapError=function(e,t){return!0===t.ok?t:err(e(t.error))},andThen=function(e,t){return!0===t.ok?e(t.result):t},__assign=function(){return __assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r{const r=typeof e;return"function"===r?anyJson():fail$1(`The provided argument as ${t} should be of type function, provided: ${typeof r}`)},nonEmptyStringDecoder=string$3().where(e=>e.length>0,"Expected a non-empty string"),nonNegativeNumberDecoder=number$3().where(e=>e>=0,"Expected a non-negative number or 0"),methodDefinitionDecoder=object$1({name:nonEmptyStringDecoder,objectTypes:optional$1(array$1(nonEmptyStringDecoder)),displayName:optional$1(nonEmptyStringDecoder),accepts:optional$1(nonEmptyStringDecoder),returns:optional$1(nonEmptyStringDecoder),description:optional$1(nonEmptyStringDecoder),version:optional$1(nonNegativeNumberDecoder),supportsStreaming:optional$1(boolean$3()),flags:optional$1(object$1()),getServers:optional$1(anyJson().andThen(e=>functionCheck(e,"method definition getServers")))}),methodFilterDecoder=union$1(nonEmptyStringDecoder,methodDefinitionDecoder),instanceDecoder=object$1({application:optional$1(nonEmptyStringDecoder),applicationName:optional$1(nonEmptyStringDecoder),pid:optional$1(nonNegativeNumberDecoder),machine:optional$1(nonEmptyStringDecoder),user:optional$1(nonEmptyStringDecoder),environment:optional$1(nonEmptyStringDecoder),region:optional$1(nonEmptyStringDecoder),service:optional$1(nonEmptyStringDecoder),instance:optional$1(nonEmptyStringDecoder),windowId:optional$1(nonEmptyStringDecoder),peerId:optional$1(nonEmptyStringDecoder),isLocal:optional$1(boolean$3()),api:optional$1(nonEmptyStringDecoder),getMethods:optional$1(anyJson().andThen(e=>functionCheck(e,"instance getMethods"))),getStreams:optional$1(anyJson().andThen(e=>functionCheck(e,"instance getStreams")))}),targetDecoder=union$1(constant("best"),constant("all"),constant("skipMine"),instanceDecoder,array$1(instanceDecoder)),invokeOptionsDecoder=object$1({waitTimeoutMs:optional$1(nonNegativeNumberDecoder),methodResponseTimeoutMs:optional$1(nonNegativeNumberDecoder)});var InvokeStatus;!function(e){e[e.Success=0]="Success",e[e.Error=1]="Error"}(InvokeStatus||(InvokeStatus={}));class Client{protocol;repo;instance;configuration;constructor(e,t,r,n){this.protocol=e,this.repo=t,this.instance=r,this.configuration=n}subscribe(e,t,r,n,i){const o=(e,r,n,o)=>{t.methodResponseTimeout=t.methodResponseTimeout??t.waitTimeoutMs,this.protocol.client.subscribe(r,t,e,n,o,i)},s=new Promise((r,n)=>{const i=e=>{r(e)},s=e=>{n(e)};if(!e)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");let a;if(a="string"==typeof e?{name:e}:e,!a.name)return void n("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");void 0===t&&(t={});let c=t.target;if(void 0===c&&(c="best"),"string"==typeof c&&"all"!==c&&"best"!==c)return void n(new Error(`"${c}" is not a valid target. Valid targets are "all", "best", or an instance.`));void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=t.method_response_timeout,void 0===t.methodResponseTimeout&&(t.methodResponseTimeout=this.configuration.methodResponseTimeout)),void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=t.wait_for_method_timeout,void 0===t.waitTimeoutMs&&(t.waitTimeoutMs=this.configuration.waitTimeoutMs));let l=0,u=this.getServerMethodsByFilterAndTarget(a,c);if(u.length>0)o(u,u[0].methods[0],i,s);else{const r=()=>{if(c&&t.waitTimeoutMs)if(l+=500,u=this.getServerMethodsByFilterAndTarget(a,c),u.length>0){const e=u[0].methods[0];o(u,e,i,s)}else if(l>=t.waitTimeoutMs){o(u,"string"==typeof e?{name:e}:e,i,s)}else setTimeout(r,500)};setTimeout(r,500)}});return promisify(s,r,n)}servers(e){const t=void 0===e?void 0:{...e};return this.getServers(t).map(e=>e.server.instance)}methods(e){return e="string"==typeof e?{name:e}:{...e},this.getMethods(e)}methodsForInstance(e){return this.getMethodsForInstance(e)}methodAdded(e){return this.repo.onMethodAdded(e)}methodRemoved(e){return this.repo.onMethodRemoved(e)}serverAdded(e){return this.repo.onServerAdded(e)}serverRemoved(e){return this.repo.onServerRemoved((t,r)=>{e(t,r)})}serverMethodAdded(e){return this.repo.onServerMethodAdded((t,r)=>{e({server:t,method:r})})}serverMethodRemoved(e){return this.repo.onServerMethodRemoved((t,r)=>{e({server:t,method:r})})}async invoke(e,t,r,n,i,o){return promisify((async()=>{const s="string"==typeof e?{name:e}:{...e};t||(t={}),r||(r="best"),n||(n={});const a=methodFilterDecoder.run(s);if(!a.ok){const e=`The provided 'method' argument is invalid. Error: ${JSON.stringify(a.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if("object"!=typeof t){const e="The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const c=targetDecoder.run(r);if(!c.ok){const e=`The provided 'target' argument is invalid. Error: ${JSON.stringify(c.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}const l=invokeOptionsDecoder.run(n);if(!l.ok){const e=`The provided 'options' argument is invalid. Error: ${JSON.stringify(l.error)}.`;return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(i&&"function"!=typeof i){const e="The provided 'success' function is invalid. Error: The success should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}if(o&&"function"!=typeof o){const e="The provided 'error' function is invalid. Error: The error should be a valid function";return Promise.reject(this.generateInvalidInputInvocationResult(e,s,t))}void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=n.method_response_timeout,void 0===n.methodResponseTimeoutMs&&(n.methodResponseTimeoutMs=this.configuration.methodResponseTimeout)),void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=n.wait_for_method_timeout,void 0===n.waitTimeoutMs&&(n.waitTimeoutMs=this.configuration.waitTimeoutMs));let u=this.getServerMethodsByFilterAndTarget(s,r);if(0===u.length)try{u=await this.tryToAwaitForMethods(s,r,n)}catch(n){const i=`Can not find a method matching ${JSON.stringify(e)} with server filter ${JSON.stringify(r)}`;return Promise.reject(this.generateInvalidInputInvocationResult(i,s,t))}const d=n.methodResponseTimeoutMs,h=n,p=u.map(e=>{const r=nanoid$3(10),n=e.methods[0],i=e.server,o=this.protocol.client.invoke(r,n,t,i,h);return Promise.race([o,rejectAfter(d,o,{invocationId:r,message:`Invocation timeout (${d} ms) reached for method name: ${n?.name}, target instance: ${JSON.stringify(i.instance)}, options: ${JSON.stringify(h)}`,status:InvokeStatus.Error})])}),g=await Promise.all(p),m=this.getInvocationResultObj(g,s,t);return g.every(e=>e.status===InvokeStatus.Error)?Promise.reject(m):m})(),i,o)}generateInvalidInputInvocationResult(e,t,r){const n={...t,getServers:()=>[],supportsStreaming:!1,objectTypes:t.objectTypes??[],flags:t.flags?.metadata??{}},i={invocationId:nanoid$3(10),status:InvokeStatus.Error,message:e};return this.getInvocationResultObj([i],n,r)}getInvocationResultObj(e,t,r){const n=e.filter(e=>e.status===InvokeStatus.Success).reduce((e,n)=>e=[...e,{executed_by:n.instance,returned:n.result,called_with:r,method:t,message:n.message,status:n.status}],[]),i=e.filter(e=>e.status===InvokeStatus.Error).reduce((e,n)=>e=[...e,{executed_by:n.instance,called_with:r,name:t.name,message:n.message}],[]),o=e[0];return{method:t,called_with:r,returned:o.result,executed_by:o.instance,all_return_values:n,all_errors:i,message:o.message,status:o.status}}tryToAwaitForMethods(e,t,r){return new Promise((n,i)=>{if(0===r.waitTimeoutMs)return void i();let o=0;const s=setInterval(()=>{o+=500;const a=this.getServerMethodsByFilterAndTarget(e,t);if(a.length>0)clearInterval(s),n(a);else if(o>=(r.waitTimeoutMs||1e4))return clearInterval(s),void i()},500)})}filterByTarget(e,t){if("string"!=typeof e){let r;r=Array.isArray(e)?e:[e];const n=r.reduce((e,r)=>{const n=t.filter(e=>this.instanceMatch(r,e.server.instance));return e.concat(n)},[]);return n}if("all"===e)return[...t];if("best"===e){const e=t.find(e=>e.server.instance.isLocal);if(e)return[e];if(void 0!==t[0])return[t[0]]}else if("skipMine"===e)return t.filter(({server:e})=>e.instance.peerId!==this.instance.peerId);return[]}instanceMatch(e,t){return e?.peerId&&e?.instance&&delete(e={...e}).peerId,this.containsProps(e,t)}methodMatch(e,t){return this.containsProps(e,t)}containsProps(e,t){return Object.keys(e).filter(t=>void 0!==e[t]&&null!==e[t]&&"function"!=typeof e[t]&&"object_types"!==t&&"display_name"!==t&&"id"!==t&&"gatewayId"!==t&&"identifier"!==t&&"_"!==t[0]).every(r=>{let n;const i=e[r],o=t[r];switch(r){case"objectTypes":n=(i||[]).every(e=>(o||[]).includes(e));break;case"flags":n=isSubset(o||{},i||{});break;default:n=String(i).toLowerCase()===String(o).toLowerCase()}return n})}getMethods(e){if(void 0===e)return this.repo.getMethods();return this.repo.getMethods().filter(t=>this.methodMatch(e,t))}getMethodsForInstance(e){const t=this.repo.getServers().filter(t=>this.instanceMatch(e,t.instance));if(0===t.length)return[];let r={};return 1===t.length?r=t[0].methods:t.forEach(e=>{Object.keys(e.methods).forEach(t=>{const n=e.methods[t];r[n.identifier]=n})}),Object.keys(r).map(e=>r[e])}getServers(e){const t=this.repo.getServers();return void 0===e?t.map(e=>({server:e,methods:[]})):t.reduce((t,r)=>{const n=Object.values(r.methods).filter(t=>this.methodMatch(e,t));return n.length>0&&t.push({server:r,methods:n}),t},[])}getServerMethodsByFilterAndTarget(e,t){const r=this.getServers(e);return this.filterByTarget(t,r)}}class ServerSubscription{protocol;repoMethod;subscription;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.subscription=r}get stream(){if(!this.repoMethod.stream)throw new Error("no stream");return this.repoMethod.stream}get arguments(){return this.subscription.arguments||{}}get branchKey(){return this.subscription.branchKey}get instance(){if(!this.subscription.instance)throw new Error("no instance");return this.subscription.instance}close(){this.protocol.server.closeSingleSubscription(this.repoMethod,this.subscription)}push(e){this.protocol.server.pushDataToSingle(this.repoMethod,this.subscription,e)}}let Request$1=class{protocol;repoMethod;requestContext;arguments;instance;constructor(e,t,r){this.protocol=e,this.repoMethod=t,this.requestContext=r,this.arguments=r.arguments,this.instance=r.instance}accept(){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,"")}acceptOnBranch(e){this.protocol.server.acceptRequestOnBranch(this.requestContext,this.repoMethod,e)}reject(e){this.protocol.server.rejectRequest(this.requestContext,this.repoMethod,e)}},ServerStreaming$1=class{protocol;server;constructor(e,t){this.protocol=e,this.server=t,e.server.onSubRequest((e,t)=>this.handleSubRequest(e,t)),e.server.onSubAdded((e,t)=>this.handleSubAdded(e,t)),e.server.onSubRemoved((e,t)=>this.handleSubRemoved(e,t))}handleSubRequest(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRequestHandler)return;const r=new Request$1(this.protocol,t,e);t.streamCallbacks.subscriptionRequestHandler(r)}handleSubAdded(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionAddedHandler)return;const r=new ServerSubscription(this.protocol,t,e);t.streamCallbacks.subscriptionAddedHandler(r)}handleSubRemoved(e,t){if(!t||!t.streamCallbacks||"function"!=typeof t.streamCallbacks.subscriptionRemovedHandler)return;const r=new ServerSubscription(this.protocol,t,e);t.streamCallbacks.subscriptionRemovedHandler(r)}};class ServerBranch{key;protocol;repoMethod;constructor(e,t,r){this.key=e,this.protocol=t,this.repoMethod=r}subscriptions(){return this.protocol.server.getSubscriptionList(this.repoMethod,this.key).map(e=>new ServerSubscription(this.protocol,this.repoMethod,e))}close(){this.protocol.server.closeAllSubscriptions(this.repoMethod,this.key)}push(e){this.protocol.server.pushData(this.repoMethod,e,[this.key])}}class ServerStream{_protocol;_repoMethod;_server;name;constructor(e,t,r){this._protocol=e,this._repoMethod=t,this._server=r,this.name=this._repoMethod.definition.name}branches(e){const t=this._protocol.server.getBranchList(this._repoMethod);return e?t.indexOf(e)>-1?new ServerBranch(e,this._protocol,this._repoMethod):void 0:t.map(e=>new ServerBranch(e,this._protocol,this._repoMethod))}branch(e){return this.branches(e)}subscriptions(){return this._protocol.server.getSubscriptionList(this._repoMethod).map(e=>new ServerSubscription(this._protocol,this._repoMethod,e))}get definition(){const e=this._repoMethod.definition;return{accepts:e.accepts,description:e.description,displayName:e.displayName,name:e.name,objectTypes:e.objectTypes,returns:e.returns,supportsStreaming:e.supportsStreaming,flags:e.flags?.metadata}}close(){this._protocol.server.closeAllSubscriptions(this._repoMethod),this._server.unregister(this._repoMethod.definition,!0)}push(e,t){if("string"!=typeof t&&!Array.isArray(t)&&void 0!==t)throw new Error("invalid branches should be string or string array");if("object"!=typeof e)throw new Error("Invalid arguments. Data must be an object.");this._protocol.server.pushData(this._repoMethod,e,t)}updateRepoMethod(e){this._repoMethod=e}}class Server{protocol;serverRepository;streaming;invocations=0;currentlyUnregistering={};constructor(e,t){this.protocol=e,this.serverRepository=t,this.streaming=new ServerStreaming$1(e,this),this.protocol.server.onInvoked(this.onMethodInvoked.bind(this))}createStream(e,t,r,n,i){const o=new Promise((r,n)=>{if(!e)return void n("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.");let o;if(o="string"==typeof e?{name:""+e}:{...e},!o.name)return n(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(o)}`);if(this.serverRepository.getList().some(e=>e.definition.name===o.name))return n(`A stream with the name "${o.name}" already exists! Please, provide a unique name for the stream.`);o.supportsStreaming=!0,t||(t={}),"function"!=typeof t.subscriptionRequestHandler&&(t.subscriptionRequestHandler=e=>{e.accept()});const s=this.serverRepository.add({definition:o,streamCallbacks:t,protocolState:{}});this.protocol.server.createStream(s).then(()=>{let e;i?(e=i,i.updateRepoMethod(s)):e=new ServerStream(this.protocol,s,this),s.stream=e,r(e)}).catch(e=>{s.repoId&&this.serverRepository.remove(s.repoId),n(e)})});return promisify(o,r,n)}register(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const r=async(e,r)=>{try{const n=t(e.args,e.instance);if(n&&"function"==typeof n.then){r(void 0,await n)}else r(void 0,n)}catch(e){r(e??"",e??"")}};return r.userCallback=t,this.registerCore(e,r)}registerAsync(e,t){if(!e)return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");if("function"!=typeof t)return Promise.reject(`The second parameter must be a callback function. Method: ${"string"==typeof e?e:e.name}`);const r=async(e,r)=>{try{let n=!1;const i=e=>{n||r(void 0,e),n=!0},o=e=>{n||(e||(e=""),r(e,e)),n=!0},s=t(e.args,e.instance,i,o);s&&"function"==typeof s.then&&s.then(i).catch(o)}catch(e){r(e,void 0)}};return r.userCallbackAsync=t,this.registerCore(e,r)}async unregister(e,t=!1){if(void 0===e)return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");if("function"==typeof e)return void await this.unregisterWithPredicate(e,t);let r;if(r="string"==typeof e?{name:e}:e,void 0===r.name)return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!");const n=this.serverRepository.getList().find(e=>e.definition.name===r.name&&(e.definition.supportsStreaming||!1)===t);if(!n)return Promise.reject(`Method with a name "${r.name}" does not exist or is not registered by your application!`);await this.removeMethodsOrStreams([n])}async unregisterWithPredicate(e,t){const r=this.serverRepository.getList().filter(t=>e(t.definition)).filter(e=>(e.definition.supportsStreaming||!1)===t);if(!r||0===r.length)return Promise.reject(`Could not find a ${t?"stream":"method"} matching the specified condition!`);await this.removeMethodsOrStreams(r)}removeMethodsOrStreams(e){const t=[];return e.forEach(e=>{const r=this.protocol.server.unregister(e).then(()=>{e.repoId&&this.serverRepository.remove(e.repoId)});t.push(r),this.addAsCurrentlyUnregistering(e.definition.name,r)}),Promise.all(t)}async addAsCurrentlyUnregistering(e,t){const r=new Promise(e=>setTimeout(e,5e3));this.currentlyUnregistering[e]=Promise.race([t,r]).then(()=>{delete this.currentlyUnregistering[e]})}async registerCore(e,t){let r;if(r="string"==typeof e?{name:""+e}:{...e},!r.name)return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(e)}`);const n=this.currentlyUnregistering[r.name];void 0!==n&&await n;if(this.serverRepository.getList().some(e=>e.definition.name===r.name))return Promise.reject(`A method with the name "${r.name}" already exists! Please, provide a unique name for the method.`);if(r.supportsStreaming)return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${r.name}” to be a stream, please use the “glue.interop.createStream()” method.`);const i=this.serverRepository.add({definition:r,theFunction:t,protocolState:{}});return this.protocol.server.register(i).catch(e=>{throw i?.repoId&&this.serverRepository.remove(i.repoId),e})}onMethodInvoked(e,t,r){e&&e.theFunction&&e.theFunction(r,(r,n)=>{if(null!=r)if(r.message&&"string"==typeof r.message)r=r.message;else if("string"!=typeof r)try{r=JSON.stringify(r)}catch(e){r=`un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(r)}`}n?("object"!=typeof n||Array.isArray(n))&&(n={_value:n}):n={},this.protocol.server.methodInvocationResult(e,t,r,n)})}}class InstanceWrapper{wrapped={};constructor(e,t,r){this.wrapped.getMethods=function(){return e.methodsForInstance(this)},this.wrapped.getStreams=function(){return e.methodsForInstance(this).filter(e=>e.supportsStreaming)},t&&this.refreshWrappedObject(t),r&&(r.loggedIn(()=>{this.refresh(r)}),this.refresh(r))}unwrap(){return this.wrapped}refresh(e){if(!e)return;const t=e?.resolvedIdentity,r=Object.assign({},t??{},{peerId:e?.peerId});this.refreshWrappedObject(r)}refreshWrappedObject(e){Object.keys(e).forEach(t=>{this.wrapped[t]=e[t]}),this.wrapped.user=e.user,this.wrapped.instance=e.instance,this.wrapped.application=e.application??nanoid$3(10),this.wrapped.applicationName=e.applicationName,this.wrapped.pid=e.pid??e.process??Math.floor(1e10*Math.random()),this.wrapped.machine=e.machine,this.wrapped.environment=e.environment,this.wrapped.region=e.region,this.wrapped.windowId=e.windowId,this.wrapped.isLocal=e.isLocal??!0,this.wrapped.api=e.api,this.wrapped.service=e.service,this.wrapped.peerId=e.peerId}}const hideMethodSystemFlags=e=>({...e,flags:e.flags.metadata||{}});class ClientRepository{logger;API;servers={};myServer;methodsCount={};callbacks=CallbackRegistryFactory();constructor(e,t){this.logger=e,this.API=t;const r=this.API.instance.peerId;this.myServer={id:r,methods:{},instance:this.API.instance,wrapper:this.API.unwrappedInstance},this.servers[r]=this.myServer}addServer(e,t){this.logger.debug(`adding server ${t}`);const r=this.servers[t];if(r)return r.id;const n=new InstanceWrapper(this.API,e),i={id:t,methods:{},instance:n.unwrap(),wrapper:n};return this.servers[t]=i,this.callbacks.execute("onServerAdded",i.instance),t}removeServerById(e,t){const r=this.servers[e];r?(this.logger.debug(`removing server ${e}`),Object.keys(r.methods).forEach(t=>{this.removeServerMethod(e,t)}),delete this.servers[e],this.callbacks.execute("onServerRemoved",r.instance,t)):this.logger.warn(`not aware of server ${e}, my state ${JSON.stringify(Object.keys(this.servers))}`)}addServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");if(r.methods[t.id])return;const n=this.createMethodIdentifier(t),i=this,o={identifier:n,gatewayId:t.id,name:t.name,displayName:t.display_name,description:t.description,version:t.version,objectTypes:t.object_types||[],accepts:t.input_signature,returns:t.result_signature,supportsStreaming:void 0!==t.flags&&t.flags.streaming,flags:t.flags??{},getServers:()=>i.getServersByMethod(n)};o.object_types=o.objectTypes,o.display_name=o.displayName,o.version=o.version,r.methods[t.id]=o;const s=hideMethodSystemFlags(o);return this.methodsCount[n]||(this.methodsCount[n]=0,this.callbacks.execute("onMethodAdded",s)),this.methodsCount[n]=this.methodsCount[n]+1,this.callbacks.execute("onServerMethodAdded",r.instance,s),o}removeServerMethod(e,t){const r=this.servers[e];if(!r)throw new Error("server does not exists");const n=r.methods[t];delete r.methods[t];const i=hideMethodSystemFlags(n);this.methodsCount[n.identifier]=this.methodsCount[n.identifier]-1,0===this.methodsCount[n.identifier]&&this.callbacks.execute("onMethodRemoved",i),this.callbacks.execute("onServerMethodRemoved",r.instance,i)}getMethods(){return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags)}getServers(){return Object.values(this.servers).map(this.hideServerMethodSystemFlags)}onServerAdded(e){const t=this.callbacks.add("onServerAdded",e),r=this.getServers().map(e=>e.instance);return this.returnUnsubWithDelayedReplay(t,r,e)}onMethodAdded(e){const t=this.callbacks.add("onMethodAdded",e),r=this.getMethods();return this.returnUnsubWithDelayedReplay(t,r,e)}onServerMethodAdded(e){const t=this.callbacks.add("onServerMethodAdded",e);let r=!1;const n=this.getServers();return setTimeout(()=>{n.forEach(t=>{const n=t.methods;Object.keys(n).forEach(i=>{r||e(t.instance,n[i])})})},0),()=>{r=!0,t()}}onMethodRemoved(e){return this.callbacks.add("onMethodRemoved",e)}onServerRemoved(e){return this.callbacks.add("onServerRemoved",e)}onServerMethodRemoved(e){return this.callbacks.add("onServerMethodRemoved",e)}getServerById(e){if(this.servers[e])return this.hideServerMethodSystemFlags(this.servers[e])}reset(){Object.keys(this.servers).forEach(e=>{this.removeServerById(e,"reset")}),this.servers={[this.myServer.id]:this.myServer},this.methodsCount={}}createMethodIdentifier(e){const t=e.input_signature??"",r=e.result_signature??"";return(e.name+t+r).toLowerCase()}getServersByMethod(e){const t=[];return Object.values(this.servers).forEach(r=>{Object.values(r.methods).forEach(n=>{n.identifier===e&&t.push(r.instance)})}),t}returnUnsubWithDelayedReplay(e,t,r){let n=!1;return setTimeout(()=>{t.forEach(e=>{n||r(e)})},0),()=>{n=!0,e()}}hideServerMethodSystemFlags(e){const t={};return Object.entries(e.methods).forEach(([e,r])=>{t[e]=hideMethodSystemFlags(r)}),{...e,methods:t}}extractMethodsFromServers(e){return Object.values(e).reduce((e,t)=>[...e,...Object.values(t.methods)],[])}}class ServerRepository{nextId=0;methods=[];add(e){return e.repoId=String(this.nextId),this.nextId+=1,this.methods.push(e),e}remove(e){if("string"!=typeof e)return new TypeError("Expecting a string");this.methods=this.methods.filter(t=>t.repoId!==e)}getById(e){if("string"==typeof e)return this.methods.find(t=>t.repoId===e)}getList(){return this.methods.map(e=>e)}length(){return this.methods.length}reset(){this.methods=[]}}const SUBSCRIPTION_REQUEST="onSubscriptionRequest",SUBSCRIPTION_ADDED="onSubscriptionAdded",SUBSCRIPTION_REMOVED="onSubscriptionRemoved";class ServerStreaming{session;repository;serverRepository;logger;ERR_URI_SUBSCRIPTION_FAILED="com.tick42.agm.errors.subscription.failure";callbacks=CallbackRegistryFactory();nextStreamId=0;constructor(e,t,r,n){this.session=e,this.repository=t,this.serverRepository=r,this.logger=n,e.on("add-interest",e=>{this.handleAddInterest(e)}),e.on("remove-interest",e=>{this.handleRemoveInterest(e)})}acceptRequestOnBranch(e,t,r){if("string"!=typeof r&&(r=""),"object"!=typeof t.protocolState.subscriptionsMap)throw new TypeError("The streaming method is missing its subscriptions.");if(!Array.isArray(t.protocolState.branchKeyToStreamIdMap))throw new TypeError("The streaming method is missing its branches.");const n=this.getStreamId(t,r),i=e.msg.subscription_id,o={id:i,arguments:e.arguments,instance:e.instance,branchKey:r,streamId:n,subscribeMsg:e.msg};t.protocolState.subscriptionsMap[i]=o,this.session.sendFireAndForget({type:"accepted",subscription_id:i,stream_id:n}).catch(e=>{this.logger.warn(`Failed to send accepted message for subscription ${i}: ${JSON.stringify(e)}`)}),this.callbacks.execute(SUBSCRIPTION_ADDED,o,t)}rejectRequest(e,t,r){"string"!=typeof r&&(r=""),this.sendSubscriptionFailed("Subscription rejected by user. "+r,e.msg.subscription_id)}pushData(e,t,r){if("object"!=typeof e||!Array.isArray(e.protocolState.branchKeyToStreamIdMap))return;if("object"!=typeof t)throw new Error("Invalid arguments. Data must be an object.");"string"==typeof r?r=[r]:(!Array.isArray(r)||r.length<=0)&&(r=[]);const n=e.protocolState.branchKeyToStreamIdMap.filter(e=>!r||0===r.length||r.indexOf(e.key)>=0).map(e=>e.streamId);n.forEach(e=>{const r={type:"publish",stream_id:e,data:t};this.session.sendFireAndForget(r).catch(t=>{this.logger.warn(`Failed to send publish message for stream ${e}: ${JSON.stringify(t)}`)})})}pushDataToSingle(e,t,r){if("object"!=typeof r)throw new Error("Invalid arguments. Data must be an object.");const n={type:"post",subscription_id:t.id,data:r};this.session.sendFireAndForget(n).catch(e=>{this.logger.warn(`Failed to send post message for subscription ${t.id}: ${JSON.stringify(e)}`)})}closeSingleSubscription(e,t){e.protocolState.subscriptionsMap&&delete e.protocolState.subscriptionsMap[t.id];const r={type:"drop-subscription",subscription_id:t.id,reason:"Server dropping a single subscription"};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${t.id}: ${JSON.stringify(e)}`)}),t.instance,this.callbacks.execute(SUBSCRIPTION_REMOVED,t,e)}closeMultipleSubscriptions(e,t){if("object"!=typeof e||"object"!=typeof e.protocolState.subscriptionsMap)return;if(!e.protocolState.subscriptionsMap)return;const r=e.protocolState.subscriptionsMap;let n=Object.keys(r).map(e=>r[e]);"string"==typeof t&&(n=n.filter(e=>e.branchKey===t)),n.forEach(e=>{delete r[e.id];const t={type:"drop-subscription",subscription_id:e.id,reason:"Server dropping all subscriptions on stream_id: "+e.streamId};this.session.sendFireAndForget(t).catch(t=>{this.logger.warn(`Failed to send drop-subscription message for subscription ${e.id}: ${JSON.stringify(t)}`)})})}getSubscriptionList(e,t){if("object"!=typeof e)return[];let r=[];if(!e.protocolState.subscriptionsMap)return[];const n=e.protocolState.subscriptionsMap,i=Object.keys(n).map(e=>n[e]);return r="string"!=typeof t?i:i.filter(e=>e.branchKey===t),r}getBranchList(e){if("object"!=typeof e)return[];if(!e.protocolState.subscriptionsMap)return[];const t=e.protocolState.subscriptionsMap,r=Object.keys(t).map(e=>t[e]),n=[];return r.forEach(e=>{let t="";"object"==typeof e&&"string"==typeof e.branchKey&&(t=e.branchKey),-1===n.indexOf(t)&&n.push(t)}),n}onSubAdded(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED,e)}onSubRequest(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST,e)}onSubRemoved(e){this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED,e)}handleRemoveInterest(e){const t=this.serverRepository.getById(e.method_id);if("string"!=typeof e.subscription_id||"object"!=typeof t)return;if(!t.protocolState.subscriptionsMap)return;if("object"!=typeof t.protocolState.subscriptionsMap[e.subscription_id])return;const r=t.protocolState.subscriptionsMap[e.subscription_id];delete t.protocolState.subscriptionsMap[e.subscription_id],this.callbacks.execute(SUBSCRIPTION_REMOVED,r,t)}onSubscriptionLifetimeEvent(e,t){this.callbacks.add(e,t)}getNextStreamId(){return this.nextStreamId+++""}handleAddInterest(e){const t=this.repository.getServerById(e.caller_id),r=t?.instance??{},n={msg:e,arguments:e.arguments_kv||{},instance:r},i=this.serverRepository.getById(e.method_id);if(void 0===i){const t="No method with id "+e.method_id+" on this server.";return void this.sendSubscriptionFailed(t,e.subscription_id)}i.protocolState.subscriptionsMap&&i.protocolState.subscriptionsMap[e.subscription_id]?this.sendSubscriptionFailed("A subscription with id "+e.subscription_id+" already exists.",e.subscription_id):this.callbacks.execute(SUBSCRIPTION_REQUEST,n,i)}sendSubscriptionFailed(e,t){const r={type:"error",reason_uri:this.ERR_URI_SUBSCRIPTION_FAILED,reason:e,request_id:t};this.session.sendFireAndForget(r).catch(e=>{this.logger.warn(`Failed to send subscription failed message for subscription ${t}: ${JSON.stringify(e)}`)})}getStreamId(e,t){if("string"!=typeof t&&(t=""),!e.protocolState.branchKeyToStreamIdMap)throw new Error(`streaming ${e.definition.name} method without protocol state`);const r=e.protocolState.branchKeyToStreamIdMap.filter(e=>e.key===t)[0];let n=r?r.streamId:void 0;return"string"==typeof n&&""!==n||(n=this.getNextStreamId(),e.protocolState.branchKeyToStreamIdMap.push({key:t,streamId:n})),n}}class ServerProtocol{session;clientRepository;serverRepository;logger;callbacks=CallbackRegistryFactory();streaming;constructor(e,t,r,n){this.session=e,this.clientRepository=t,this.serverRepository=r,this.logger=n,this.streaming=new ServerStreaming(e,t,r,n.subLogger("streaming")),this.session.on("invoke",e=>this.handleInvokeMessage(e))}createStream(e){return e.protocolState.subscriptionsMap={},e.protocolState.branchKeyToStreamIdMap=[],this.register(e,!0)}register(e,t){const r=e.definition,n=Object.assign({},{metadata:r.flags??{}},{streaming:t||!1}),i={type:"register",methods:[{id:e.repoId,name:r.name,display_name:r.displayName,description:r.description,version:r.version,flags:n,object_types:r.objectTypes||r.object_types,input_signature:r.accepts,result_signature:r.returns,restrictions:void 0}]};return this.session.send(i,{methodId:e.repoId}).then(()=>{this.logger.debug("registered method "+e.definition.name+" with id "+e.repoId)}).catch(t=>{throw this.logger.warn(`failed to register method ${e.definition.name} with id ${e.repoId} - ${JSON.stringify(t)}`),t})}onInvoked(e){this.callbacks.add("onInvoked",e)}methodInvocationResult(e,t,r,n){let i;i=r||""===r?{type:"error",request_id:t,reason_uri:"agm.errors.client_error",reason:r,context:n,peer_id:void 0}:{type:"yield",invocation_id:t,peer_id:this.session.peerId,result:n,request_id:void 0},this.session.sendFireAndForget(i).catch(r=>{this.logger.warn(`Failed to send method invocation result for method ${e.definition.name} invocation ${t} - ${JSON.stringify(r)}`)})}async unregister(e){const t={type:"unregister",methods:[e.repoId]};await this.session.send(t)}getBranchList(e){return this.streaming.getBranchList(e)}getSubscriptionList(e,t){return this.streaming.getSubscriptionList(e,t)}closeAllSubscriptions(e,t){this.streaming.closeMultipleSubscriptions(e,t)}pushData(e,t,r){this.streaming.pushData(e,t,r)}pushDataToSingle(e,t,r){this.streaming.pushDataToSingle(e,t,r)}closeSingleSubscription(e,t){this.streaming.closeSingleSubscription(e,t)}acceptRequestOnBranch(e,t,r){this.streaming.acceptRequestOnBranch(e,t,r)}rejectRequest(e,t,r){this.streaming.rejectRequest(e,t,r)}onSubRequest(e){this.streaming.onSubRequest(e)}onSubAdded(e){this.streaming.onSubAdded(e)}onSubRemoved(e){this.streaming.onSubRemoved(e)}handleInvokeMessage(e){const t=e.invocation_id,r=e.caller_id,n=e.method_id,i=e.arguments_kv,o=this.serverRepository.getList().filter(e=>e.repoId===n)[0];if(void 0===o)return;const s=this.clientRepository.getServerById(r)?.instance,a={args:i,instance:s};this.callbacks.execute("onInvoked",o,t,a)}}class UserSubscription{repository;subscriptionData;get requestArguments(){return this.subscriptionData.params.arguments||{}}get servers(){return this.subscriptionData.trackedServers.reduce((e,t)=>{if(t.subscriptionId){const r=this.repository.getServerById(t.serverId)?.instance;r&&e.push(r)}return e},[])}get serverInstance(){return this.servers[0]}get stream(){return this.subscriptionData.method}constructor(e,t){this.repository=e,this.subscriptionData=t}onData(e){if("function"!=typeof e)throw new TypeError("The data callback must be a function.");this.subscriptionData.handlers.onData.push(e),1===this.subscriptionData.handlers.onData.length&&this.subscriptionData.queued.data.length>0&&this.subscriptionData.queued.data.forEach(t=>{e(t)})}onClosed(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onClosed.push(e)}onFailed(e){}onConnected(e){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.subscriptionData.handlers.onConnected.push(e)}close(){this.subscriptionData.close()}setNewSubscription(e){this.subscriptionData=e}}class TimedCache{config;cache=[];timeoutIds=[];constructor(e){this.config=e}add(e){const t=nanoid$3(10);this.cache.push({id:t,element:e});const r=setTimeout(()=>{const e=this.cache.findIndex(e=>e.id===t);e<0||this.cache.splice(e,1)},this.config.ELEMENT_TTL_MS);this.timeoutIds.push(r)}flush(){const e=this.cache.map(e=>e.element);return this.timeoutIds.forEach(e=>clearInterval(e)),this.cache=[],this.timeoutIds=[],e}}const STATUS_AWAITING_ACCEPT="awaitingAccept",STATUS_SUBSCRIBED="subscribed",ERR_MSG_SUB_FAILED="Subscription failed.",ERR_MSG_SUB_REJECTED="Subscription rejected.",ON_CLOSE_MSG_SERVER_INIT="ServerInitiated",ON_CLOSE_MSG_CLIENT_INIT="ClientInitiated";class ClientStreaming{session;repository;logger;subscriptionsList={};timedCache=new TimedCache({ELEMENT_TTL_MS:1e4});subscriptionIdToLocalKeyMap={};nextSubLocalKey=0;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("subscribed",this.handleSubscribed),e.on("event",this.handleEventData),e.on("subscription-cancelled",this.handleSubscriptionCancelled)}subscribe(e,t,r,n,i,o){if(0===r.length)return void i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED+" No available servers matched the target params."});const s=this.getNextSubscriptionLocalKey(),a=this.registerSubscription(s,e,t,n,i,t.methodResponseTimeout||1e4,o);"object"==typeof a?r.forEach(r=>{const n=r.server.id,i=r.methods.find(t=>t.name===e.name);if(!i)return void this.logger.error(`can not find method ${e.name} for target ${r.server.id}`);a.trackedServers.push({serverId:n,subscriptionId:void 0});const o={type:"subscribe",server_id:n,method_id:i.gatewayId,arguments_kv:t.arguments};this.session.send(o,{serverId:n,subLocalKey:s}).then(e=>this.handleSubscribed(e)).catch(e=>this.handleErrorSubscribing(e))}):i({method:e,called_with:t.arguments,message:ERR_MSG_SUB_FAILED+" Unable to register the user callbacks."})}drainSubscriptions(){const e=Object.values(this.subscriptionsList);return this.subscriptionsList={},this.subscriptionIdToLocalKeyMap={},e}drainSubscriptionsCache(){return this.timedCache.flush()}getNextSubscriptionLocalKey(){const e=this.nextSubLocalKey;return this.nextSubLocalKey+=1,e}registerSubscription(e,t,r,n,i,o,s){const a={localKey:e,status:STATUS_AWAITING_ACCEPT,method:t,params:r,success:n,error:i,trackedServers:[],handlers:{onData:s?.handlers.onData||[],onClosed:s?.handlers.onClosed||[],onConnected:s?.handlers.onConnected||[]},queued:{data:[],closers:[]},timeoutId:void 0,close:()=>this.closeSubscription(e),subscription:s?.subscription};return s||(r.onData&&a.handlers.onData.push(r.onData),r.onClosed&&a.handlers.onClosed.push(r.onClosed),r.onConnected&&a.handlers.onConnected.push(r.onConnected)),this.subscriptionsList[e]=a,a.timeoutId=setTimeout(()=>{if(void 0===this.subscriptionsList[e])return;const n=this.subscriptionsList[e];n.status===STATUS_AWAITING_ACCEPT?(i({method:t,called_with:r.arguments,message:ERR_MSG_SUB_FAILED+" Subscription attempt timed out after "+o+" ms."}),delete this.subscriptionsList[e]):n.status===STATUS_SUBSCRIBED&&n.trackedServers.length>0&&(n.trackedServers=n.trackedServers.filter(e=>void 0!==e.subscriptionId),delete n.timeoutId,n.trackedServers.length<=0&&(this.callOnClosedHandlers(n),delete this.subscriptionsList[e]))},o),a}handleErrorSubscribing=e=>{const t=e._tag,r=t.subLocalKey,n=this.subscriptionsList[r];if("object"==typeof n&&(n.trackedServers=n.trackedServers.filter(e=>e.serverId!==t.serverId),n.trackedServers.length<=0)){if(clearTimeout(n.timeoutId),n.status===STATUS_AWAITING_ACCEPT){const t="string"==typeof e.reason&&""!==e.reason?' Publisher said "'+e.reason+'".':" No reason given.",r="object"==typeof n.params.arguments?JSON.stringify(n.params.arguments):"{}";n.error({message:ERR_MSG_SUB_REJECTED+t+" Called with:"+r,called_with:n.params.arguments,method:n.method})}else n.status===STATUS_SUBSCRIBED&&this.callOnClosedHandlers(n);delete this.subscriptionsList[r]}};handleSubscribed=e=>{const t=e._tag.subLocalKey,r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=e._tag.serverId,i=r.trackedServers.filter(e=>e.serverId===n)[0];if("object"!=typeof i)return;i.subscriptionId=e.subscription_id,this.subscriptionIdToLocalKeyMap[e.subscription_id]=t;const o=r.status===STATUS_AWAITING_ACCEPT;if(r.status=STATUS_SUBSCRIBED,o){let e=!1,t=r.subscription;t?(t.setNewSubscription(r),r.success(t),e=!0):(t=new UserSubscription(this.repository,r),r.subscription=t,r.success(t));for(const n of r.handlers.onConnected)try{n(t.serverInstance,e)}catch(e){}}};handleEventData=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.filter(t=>t.subscriptionId===e.subscription_id);if(1!==n.length)return;const i=e.oob,o=n[0].serverId,s=this.repository.getServerById(o),a=()=>({data:e.data,server:s?.instance??{},requestArguments:r.params.arguments,message:void 0,private:i}),c=r.handlers.onData,l=r.queued.data;c.length>0?c.forEach(e=>{"function"==typeof e&&e(a())}):l.push(a())};handleSubscriptionCancelled=e=>{const t=this.subscriptionIdToLocalKeyMap[e.subscription_id];if(void 0===t)return;const r=this.subscriptionsList[t];if("object"!=typeof r)return;const n=r.trackedServers.length-1;r.trackedServers=r.trackedServers.filter(t=>t.subscriptionId!==e.subscription_id||(r.queued.closers.push(t.serverId),!1)),r.trackedServers.length===n&&(r.trackedServers.length<=0&&(this.timedCache.add(r),clearTimeout(r.timeoutId),this.callOnClosedHandlers(r),delete this.subscriptionsList[t]),delete this.subscriptionIdToLocalKeyMap[e.subscription_id])};callOnClosedHandlers(e,t){const r=e.queued.closers.length,n=r>0?e.queued.closers[r-1]:null;let i;void 0!==n&&"string"==typeof n&&(i=this.repository.getServerById(n)?.instance??{}),e.handlers.onClosed.forEach(r=>{"function"==typeof r&&r({message:t||ON_CLOSE_MSG_SERVER_INIT,requestArguments:e.params.arguments||{},server:i,stream:e.method})})}closeSubscription(e){const t=this.subscriptionsList[e];"object"==typeof t&&(t.trackedServers.forEach(e=>{void 0!==e.subscriptionId&&(t.queued.closers.push(e.serverId),this.session.sendFireAndForget({type:"unsubscribe",subscription_id:e.subscriptionId,reason_uri:"",reason:ON_CLOSE_MSG_CLIENT_INIT}).catch(t=>{this.logger.warn(`Error sending unsubscribe for subscription id ${e.subscriptionId}: ${JSON.stringify(t)}`)}),delete this.subscriptionIdToLocalKeyMap[e.subscriptionId])}),t.trackedServers=[],this.callOnClosedHandlers(t,ON_CLOSE_MSG_CLIENT_INIT),delete this.subscriptionsList[e])}}class ClientProtocol{session;repository;logger;streaming;constructor(e,t,r){this.session=e,this.repository=t,this.logger=r,e.on("peer-added",e=>this.handlePeerAdded(e)),e.on("peer-removed",e=>this.handlePeerRemoved(e)),e.on("methods-added",e=>this.handleMethodsAddedMessage(e)),e.on("methods-removed",e=>this.handleMethodsRemovedMessage(e)),this.streaming=new ClientStreaming(e,t,r)}subscribe(e,t,r,n,i,o){this.streaming.subscribe(e,t,r,n,i,o)}invoke(e,t,r,n){const i=n.id,o={type:"call",server_id:i,method_id:t.gatewayId,arguments_kv:r};return this.session.send(o,{invocationId:e,serverId:i}).then(e=>this.handleResultMessage(e)).catch(e=>this.handleInvocationError(e))}drainSubscriptions(){return this.streaming.drainSubscriptions()}drainSubscriptionsCache(){return this.streaming.drainSubscriptionsCache()}handlePeerAdded(e){const t=e.new_peer_id,r=e.identity,n=!e.meta||e.meta.local,i=Number(r.process),o={machine:r.machine,pid:isNaN(i)?r.process:i,instance:r.instance,application:r.application,applicationName:r.applicationName,environment:r.environment,region:r.region,user:r.user,windowId:r.windowId,peerId:t,api:r.api,isLocal:n};this.repository.addServer(o,t)}handlePeerRemoved(e){const t=e.removed_id,r=e.reason;this.repository.removeServerById(t,r)}handleMethodsAddedMessage(e){const t=e.server_id;e.methods.forEach(e=>{this.repository.addServerMethod(t,e)})}handleMethodsRemovedMessage(e){const t=e.server_id,r=e.methods,n=this.repository.getServerById(t);if(n){Object.keys(n.methods).forEach(e=>{const i=n.methods[e];r.indexOf(i.gatewayId)>-1&&this.repository.removeServerMethod(t,e)})}}handleResultMessage(e){const t=e._tag.invocationId,r=e.result,n=e._tag.serverId,i=this.repository.getServerById(n);return{invocationId:t,result:r,instance:i?.instance,status:InvokeStatus.Success,message:""}}handleInvocationError(e){if(this.logger.debug(`handle invocation error ${JSON.stringify(e)}`),"_tag"in e){const t=e._tag.invocationId,r=e._tag.serverId,n=this.repository.getServerById(r),i=e.reason;return{invocationId:t,result:e.context,instance:n?.instance,status:InvokeStatus.Error,message:i}}return{invocationId:"",message:e.message,status:InvokeStatus.Error,error:e}}}function gW3ProtocolFactory(e,t,r,n,i,o){const s=i.logger.subLogger("gw3-protocol");let a;const c=new Promise(e=>{a=e}),l=t.domain("agm",["subscribed"]),u=new ServerProtocol(l,r,n,s.subLogger("server")),d=new ClientProtocol(l,r,s.subLogger("client"));return l.onJoined(i=>{r.addServer(e,t.peerId),i?async function(){s.info("reconnected - will replay registered methods and subscriptions"),d.drainSubscriptionsCache().forEach(e=>{const t=e.method,r=Object.assign({},e.params);s.info(`trying to soft-re-subscribe to method ${t.name}, with params: ${JSON.stringify(r)}`),o.client.subscribe(t,r,void 0,void 0,e).then(()=>s.info(`soft-subscribing to method ${t.name} DONE`)).catch(e=>s.warn(`subscribing to method ${t.name} failed: ${JSON.stringify(e)}}`))});const e=[],t=d.drainSubscriptions();for(const r of t){const t=r.method,n=Object.assign({},r.params);s.info(`trying to re-subscribe to method ${t.name}, with params: ${JSON.stringify(n)}`),e.push(o.client.subscribe(t,n,void 0,void 0,r).then(()=>s.info(`subscribing to method ${t.name} DONE`)))}const r=n.getList();n.reset();for(const t of r){const r=t.definition;t.stream?e.push(o.server.createStream(r,t.streamCallbacks,void 0,void 0,t.stream).then(()=>s.info(`subscribing to method ${r.name} DONE`)).catch(()=>s.warn(`subscribing to method ${r.name} FAILED`))):t?.theFunction?.userCallback?e.push(o.register(r,t.theFunction.userCallback).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`))):t?.theFunction?.userCallbackAsync&&e.push(o.registerAsync(r,t.theFunction.userCallbackAsync).then(()=>s.info(`registering method ${r.name} DONE`)).catch(()=>s.warn(`registering method ${r.name} FAILED`)))}await Promise.all(e),s.info("Interop is re-announced")}().then(()=>t.setLibReAnnounced({name:"interop"})).catch(e=>s.warn(`Error while re-announcing interop: ${JSON.stringify(e)}`)):a&&(a({client:d,server:u}),a=void 0)}),l.onLeft(()=>{r.reset()}),l.join(),c}class Interop{instance;readyPromise;client;server;unwrappedInstance;protocol;clientRepository;serverRepository;constructor(e){if(void 0===e)throw new Error("configuration is required");if(void 0===e.connection)throw new Error("configuration.connections is required");const t=e.connection;let r;if("number"!=typeof e.methodResponseTimeout&&(e.methodResponseTimeout=3e4),"number"!=typeof e.waitTimeoutMs&&(e.waitTimeoutMs=3e4),this.unwrappedInstance=new InstanceWrapper(this,void 0,t),this.instance=this.unwrappedInstance.unwrap(),this.clientRepository=new ClientRepository(e.logger.subLogger("cRep"),this),this.serverRepository=new ServerRepository,3!==t.protocolVersion)throw new Error(`protocol ${t.protocolVersion} not supported`);r=gW3ProtocolFactory(this.instance,t,this.clientRepository,this.serverRepository,e,this),this.readyPromise=r.then(t=>(this.protocol=t,this.client=new Client(this.protocol,this.clientRepository,this.instance,e),this.server=new Server(this.protocol,this.serverRepository),this))}ready(){return this.readyPromise}serverRemoved(e){return this.client.serverRemoved(e)}serverAdded(e){return this.client.serverAdded(e)}serverMethodRemoved(e){return this.client.serverMethodRemoved(e)}serverMethodAdded(e){return this.client.serverMethodAdded(e)}methodRemoved(e){return this.client.methodRemoved(e)}methodAdded(e){return this.client.methodAdded(e)}methodsForInstance(e){return this.client.methodsForInstance(e)}methods(e){return this.client.methods(e)}servers(e){return this.client.servers(e)}subscribe(e,t,r,n){return this.client.subscribe(e,t,r,n)}createStream(e,t,r,n){return this.server.createStream(e,t,r,n)}unregister(e){return this.server.unregister(e)}registerAsync(e,t){return this.server.registerAsync(e,t)}register(e,t){return this.server.register(e,t)}invoke(e,t,r,n,i,o){return this.client.invoke(e,t,r,n,i,o)}waitForMethod(e){const t=new PromiseWrapper$1,r=this.client.methodAdded(n=>{n.name===e&&(r(),t.resolve(n))});return t.promise}}const successMessages=["subscribed","success"];class MessageBus{connection;logger;peerId;session;subscriptions;readyPromise;constructor(e,t){this.connection=e,this.logger=t,this.peerId=e.peerId,this.subscriptions=[],this.session=e.domain("bus",successMessages),this.readyPromise=this.session.join(),this.readyPromise.then(()=>{this.watchOnEvent()})}ready(){return this.readyPromise}publish=(e,t,r)=>{const{routingKey:n,target:i}=r||{},o=this.removeEmptyValues({type:"publish",topic:e,data:t,peer_id:this.peerId,routing_key:n,target_identity:i});this.session.send(o).catch(t=>{this.logger.error(`Failed to publish message to topic ${e} with routing key ${n} for ${JSON.stringify(i)}: ${JSON.stringify(t)}`)})};subscribe=(e,t,r)=>new Promise((n,i)=>{const{routingKey:o,target:s}=r||{},a=this.removeEmptyValues({type:"subscribe",topic:e,peer_id:this.peerId,routing_key:o,source:s});this.session.send(a).then(r=>{const{subscription_id:i}=r;this.subscriptions.push({subscription_id:i,topic:e,callback:t,source:s}),n({unsubscribe:()=>(this.session.send({type:"unsubscribe",subscription_id:i,peer_id:this.peerId}).then(()=>{this.subscriptions=this.subscriptions.filter(e=>e.subscription_id!==i)}).catch(e=>{this.logger.warn(`Failed to send unsubscribe request for ${i}: ${JSON.stringify(e)}`)}),Promise.resolve())})}).catch(e=>i(e))});watchOnEvent=()=>{this.session.on("event",e=>{const{data:t,subscription_id:r}=e,n=e["publisher-identity"],i=this.subscriptions.find(e=>e.subscription_id===r);i&&(i.source?this.keysMatch(i.source,n)&&i.callback(t,i.topic,n):i.callback(t,i.topic,n))})};removeEmptyValues(e){const t={};return Object.keys(e).forEach(r=>{void 0!==e[r]&&null!==e[r]&&(t[r]=e[r])}),t}keysMatch(e,t){const r=Object.keys(e);let n=!0;return r.forEach(r=>{e[r]!==t[r]&&(n=!1)}),n}}const IOConnectCoreFactory=(e,t)=>{const r="object"==typeof window?window.iodesktop??window.glue42gd:void 0,n="object"==typeof window?window.gdPreloadPromise??Promise.resolve():Promise.resolve(),i=timer("glue"),o=prepareConfig(e=e||{},t=t||{},r);let s,a,c,l,u,d,h;const p={};function g(e,t,r){h=c.canPublish("trace"),h&&c.trace(`registering ${e} module`);const n=n=>{if(t.initTime=r.stop(),t.initEndTime=r.endTime,t.marks=r.marks,!h)return;const i=n?`${e} failed - ${n.message}`:`${e} is ready - ${r.endTime-r.startTime}`;c.trace(i)};t.initStartTime=r.startTime,t.ready?t.ready().then(()=>{n()}).catch(e=>{const t="string"==typeof e?new Error(e):e;n(t)}):n(),Array.isArray(e)||(e=[e]),e.forEach(e=>{p[e]=t,IOConnectCoreFactory[e]=t})}function m(){const e=timer("metrics"),t=o.metrics,n=r?.getMetricsPublishingEnabled,i=o.connection.identity,a=n||(()=>!0),u=("boolean"!=typeof t&&t.disableAutoAppSystem)??!1;return l=metrics({connection:t?s:void 0,logger:c.subLogger("metrics"),canUpdateMetric:a,system:"Glue42",service:i?.service??r?.applicationName??o.application,instance:i?.instance??i?.windowId??nanoid$3(10),disableAutoAppSystem:u,pagePerformanceMetrics:"boolean"!=typeof t?t?.pagePerformanceMetrics:void 0}),g("metrics",l,e),Promise.resolve()}function f(){const e=timer("interop"),t={connection:s,logger:c.subLogger("interop")};return a=new Interop(t),Logger.Interop=a,g(["interop","agm"],a,e),Promise.resolve()}function y(){const e=o.activities&&3===s.protocolVersion;if(o.contexts||e){const e=timer("contexts");u=new ContextsModule({connection:s,logger:c.subLogger("contexts"),trackAllContexts:"object"==typeof o.contexts&&o.contexts.trackAllContexts,reAnnounceKnownContexts:"object"==typeof o.contexts&&o.contexts.reAnnounceKnownContexts,subscribeOnGet:"object"!=typeof o.contexts||o.contexts.subscribeOnGet,subscribeOnUpdate:"object"!=typeof o.contexts||o.contexts.subscribeOnUpdate,onlyReAnnounceSubscribedContexts:"object"!=typeof o.contexts||o.contexts.onlyReAnnounceSubscribedContexts}),g("contexts",u,e)}else{const e=s.replayer;e&&e.drain(ContextMessageReplaySpec.name)}return Promise.resolve()}async function $(){if(!o.bus)return Promise.resolve();const e=timer("bus");return d=new MessageBus(s,c.subLogger("bus")),g("bus",d,e),Promise.resolve()}function b(e){try{return e.forEach(e=>{!function(e,t){const r=timer(e),n=t(p);n&&g(e,n,r)}(e.name,e.create)}),Promise.resolve()}catch(e){return Promise.reject(e)}}return n.then(function(){const e=timer("logger");return c=new Logger(`${o.connection.identity?.application}`,void 0,o.customLogger),c.consoleLevel(o.logger.console),c.publishLevel(o.logger.publish),c.canPublish("debug")&&c.debug("initializing glue..."),g("logger",c,e),Promise.resolve(void 0)}).then(function(){const e=timer("connection");s=new Connection(o.connection,c.subLogger("connection"));let t=Promise.resolve(o.auth);return o.connection&&!o.auth&&(r?t=r.getGWToken().then(e=>({gatewayToken:e})):"undefined"!=typeof window&&window?.glue42electron?"string"==typeof window.glue42electron.gwToken&&(t=Promise.resolve({gatewayToken:window.glue42electron.gwToken})):t=Promise.reject("You need to provide auth information")),t.then(t=>{let r;if(e.mark("auth-promise-resolved"),"[object Object]"!==Object.prototype.toString.call(t))throw new Error("Invalid auth object - "+JSON.stringify(t));return r=t,s.login(r)}).then(()=>(g("connection",s,e),o)).catch(e=>{throw s&&s.logout(),e})}).then(()=>Promise.all([m(),f(),y(),$()])).then(()=>a.readyPromise).then(()=>async function(){const t="T42.ACS.RegisterInstance";if(Utils.isNode()&&"undefined"==="undefined".env._GD_STARTING_CONTEXT_&&void 0!==e?.application&&a.methods({name:t}).length>0)try{await a.invoke(t,{appName:e?.application,pid:process.pid})}catch(e){const t=e;c.error(`Cannot register as an instance: ${JSON.stringify(t.message)}`)}}()).then(()=>b(o.libs||[])).then(function(){const e=Object.keys(p).map(e=>{const t=p[e];return t.ready?t.ready():Promise.resolve()});return Promise.all(e)}).then(function(){const n={coreVersion:version$2,version:o.version};i.stop();const h={feedback:e=>{a&&a.invoke("T42.ACS.Feedback",e,"best")},info:n,logger:c,interop:a,agm:a,connection:s,metrics:l,contexts:u,bus:d,version:o.version,userConfig:e,done:()=>(c?.info("done called by user..."),s.logout())};if(h.performance={get glueVer(){return o.version},get glueConfig(){return JSON.stringify(e)},get browser(){return window.performance.timing.toJSON()},get memory(){return window.performance.memory},get initTimes(){const e=getAllTimers();return Object.keys(e).map(t=>{const r=e[t];return{name:t,duration:r.endTime-r.startTime,marks:r.marks,startTime:r.startTime,endTime:r.endTime}})}},Object.keys(p).forEach(e=>{const t=p[e];h[e]=t}),h.config={},Object.keys(o).forEach(e=>{h.config[e]=o[e]}),t&&t.extOptions&&Object.keys(t.extOptions).forEach(e=>{h.config[e]=t?.extOptions[e]}),t?.enrichGlue&&t.enrichGlue(h),r&&r.updatePerfData&&r.updatePerfData(h.performance),h.agm){const e=(e,t,r)=>function(){return h.logger.warn(`glue.js - 'glue.agm.${t}' method is deprecated, use 'glue.interop.${r}' instead.`),e.apply(h.agm,arguments)},t=h.agm;t.method_added=e(h.agm.methodAdded,"method_added","methodAdded"),t.method_removed=e(h.agm.methodRemoved,"method_removed","methodRemoved"),t.server_added=e(h.agm.serverAdded,"server_added","serverAdded"),t.server_method_aded=e(h.agm.serverMethodAdded,"server_method_aded","serverMethodAdded"),t.server_method_removed=e(h.agm.serverMethodRemoved,"server_method_removed","serverMethodRemoved")}return h}).catch(e=>Promise.reject({err:e,libs:p}))};"undefined"!=typeof window&&(window.IOConnectCore=IOConnectCoreFactory),IOConnectCoreFactory.version=version$2,IOConnectCoreFactory.default=IOConnectCoreFactory;const PromiseWrap=(e,t,r)=>new Promise((n,i)=>{let o=!0;const s=setTimeout(()=>{if(!o)return;o=!1;i(r||`Promise timeout hit: ${t}`)},t);e().then(e=>{o&&(o=!1,clearTimeout(s),n(e))}).catch(e=>{o&&(o=!1,clearTimeout(s),i(e))})}),PromisePlus=(e,t,r)=>new Promise((n,i)=>{const o=setTimeout(()=>{i(r||`Promise timeout hit: ${t}`)},t);new Promise(e).then(e=>{clearTimeout(o),n(e)}).catch(e=>{clearTimeout(o),i(e)})});var version$1="4.2.4";class GlueController{portsBridge;sessionStorage;_config;_systemGlue;_contextsTrackingGlue;_clientGlue;_systemStream;_workspacesStream;_platformClientWindowId;_systemSettings;constructor(e,t){this.portsBridge=e,this.sessionStorage=t}get logger(){return logger.get("glue.controller")}get workspaces(){return this._clientGlue.workspaces?this._clientGlue.workspaces:ioError.raiseError("Cannot access the Workspaces API")}get isWorkspacesEnabled(){return!!this._clientGlue.workspaces}get me(){return this._clientGlue.interop.instance}get platformVersion(){return version$1}get clientGlue(){return this._clientGlue}get contextsTrackingGlue(){return this._contextsTrackingGlue}get systemGlue(){return this._systemGlue}get platformWindowId(){return this._platformClientWindowId.slice()}async start(e){this._config=e;const t=this.sessionStorage.getSystemSettings();if(!t)return ioError.raiseError("Cannot initiate the glue controller, because the system settings are not defined");this._systemSettings=t,this._systemGlue=await this.initSystemGlue(e.browser),logger.setLogger(this._systemGlue.logger),this.logger?.debug(`system glue initialized successfully with config ${JSON.stringify(e.browser)}`),this._contextsTrackingGlue=await this.setUpCtxTracking(e),this.logger?.debug("glueController started successfully")}async initClientGlue(e,t,r,n){this.logger?.debug(`initializing client glue with config: ${JSON.stringify(e)}, factory: ${t?"custom":"default"}, isWorkspaceFrame: ${r}, platformApi: ${n?"provided":"none"}`);const i=await this.portsBridge.createInternalClient();this.registerClientWindow(r);const o={application:"Platform",gateway:{webPlatform:{port:i,windowId:this.platformWindowId}}},s=Object.assign({},e,o);return this._clientGlue=t?await t(s):await iOConnectBrowserFactory(s),this._clientGlue.webPlatform=n,this.logger?.debug("client glue initialized successfully"),this._clientGlue}async createPlatformSystemMethod(e){await this.createMethodAsync(GlueWebPlatformControlName,e)}async createPlatformSystemStream(){this._systemStream=await this.createStream(GlueWebPlatformStreamName)}async createSystemStream(e){return this.createStream(e)}async createWorkspacesStream(){this._workspacesStream=await this.createStream(GlueWebPlatformWorkspacesStreamName)}async createWorkspacesEventsReceiver(e){await this._systemGlue.interop.register(GlueWorkspacesEventsReceiverName,t=>e(t))}pushSystemMessage(e,t,r){if(!this._systemStream)return ioError.raiseError(`Cannot push data to domain: ${e}, because the system stream is not created`);this._systemStream.push({domain:e,operation:t,data:r})}pushWorkspacesMessage(e){if(!this._workspacesStream)return ioError.raiseError("Cannot push data to domain: workspaces, because the workspaces stream is not created");this._workspacesStream.push({data:e})}async callFrame(e,t,r){const n={operation:e.name,operationArguments:t},i=`Internal Platform->Frame Communication Error. Attempted calling workspace frame: ${r} for operation ${e.name} `;if(e.dataDecoder){const t=e.dataDecoder.run(n.operationArguments);if(!t.ok)return ioError.raiseError(`${i} OutBound validation failed: ${JSON.stringify(t.error)}`)}const o=GlueWorkspaceFrameClientControlName,s=await this.transmitMessage(o,n,i,{windowId:r},{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS});if(e.resultDecoder){const t=e.resultDecoder.run(s);if(!t.ok)return ioError.raiseError(`${i} Result validation failed: ${JSON.stringify(t.error)}`)}return s}async isFrameOperationSupported(e,t){try{return!0===(await this.callFrame({name:"operationCheck",execute:()=>Promise.resolve()},{operation:e},t)).isSupported}catch{return!1}}isValidWindowId(e){if(!e)return!1;return[...this.sessionStorage.getAllWindowsData(),...this.sessionStorage.getAllNonGlue()].some(t=>t.windowId===e)}async sendShutDownSignals(){const e=this.clientGlue.windows.list().filter(e=>e.id!==this.platformWindowId);await Promise.all(e.map(e=>e.close()));const t={domain:"system",operation:"platformShutdown"},r=`Internal Platform-> ${t.domain} Domain Communication Error. Attempted sending shutdown signal to all clients.`,n=this.getLocalServers().filter(t=>e.every(e=>e.id!==t.windowId)).map(e=>({instance:e.instance}));try{await this.transmitMessage(GlueClientControlName,t,r,n,{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS})}catch(e){console.warn("Failed to send shutdown signal to all clients",e)}}shutdown(){this.systemGlue.connection.logout(),this.contextsTrackingGlue?.connection.logout(),this.clientGlue.connection.logout()}async checkClientOperationSupport(e,t,r){try{return await this.callInstance(e,{name:"operationCheck",execute:async()=>{}},{operation:t.name},r)}catch(e){return{isSupported:!1}}}async callInstance(e,t,r,n,i){return this.callClient(e,t,r,n,"instance",i)}async callWindow(e,t,r,n,i){return this.callClient(e,t,r,n,"window",i)}async callClient(e,t,r,n,i="window",o){const s=t.name,a={domain:e,operation:s,data:r},c={...n,isLocal:!0},l=`Internal Platform-> ${e} Domain Communication Error. Attempted calling client ${i}: ${JSON.stringify(c)} for operation ${s}.`;if(t.dataDecoder){const e=t.dataDecoder.run(a.data);if(!e.ok)return ioError.raiseError(`${l} OutBound validation failed: ${JSON.stringify(e.error)}`)}const u=await this.transmitMessage(GlueClientControlName,a,l,c,{methodResponseTimeoutMs:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1,waitTimeoutMs:DEFAULT_WAIT_TIMEOUT_MS,...o});if(t.resultDecoder){const e=t.resultDecoder.run(u);if(!e.ok)return ioError.raiseError(`${l} Result validation failed when calling ${i}: ${JSON.stringify(c)} for operation ${s}: ${JSON.stringify(e.error)}`)}return u}setStartContext(e,t,r){return PromisePlus((n,i)=>{let o;const s=waitFor(2,()=>{n(),o()}),a=`___${r}___${e}`;(this._clientGlue.contexts.all().some(e=>e===a)?this.waitContextDestroy(a):Promise.resolve()).then(()=>this._clientGlue.contexts.subscribe(a,s)).then(e=>(o=e,this._systemGlue.contexts.set(a,t))).then(s).catch(i)},1e4,`Timed out waiting to set the ${r} context for: ${e}`)}waitContextDestroy(e){return new Promise((t,r)=>{let n=0;const i=setInterval(()=>{const o=this._clientGlue.contexts.all().some(t=>t===e);if(++n,!o)return clearInterval(i),void t();50===n&&(clearInterval(i),r(`Timed out waiting for context: ${e} to disappear`))},100)})}async clearContext(e,t){const r=`___${t}___${e}`,n=this._systemGlue.contexts.all().some(e=>e===r);n&&await this._systemGlue.contexts.destroy(r)}async preserveAllWorkspaceWindowsContext(e){const t=this.sessionStorage.pickWorkspaceClients(t=>t.workspaceId===e);for(const e of t){const t=await this._systemGlue.contexts.get(`___window___${e.windowId}`);t&&("object"!=typeof t||Object.keys(t).length)&&await this._systemGlue.contexts.set(`___window-hibernation___${e.windowId}`,t)}}async pullHibernatedContext(e){const t=`___window-hibernation___${e}`,r=this._systemGlue.contexts.all().some(e=>e===t);if(!r)return;const n=await this._systemGlue.contexts.get(t);return await this._systemGlue.contexts.destroy(t),n}getServers(){return this._clientGlue.interop.servers()}getLocalServers(){return this.getServers().filter(e=>e.isLocal)}subscribeForServerAdded(e){return this._clientGlue.interop.serverAdded(e)}subscribeForMethodAdded(e){return this._clientGlue.interop.methodAdded(e)}invokeMethod(e,t,r,n,i,o){return this._clientGlue.interop.invoke(e,t,r,n,i,o)}setContext(e,t){return this._systemGlue.contexts.set(e,t)}destroyContext(e){return this._systemGlue.contexts.destroy(e)}getAllContexts(){return this._clientGlue.contexts.all()}switchTransport(e,t){if("contextsTrack"===t)return this._contextsTrackingGlue?this._contextsTrackingGlue.connection.switchTransport(e):Promise.resolve({success:!0});return("system"===t?this._systemGlue:this._clientGlue).connection.switchTransport(e)}onDisconnected(e){return this._systemGlue.connection.disconnected(e)}getSystemGlueTransportName(){return this._systemGlue.connection.transport.name()}async importLayout(e){await this._clientGlue.layouts.import([e],"merge")}async getLayout(e){return await this._clientGlue.layouts.get(e,"Global")}async openWindow(e){this._clientGlue.windows.list().find(t=>t.name===e.name)&&(e.name=`${e.name}-${nanoid$5(7)}`);const t={context:e.context,top:e.bounds?.top,left:e.bounds?.left,width:e.bounds?.width,height:e.bounds?.height,layoutComponentId:e.layoutComponentId};return await this._clientGlue.windows.open(e.name,e.url,t)}async startApp(e){const t={waitForAGMReady:!1,top:e.bounds?.top,left:e.bounds?.left,width:e.bounds?.width,height:e.bounds?.height,layoutComponentId:e.layoutComponentId,channelId:e.channelId};return await this._clientGlue.appManager.application(e.name).start(e.context,t)}async getOrCreateWorkspaceFrame({bounds:e,layoutComponentId:t,frameId:r}){return r?await this.workspaces.getFrame(e=>e.id===r):await this.workspaces.createEmptyFrame({frameConfig:{bounds:e||void 0},layoutComponentId:t||void 0})}getAppNameByInstanceId(e){return this._clientGlue.interop.servers().find(t=>t.instance===e)?.application}getAllWindowNames(){return this._clientGlue.windows.list().map(e=>e.name)}getAllOpenedIds(){return this._clientGlue.windows.list().map(e=>e.id)}getAllOtherNonPlatformWindows(e){return this._clientGlue.windows.list().filter(t=>"Platform"!==t.name&&t.id!==e)}async getAllOpenedFrameIds(){return(await this.workspaces.getAllFrames()).map(e=>e.id)}getAllApplicationNames(){return this._clientGlue.appManager.applications().map(e=>e.name)}getAllApplications(){return this._clientGlue.appManager.applications()}getAllLayoutsSummaries(){return this._clientGlue.layouts.getAll("Global")}getAllWorkspacesSummaries(){return this._clientGlue.layouts.getAll("Workspace")}async getWorkspaceWindowById(e){return this._clientGlue.workspaces?.getWindow(t=>t.id===e)}getWindowById(e){return this._clientGlue.windows.list().find(t=>t.id===e)}async getAllWorkspacesFrames(){return await this.workspaces.getAllFrames()}async getWorkspacesByFrameId(e){return await this.workspaces.getAllWorkspaces(t=>t.frameId===e)}registerProvider(e){return this._clientGlue.search?this._clientGlue.search.registerProvider(e):ioError.raiseError("Cannot start the search provider for Glue42 Core Plus, because the Search API is missing")}async processServerApplicationsData(e){const t=e,r=await this._clientGlue.appManager.inMemory.import(t,"merge");r.errors&&r.errors.length&&r.errors.forEach(e=>{this.logger?.warn(`App: ${e.app} was not imported, because of error: ${e.error}`)})}async initSystemGlue(e){const t=await this.portsBridge.createInternalClient(),r=e?.systemLogger?.level??"warn",n=await IOConnectCoreFactory({application:"Platform-System",gateway:{webPlatform:{port:t}},logger:r,customLogger:e?.systemLogger?.customLogger,identity:{instance:this._systemSettings.systemInstanceId}});return this.logger?.debug("system glue initialized successfully"),n}async setUpCtxTracking(e){if(this._config.connection.preferred)return await this.initContextsTrackingGlue({reAnnounceKnownContexts:!0,trackAllContexts:!0},e)}async initContextsTrackingGlue(e,t){this.logger?.debug(`initializing contexts tracking glue with contexts settings - ${JSON.stringify(e)}`);const r=await this.portsBridge.createInternalClient(),n=await IOConnectCoreFactory({application:"Platform-Contexts-Track",gateway:{webPlatform:{port:r}},logger:t?.browser?.systemLogger?.level??"warn",customLogger:t?.browser?.systemLogger?.customLogger,contexts:e,identity:{instance:this._systemSettings.ctxTrackInstanceId}});return this.logger?.debug("contexts tracking glue initialized successfully"),n}registerClientWindow(e){const t=window.name?window.name:`g42-${nanoid$5(10)}`;if(e){const e=this.sessionStorage.getPlatformFrame();if(this._platformClientWindowId=e?e.windowId:t,!e){const e={windowId:this.platformWindowId,active:!0,isPlatform:!0};this.sessionStorage.saveFrameData(e)}return void(window.name=this.platformWindowId)}const r=this.sessionStorage.getWindowDataByName("Platform");this._platformClientWindowId=r?r.windowId:t,r||this.sessionStorage.saveWindowData({name:"Platform",windowId:this.platformWindowId}),window.name=this.platformWindowId}async createMethodAsync(e,t){await this._systemGlue.interop.registerAsync(e,t)}async createStream(e){return this._systemGlue.interop.createStream(e)}async transmitMessage(e,t,r,n,i){let o;try{if(o=await this._systemGlue.interop.invoke(e,t,n,i),!o)throw new Error(`${r} Received unsupported result from the client - empty result`);if(!Array.isArray(o.all_return_values)||0===o.all_return_values.length)throw new Error(`${r} Received unsupported result from the client - empty values collection`)}catch(e){if(e&&e.all_errors&&e.all_errors.length){const t=e.all_errors[0].message;return ioError.raiseError(`${r} -> Inner message: ${t}`)}return ioError.raiseError(`${r} -> Inner message: ${e.message}`)}return o.all_return_values[0].returned}}class PortsBridge{gateway;sessionStorage;windowsStateController;ioc;registry=CallbackRegistryFactory$2();transactionsController;allPorts={};allClients=[];unLoadStarted=!1;isPreferredActivated=!1;activePreferredTransportConfig;_communicationId;startUpPromise;startupResolve;_genericMessageHandler;_unloaderHandler;connectionConfig;constructor(e,t,r,n){this.gateway=e,this.sessionStorage=t,this.windowsStateController=r,this.ioc=n,this.transactionsController=this.ioc.transactionsController}get logger(){return logger.get("ports.bridge.controller")}shutdown(){window.removeEventListener("message",this._genericMessageHandler),window.removeEventListener("pagehide",this._unloaderHandler),this.registry.clear(),this.allPorts={},this.allClients=[],this.isPreferredActivated=!1,this.unLoadStarted=!1}async configure(e){this.connectionConfig=e.connection,this.startUpPromise=new Promise(e=>{this.startupResolve=e});const t=this.sessionStorage.getSystemSettings();if(!t)return ioError.raiseError("Cannot initiate the platform port bridge, because the system settings are not defined");this._communicationId=t.systemInstanceId,await this.gateway.start(e?.gateway,e?.user),this.setupListeners()}start(){this.startupResolve()}async createInternalClient(){const e=this.ioc.createMessageChannel();return await this.gateway.setupInternalClient(e.port1),e.port2}onClientUnloaded(e){return this.registry.add("client-unloaded",e)}async handleExtConnectionRequest(e,t){const r=e.glue42core;if(!!!r.parentWindowId){const e=r.clientId,t={windowId:e,name:e};await this.ioc.windowsController.processNewWindow(t)}await this.gateway.connectExtClient(t,(e,t)=>{this.removeClient({clientId:e},t)});const n=this.sessionStorage.getWindowDataByName("Platform")?.windowId,i={glue42core:{type:Glue42CoreMessageTypes.connectionAccepted.name,parentWindowId:n,appName:"ext-no-app",clientId:r.clientId,clientType:"child"}};this.allPorts[r.clientId]=t,t.postMessage(i)}setActivePreferredTransportConfig(e){"secondary"!==e.type?delete this.activePreferredTransportConfig:this.activePreferredTransportConfig=e}setPreferredActivated(){this.isPreferredActivated=!0}async switchAllClientsTransport(e){const t=Object.keys(this.allPorts).map(t=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.transportSwitchRequest.name,timeout:defaultClientPortRequestTimeoutMS,clientId:t,args:{switchSettings:e}}));await Promise.all(t)}async checkClientsPreferredLogic(){const e=Object.keys(this.allPorts).map(e=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.checkPreferredLogic.name,timeout:defaultClientPreferredLogicTestTimeoutMS,clientId:e}));try{return await Promise.all(e),{success:!0}}catch(e){return{success:!1}}}async checkClientsPreferredConnection(e){const t=Object.keys(this.allPorts).map(t=>this.sendClientPortRequest({type:Glue42CoreMessageTypes.checkPreferredConnection.name,args:{url:e},timeout:defaultClientPortRequestTimeoutMS,clientId:t}));try{return await Promise.all(t),{success:!0}}catch(e){return{success:!1}}}removeGwClient(e){const t=this.allClients.find(t=>t.bridgeInstanceId===e);t&&(this.allClients=this.allClients.filter(t=>t.bridgeInstanceId!==e),t.client.close(),this.allPorts[t.clientId]&&delete this.allPorts[t.clientId])}unloader(){this.unLoadStarted=!0;for(const e in this.allPorts)this.allPorts[e].postMessage({type:"platformUnload"});this.sessionStorage.handlePlatformUnloadCleanup()}genericMessageHandler(e){if(e.data?.type===FDC3HelloRequestType)return void this.processFDC3WebRequest(e);const t=e.data?.glue42core;t&&!this.unLoadStarted&&(t.type!==Glue42CoreMessageTypes.connectionRequest.name?t.type!==Glue42CoreMessageTypes.platformPing.name?t.type!==Glue42CoreMessageTypes.parentPing.name||this.startUpPromise.then(()=>this.handleParentPing(e.source,e.origin)):this.startUpPromise.then(()=>this.handlePlatformPing(e.source,e.origin)):this.startUpPromise.then(()=>this.handleRemoteConnectionRequest(e.source,e.origin,t.clientId,t.clientType,t.bridgeInstanceId,t.selfAssignedWindowId)))}async handleRemoteConnectionRequest(e,t,r,n,i,o){if(checkIsOriginBlocked(t,this.connectionConfig.blockList)){const r=`Origin '${t}' is blocked by the Platform.`;return this.rejectClientConnection(e,r,t)}const s=this.ioc.createMessageChannel(),a=await this.gateway.connectClient(s.port1);this.setupGwClientPort({client:a,clientId:r,clientPort:s.port1}),this.allClients.push({client:a,bridgeInstanceId:i,clientId:r,source:e});const c=this.sessionStorage.getBridgeInstanceData(i),l=c?.appName,u=this.sessionStorage.getWindowDataByName("Platform")?.windowId,d={glue42core:{type:Glue42CoreMessageTypes.connectionAccepted.name,port:s.port2,connectionProtocolVersion:connectionProtocolVersion,communicationId:this._communicationId,isPreferredActivated:this.isPreferredActivated,parentWindowId:u,appName:l,clientId:r,clientType:n}};o&&await this.ioc.windowsController.registerSelfAssignedWindow({windowId:o,name:o},o),e.postMessage(d,t,[s.port2])}rejectClientConnection(e,t,r){this.logger?.error(t);const n={glue42core:{type:Glue42CoreMessageTypes.connectionRejected.name,error:t}};e.postMessage(n,r)}processFDC3WebRequest(e){const t=this.windowsStateController.getAll().find(t=>t.window===e.source);if(!t)return void this.logger?.warn("[Browser Platform] FDC3 Hello request received from an unknown source, ignoring it.");const r={type:FDC3HelloResponseType,meta:{connectionAttemptUuid:e.data?.meta.connectionAttemptUuid,timestamp:(new Date).toISOString()},payload:{iframeUrl:`${window.fdc3ProxyUrl??FDC3ProxyUrl}?parentId=${t.windowId}`}};e.source.postMessage(r,e.origin)}handleParentPing(e,t){const r={glue42core:{type:Glue42CoreMessageTypes.parentReady.name}};e.postMessage(r,t)}handlePlatformPing(e,t){const r={glue42core:{type:Glue42CoreMessageTypes.platformReady.name}};e.postMessage(r,t)}removeClient(e,t,r){const{clientId:n,ownWindowId:i}=e;this.allPorts[n]&&!r&&delete this.allPorts[n];const o=this.allClients.find(e=>e.clientId===n);if(!o)return void this.logger?.warn(`Received client unload for unknown client: ${n}, ignoring it`);if(this.allClients=this.allClients.filter(e=>e.clientId!==n),o.client.close(),!t)return;const s={windowId:i,win:o.source};this.registry.execute("client-unloaded",s)}setupGwClientPort(e){this.allPorts[e.clientId]&&this.allPorts[e.clientId].onmessage&&(this.allPorts[e.clientId].onmessage=null),this.allPorts[e.clientId]=e.clientPort,e.clientPort.onmessage=t=>{const r=t.data?.glue42core,n=r?.type;if(n!==Glue42CoreMessageTypes.clientUnload.name&&n!==Glue42CoreMessageTypes.gatewayDisconnect.name){if(n===Glue42CoreMessageTypes.transportSwitchResponse.name){return void(r.args.success?this.transactionsController.completeTransaction(r.transactionId):this.transactionsController.failTransaction(r.transactionId,`The client: ${e.clientId} could not connect using the provided transport config.`))}if(n===Glue42CoreMessageTypes.getCurrentTransport.name){const t=r.transactionId;return void e.clientPort.postMessage({type:Glue42CoreMessageTypes.getCurrentTransportResponse.name,args:{transportState:this.getCurrentTransportState()},transactionId:t})}if(n===Glue42CoreMessageTypes.checkPreferredLogicResponse.name)return this.transactionsController.completeTransaction(r.transactionId);if(n===Glue42CoreMessageTypes.checkPreferredConnectionResponse.name){const t=r.args;return t.error?this.transactionsController.failTransaction(r.transactionId,t.error):t.live?this.transactionsController.completeTransaction(r.transactionId):this.transactionsController.failTransaction(r.transactionId,`Client ${e.clientId} could not connect to the preferred WS.`)}this.allClients.every(t=>t.client!==e.client)?this.logger?.trace(`Ignoring a protocol message, because the destination client has been disconnected: ${JSON.stringify(t.data)}`):e.client.send(t.data)}else this.removeClient(r.data,!0,r.type===Glue42CoreMessageTypes.gatewayDisconnect.name)}}getCurrentTransportState(){const e=this.ioc.glueController.getSystemGlueTransportName();return{transportName:e,type:e===webPlatformTransportName?"default":"secondary",transportConfig:e===webPlatformTransportName?void 0:this.activePreferredTransportConfig?.transportConfig}}sendClientPortRequest(e){const t=this.allPorts[e.clientId];if(!t)return ioError.raiseError(`Cannot sent port request: ${e.type} to ${e.clientId}, because there is no such client`);const r=this.transactionsController.createTransaction(e.type,e.timeout||defaultClientPortRequestTimeoutMS),n=e.type,i=e.args;return t.postMessage({type:n,args:i,transactionId:r.id}),r.lock}setupListeners(){this._genericMessageHandler=this.genericMessageHandler.bind(this),window.addEventListener("message",this._genericMessageHandler),this._unloaderHandler=this.unloader.bind(this),window.addEventListener("pagehide",this._unloaderHandler)}}const windowOperationDecoder=oneOf$1(constant$2("openWindow"),constant$2("windowHello"),constant$2("getUrl"),constant$2("getTitle"),constant$2("setTitle"),constant$2("moveResize"),constant$2("focus"),constant$2("close"),constant$2("getBounds"),constant$2("getFrameBounds"),constant$2("registerWorkspaceWindow"),constant$2("unregisterWorkspaceWindow"),constant$2("operationCheck"),constant$2("focusChange"),constant$2("getChannel"),constant$2("setZoomFactor"),constant$2("refresh")),openWindowConfigDecoder=object$3({name:nonEmptyStringDecoder$2,url:nonEmptyStringDecoder$2,options:optional$3(windowOpenSettingsDecoder)});object$3({windowId:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2});const simpleWindowDecoder=object$3({windowId:nonEmptyStringDecoder$2}),windowBoundsResultDecoder=object$3({windowId:nonEmptyStringDecoder$2,bounds:windowBoundsDecoder}),frameWindowBoundsResultDecoder=object$3({bounds:windowBoundsDecoder}),windowUrlResultDecoder=object$3({windowId:nonEmptyStringDecoder$2,url:nonEmptyStringDecoder$2}),windowMoveResizeConfigDecoder=object$3({windowId:nonEmptyStringDecoder$2,top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relative:optional$3(boolean$4())}),windowTitleConfigDecoder=object$3({windowId:nonEmptyStringDecoder$2,title:string$5()}),windowChannelResultDecoder=object$3({channel:optional$3(nonEmptyStringDecoder$2)}),windowZoomFactorConfigDecoder=object$3({windowId:nonEmptyStringDecoder$2,factorIndex:nonNegativeNumberDecoder$2}),workspacesOperationDecoder=oneOf$1(constant$2("isWindowInWorkspace"),constant$2("createWorkspace"),constant$2("createFrame"),constant$2("initFrame"),constant$2("getAllFramesSummaries"),constant$2("getFrameSummary"),constant$2("getAllWorkspacesSummaries"),constant$2("getWorkspaceSnapshot"),constant$2("getAllLayoutsSummaries"),constant$2("openWorkspace"),constant$2("deleteLayout"),constant$2("saveLayout"),constant$2("importLayout"),constant$2("exportAllLayouts"),constant$2("restoreItem"),constant$2("maximizeItem"),constant$2("focusItem"),constant$2("closeItem"),constant$2("closeWorkspace"),constant$2("resizeItem"),constant$2("moveFrame"),constant$2("getFrameSnapshot"),constant$2("forceLoadWindow"),constant$2("ejectWindow"),constant$2("setItemTitle"),constant$2("moveWindowTo"),constant$2("addWindow"),constant$2("addContainer"),constant$2("bundleWorkspace"),constant$2("bundleItem"),constant$2("changeFrameState"),constant$2("getFrameState"),constant$2("getFrameBounds"),constant$2("frameHello"),constant$2("hibernateWorkspace"),constant$2("resumeWorkspace"),constant$2("getWorkspacesConfig"),constant$2("lockWorkspace"),constant$2("lockContainer"),constant$2("lockWindow"),constant$2("pinWorkspace"),constant$2("unpinWorkspace"),constant$2("getWorkspaceIcon"),constant$2("setWorkspaceIcon"),constant$2("checkStarted"),constant$2("getPlatformFrameId"),constant$2("getWorkspaceWindowsOnLayoutSaveContext"),constant$2("getWorkspacesLayouts"),constant$2("setMaximizationBoundary"),constant$2("operationCheck"),constant$2("getWorkspaceWindowFrameBounds"),constant$2("focusChange"),constant$2("bringBackToWorkspace"),constant$2("showChannelsLink")),frameHelloDecoder=object$3({windowId:optional$3(nonEmptyStringDecoder$2)}),workspaceWindowDataDecoder=object$3({name:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,workspaceId:optional$3(nonEmptyStringDecoder$2),appName:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),channelId:optional$3(nonEmptyStringDecoder$2)}),isWindowInSwimlaneResultDecoder=object$3({inWorkspace:boolean$4()}),allParentDecoder=oneOf$1(constant$2("workspace"),constant$2("row"),constant$2("column"),constant$2("group")),subParentDecoder=oneOf$1(constant$2("row"),constant$2("column"),constant$2("group")),frameStateDecoder=oneOf$1(constant$2("maximized"),constant$2("minimized"),constant$2("normal"));object$3({saveLayout:optional$3(boolean$4())});const deleteLayoutConfigDecoder=object$3({name:nonEmptyStringDecoder$2}),swimlaneWindowDefinitionDecoder=object$3({type:optional$3(constant$2("window")),appName:optional$3(nonEmptyStringDecoder$2),windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),strictSwimlaneWindowDefinitionDecoder=object$3({type:constant$2("window"),appName:optional$3(nonEmptyStringDecoder$2),windowId:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2())}),parentDefinitionDecoder=object$3({type:optional$3(subParentDecoder),children:optional$3(lazy$1(()=>array$3(oneOf$1(swimlaneWindowDefinitionDecoder,parentDefinitionDecoder)))),config:optional$3(anyJson$2())}),groupDefinitionConfigDecoder=object$3({minWidth:optional$3(number$5()),maxWidth:optional$3(number$5()),minHeight:optional$3(number$5()),maxHeight:optional$3(number$5()),allowExtract:optional$3(boolean$4()),allowReorder:optional$3(boolean$4()),allowDrop:optional$3(boolean$4()),allowDropHeader:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),showMaximizeButton:optional$3(boolean$4()),showEjectButton:optional$3(boolean$4()),showAddWindowButton:optional$3(boolean$4())}),rowDefinitionConfigDecoder=object$3({minHeight:optional$3(number$5()),maxHeight:optional$3(number$5()),allowDrop:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),isPinned:optional$3(boolean$4()),maximizationBoundary:optional$3(boolean$4())}),columnDefinitionConfigDecoder=object$3({minWidth:optional$3(number$5()),maxWidth:optional$3(number$5()),allowDrop:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),isPinned:optional$3(boolean$4()),maximizationBoundary:optional$3(boolean$4())}),strictColumnDefinitionDecoder=object$3({type:constant$2("column"),children:optional$3(lazy$1(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(columnDefinitionConfigDecoder)}),strictRowDefinitionDecoder=object$3({type:constant$2("row"),children:optional$3(lazy$1(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(rowDefinitionConfigDecoder)}),strictGroupDefinitionDecoder=object$3({type:constant$2("group"),children:optional$3(lazy$1(()=>array$3(oneOf$1(strictSwimlaneWindowDefinitionDecoder,strictParentDefinitionDecoder)))),config:optional$3(groupDefinitionConfigDecoder)}),strictParentDefinitionDecoder=oneOf$1(strictGroupDefinitionDecoder,strictColumnDefinitionDecoder,strictRowDefinitionDecoder);oneOf$1(string$5().where(e=>"maximized"===e.toLowerCase(),"Expected a case insensitive variation of 'maximized'"),string$5().where(e=>"normal"===e.toLowerCase(),"Expected a case insensitive variation of 'normal'"));const newFrameConfigDecoder=object$3({bounds:optional$3(object$3({left:optional$3(number$5()),top:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2)})),frameId:optional$3(nonEmptyStringDecoder$2)}),loadStrategyDecoder=oneOf$1(constant$2("direct"),constant$2("delayed"),constant$2("lazy")),restoreWorkspaceConfigDecoder=object$3({app:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),loadStrategy:optional$3(loadStrategyDecoder),title:optional$3(nonEmptyStringDecoder$2),reuseWorkspaceId:optional$3(nonEmptyStringDecoder$2),frameId:optional$3(nonEmptyStringDecoder$2),lockdown:optional$3(boolean$4()),activateFrame:optional$3(boolean$4()),newFrame:optional$3(oneOf$1(newFrameConfigDecoder,boolean$4())),noTabHeader:optional$3(boolean$4()),inMemoryLayout:optional$3(boolean$4()),isPinned:optional$3(boolean$4()),icon:optional$3(nonEmptyStringDecoder$2),isSelected:optional$3(boolean$4()),positionIndex:optional$3(nonNegativeNumberDecoder$2)}),openWorkspaceConfigDecoder=object$3({name:nonEmptyStringDecoder$2,restoreOptions:optional$3(restoreWorkspaceConfigDecoder)}),workspaceDefinitionDecoder=object$3({children:optional$3(array$3(oneOf$1(swimlaneWindowDefinitionDecoder,parentDefinitionDecoder))),context:optional$3(anyJson$2()),config:optional$3(object$3({title:optional$3(nonEmptyStringDecoder$2),position:optional$3(nonNegativeNumberDecoder$2),isFocused:optional$3(boolean$4()),loadStrategy:optional$3(loadStrategyDecoder),noTabHeader:optional$3(boolean$4()),allowDrop:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),allowExtract:optional$3(boolean$4()),allowWindowReorder:optional$3(boolean$4()),allowSystemHibernation:optional$3(boolean$4()),showSaveButton:optional$3(boolean$4()),allowWorkspaceTabReorder:optional$3(boolean$4()),allowWorkspaceTabExtract:optional$3(boolean$4()),showCloseButton:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),positionIndex:optional$3(nonNegativeNumberDecoder$2)})),frame:optional$3(object$3({reuseFrameId:optional$3(nonEmptyStringDecoder$2),newFrame:optional$3(oneOf$1(boolean$4(),newFrameConfigDecoder))}))});object$3({type:allParentDecoder,definition:optional$3(oneOf$1(workspaceDefinitionDecoder,parentDefinitionDecoder))});const workspaceCreateConfigDecoder=intersection$1(workspaceDefinitionDecoder,object$3({saveConfig:optional$3(object$3({saveLayout:optional$3(boolean$4())}))})),getFrameSummaryConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2}),frameSummaryDecoder=object$3({id:nonEmptyStringDecoder$2,isFocused:optional$3(boolean$4()),isInitialized:optional$3(boolean$4()),initializationContext:optional$3(object$3({context:optional$3(anyJson$2())}))});object$3({id:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,positionIndex:number$5(),title:nonEmptyStringDecoder$2,focused:boolean$4(),layoutName:optional$3(nonEmptyStringDecoder$2),isSelected:optional$3(boolean$4())}),object$3({type:subParentDecoder,id:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,positionIndex:number$5()});const eventTypeDecoder=oneOf$1(constant$2("frame"),constant$2("workspace"),constant$2("container"),constant$2("window"));object$3({type:eventTypeDecoder,branch:nonEmptyStringDecoder$2}),oneOf$1(constant$2("opened"),constant$2("closing"),constant$2("closed"),constant$2("focus"),constant$2("added"),constant$2("loaded"),constant$2("removed"),constant$2("childrenUpdate"),constant$2("containerChange"),constant$2("maximized"),constant$2("restored"),constant$2("minimized"),constant$2("normal"),constant$2("selected"),constant$2("lock-configuration-changed"),constant$2("hibernated"),constant$2("resumed"));const workspaceConfigResultDecoder=object$3({frameId:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2,positionIndex:nonNegativeNumberDecoder$2,name:nonEmptyStringDecoder$2,layoutName:optional$3(nonEmptyStringDecoder$2),isHibernated:boolean$4(),isSelected:boolean$4(),lastActive:number$5(),allowDrop:optional$3(boolean$4()),allowExtract:optional$3(boolean$4()),allowWindowReorder:optional$3(boolean$4()),allowSystemHibernation:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),showCloseButton:optional$3(boolean$4()),showSaveButton:optional$3(boolean$4()),allowWorkspaceTabReorder:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),showAddWindowButtons:optional$3(boolean$4()),showEjectButtons:optional$3(boolean$4()),showWindowCloseButtons:optional$3(boolean$4()),minWidth:optional$3(number$5()),maxWidth:optional$3(number$5()),minHeight:optional$3(number$5()),maxHeight:optional$3(number$5()),widthInPx:optional$3(number$5()),heightInPx:optional$3(number$5())}),baseChildSnapshotConfigDecoder=object$3({frameId:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,positionIndex:number$5()}),parentSnapshotConfigDecoder=anyJson$2(),swimlaneWindowSnapshotConfigDecoder=intersection$1(baseChildSnapshotConfigDecoder,object$3({windowId:optional$3(nonEmptyStringDecoder$2),isMaximized:optional$3(boolean$4()),isFocused:boolean$4(),isSelected:optional$3(boolean$4()),title:optional$3(string$5()),appName:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),channel:optional$3(nonEmptyStringDecoder$2)})),childSnapshotResultDecoder=object$3({id:optional$3(nonEmptyStringDecoder$2),config:oneOf$1(parentSnapshotConfigDecoder,swimlaneWindowSnapshotConfigDecoder),children:optional$3(lazy$1(()=>array$3(childSnapshotResultDecoder))),type:oneOf$1(constant$2("window"),constant$2("row"),constant$2("column"),constant$2("group"))}),workspaceSnapshotResultDecoder=object$3({id:nonEmptyStringDecoder$2,config:workspaceConfigResultDecoder,children:array$3(childSnapshotResultDecoder),frameSummary:frameSummaryDecoder,context:optional$3(anyJson$2())}),customWorkspaceChildSnapshotDecoder=object$3({id:nonEmptyStringDecoder$2,config:oneOf$1(parentSnapshotConfigDecoder,swimlaneWindowSnapshotConfigDecoder),children:optional$3(lazy$1(()=>array$3(customWorkspaceChildSnapshotDecoder))),type:oneOf$1(constant$2("window"),constant$2("row"),constant$2("column"),constant$2("group"))}),groupLayoutItemDecoder=object$3({type:constant$2("group"),config:anyJson$2(),children:array$3(oneOf$1(windowLayoutItemDecoder))}),columnLayoutItemDecoder=object$3({type:constant$2("column"),config:anyJson$2(),children:array$3(oneOf$1(groupLayoutItemDecoder,windowLayoutItemDecoder,lazy$1(()=>columnLayoutItemDecoder),lazy$1(()=>rowLayoutItemDecoder)))}),rowLayoutItemDecoder=object$3({type:constant$2("row"),config:anyJson$2(),children:array$3(oneOf$1(columnLayoutItemDecoder,groupLayoutItemDecoder,windowLayoutItemDecoder,lazy$1(()=>rowLayoutItemDecoder)))}),workspaceLayoutDecoder=object$3({name:nonEmptyStringDecoder$2,type:constant$2("Workspace"),metadata:optional$3(anyJson$2()),components:array$3(object$3({type:constant$2("Workspace"),application:optional$3(nonEmptyStringDecoder$2),state:object$3({config:anyJson$2(),context:anyJson$2(),children:array$3(oneOf$1(rowLayoutItemDecoder,columnLayoutItemDecoder,groupLayoutItemDecoder,windowLayoutItemDecoder))})}))}),workspacesLayoutImportConfigDecoder=object$3({layout:workspaceLayoutDecoder,mode:oneOf$1(constant$2("replace"),constant$2("merge"))}),exportedLayoutsResultDecoder=object$3({layouts:array$3(workspaceLayoutDecoder)}),frameSummaryResultDecoder=frameSummaryDecoder,frameSummariesResultDecoder=object$3({summaries:array$3(frameSummaryResultDecoder)}),workspaceSummaryResultDecoder=object$3({id:nonEmptyStringDecoder$2,config:workspaceConfigResultDecoder}),workspaceSummariesResultDecoder=object$3({summaries:array$3(workspaceSummaryResultDecoder)}),frameSnapshotResultDecoder=object$3({id:nonEmptyStringDecoder$2,config:anyJson$2(),workspaces:array$3(workspaceSnapshotResultDecoder)}),layoutSummaryDecoder=object$3({name:nonEmptyStringDecoder$2}),layoutSummariesDecoder=object$3({summaries:array$3(layoutSummaryDecoder)}),simpleWindowOperationSuccessResultDecoder=object$3({windowId:nonEmptyStringDecoder$2}),voidResultDecoder=anyJson$2(),frameStateResultDecoder=object$3({state:frameStateDecoder}),frameBoundsDecoder=object$3({top:number$5(),left:number$5(),width:nonNegativeNumberDecoder$2,height:nonNegativeNumberDecoder$2}),frameBoundsResultDecoder=object$3({bounds:frameBoundsDecoder}),resizeConfigDecoder=object$3({width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relative:optional$3(boolean$4())}),moveConfigDecoder=object$3({top:optional$3(number$5()),left:optional$3(number$5()),relative:optional$3(boolean$4())}),simpleItemConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2}),ejectWindowDataDecoder=object$3({itemId:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2)}),frameSnapshotConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2,excludeIds:optional$3(boolean$4())}),frameStateConfigDecoder=object$3({frameId:nonEmptyStringDecoder$2,requestedState:frameStateDecoder}),setItemTitleConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2}),moveWindowConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2,containerId:nonEmptyStringDecoder$2}),resizeItemConfigDecoder=intersection$1(simpleItemConfigDecoder,resizeConfigDecoder),moveFrameConfigDecoder=intersection$1(simpleItemConfigDecoder,moveConfigDecoder);object$3({id:nonEmptyStringDecoder$2,type:subParentDecoder});const addWindowConfigDecoder=object$3({definition:swimlaneWindowDefinitionDecoder,parentId:nonEmptyStringDecoder$2,parentType:allParentDecoder}),addContainerConfigDecoder=object$3({definition:strictParentDefinitionDecoder,parentId:nonEmptyStringDecoder$2,parentType:allParentDecoder}),addItemResultDecoder=object$3({itemId:nonEmptyStringDecoder$2,windowId:optional$3(nonEmptyStringDecoder$2)});object$3({live:boolean$4()});const bundleWorkspaceConfigDecoder=object$3({type:oneOf$1(constant$2("row"),constant$2("column")),workspaceId:nonEmptyStringDecoder$2}),bundleItemConfigDecoder=object$3({type:oneOf$1(constant$2("row"),constant$2("column")),itemId:nonEmptyStringDecoder$2}),workspaceSelectorDecoder=object$3({workspaceId:nonEmptyStringDecoder$2}),containerSummaryResultDecoder=object$3({itemId:nonEmptyStringDecoder$2,config:parentSnapshotConfigDecoder});object$3({frameSummary:frameSummaryDecoder,frameBounds:optional$3(frameBoundsDecoder)}),object$3({workspaceSummary:workspaceSummaryResultDecoder,frameSummary:frameSummaryDecoder,frameBounds:optional$3(frameBoundsDecoder)}),object$3({containerSummary:containerSummaryResultDecoder}),object$3({windowSummary:object$3({itemId:nonEmptyStringDecoder$2,parentId:nonEmptyStringDecoder$2,config:swimlaneWindowSnapshotConfigDecoder})});const workspaceLayoutSaveConfigDecoder=object$3({name:nonEmptyStringDecoder$2,workspaceId:nonEmptyStringDecoder$2,saveContext:optional$3(boolean$4())}),lockWorkspaceDecoder=object$3({workspaceId:nonEmptyStringDecoder$2,config:optional$3(object$3({allowDrop:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),allowExtract:optional$3(boolean$4()),allowWindowReorder:optional$3(boolean$4()),allowSystemHibernation:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4()),showCloseButton:optional$3(boolean$4()),showSaveButton:optional$3(boolean$4()),allowWorkspaceTabReorder:optional$3(boolean$4()),showWindowCloseButtons:optional$3(boolean$4()),showEjectButtons:optional$3(boolean$4()),showAddWindowButtons:optional$3(boolean$4())}))}),lockWindowDecoder=object$3({windowPlacementId:nonEmptyStringDecoder$2,config:optional$3(object$3({allowExtract:optional$3(boolean$4()),allowReorder:optional$3(boolean$4()),showCloseButton:optional$3(boolean$4())}))}),lockRowDecoder=object$3({itemId:nonEmptyStringDecoder$2,type:constant$2("row"),config:optional$3(object$3({allowDrop:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4())}))}),lockColumnDecoder=object$3({itemId:nonEmptyStringDecoder$2,type:constant$2("column"),config:optional$3(object$3({allowDrop:optional$3(boolean$4()),allowSplitters:optional$3(boolean$4())}))}),lockGroupDecoder=object$3({itemId:nonEmptyStringDecoder$2,type:constant$2("group"),config:optional$3(object$3({allowExtract:optional$3(boolean$4()),allowReorder:optional$3(boolean$4()),allowDrop:optional$3(boolean$4()),allowDropHeader:optional$3(boolean$4()),allowDropLeft:optional$3(boolean$4()),allowDropTop:optional$3(boolean$4()),allowDropRight:optional$3(boolean$4()),allowDropBottom:optional$3(boolean$4()),showMaximizeButton:optional$3(boolean$4()),showEjectButton:optional$3(boolean$4()),showAddWindowButton:optional$3(boolean$4())}))}),lockContainerDecoder=oneOf$1(lockColumnDecoder,lockGroupDecoder,lockRowDecoder),pinWorkspaceDecoder=object$3({workspaceId:nonEmptyStringDecoder$2,icon:optional$3(nonEmptyStringDecoder$2)}),setWorkspaceIconDecoder=object$3({workspaceId:nonEmptyStringDecoder$2,icon:optional$3(nonEmptyStringDecoder$2)}),workspaceIconDecoder=object$3({icon:optional$3(nonEmptyStringDecoder$2)});object$3({applicationName:optional$3(string$5()),frameConfig:optional$3(newFrameConfigDecoder),context:optional$3(object$3()),layoutComponentId:optional$3(nonEmptyStringDecoder$2)});const restoreWorkspaceDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,restoreOptions:optional$3(restoreWorkspaceConfigDecoder)});object$3({frameId:nonEmptyStringDecoder$2,workspaces:array$3(oneOf$1(workspaceDefinitionDecoder,restoreWorkspaceDefinitionDecoder))});const getWorkspaceWindowsOnLayoutSaveContextConfigDecoder=object$3({layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),layoutName:nonEmptyStringDecoder$2,windowIds:array$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreContexts:optional$3(boolean$4())}),setMaximizationBoundaryConfigDecoder=object$3({itemId:nonEmptyStringDecoder$2,enabled:boolean$4()}),workspaceWindowOnSaveDataDecoder=object$3({windowId:nonEmptyStringDecoder$2,windowContext:optional$3(anyJson$2())}),getWorkspaceWindowsOnLayoutSaveContextResult=object$3({windowsOnSaveData:array$3(workspaceWindowOnSaveDataDecoder)}),getWorkspacesLayoutsConfigDecoder=object$3({frameId:nonEmptyStringDecoder$2,layoutName:nonEmptyStringDecoder$2,layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),context:optional$3(anyJson$2()),ignoreContexts:optional$3(boolean$4())}),getWorkspacesLayoutsResponseDecoder=object$3({workspaces:array$3(workspaceSnapshotResultDecoder)}),showChannelsLinkDecoder=object$3({windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2,channelsNames:array$3(nonEmptyStringDecoder$2)}),ZOOM_FACTORS=Object.freeze({0:24,1:33,2:50,3:67,4:75,5:80,6:90,7:100,8:110,9:125,10:150,11:175,12:200,13:250,14:300,15:400,16:500});class WindowsController{glueController;sessionController;stateController;ioc;started=!1;clientResponseTimeoutMs;defaultBounds;explicitClosingWindowIds={};connectionConfig;refreshLocks={};operations={openWindow:{name:"openWindow",execute:this.openWindow.bind(this),dataDecoder:openWindowConfigDecoder},windowHello:{name:"windowHello",execute:this.handleWindowHello.bind(this)},getBounds:{name:"getBounds",dataDecoder:simpleWindowDecoder,resultDecoder:windowBoundsResultDecoder,execute:this.handleGetBounds.bind(this)},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleWindowDecoder,resultDecoder:frameWindowBoundsResultDecoder,execute:this.handleGetBounds.bind(this)},getUrl:{name:"getUrl",dataDecoder:simpleWindowDecoder,resultDecoder:windowUrlResultDecoder,execute:this.handleGetUrl.bind(this)},moveResize:{name:"moveResize",dataDecoder:windowMoveResizeConfigDecoder,execute:this.handleMoveResize.bind(this)},focus:{name:"focus",dataDecoder:simpleWindowDecoder,execute:this.handleFocus.bind(this)},close:{name:"close",dataDecoder:simpleWindowDecoder,execute:this.handleClose.bind(this)},getTitle:{name:"getTitle",dataDecoder:simpleWindowDecoder,resultDecoder:windowTitleConfigDecoder,execute:this.handleGetTitle.bind(this)},setTitle:{name:"setTitle",dataDecoder:windowTitleConfigDecoder,execute:this.handleSetTitle.bind(this)},registerWorkspaceWindow:{name:"registerWorkspaceWindow",dataDecoder:workspaceWindowDataDecoder,execute:this.registerWorkspaceWindow.bind(this)},unregisterWorkspaceWindow:{name:"unregisterWorkspaceWindow",dataDecoder:simpleWindowDecoder,execute:this.handleWorkspaceClientRemoval.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder,execute:this.handleFocusEvent.bind(this)},getChannel:{name:"getChannel",dataDecoder:simpleWindowDecoder,resultDecoder:windowChannelResultDecoder,execute:this.handleGetChannel.bind(this)},setZoomFactor:{name:"setZoomFactor",dataDecoder:windowZoomFactorConfigDecoder,execute:this.handleSetZoomFactor.bind(this)},refresh:{name:"refresh",dataDecoder:simpleWindowDecoder,execute:this.handleRefresh.bind(this)}};constructor(e,t,r,n){this.glueController=e,this.sessionController=t,this.stateController=r,this.ioc=n}get logger(){return logger.get("windows.controller")}get moveResizeOperation(){return this.operations.moveResize}get getFrameBoundsOperation(){return this.operations.getFrameBounds}get setTitleOperation(){return this.operations.setTitle}get getBoundsOperation(){return this.operations.getBounds}handlePlatformShutdown(){this.started=!1}async start(e){this.clientResponseTimeoutMs=e.windows.windowResponseTimeoutMs,this.defaultBounds=e.windows.defaultWindowOpenBounds,this.started=!0,this.connectionConfig=e.connection,this.stateController.onWindowDisappeared(e=>this.cleanUpWindow(e).catch(t=>this.logger?.warn(`error while cleaning up window ${e}: ${t?.message}`)))}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=windowOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This window request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Windows request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Windows request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async getWindowTitle(e,t){return(await this.handleGetTitle({windowId:e},t)).title}async getWindowBounds(e,t){return(await this.handleGetBounds({windowId:e},t)).bounds}async processNewWindow(e,t,r){this.logger?.trace(`processing a new window with id: ${e.windowId} and name: ${e.name}`),this.sessionController.saveWindowData(e),r&&this.stateController.add(r,e.windowId),t&&(this.logger?.trace(`setting the context for window ${e.windowId}`),await this.glueController.setStartContext(e.windowId,t,"window")),this.emitStreamData("windowAdded",e)}async handleWorkspaceClientRemoval(e){this.sessionController.removeEjectedWindowId(e.windowId),await this.cleanUpWindow(e.windowId),this.ioc.portsBridge.removeGwClient(e.windowId)}handleClientUnloaded(e,t){if(this.logger?.trace(`handling unloading of ${e}`),e&&!this.explicitClosingWindowIds[e]){if(!t||t.closed)return this.logger?.trace(`${e} detected as closed, processing window cleanup`),void this.cleanUpWindow(e).catch(t=>this.logger?.warn(`error while cleaning up window ${e}: ${t.message}`));this.logger?.trace(`${e} detected as not closed, adding to state controller`),this.stateController.add(t,e)}}setExplicitClosingWindowId(e){this.explicitClosingWindowIds[e]=!0}async cleanUpWindow(e){this.stateController.remove(e);if(this.sessionController.fullWindowClean(e)){try{await this.glueController.clearContext(e,"window")}catch(t){this.logger?.warn(`error while clearing the context of window ${e}: ${t?.message}`)}this.emitStreamData("windowRemoved",{windowId:e}),delete this.explicitClosingWindowIds[e],await this.waitEventFlush()}}async registerSelfAssignedWindow(e,t){this.logger?.trace(`[${t}] handling workspace window registration with id: ${e.windowId} and name: ${e.name}`),this.sessionController.saveWindowData({windowId:e.windowId,name:e.name,selfAssigned:!0}),this.sessionController.saveNonGlue({windowId:e.windowId}),this.emitStreamData("windowAdded",{windowId:e.windowId,name:e.name}),this.logger?.trace(`[${t}] workspace window registered successfully with id ${e.windowId} and name ${e.name}`)}async registerWorkspaceWindow(e,t){this.logger?.trace(`[${t}] handling workspace window registration with id: ${e.windowId} and name: ${e.name}`),this.sessionController.removeEjectedWindowId(e.windowId),e.channelId&&this.sessionController.addWindowChannel(e.windowId,e.channelId),this.sessionController.saveWindowData({windowId:e.windowId,name:e.name,initialChannelId:e.channelId}),this.sessionController.saveWorkspaceClient({windowId:e.windowId,frameId:e.frameId,initialTitle:e.title,workspaceId:e.workspaceId}),this.sessionController.saveNonGlue({windowId:e.windowId});const r=await this.glueController.pullHibernatedContext(e.windowId),n=e.context||r;n&&await this.glueController.setStartContext(e.windowId,n,"window"),this.emitStreamData("windowAdded",{windowId:e.windowId,name:e.name}),this.logger?.trace(`[${t}] workspace window registered successfully with id ${e.windowId} and name ${e.name}`)}async handleFocusEvent(e,t){this.logger?.trace(`[${t}] handling focus event from window id: ${e.windowId} and hasFocus: ${e.hasFocus}`),this.emitStreamData("focusChange",e),this.logger?.trace(`[${t}] focus event from window id: ${e.windowId} and hasFocus: ${e.hasFocus} handled`)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("windows",e,t)}async openWindow(e,t){if(this.sessionController.getWindowDataByName(e.name))return ioError.raiseError(`Cannot open a window with name: ${e.name}, because a window with that name already exists.`);if(checkIsOriginBlocked(e.url,this.connectionConfig.blockList))return ioError.raiseError(`Cannot open a window with url: ${e.url}, because its origin is blocked by the Platform`);this.logger?.trace(`[${t}] handling open command with a valid name: ${e.name}, url: ${e.url} and options: ${JSON.stringify(e.options)}`);const r=await this.getStartingBounds(e,t),n=e.options?.windowId??`g42-${nanoid$5(10)}`,i={name:e.name,windowId:n,initialBounds:r,initialUrl:e.url,initialContext:e.options?.context,layoutComponentId:e.options?.layoutComponentId},o=`left=${r.left},top=${r.top},width=${r.width},height=${r.height}`;this.logger?.trace(`[${t}] calling native window open with bounds: ${o}`);const s=window.open(e.url,i.windowId,o);return s?(await this.processNewWindow(i,e.options?.context,s),this.logger?.trace(`[${t}] the new window is opened, saved in session, state and announced, responding to the caller`),i):ioError.raiseError(`Cannot open window with url: ${e.url} and name: ${e.name}. The most likely reason is that the user has not approved popups or has a blocker.`)}async handleWindowHello(e,t){if(this.logger?.trace(`[${t}] handling a hello message from a real windowId: ${e.windowId}`),e.windowId){this.stateController.remove(e.windowId),this.sessionController.removeNonGlue({windowId:e.windowId});const r=this.sessionController.getWorkspaceClientById(e.windowId);if(r&&r.initialTitle){const n=e.windowId,i=r.initialTitle;PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setTitle,{windowId:n,title:i},{windowId:n}),this.clientResponseTimeoutMs).catch(e=>this.logger?.trace(`[${t}] error while setting the workspace window title: ${e.message}`))}}const r=!(!e.windowId||!this.sessionController.getFrameData(e.windowId)),n=this.sessionController.getAllWindowsData().map(e=>({windowId:e.windowId,name:e.name}));this.logger?.trace(`[${t}] a full list of all current windows has been compiled, sending it to the caller`);const i=e.windowId?this.refreshLocks[e.windowId]:void 0;return i&&e.windowId&&(i.open(),delete this.refreshLocks[e.windowId]),{windows:n,isWorkspaceFrame:r}}handleGetUrl(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the url of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get url request for window ${e.windowId}`);const r=`Cannot get the url of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getUrl,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}handleGetTitle(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the title of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get title request for window ${e.windowId}`);const r=`Cannot get the title of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getTitle,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleSetTitle(e,t){if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot set the title of window: ${e.windowId}, because it does not exist for the platform`);this.sessionController.getWorkspaceClientById(e.windowId)&&await this.ioc.workspacesController.setItemTitle({itemId:e.windowId,title:e.title},t),this.logger?.trace(`[${t}] handling a set title request for window ${e.windowId} and title: ${e.title}`);const r=`Cannot set the title of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setTitle,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleMoveResize(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot move resize window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more control`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot move resize window: ${e.windowId}, because it does not exist for the platform`);if("Platform"===r.name)return ioError.raiseError("Move-resizing the main application is not allowed");this.logger?.trace(`[${t}] handling a move resize request for window ${e.windowId} and data: ${JSON.stringify(e)}`);const n=`Cannot move resize window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.moveResize,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,n),await this.pause(500)}handleGetBounds(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot get bounds of window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more info`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the bounds of window: ${e.windowId}, because it does not exist for the platform`);this.logger?.trace(`[${t}] handling a get bounds request for window ${e.windowId}`);const r=`Cannot get the bounds of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getBounds,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleFocus(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return ioError.raiseError(`Cannot focus window id ${e.windowId}, because it is in a workspace. Consider using the workspaces API to get more control`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot focus window: ${e.windowId}, because it is not known by the platform`);this.logger?.trace(`[${t}] handling a focus request for window ${e.windowId}`),window.open(void 0,r.windowId)}async handleClose(e,t){if(this.sessionController.getWorkspaceClientById(e.windowId))return this.logger?.trace(`[${t}] this window is detected as a workspace window, closing via the workspaces controller`),void await this.ioc.workspacesController.closeItem({itemId:e.windowId},t);if(this.sessionController.getInstanceData(e.windowId))return this.logger?.trace(`[${t}] this window is detected as an application instance, closing via the appManager controller`),void await this.ioc.applicationsController.handleInstanceStop({id:e.windowId},t);const r=this.sessionController.getWindowDataById(e.windowId);return r?"Platform"===r.name?ioError.raiseError("Closing the main application is not allowed"):r.selfAssigned?ioError.raiseError("Closing self-assigned windows (windows not opened by the Glue API) is not allowed"):(this.logger?.trace(`[${t}] handling a close request for window ${e.windowId}`),window.open(void 0,r.windowId)?.close(),await this.cleanUpWindow(r.windowId),void this.logger?.trace(`[${t}] window ${e.windowId} has been closed, removed from session, state and announced`)):ioError.raiseError(`Cannot close window: ${e.windowId}, because it is not known by the platform`)}async getStartingBounds(e,t){const r={top:e.options?.top??this.defaultBounds.top,left:e.options?.left??this.defaultBounds.left,height:e.options?.height??this.defaultBounds.height,width:e.options?.width??this.defaultBounds.width};if(!e.options?.relativeTo)return r;const n=e.options.relativeTo,i=this.sessionController.getWindowDataById(n);if(!i)return r;try{const n=(await this.handleGetBounds({windowId:i.windowId},t)).bounds,o=e.options.relativeDirection??"right";return getRelativeBounds(r,n,o)}catch(e){return r}}pause(e){return new Promise(t=>setTimeout(t,e))}handleGetChannel(e,t){this.logger?.trace(`[${t}] handling a get channel request for window ${e.windowId}`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot get the channel of window: ${e.windowId}, because it does not exist for the platform`);const r=`Cannot get the channel of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;return PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.getChannel,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r)}async handleSetZoomFactor(e,t){this.logger?.trace(`[${t}] handling a set zoom factor request for window ${e.windowId} and factor: ${ZOOM_FACTORS[e.factorIndex]}`);if(!this.sessionController.getWindowDataById(e.windowId))return ioError.raiseError(`Cannot set the zoom factor of window: ${e.windowId}, because it does not exist for the platform`);const r=`Cannot set the zoom factor of window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`;await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.setZoomFactor,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,r),this.emitStreamData("zoomFactorChange",e)}async handleRefresh(e,t){this.logger?.trace(`[${t}] handling a refresh request for window ${e.windowId}`);const r=this.sessionController.getWindowDataById(e.windowId);if(!r)return ioError.raiseError(`Cannot refresh window: ${e.windowId}, because it does not exist for the platform`);if("Platform"===r.name)return ioError.raiseError("Refreshing the main application is not allowed");const n=`Cannot refresh window: ${e.windowId}, because it is either a non-glue window or it hasn't initiated it's glue yet`,{isSupported:i}=await this.glueController.checkClientOperationSupport("windows",this.operations.refresh,{instance:e.windowId});if(!i)return ioError.raiseError(`[${t}] Cannot handle refresh request, because the target instance does not support the operation`);await PromiseWrap(()=>this.glueController.callWindow("windows",this.operations.refresh,e,{windowId:e.windowId}),this.clientResponseTimeoutMs,n);const o=this.createRefreshLock();this.refreshLocks[e.windowId]=o,await o.lock}createRefreshLock(){let e;const t=PromisePlus(t=>{e=t},3e3,"The refresh lock was not opened in time, this is most likely a bug in the platform");if(!e)throw new Error("The open function for the refresh lock was not initialized properly");return{open:e,lock:t}}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}class SessionStorageController{cache={};sessionStorage;windowsNamespace="g42_core_windows";instancesNamespace="g42_core_instances";bridgeInstancesNamespace="g42_core_bridge";nonGlueNamespace="g42_core_nonglue";workspaceWindowsNamespace="g42_core_workspace_clients";workspaceFramesNamespace="g42_core_workspace_frames";workspaceHibernationNamespace="g42_core_workspace_hibernation";globalLayoutsNamespace="g42_core_layouts_global";workspaceLayoutsNamespace="g42_core_layouts_workspace";appDefsNamespace="g42_core_app_definitions";appDefsInmemoryNamespace="g42_core_app_definitions_inmemory";notificationsNamespace="g42_core_notifications";prefsRestSchedulerNamespace="g42_core_prefs_rest_scheduler";layoutsSystemNamespace="g42_core_layouts_system";systemNamespace="g42_system";workspaceFrameCache="g42_workspace_frame_cache";channelsNamespace="g42_core_channels";ejectedWindowIdsNamespace="g42_core_ejected_windows";allNamespaces=[this.bridgeInstancesNamespace,this.windowsNamespace,this.instancesNamespace,this.nonGlueNamespace,this.workspaceWindowsNamespace,this.workspaceFramesNamespace,this.globalLayoutsNamespace,this.workspaceLayoutsNamespace,this.appDefsNamespace,this.workspaceHibernationNamespace,this.appDefsInmemoryNamespace,this.notificationsNamespace,this.prefsRestSchedulerNamespace,this.workspaceFrameCache,this.channelsNamespace,this.ejectedWindowIdsNamespace];get logger(){return logger.get("session.storage")}start(){this.sessionStorage=window.sessionStorage,this.allNamespaces.forEach(e=>{this.getItem(e)||this.setItem(e,JSON.stringify([]))})}shutdown(){this.allNamespaces.forEach(e=>{this.setItem(e,JSON.stringify([]))}),this.removeItem(this.systemNamespace),this.removeItem(this.layoutsSystemNamespace)}getSystemSettings(){const e=this.getItem(this.systemNamespace);if(e)return JSON.parse(e)}setSystemSettings(e){this.setItem(this.systemNamespace,JSON.stringify(e))}getLayoutsSystemData(){const e=this.getItem(this.layoutsSystemNamespace);return e?JSON.parse(e):{}}setLayoutsSystemData(e){this.setItem(this.layoutsSystemNamespace,JSON.stringify(e))}getTimeout(e){const t=this.getNamespaceData(this.workspaceHibernationNamespace);return t.find(t=>t.workspaceId===e)?.timeout}removeTimeout(e){const t=this.getNamespaceData(this.workspaceHibernationNamespace);t.find(t=>t.workspaceId===e)&&this.setItem(this.workspaceHibernationNamespace,JSON.stringify(t.filter(t=>t.workspaceId!==e)))}saveTimeout(e,t){const r=this.getNamespaceData(this.workspaceHibernationNamespace);r.some(t=>t.workspaceId===e)||(r.push({workspaceId:e,timeout:t}),this.setItem(this.workspaceHibernationNamespace,JSON.stringify(r)))}exportClearTimeouts(){const e=this.getNamespaceData(this.workspaceHibernationNamespace);return this.setItem(this.workspaceHibernationNamespace,JSON.stringify([])),e}getAllApps(e){const t="remote"===e?this.appDefsNamespace:this.appDefsInmemoryNamespace;return this.getNamespaceData(t)}overwriteApps(e,t){const r="remote"===t?this.appDefsNamespace:this.appDefsInmemoryNamespace;this.setItem(r,JSON.stringify(e))}removeApp(e,t){const r="remote"===t?this.appDefsNamespace:this.appDefsInmemoryNamespace,n=this.getAllApps(t),i=n.find(t=>t.name===e);return i&&this.setItem(r,JSON.stringify(n.filter(t=>t.name!==e))),i}getLayoutSnapshot(e){const t="Global"===e?this.globalLayoutsNamespace:this.workspaceLayoutsNamespace;return{layouts:this.getNamespaceData(t)}}saveLayoutSnapshot(e,t){const r="Global"===t?this.globalLayoutsNamespace:this.workspaceLayoutsNamespace;this.setItem(r,JSON.stringify(e.layouts))}saveFrameData(e){const t=this.getNamespaceData(this.workspaceFramesNamespace);t.some(t=>t.windowId===e.windowId)||(t.push(e),this.setItem(this.workspaceFramesNamespace,JSON.stringify(t)))}getPlatformFrame(){return this.getAllFrames().find(e=>e.isPlatform)}getAllFrames(){return this.getNamespaceData(this.workspaceFramesNamespace)}getFrameData(e){return this.getAllFrames().find(t=>t.windowId===e)}setFrameActive(e){const t=this.getAllFrames(),r=t.find(t=>t.windowId===e);r&&!r.active&&(r.active=!0,this.setItem(this.workspaceFramesNamespace,JSON.stringify(t)))}removeFrameData(e){return!!e&&this.doRemove(e,this.workspaceFramesNamespace)}saveWorkspaceClient(e){const t=this.getNamespaceData(this.workspaceWindowsNamespace);t.some(t=>t.windowId===e.windowId)||(t.push(e),this.setItem(this.workspaceWindowsNamespace,JSON.stringify(t)))}getWorkspaceClientById(e){return this.getNamespaceData(this.workspaceWindowsNamespace).find(t=>t.windowId===e)}pickWorkspaceClients(e){return this.getNamespaceData(this.workspaceWindowsNamespace).filter(e)}removeWorkspaceClient(e){return!!e&&this.doRemove(e,this.workspaceWindowsNamespace)}getAllNonGlue(){return this.getNamespaceData(this.nonGlueNamespace)}saveNonGlue(e){const t=this.getNamespaceData(this.nonGlueNamespace);return t.some(t=>t.windowId===e.windowId)?(this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`),!1):(this.logger?.trace(`saving non glue window with id: ${e.windowId}`),t.push(e),this.setItem(this.nonGlueNamespace,JSON.stringify(t)),!0)}removeNonGlue(e){return!(!e||!e.windowId)&&(this.logger?.trace(`removing non glue window with id: ${e.windowId}`),this.doRemove(e.windowId,this.nonGlueNamespace))}saveBridgeInstanceData(e){const t=this.getNamespaceData(this.bridgeInstancesNamespace);t.some(t=>t.windowId===e.windowId)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`):(this.logger?.trace(`saving new instance with id: ${e.windowId} and app name: ${e.appName}`),t.push(e),this.setItem(this.bridgeInstancesNamespace,JSON.stringify(t)))}getBridgeInstanceData(e){return this.getNamespaceData(this.bridgeInstancesNamespace).find(t=>t.windowId===e)}removeBridgeInstanceData(e){const t=this.getNamespaceData(this.bridgeInstancesNamespace);this.setItem(this.bridgeInstancesNamespace,JSON.stringify(t.filter(t=>t.windowId!==e)))}saveInstanceData(e){const t=this.getNamespaceData(this.instancesNamespace);t.some(t=>t.id===e.id)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this id already exists`):(this.logger?.trace(`saving new instance with id: ${e.id} and app name: ${e.applicationName}`),t.push(e),this.setItem(this.instancesNamespace,JSON.stringify(t)))}removeInstance(e){this.logger?.trace(`removing instance with id: ${e}`);const t=this.getAllInstancesData();this.setItem(this.instancesNamespace,JSON.stringify(t.filter(t=>t.id!==e))),this.removeBridgeInstanceData(e)}getInstanceData(e){return this.getAllInstancesData().find(t=>t.id===e)}getAllInstancesData(){return this.getNamespaceData(this.instancesNamespace)}removeNotification(e){const t=this.getNamespaceData(this.notificationsNamespace);t.find(t=>t.id===e)&&this.setItem(this.notificationsNamespace,JSON.stringify(t.filter(t=>t.id!==e)))}saveNewNotification(e){const t=this.getAllNotifications();if(t.some(t=>t.id===e.id))return ioError.raiseError(`Notification with id ${e.id} already exists`);this.logger?.trace(`saving notification with id: ${e.id}`),t.push(e),this.setItem(this.notificationsNamespace,JSON.stringify(t))}updateNotification(e){const t=this.getAllNotifications(),r=t.findIndex(t=>t.id===e.id);if(-1===r)return ioError.raiseError(`Notification with id ${e.id} does not exist`);this.logger?.trace(`updating notification with id: ${e.id}`),t[r]=e,this.setItem(this.notificationsNamespace,JSON.stringify(t))}getNotification(e){return this.getAllNotifications().find(t=>t.id===e)}getAllNotifications(){return this.getNamespaceData(this.notificationsNamespace)}savePrefsRestSchedulerCache(e){const t=this.getAllPrefsRestSchedulerCache();t.some(t=>t.app===e.app)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this app already exists`):(this.logger?.trace(`saving prefs rest scheduler cache for app: ${e.app}`),t.push(e),this.setItem(this.prefsRestSchedulerNamespace,JSON.stringify(t)))}getAllPrefsRestSchedulerCache(){return this.getNamespaceData(this.prefsRestSchedulerNamespace)}clearAllPrefsRestSchedulerCache(){this.setItem(this.prefsRestSchedulerNamespace,JSON.stringify([]))}saveWindowData(e){const t=this.getAllWindowsData();t.some(t=>t.name===e.name)?this.logger?.trace(`did not save this data: ${JSON.stringify(e)}, because an entry with this name already exists`):(this.logger?.trace(`saving window with id: ${e.windowId} and name: ${e.name}`),t.push(e),this.setItem(this.windowsNamespace,JSON.stringify(t)))}getAllWindowsData(){return this.getNamespaceData(this.windowsNamespace)}getWindowDataById(e){return this.getAllWindowsData().find(t=>t.windowId===e)}getWindowDataByName(e){return this.getAllWindowsData().find(t=>t.name===e)}removeWindowData(e){return!!e&&(this.logger?.trace(`removing window with id: ${e}`),this.doRemove(e,this.windowsNamespace))}fullWindowClean(e){const t=this.removeWindowData(e),r=this.removeNonGlue({windowId:e}),n=this.removeWorkspaceClient(e);return t||r||n}addWindowChannel(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`adding channel data for window with id: ${e}`),r[n].channels=Array.from(new Set([...r[n].channels||[],t])),this.setItem(this.channelsNamespace,JSON.stringify(r))}setChannelsForWindow(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:t}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`adding channels data for window with id: ${e}`),r[n].channels=Array.from(new Set(t)),this.setItem(this.channelsNamespace,JSON.stringify(r))}setAdditionalChannelForWindow(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry`),r.push({windowId:e,channels:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`add additional channel data for window with id: ${e}`),r[n].channels=Array.from(new Set([...r[n].channels??[],t])),this.setItem(this.channelsNamespace,JSON.stringify(r))}addChannelRestrictionsByWindowId(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry with restrictions`),r.push({windowId:e,restrictions:[t]}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`channel data found for window with id: ${e}, updating restrictions`);const i=r[n].restrictions?.some(e=>e.name===t.name);r[n].restrictions=i?[t]:[...r[n].restrictions||[],t],this.setItem(this.channelsNamespace,JSON.stringify(r))}addAllChannelsRestrictionsByWindowId(e,t){const r=this.getNamespaceData(this.channelsNamespace),n=r.findIndex(t=>t.windowId===e);if(-1===n)return this.logger?.trace(`no channel data found for window with id: ${e}, creating new entry with restrictions`),r.push({windowId:e,restrictions:t}),this.setItem(this.channelsNamespace,JSON.stringify(r));this.logger?.trace(`channel data found for window with id: ${e}, updating restrictions`),r[n].restrictions=t,this.setItem(this.channelsNamespace,JSON.stringify(r))}addEjectedWindowId(e){const t=this.getNamespaceData(this.ejectedWindowIdsNamespace),r=Array.from(new Set([...t,e]));this.setItem(this.ejectedWindowIdsNamespace,JSON.stringify(r))}removeEjectedWindowId(e){const t=this.getNamespaceData(this.ejectedWindowIdsNamespace).filter(t=>t!==e);this.setItem(this.ejectedWindowIdsNamespace,JSON.stringify(t))}getEjectedWindowIds(){return this.getNamespaceData(this.ejectedWindowIdsNamespace)}getWindowChannelData(e){return this.getNamespaceData(this.channelsNamespace).find(t=>t.windowId===e)}getAllWindowsChannelData(){return this.getNamespaceData(this.channelsNamespace)}removeWindowChannelData(e){return!!e&&this.doRemove(e,this.channelsNamespace)}handlePlatformUnloadCleanup(){const e=this.getNamespaceData(this.workspaceWindowsNamespace);if(!e.length)return;this.getAllWindowsData().forEach(t=>{const r=e.find(e=>e.windowId===t.windowId);if(!r)return;const n=this.getFrameData(r.frameId);n?.isPlatform&&(this.fullWindowClean(t.windowId),this.removeWindowChannelData(t.windowId),this.removeInstance(t.windowId))})}doRemove(e,t){const r=this.getNamespaceData(t).reduce((t,r)=>(r.windowId===e?t.removed=!0:t.newData.push(r),t),{removed:!1,newData:[]});return this.setItem(t,JSON.stringify(r.newData)),r.removed}getNamespaceData(e){const t=this.getItem(e);return t?JSON.parse(t):[]}getItem(e){const t=this.sessionStorage.getItem(e);return t?(this.cache[e]=t,t):(this.doFullRecovery(),this.cache[e])}setItem(e,t){this.cache[e]=t,this.sessionStorage.setItem(e,t)}removeItem(e){delete this.cache[e],this.sessionStorage.removeItem(e)}doFullRecovery(){this.logger?.warn("Session storage is empty or corrupted, performing full recovery from in-memory cache");this.allNamespaces.filter(e=>e!==this.systemNamespace&&e!==this.layoutsSystemNamespace).forEach(e=>{const t=this.cache[e]??JSON.stringify([]);this.setItem(e,t)}),this.setItem(this.systemNamespace,this.cache[this.systemNamespace]??JSON.stringify({})),this.setItem(this.layoutsSystemNamespace,this.cache[this.layoutsSystemNamespace]??JSON.stringify({})),this.logger?.info("Full recovery completed, session storage is now restored from in-memory cache")}}class WindowsStateController{sessionStorage;registry=CallbackRegistryFactory$2();checkIntervalMs=500;childrenToCheck=[];checkerCancelled=!1;currentTimeout;constructor(e){this.sessionStorage=e}get logger(){return logger.get("state.controller")}start(){this.checkerCancelled=!1;const e=this.sessionStorage.getAllNonGlue(),t=this.sessionStorage.pickWorkspaceClients(()=>!0);this.logger?.debug(`starting state controller with ${e.length} non-glue windows and ${t.length} workspace clients from previous session`);e.filter(e=>t.every(t=>t.windowId!==e.windowId)).forEach(e=>{this.logger?.trace(`detected non glue window with id ${e.windowId} from previous session, attempting reference refresh`);const t=window.open(void 0,e.windowId);t&&this.childrenToCheck.push({window:t,windowId:e.windowId})}),this.checkWindows(),this.logger?.debug(`state controller startup completed with ${this.childrenToCheck.length} windows to monitor`)}add(e,t){this.logger?.trace(`adding window id: ${t} to non glue state checking`);this.sessionStorage.saveNonGlue({windowId:t})&&this.childrenToCheck.push({window:e,windowId:t})}getAll(){return this.logger?.trace("getting all non glue windows"),this.childrenToCheck}remove(e){this.logger?.trace(`removing window id: ${e} from non glue state checking`),this.sessionStorage.removeNonGlue({windowId:e}),this.childrenToCheck=this.childrenToCheck.filter(t=>t.windowId!==e)}cancel(){this.logger?.debug("cancelling state controller"),this.currentTimeout&&clearTimeout(this.currentTimeout),this.checkerCancelled=!0,this.registry.clear()}onWindowDisappeared(e){return this.registry.add("window-disappear",e)}checkWindows(){this.checkerCancelled||(this.childrenToCheck.forEach(e=>{if(!e.window||e.window.closed)return this.logger?.trace(`non glue window ${e.windowId} has disappeared, removing from collections and announcing.`),this.remove(e.windowId),void this.registry.execute("window-disappear",e.windowId)}),this.currentTimeout=setTimeout(this.checkWindows.bind(this),this.checkIntervalMs))}}const intentsOperationTypesDecoder=oneOf$1(constant$2("findIntent"),constant$2("getIntents"),constant$2("raise"),constant$2("operationCheck"),constant$2("filterHandlers"),constant$2("getIntentsByHandler")),intentHandlerDecoder=object$3({applicationName:nonEmptyStringDecoder$2,applicationTitle:optional$3(string$5()),applicationDescription:optional$3(string$5()),applicationIcon:optional$3(string$5()),type:oneOf$1(constant$2("app"),constant$2("instance")),displayName:optional$3(string$5()),contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),instanceId:optional$3(string$5()),instanceTitle:optional$3(string$5()),resultType:optional$3(nonEmptyStringDecoder$2),customConfig:optional$3(object$3())}),intentDecoder=object$3({name:nonEmptyStringDecoder$2,handlers:array$3(intentHandlerDecoder)}),intentTargetDecoder=oneOf$1(constant$2("startNew"),constant$2("reuse"),object$3({app:optional$3(nonEmptyStringDecoder$2),instance:optional$3(nonEmptyStringDecoder$2)})),intentContextDecoder=object$3({type:optional$3(nonEmptyStringDecoder$2),data:optional$3(object$3())}),intentsDecoder=array$3(intentDecoder),wrappedIntentsDecoder=object$3({intents:intentsDecoder}),wrappedIntentFilterDecoder=object$3({filter:optional$3(object$3({name:optional$3(nonEmptyStringDecoder$2),contextType:optional$3(nonEmptyStringDecoder$2),resultType:optional$3(nonEmptyStringDecoder$2)}))});object$3({applicationName:nonEmptyStringDecoder$2,applicationIcon:optional$3(string$5()),instanceId:optional$3(string$5())});const applicationStartOptionsDecoder=object$3({top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(windowRelativeDirectionDecoder),waitForAGMReady:optional$3(boolean$4()),channelId:optional$3(nonEmptyStringDecoder$2)}),intentRequestDecoder=object$3({intent:nonEmptyStringDecoder$2,target:optional$3(intentTargetDecoder),context:optional$3(intentContextDecoder),options:optional$3(applicationStartOptionsDecoder),handlers:optional$3(array$3(intentHandlerDecoder)),timeout:optional$3(nonNegativeNumberDecoder$2),waitUserResponseIndefinitely:optional$3(boolean$4()),clearSavedHandler:optional$3(boolean$4())}),resolverConfigDecoder=object$3({enabled:optional$3(boolean$4()),appName:string$5(),waitResponseTimeout:number$5()}),intentResultDecoder=object$3({request:intentRequestDecoder,handler:intentHandlerDecoder,result:anyJson$2()}),resolverResponseDecoder=object$3({intent:nonEmptyStringDecoder$2,handler:intentHandlerDecoder,correlationId:optional$3(string$5()),userSettings:object$3({preserveChoice:optional$3(boolean$4())})}),handlerExclusionCriteriaApplicationNameDecoder=object$3({applicationName:nonEmptyStringDecoder$2}),handlerExclusionCriteriaInstanceIdDecoder=object$3({instanceId:nonEmptyStringDecoder$2}),handlerExclusionCriteriaDecoder=oneOf$1(handlerExclusionCriteriaApplicationNameDecoder,handlerExclusionCriteriaInstanceIdDecoder),handlerFilterDecoder=object$3({title:optional$3(nonEmptyStringDecoder$2),openResolver:optional$3(boolean$4()),timeout:optional$3(nonNegativeNumberDecoder$2),intent:optional$3(nonEmptyStringDecoder$2),contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),resultType:optional$3(nonEmptyStringDecoder$2),applicationNames:optional$3(array$3(nonEmptyStringDecoder$2)),excludeList:optional$3(array$3(handlerExclusionCriteriaDecoder))}),filterHandlersResultDecoder=object$3({handlers:array$3(intentHandlerDecoder)}),embeddedResolverConfigDecoder=object$3({enabled:boolean$4(),initialCaller:object$3({instanceId:nonEmptyStringDecoder$2})}),filterHandlersWithResolverConfigDecoder=object$3({filterHandlersRequest:handlerFilterDecoder,resolverConfig:resolverConfigDecoder,embeddedResolverConfig:optional$3(embeddedResolverConfigDecoder)}),intentInfoDecoder=object$3({intent:nonEmptyStringDecoder$2,contextTypes:optional$3(array$3(nonEmptyStringDecoder$2)),description:optional$3(nonEmptyStringDecoder$2),displayName:optional$3(nonEmptyStringDecoder$2),icon:optional$3(nonEmptyStringDecoder$2),resultType:optional$3(nonEmptyStringDecoder$2)}),getIntentsResultDecoder=object$3({intents:array$3(intentInfoDecoder)}),raiseIntentRequestDecoder=object$3({intentRequest:intentRequestDecoder,resolverConfig:resolverConfigDecoder,embeddedResolverConfig:optional$3(embeddedResolverConfigDecoder)}),appManagerOperationTypesDecoder=oneOf$1(constant$2("appHello"),constant$2("applicationStart"),constant$2("instanceStop"),constant$2("registerWorkspaceApp"),constant$2("unregisterWorkspaceApp"),constant$2("export"),constant$2("import"),constant$2("remove"),constant$2("clear"),constant$2("registerRemoteApps"),constant$2("operationCheck")),basicInstanceDataDecoder=object$3({id:nonEmptyStringDecoder$2}),instanceDataDecoder=object$3({id:nonEmptyStringDecoder$2,applicationName:nonEmptyStringDecoder$2}),applicationDataDecoder=object$3({name:nonEmptyStringDecoder$2,type:nonEmptyStringDecoder$2.where(e=>"window"===e,"Expected a value of window"),createOptions:applicationDetailsDecoder,instances:array$3(instanceDataDecoder),userProperties:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),version:optional$3(nonEmptyStringDecoder$2),icon:optional$3(string$5()),caption:optional$3(nonEmptyStringDecoder$2)});object$3({name:nonEmptyStringDecoder$2,type:nonEmptyStringDecoder$2.where(e=>"window"===e,"Expected a value of window"),createOptions:applicationDetailsDecoder,userProperties:optional$3(anyJson$2()),title:optional$3(nonEmptyStringDecoder$2),version:optional$3(nonEmptyStringDecoder$2),icon:optional$3(string$5()),caption:optional$3(nonEmptyStringDecoder$2)});const appHelloSuccessDecoder$1=object$3({apps:array$3(applicationDataDecoder),initialChannelId:optional$3(nonEmptyStringDecoder$2)}),appHelloDecoder=object$3({windowId:optional$3(nonEmptyStringDecoder$2)}),originAppDecoder=object$3({interopInstance:nonEmptyStringDecoder$2,name:optional$3(nonEmptyStringDecoder$2)}),startReasonDecoder=object$3({originApp:originAppDecoder,intentRequest:optional$3(intentRequestDecoder)}),applicationStartConfigDecoder=object$3({name:nonEmptyStringDecoder$2,id:optional$3(nonEmptyStringDecoder$2),context:optional$3(anyJson$2()),top:optional$3(number$5()),left:optional$3(number$5()),width:optional$3(nonNegativeNumberDecoder$2),height:optional$3(nonNegativeNumberDecoder$2),relativeTo:optional$3(nonEmptyStringDecoder$2),relativeDirection:optional$3(oneOf$1(constant$2("top"),constant$2("left"),constant$2("right"),constant$2("bottom"))),waitForAGMReady:optional$3(boolean$4()),forceChromeTab:optional$3(boolean$4()),layoutComponentId:optional$3(nonEmptyStringDecoder$2),channelId:optional$3(nonEmptyStringDecoder$2),startReason:optional$3(startReasonDecoder)}),appsImportOperationDecoder=object$3({definitions:array$3(allApplicationDefinitionsDecoder),mode:oneOf$1(constant$2("replace"),constant$2("merge"))}),appRemoveConfigDecoder=object$3({name:nonEmptyStringDecoder$2}),appsExportOperationDecoder=object$3({definitions:array$3(glueCoreAppDefinitionDecoder)}),appsRemoteRegistrationDecoder=object$3({definitions:array$3(allApplicationDefinitionsDecoder)});class ApplicationsController{glueController;sessionStorage;stateController;appDirectory;managerController;ioc;registry=CallbackRegistryFactory$2();config;connectionConfig;applicationStartTimeoutMs=15e3;managerAppsCheckCount=0;started=!1;defaultBounds;explicitClosingInstanceIds={};isManagerConfigured;locks={};operations={appHello:{name:"appHello",dataDecoder:appHelloDecoder,resultDecoder:appHelloSuccessDecoder$1,execute:this.handleAppHello.bind(this)},applicationStart:{name:"applicationStart",dataDecoder:applicationStartConfigDecoder,resultDecoder:instanceDataDecoder,execute:this.handleApplicationStart.bind(this)},instanceStop:{name:"instanceStop",dataDecoder:basicInstanceDataDecoder,execute:this.handleInstanceStop.bind(this)},registerWorkspaceApp:{name:"registerWorkspaceApp",dataDecoder:workspaceWindowDataDecoder,execute:this.registerWorkspaceApp.bind(this)},unregisterWorkspaceApp:{name:"unregisterWorkspaceApp",dataDecoder:simpleWindowDecoder,execute:this.unregisterWorkspaceApp.bind(this)},import:{name:"import",dataDecoder:appsImportOperationDecoder,execute:this.handleImport.bind(this)},remove:{name:"remove",dataDecoder:appRemoveConfigDecoder,execute:this.handleRemove.bind(this)},export:{name:"export",resultDecoder:appsExportOperationDecoder,execute:this.handleExport.bind(this)},clear:{name:"clear",execute:this.handleClear.bind(this)},registerRemoteApps:{name:"registerRemoteApps",dataDecoder:appsRemoteRegistrationDecoder,execute:this.handleRegisterRemoteApps.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i,o){this.glueController=e,this.sessionStorage=t,this.stateController=r,this.appDirectory=n,this.managerController=i,this.ioc=o}get logger(){return logger.get("applications.controller")}handlePlatformShutdown(){this.managerAppsCheckCount=0,this.locks={},this.started=!1,this.appDirectory.stop()}async start(e){this.defaultBounds=e.windows.defaultWindowOpenBounds,this.logger?.trace("initializing applications"),this.config=e.applications,this.connectionConfig=e.connection,this.isManagerConfigured=!!e.manager?.url,await this.appDirectory.start({config:e.applications,appsStateChange:e=>this.emitStreamData("appDirectoryStateChange",e),sequelizer:this.ioc.createSequelizer(),isManagerConfigured:this.isManagerConfigured}),this.started=!0,this.stateController.onWindowDisappeared(e=>this.processInstanceClosed(e).catch(e=>this.logger?.warn(`error while processing instance closed: ${e?.message}`))),this.logger?.trace("initialization is completed")}async ready(){if(!this.isManagerConfigured)return;const e=this.managerController.getAllApps();await this.confirmApps(e)}async confirmApps(e){const t=this.glueController.clientGlue,r=e.every(e=>{const r=e.appId??e.name;return!!t.appManager.application(r)});return++this.managerAppsCheckCount,r?this.logger?.trace("all manager applications are loaded, proceeding"):this.managerAppsCheckCount>10?ioError.raiseError("not all manager applications are loaded after 10 checks, stopping the process"):(this.logger?.trace("not all manager applications are loaded, waiting for them to be loaded"),await wait(500),this.confirmApps(e))}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=appManagerOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This appManager request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`AppManager request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`AppManager request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(e,t){if(this.logger?.trace(`handling unloading of ${e}`),e&&!this.explicitClosingInstanceIds[e])return!t||t.closed?(this.logger?.trace(`${e} detected as closed, processing instance closed`),void this.processInstanceClosed(e).catch(e=>this.logger?.warn(`error while processing instance closed: ${e.message}`))):void this.logger?.trace(`${e} detected as not closed, skipping instance closed procedure`)}async unregisterWorkspaceApp(e){this.sessionStorage.removeEjectedWindowId(e.windowId),this.ioc.windowsController.setExplicitClosingWindowId(e.windowId),this.explicitClosingInstanceIds[e.windowId]=!0,await this.processInstanceClosed(e.windowId),await this.ioc.windowsController.cleanUpWindow(e.windowId),this.ioc.portsBridge.removeGwClient(e.windowId)}async handleApplicationStart(e,t){this.logger?.trace(`[${t}] handling application start command for application: ${e.name}`);const r=new Date,n=(await this.appDirectory.getAll()).find(t=>t.name===e.name);if(!n)return ioError.raiseError(`Cannot start an instance of application: ${e.name}, because it is not found.`);if(checkIsOriginBlocked(n.createOptions.url,this.connectionConfig.blockList))return ioError.raiseError(`Cannot start an instance of application: ${e.name}, because its origin is blocked by the Platform`);const i={id:e.id??`g42-${nanoid$5(10)}`,applicationName:e.name},o=await this.getStartingBounds(n.createOptions,e,t),s=e.forceChromeTab?void 0:`left=${o.left},top=${o.top},width=${o.width},height=${o.height}`;this.logger?.trace(`[${t}] open arguments are valid, opening to bounds: ${s}`);const a=window.open(n.createOptions.url,i.id,s);if(!a)return ioError.raiseError(`Cannot start an instance with url: ${n.createOptions.url} for application: ${e.name}. The most likely reason is that the user has not approved popups or has a blocker.`);this.sessionStorage.saveBridgeInstanceData({windowId:i.id,appName:i.applicationName});const c={data:i,context:e.context};if(await this.processNewInstance(c),this.logger?.trace(`[${t}] the new window has been opened successfully with id: ${i.id}, checking for AGM ready and notifying windows`),e.waitForAGMReady&&(this.logger?.trace(`[${t}] wait for AGM is set, configuring the lock`),this.setLock(i.id)),await this.notifyWindows(n.createOptions.url,i,o,a,e.context,e.layoutComponentId,e.channelId),e.channelId&&this.sessionStorage.addWindowChannel(i.id,e.channelId),this.locks[i.id])try{await PromiseWrap(()=>this.locks[i.id]?.keyOne,this.applicationStartTimeoutMs)}catch(t){return delete this.locks[i.id],ioError.raiseError(`Application start for ${e.name} timed out waiting for client to initialize Glue`)}this.logger?.trace(`[${t}] the windows controller has been successfully notified`),this.logger?.trace(`[${t}] the new instance with id ${i.id} has been saved, announced and context set, lifting key two and responding to caller`),this.locks[i.id]?.openKeyTwo();const l=this.glueController.getLocalServers().find(({instance:e})=>i.id===e),u={start:r,end:new Date};return this.registry.execute("instance-started",{id:i.id,api:l?.api,applicationName:i.applicationName,startup:u}),i}onInstanceStarted(e){return"function"!=typeof e?ioError.raiseError("onInstanceStarted requires a single argument of type function"):this.registry.add("instance-started",e)}async processInstanceClosed(e){if(!e)return;const t=this.sessionStorage.getInstanceData(e);if(t){delete this.locks[t.id],this.sessionStorage.removeInstance(t.id);try{await this.glueController.clearContext(e,"instance")}catch(t){this.logger?.warn(`error while clearing the context of instance ${e}: ${t?.message}`)}this.emitStreamData("instanceStopped",t),await this.waitEventFlush(),delete this.explicitClosingInstanceIds[t.id]}}async notifyWindows(e,t,r,n,i,o,s){const a={windowId:t.id,name:`${t.applicationName}_${t.id}`,initialUrl:e,initialContext:i,initialBounds:r,layoutComponentId:o,initialChannelId:s};await this.ioc.windowsController.processNewWindow(a,i,n)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleAppHello(e,t){this.logger?.trace(`[${t}] handling hello message for id: ${e.windowId}`),e.windowId&&this.locks[e.windowId]&&(this.logger?.trace(`[${t}] found an app lock, unlocking key one and waiting for the second one`),this.locks[e.windowId].openKeyOne(),await this.locks[e.windowId].keyTwo,delete this.locks[e.windowId],this.logger?.trace(`[${t}] the lock is lifted, proceeding`));const r=this.sessionStorage.getAllInstancesData(),n=(await this.appDirectory.getAll()).map(e=>{const t=r.filter(t=>t.applicationName===e.name);return{...e,instances:t}});if(e.windowId){this.logger?.trace(`[${t}] there is a valid windowId, removing ${e.windowId} from the state controller`),this.stateController.remove(e.windowId);const r=n.find(t=>t.instances.some(t=>t.id===e.windowId));if(r?.title){const n=e.windowId,i=r.title;PromiseWrap(()=>this.glueController.callWindow("windows",this.ioc.windowsController.setTitleOperation,{windowId:n,title:i},{windowId:n}),2e4).catch(e=>this.logger?.trace(`[${t}] error while setting the application instance title: ${e.message}`))}}if(!e.windowId){this.logger?.trace(`[${t}] no windowId was provided, returning all apps without initialChannelId`);return{apps:n}}const i=this.sessionStorage.getWindowDataById(e.windowId),o=this.sessionStorage.getWindowChannelData(e.windowId),s=o?o.channels?.[0]:i?.initialChannelId,a={apps:n,initialChannelId:s};return this.logger?.trace(`[${t}] compiled a list of all active applications and instances and returning it to the caller with initialChannelId: ${s}`),a}async handleInstanceStop(e,t){this.logger?.trace(`[${t}] handling stop command for instance: ${e.id}`);if(this.sessionStorage.getWorkspaceClientById(e.id))return this.logger?.trace(`[${t}] this instance is detected as a workspace window, closing via the workspaces controller`),void await this.ioc.workspacesController.closeItem({itemId:e.id},t);if(!this.sessionStorage.getInstanceData(e.id))return ioError.raiseError(`Cannot close instance: ${e.id}, because it is not known by the platform`);const r=this.sessionStorage.getWindowDataById(e.id);if(!r)return ioError.raiseError(`Cannot close instance: ${e.id}, because it's window is not known by the platform`);this.ioc.windowsController.setExplicitClosingWindowId(e.id),this.explicitClosingInstanceIds[e.id]=!0,window.open(void 0,r.windowId)?.close(),await this.processInstanceClosed(e.id),await this.ioc.windowsController.cleanUpWindow(e.id),this.logger?.trace(`[${t}] instance ${e.id} has been closed, removed from store, announced stopped and notified windows, responding to caller`)}async handleRegisterRemoteApps(e,t){if(this.logger?.trace(`[${t}] handling remote bypass command`),this.config.remote)return ioError.raiseError(`[${t}] cannot accept remote apps from the protocol, because there is an active remote configuration.`);await this.appDirectory.processAppDefinitions(e.definitions,{mode:"replace",type:"remote"}),this.logger?.trace(`[${t}] remote bypass command completed`)}async handleImport(e,t){this.logger?.trace(`[${t}] handling import command`),await this.appDirectory.processAppDefinitions(e.definitions,{type:"inmemory",mode:e.mode}),this.logger?.trace(`[${t}] import command completed`)}async handleRemove(e,t){this.logger?.trace(`[${t}] handling remove command for ${e.name}`);const r=await this.appDirectory.removeInMemory(e.name);r&&(this.logger?.trace(`definition ${r.name} removed successfully`),this.emitStreamData("appDirectoryStateChange",{appsRemoved:[r],appsAdded:[],appsChanged:[]}))}async handleExport(e,t){this.logger?.trace(`[${t}] handling export command`);const r=await this.appDirectory.exportInMemory();return this.logger?.trace(`[${t}] export command successful`),{definitions:r}}async handleClear(e,t){this.logger?.trace(`[${t}] handling clear command`),await this.appDirectory.processAppDefinitions([],{type:"inmemory",mode:"replace"}),this.logger?.trace(`[${t}] all in-memory apps are cleared`)}setLock(e){const t={},r=new Promise(e=>{t.openKeyOne=e}),n=new Promise(e=>{t.openKeyTwo=e});t.keyOne=r,t.keyTwo=n,this.locks[e]=t}async registerWorkspaceApp(e,t){if(!e.appName)return ioError.raiseError(`Cannot register application with config: ${JSON.stringify(e)}, because no app name was found`);const r=await this.appDirectory.getAll();if(e.appName===defaultNoAppWindowComponentAppName$1)return await this.ioc.windowsController.registerWorkspaceWindow(e,t);if(!r.some(t=>t.name===e.appName))return ioError.raiseError(`Cannot register application with config: ${JSON.stringify(e)}, because no app with this name name was found`);this.sessionStorage.removeEjectedWindowId(e.windowId),e.channelId&&this.sessionStorage.addWindowChannel(e.windowId,e.channelId),this.sessionStorage.saveBridgeInstanceData({windowId:e.windowId,appName:e.appName}),this.logger?.trace(`[${t}] processing valid workspace application registration with id ${e.windowId}, app name ${e.appName} and frame ${e.frameId}`),e.context&&await this.glueController.setStartContext(e.windowId,e.context,"instance");const n={id:e.windowId,applicationName:e.appName};this.sessionStorage.saveInstanceData(n),this.emitStreamData("instanceStarted",n),this.logger?.trace(`[${t}] instance registration is completed and announced, calling windows registration`),await this.ioc.windowsController.registerWorkspaceWindow(e,t)}async processNewInstance(e){e.context&&await this.glueController.setStartContext(e.data.id,e.context,"instance"),this.sessionStorage.saveInstanceData(e.data),this.emitStreamData("instanceStarted",e.data)}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("appManager",e,t)}async getStartingBounds(e,t,r){const n={top:t.top??e.top??this.defaultBounds.top,left:t.left??e.left??this.defaultBounds.left,width:t.width??e.width??this.defaultBounds.width,height:t.height??e.height??this.defaultBounds.height};if(!t.relativeTo)return n;try{const e=await this.ioc.windowsController.getWindowBounds(t.relativeTo,r),i=t.relativeDirection??"right";return getRelativeBounds(n,e,i)}catch(e){return n}}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}const layoutsOperationTypesDecoder=oneOf$1(constant$2("get"),constant$2("getAll"),constant$2("export"),constant$2("import"),constant$2("remove"),constant$2("save"),constant$2("restore"),constant$2("rename"),constant$2("getGlobalPermissionState"),constant$2("checkGlobalActivated"),constant$2("requestGlobalPermission"),constant$2("operationCheck"),constant$2("getDefaultGlobal"),constant$2("setDefaultGlobal"),constant$2("clearDefaultGlobal"),constant$2("updateMetadata"),constant$2("getCurrent")),newLayoutOptionsDecoder=object$3({name:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),metadata:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2)),setAsCurrent:optional$3(boolean$4()),ignoreContexts:optional$3(boolean$4())}),restoreOptionsDecoder=object$3({name:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),closeRunningInstance:optional$3(boolean$4()),closeMe:optional$3(boolean$4()),timeout:optional$3(nonNegativeNumberDecoder$2)}),simpleLayoutConfigDecoder=object$3({name:nonEmptyStringDecoder$2,type:layoutTypeDecoder}),getAllLayoutsConfigDecoder=object$3({type:layoutTypeDecoder}),saveLayoutConfigDecoder=object$3({layout:newLayoutOptionsDecoder}),renameLayoutConfigDecoder=object$3({layout:glueLayoutDecoder,newName:nonEmptyStringDecoder$2}),layoutResultDecoder=object$3({status:nonEmptyStringDecoder$2}),updateLayoutMetadataConfigDecoder=object$3({layout:glueLayoutDecoder}),restoreLayoutConfigDecoder=object$3({layout:restoreOptionsDecoder}),allLayoutsFullConfigDecoder=object$3({layouts:array$3(glueLayoutDecoder)}),importModeDecoder=oneOf$1(constant$2("replace"),constant$2("merge")),layoutsImportConfigDecoder=object$3({layouts:array$3(glueLayoutDecoder),mode:importModeDecoder,skipManagerRequest:optional$3(boolean$4())}),allLayoutsSummariesResultDecoder=object$3({summaries:array$3(layoutSummaryDecoder$1)});object$3({layout:glueLayoutDecoder});const optionalSimpleLayoutResult=object$3({layout:optional$3(glueLayoutDecoder)}),setDefaultGlobalConfigDecoder=object$3({name:nonEmptyStringDecoder$2});object$3({layoutType:oneOf$1(constant$2("Global"),constant$2("Workspace")),layoutName:nonEmptyStringDecoder$2,context:optional$3(anyJson$2()),instances:optional$3(array$3(nonEmptyStringDecoder$2)),ignoreInstances:optional$3(array$3(nonEmptyStringDecoder$2))}),object$3({windowContext:optional$3(anyJson$2())});const fullSaveRequestResponseDecoder=object$3({bounds:windowBoundsDecoder,windowContext:optional$3(anyJson$2()),url:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2,application:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2,initialContext:optional$3(anyJson$2())});object$3({windowContext:optional$3(anyJson$2()),windowId:nonEmptyStringDecoder$2,frameId:nonEmptyStringDecoder$2}),object$3({windows:array$3(fullSaveRequestResponseDecoder)});const permissionStateResultDecoder=object$3({state:oneOf$1(constant$2("prompt"),constant$2("denied"),constant$2("granted"))}),simpleAvailabilityResultDecoder=object$3({isAvailable:boolean$4()}),defaultNoAppWindowComponentAppName="no-app-window",defaultPermissionTimeoutMS=25e3,defaultRestHeaders$1={"Content-Type":"application/json",Accept:"application/json"},defaultRestRequestTimeoutMS$1=3e4,layoutEventOperations={added:"layoutAdded",changed:"layoutChanged",removed:"layoutRemoved",renamed:"layoutRenamed"},getWindowManagementPermissionStatus=async e=>{try{return await navigator.permissions.query({name:"window-management"})}catch(t){e?.warn(extractErrorMsg$1(t));return await navigator.permissions.query({name:"window-placement"})}};class LayoutsController{glueController;globalBuilder;globalRestorer;localStore;managerStore;restStore;sessionStore;registry=CallbackRegistryFactory$2();unsubFuncs=[];started=!1;store;operations={get:{name:"get",dataDecoder:simpleLayoutConfigDecoder,resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetLayout.bind(this)},getAll:{name:"getAll",dataDecoder:getAllLayoutsConfigDecoder,resultDecoder:allLayoutsSummariesResultDecoder,execute:this.handleGetAll.bind(this)},getCurrent:{name:"getCurrent",resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetCurrentLayout.bind(this)},export:{name:"export",dataDecoder:getAllLayoutsConfigDecoder,resultDecoder:allLayoutsFullConfigDecoder,execute:this.handleExport.bind(this)},import:{name:"import",dataDecoder:layoutsImportConfigDecoder,execute:this.handleImport.bind(this)},remove:{name:"remove",dataDecoder:simpleLayoutConfigDecoder,execute:this.handleRemove.bind(this)},rename:{name:"rename",dataDecoder:renameLayoutConfigDecoder,resultDecoder:layoutResultDecoder,execute:this.handleRename.bind(this)},save:{name:"save",dataDecoder:saveLayoutConfigDecoder,execute:this.handleSave.bind(this)},restore:{name:"restore",dataDecoder:restoreLayoutConfigDecoder,execute:this.handleRestore.bind(this)},getGlobalPermissionState:{name:"getGlobalPermissionState",resultDecoder:permissionStateResultDecoder,execute:this.handleGetGlobalPermissionState.bind(this)},requestGlobalPermission:{name:"requestGlobalPermission",resultDecoder:simpleAvailabilityResultDecoder,execute:this.handleRequestGlobalPermission.bind(this)},checkGlobalActivated:{name:"checkGlobalActivated",resultDecoder:simpleAvailabilityResultDecoder,execute:this.handleCheckGlobalActivated.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},getDefaultGlobal:{name:"getDefaultGlobal",resultDecoder:optionalSimpleLayoutResult,execute:this.handleGetDefaultGlobal.bind(this)},setDefaultGlobal:{name:"setDefaultGlobal",dataDecoder:setDefaultGlobalConfigDecoder,execute:this.handleSetDefaultGlobal.bind(this)},clearDefaultGlobal:{name:"clearDefaultGlobal",execute:this.handleClearDefaultGlobal.bind(this)},updateMetadata:{name:"updateMetadata",dataDecoder:updateLayoutMetadataConfigDecoder,execute:this.handleUpdateMetadata.bind(this)}};constructor(e,t,r,n,i,o,s){this.glueController=e,this.globalBuilder=t,this.globalRestorer=r,this.localStore=n,this.managerStore=i,this.restStore=o,this.sessionStore=s}get logger(){return logger.get("layouts.controller")}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.store.stop()}async start(e){this.store=this.getStore(e),this.setupStoreListeners(),await this.store.start(e),this.started=!0,this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this windows control message, because the controller has not been started");const t=e.data,r=e.commandId,n=layoutsOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This layouts request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Layouts request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r,e.callerId,e.callerType),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Layouts request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleSave(e,t){this.logger?.trace(`[${t}] handling save layout with config: ${JSON.stringify(e)}`),await this.checkRequestPermission("save"),this.logger?.trace(`[${t}] the required permissions are granted, proceeding.`);const r=await this.globalBuilder.saveGlobalLayout(e,t);return(e.layout.setAsCurrent??!0)&&this.sessionStore.setLayoutsSystemData({currentLayoutName:r.name}),this.logger?.trace(`[${t}] layout ${e.layout.name} was saved successfully`),{layout:r}}async handleRestore(e,t,r,n){this.logger?.trace(`[${t}] handling restore layout with config: ${JSON.stringify(e)}`),await this.checkRequestPermission("restore",e.layout.timeout);const i=new Date,o=await this.get("Global",e.layout.name,t);if(!o)return ioError.raiseError(`Layout with name "${e.layout.name}" and type: "Global" cannot be found`);await this.globalRestorer.restoreGlobalLayout(e,t,r,n);const s=new Date;this.registry.execute("layout-restored",{layoutName:e.layout.name,startTime:i,endTime:s}),await this.emitData({operation:"layoutRestored",layout:o}),this.logger?.trace(`[${t}] layout ${e.layout.name} was restored successfully`)}onLayoutRestored(e){return"function"!=typeof e?ioError.raiseError("onLayoutRestored requires a single argument of type function"):this.registry.add("layout-restored",e)}async handleGetAll(e,t){this.logger?.trace(`[${t}] handling get all layout summaries request for type: ${e.type}`);const r=(await this.store.getAllLayouts(e.type,t)).map(e=>({name:e.name,type:e.type,context:e.context,metadata:e.metadata}));return this.logger?.trace(`[${t}] all summaries have been compiled, responding to caller`),{summaries:r}}async handleGetCurrentLayout(e,t){this.logger?.trace(`[${t}] handling get current layout request`);const{currentLayoutName:r}=this.sessionStore.getLayoutsSystemData(),n=r?await this.get("Global",r,t):void 0;return this.logger?.trace(`[${t}] request completed, responding to the caller with layout with name: ${r}`),{layout:n}}async handleExport(e,t){this.logger?.trace(`[${t}] handling get all layout full request for type: ${e.type}`);const r=await this.store.getAllLayouts(e.type,t);return this.logger?.trace(`[${t}] full layouts collection have been compiled, responding to caller`),{layouts:r}}async handleImport(e,t){this.logger?.trace(`[${t}] handling mass import request for layout names: ${e.layouts.map(e=>e.name).join(", ")}`);const r=e.layouts.filter(e=>"Workspace"===e.type),n=e.layouts.filter(e=>"Global"===e.type).map(e=>({...e,token:e.token??generateLayoutToken()}));await this.store.saveLayouts(r,n,e.mode,t),this.logger?.trace(`[${t}] mass import completed, responding to caller`)}async handleRemove(e,t){this.logger?.trace(`[${t}] handling remove request for ${JSON.stringify(e)}`);const r=await this.get(e.type,e.name,t);r?(await this.store.deleteLayout(r,t),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed`)):this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" cannot be found and therefore cannot be removed`)}async handleRename(e,t){this.logger?.trace(`[${t}] handling rename request for ${JSON.stringify(e)}`);const r=e.layout.name;if(e.newName===r)return this.logger?.trace(`[${t}] The provided new layout name ${e.newName} is the same as the current one.`),{status:"Success"};const n=await this.get(e.layout.type,r,t);if(!n){const n=`layout with name "${r}" and type: "${e.layout.type}" cannot be found`;return this.logger?.trace(`[${t}] ${n}`),{status:n}}return await this.store.renameLayout(n,e.newName,t)}async handleUpdateMetadata(e,t){this.logger?.trace(`[${t}] handling update metadata request for ${JSON.stringify(e)}`);const r=await this.get(e.layout.type,e.layout.name,t);if(!r)return ioError.raiseError(`Layout with name "${e.layout.name}" and type: "${e.layout.type}" cannot be found`);const n={...r,metadata:e.layout.metadata};return"Global"===r.type?await this.store.saveLayouts([],[n],"merge",t):await this.store.saveLayouts([n],[],"merge",t)}async handleGetLayout(e,t){this.logger?.trace(`[${t}] handling get layout request for name: ${e.name} and type: ${e.type}`);const r=(await this.store.getAllLayouts(e.type,t)).find(t=>t.name===e.name);return this.logger?.trace(`[${t}] request completed, responding to the caller`),{layout:r}}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleGetGlobalPermissionState(e,t){this.logger?.trace(`[${t}] handling Get Global Permission State request`);const{state:r}=await getWindowManagementPermissionStatus(this.logger);return this.logger?.trace(`[${t}] request completed with state: ${r}, responding to the caller`),{state:r}}async handleRequestGlobalPermission(e,t){this.logger?.trace(`[${t}] handling Request Global Permission command`);const{state:r}=await getWindowManagementPermissionStatus(this.logger);if("granted"===r)return{isAvailable:!0};if("denied"===r)return{isAvailable:!1};try{return await window.getScreenDetails(),this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!0}}catch(e){return this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!1}}}async handleCheckGlobalActivated(e,t){return this.logger?.trace(`[${t}] handling Check Global Activated request`),this.logger?.trace(`[${t}] request completed, responding to the caller`),{isAvailable:!0}}async handleGetDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Get Default Global request`);return{layout:await this.store.getDefaultLayout(t)}}async handleSetDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Set Default Global request for name: ${e.name}`);const r=(await this.store.getAllLayouts("Global",t)).find(t=>t.name===e.name);if(!r)return ioError.raiseError(`Layout ${e.name} does not exist`);await this.store.setDefaultLayout(e.name,t),await this.emitData({operation:"defaultLayoutChanged",layout:{name:r.name}})}async handleClearDefaultGlobal(e,t){this.logger?.trace(`[${t}] handling Clear Default Global request`),await this.store.clearDefaultLayout(t),await this.emitData({operation:"defaultLayoutChanged"}),this.logger?.trace(`[${t}] request completed, responding to the caller`)}updateCurrentLayoutIfNeeded(e){if("Global"!==e.layout.type)return;const t=this.sessionStore.getLayoutsSystemData(),r=e.operation===layoutEventOperations.renamed&&t.currentLayoutName===e.layout.prevName,n=e.operation===layoutEventOperations.removed&&t.currentLayoutName===e.layout.name;(r||n)&&(r&&(t.currentLayoutName=e.layout.name),n&&(t.currentLayoutName=void 0),this.sessionStore.setLayoutsSystemData(t))}async emitData(e){this.logger?.trace(`sending notification of event: ${e.operation} with data: ${JSON.stringify(e)}`),this.glueController.pushSystemMessage("layouts",e.operation,e.layout)}async announceEvents(e){let t=0;for(const r of e)++t,t%10==0&&await this.waitEventFlush(),await this.emitData(r)}async get(e,t,r){return(await this.store.getAllLayouts(e,r)).find(r=>r.name===t&&r.type===e)}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}async checkRequestPermission(e,t=defaultPermissionTimeoutMS){if(window.gtf)return;const{state:r}=await getWindowManagementPermissionStatus(this.logger);switch(r){case"granted":return;case"prompt":try{return void await PromiseWrap(()=>window.getScreenDetails(),t,"Timeout waiting for user permission for Multi-Screen Window Placement")}catch(t){return ioError.raiseError(`Cannot complete operation ${e} for Global Layouts, because the user has not granted the Multi-Screen Window Placement permission`)}case"denied":return ioError.raiseError(`Cannot complete operation ${e} for Global Layouts, because the user has denied the Multi-Screen Window Placement permission`)}}setupStoreListeners(){const e=this.store.onLayoutsAdded(e=>{this.announceEvents(e.map(e=>({operation:layoutEventOperations.added,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),t=this.store.onLayoutsChanged(e=>{this.announceEvents(e.map(e=>({operation:layoutEventOperations.changed,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),r=this.store.onLayoutsRemoved(e=>{const t=layoutEventOperations.removed;this.announceEvents(e.map(e=>({operation:t,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e))),e.forEach(e=>this.updateCurrentLayoutIfNeeded({operation:t,layout:e}))}),n=this.store.onLayoutsRenamed(e=>{const t=layoutEventOperations.renamed;this.announceEvents(e.map(e=>({operation:t,layout:e}))).catch(e=>this.logger?.warn(extractErrorMsg$1(e))),e.forEach(e=>this.updateCurrentLayoutIfNeeded({operation:t,layout:e}))});this.unsubFuncs.push(e,t,r,n)}getStore(e){const t=e.layouts?.mode,r=!(!e?.manager?.url||!e?.manager?.features?.layoutsStore),n=!!e?.layouts?.rest?.url;return!t&&r?this.managerStore:!t&&n?this.restStore:t||r?"idb"===t||"session"===t?(this.checkForConflictingLocalSettings(n),this.localStore):"rest"===t&&n?this.restStore:"rest"!==t||n?"manager"===t&&r?this.managerStore:"manager"!==t||r?ioError.raiseError("Cannot set layouts store."):ioError.raiseError("The layouts store is configured to be managed, but the manager is not configured."):ioError.raiseError("The layouts store is configured to be rest, but the rest url is not configured."):this.localStore}checkForConflictingLocalSettings(e){if(e)return ioError.raiseError("Layouts store is configured to be local, but the rest url is also configured. Please either remove de-config rest or set the layouts store to be rest.")}}const instanceOfAny=(e,t)=>t.some(t=>e instanceof t);let idbProxyableTypes,cursorAdvanceMethods;function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const cursorRequestMap=new WeakMap,transactionDoneMap=new WeakMap,transactionStoreNamesMap=new WeakMap,transformCache=new WeakMap,reverseTransformCache=new WeakMap;function promisifyRequest(e){const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",o)},i=()=>{t(wrap(e.result)),n()},o=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",o)});return t.then(t=>{t instanceof IDBCursor&&cursorRequestMap.set(t,e)}).catch(()=>{}),reverseTransformCache.set(t,e),t}function cacheDonePromiseForTransaction(e){if(transactionDoneMap.has(e))return;const t=new Promise((t,r)=>{const n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",o),e.removeEventListener("abort",o)},i=()=>{t(),n()},o=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",o),e.addEventListener("abort",o)});transactionDoneMap.set(e,t)}let idbProxyTraps={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return transactionDoneMap.get(e);if("objectStoreNames"===t)return e.objectStoreNames||transactionStoreNamesMap.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return wrap(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function replaceTraps(e){idbProxyTraps=e(idbProxyTraps)}function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?getCursorAdvanceMethods().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(cursorRequestMap.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...r){const n=e.call(unwrap(this),t,...r);return transactionStoreNamesMap.set(n,t.sort?t.sort():[t]),wrap(n)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&cacheDonePromiseForTransaction(e),instanceOfAny(e,getIdbProxyableTypes())?new Proxy(e,idbProxyTraps):e)}function wrap(e){if(e instanceof IDBRequest)return promisifyRequest(e);if(transformCache.has(e))return transformCache.get(e);const t=transformCachableValue(e);return t!==e&&(transformCache.set(e,t),reverseTransformCache.set(t,e)),t}const unwrap=e=>reverseTransformCache.get(e);function openDB(e,t,{blocked:r,upgrade:n,blocking:i,terminated:o}={}){const s=indexedDB.open(e,t),a=wrap(s);return n&&s.addEventListener("upgradeneeded",e=>{n(wrap(s.result),e.oldVersion,e.newVersion,wrap(s.transaction),e)}),r&&s.addEventListener("blocked",e=>r(e.oldVersion,e.newVersion,e)),a.then(e=>{o&&e.addEventListener("close",()=>o()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}function deleteDB(e,{blocked:t}={}){const r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",e=>t(e.oldVersion,e)),wrap(r).then(()=>{})}const readMethods=["get","getKey","getAll","getAllKeys","count"],writeMethods=["put","add","delete","clear"],cachedMethods=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(cachedMethods.get(t))return cachedMethods.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,i=writeMethods.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!i&&!readMethods.includes(r))return;const o=async function(e,...t){const o=this.transaction(e,i?"readwrite":"readonly");let s=o.store;return n&&(s=s.index(t.shift())),(await Promise.all([s[r](...t),i&&o.done]))[0]};return cachedMethods.set(t,o),o}replaceTraps(e=>({...e,get:(t,r,n)=>getMethod(t,r)||e.get(t,r,n),has:(t,r)=>!!getMethod(t,r)||e.has(t,r)}));class IDBController{_database;defaultDBName="glue42core";dbName=this.defaultDBName;dbVersion=3;globalLayoutsObjectStoreName="globalLayouts";prefsObjectStoreName="prefs";serviceWorkerObjectStoreName="serviceWorker";workspaceLayoutsObjectStoreName="workspaceLayouts";constructor(){"indexedDB"in window||ioError.raiseError("Cannot initialize the local storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open database")}async start(e){e?.id&&(this.dbName=e?.id);const t=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=t}stop(){this.database.close(),delete this._database,this.dbName=this.defaultDBName}getAllLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.getAll(t)}deleteLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.delete(r,e)}clearLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.clear(t)}getLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.get(r,e)}storeLayout(e){runDecoderWithIOError(glueLayoutDecoder,e);const t=this.getLayoutsObjectStoreName(e.type);return this.database.put(t,e,e.name)}async renameLayout(e,t){runDecoderWithIOError(glueLayoutDecoder,e);const r=this.getLayoutsObjectStoreName(e.type),n=this.database.transaction(r,"readwrite");return await Promise.all([n.store.delete(t),n.store.put(e,e.name),n.done]),e}getLayoutsObjectStoreName(e){switch(e){case"Workspace":return this.workspaceLayoutsObjectStoreName;case"Global":return this.globalLayoutsObjectStoreName;default:return ioError.raiseError(`The provided layout type is not recognized: ${e}`)}}clearServiceWorker(){return this.database.clear(this.serviceWorkerObjectStoreName)}storeServiceWorker(e){return this.database.put(this.serviceWorkerObjectStoreName,e,"workerData")}async clearAllPrefs(e){const t=(await this.getAllPrefs()).map(({app:t})=>({app:t,data:{},lastUpdate:e})),r=this.database.transaction(this.prefsObjectStoreName,"readwrite");return await Promise.all([...t.map(e=>r.store.put(e,e.app)),r.done]),t}getAllPrefs(){return this.database.getAll(this.prefsObjectStoreName)}getPrefs(e){return this.database.get(this.prefsObjectStoreName,e)}deletePrefs(e){return this.database.delete(this.prefsObjectStoreName,e)}async replaceAllPrefs(e){const t=this.database.transaction(this.prefsObjectStoreName,"readwrite");return await t.store.clear(),await Promise.all([...e.map(e=>t.store.put(e,e.app)),t.done]),e}async setPrefs(e){return await this.database.put(this.prefsObjectStoreName,e,e.app),e}async updatePrefs(e){const t=await this.database.get(this.prefsObjectStoreName,e.app),r=t?{app:e.app,data:{...t.data,...e.data},lastUpdate:e.lastUpdate}:e;return this.setPrefs(r)}setUpDB(e){e.objectStoreNames.contains(this.workspaceLayoutsObjectStoreName)||e.createObjectStore(this.workspaceLayoutsObjectStoreName),e.objectStoreNames.contains(this.globalLayoutsObjectStoreName)||e.createObjectStore(this.globalLayoutsObjectStoreName),e.objectStoreNames.contains(this.serviceWorkerObjectStoreName)||e.createObjectStore(this.serviceWorkerObjectStoreName),e.objectStoreNames.contains(this.prefsObjectStoreName)||e.createObjectStore(this.prefsObjectStoreName)}}const defaultLoadingConfig={defaultStrategy:"direct",delayed:{batch:1,initialOffsetInterval:1e3,interval:5e3},showDelayedIndicator:!1};class WorkspacesController{framesController;glueController;stateController;hibernationWatcher;sequelizer;sessionStorageController;ioc;registry=CallbackRegistryFactory$2();_started=!1;settings;defaultWindowOpenBounds;connectionConfig;operations={frameHello:{name:"frameHello",dataDecoder:frameHelloDecoder,execute:this.handleFrameHello.bind(this)},isWindowInWorkspace:{name:"isWindowInWorkspace",dataDecoder:simpleItemConfigDecoder,resultDecoder:isWindowInSwimlaneResultDecoder,execute:this.isWindowInWorkspace.bind(this)},createWorkspace:{name:"createWorkspace",dataDecoder:workspaceCreateConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.createWorkspace.bind(this)},createFrame:{name:"createFrame",resultDecoder:frameSummaryResultDecoder,execute:this.createFrame.bind(this)},initFrame:{name:"initFrame",resultDecoder:voidResultDecoder,execute:this.initFrame.bind(this)},getAllFramesSummaries:{name:"getAllFramesSummaries",resultDecoder:frameSummariesResultDecoder,execute:this.getAllFramesSummaries.bind(this)},getFrameSummary:{name:"getFrameSummary",dataDecoder:getFrameSummaryConfigDecoder,resultDecoder:frameSummaryDecoder,execute:this.getFrameSummary.bind(this)},getAllWorkspacesSummaries:{name:"getAllWorkspacesSummaries",resultDecoder:workspaceSummariesResultDecoder,execute:this.getAllWorkspacesSummaries.bind(this)},getWorkspaceSnapshot:{name:"getWorkspaceSnapshot",dataDecoder:simpleItemConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.getWorkspaceSnapshot.bind(this)},getAllLayoutsSummaries:{name:"getAllLayoutsSummaries",resultDecoder:layoutSummariesDecoder,execute:this.getAllLayoutsSummaries.bind(this)},openWorkspace:{name:"openWorkspace",dataDecoder:openWorkspaceConfigDecoder,resultDecoder:workspaceSnapshotResultDecoder,execute:this.openWorkspace.bind(this)},deleteLayout:{name:"deleteLayout",dataDecoder:deleteLayoutConfigDecoder,resultDecoder:voidResultDecoder,execute:this.deleteLayout.bind(this)},saveLayout:{name:"saveLayout",dataDecoder:workspaceLayoutSaveConfigDecoder,resultDecoder:workspaceLayoutDecoder,execute:this.saveLayout.bind(this)},importLayout:{name:"importLayout",dataDecoder:workspacesLayoutImportConfigDecoder,resultDecoder:voidResultDecoder,execute:this.importLayout.bind(this)},exportAllLayouts:{name:"exportAllLayouts",resultDecoder:exportedLayoutsResultDecoder,execute:this.exportAllLayouts.bind(this)},restoreItem:{name:"restoreItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.restoreItem.bind(this)},maximizeItem:{name:"maximizeItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.maximizeItem.bind(this)},focusItem:{name:"focusItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.focusItem.bind(this)},closeItem:{name:"closeItem",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.closeItem.bind(this)},closeWorkspace:{name:"closeWorkspace",dataDecoder:simpleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.closeWorkspace.bind(this)},resizeItem:{name:"resizeItem",dataDecoder:resizeItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.resizeItem.bind(this)},changeFrameState:{name:"changeFrameState",dataDecoder:frameStateConfigDecoder,resultDecoder:voidResultDecoder,execute:this.changeFrameState.bind(this)},getFrameState:{name:"getFrameState",dataDecoder:simpleItemConfigDecoder,resultDecoder:frameStateResultDecoder,execute:this.getFrameState.bind(this)},getFrameBounds:{name:"getFrameBounds",dataDecoder:simpleItemConfigDecoder,resultDecoder:frameBoundsResultDecoder,execute:this.getFrameBounds.bind(this)},moveFrame:{name:"moveFrame",dataDecoder:moveFrameConfigDecoder,resultDecoder:voidResultDecoder,execute:this.moveFrame.bind(this)},getFrameSnapshot:{name:"getFrameSnapshot",dataDecoder:frameSnapshotConfigDecoder,resultDecoder:frameSnapshotResultDecoder,execute:this.getFrameSnapshot.bind(this)},forceLoadWindow:{name:"forceLoadWindow",dataDecoder:simpleItemConfigDecoder,resultDecoder:simpleWindowOperationSuccessResultDecoder,execute:this.forceLoadWindow.bind(this)},ejectWindow:{name:"ejectWindow",dataDecoder:ejectWindowDataDecoder,resultDecoder:simpleWindowOperationSuccessResultDecoder,execute:this.ejectWindow.bind(this)},setItemTitle:{name:"setItemTitle",dataDecoder:setItemTitleConfigDecoder,resultDecoder:voidResultDecoder,execute:this.setItemTitle.bind(this)},moveWindowTo:{name:"moveWindowTo",dataDecoder:moveWindowConfigDecoder,resultDecoder:voidResultDecoder,execute:this.moveWindowTo.bind(this)},addWindow:{name:"addWindow",dataDecoder:addWindowConfigDecoder,resultDecoder:addItemResultDecoder,execute:this.addWindow.bind(this)},addContainer:{name:"addContainer",dataDecoder:addContainerConfigDecoder,resultDecoder:addItemResultDecoder,execute:this.addContainer.bind(this)},bundleWorkspace:{name:"bundleWorkspace",dataDecoder:bundleWorkspaceConfigDecoder,resultDecoder:voidResultDecoder,execute:this.bundleWorkspace.bind(this)},bundleItem:{name:"bundleItem",dataDecoder:bundleItemConfigDecoder,resultDecoder:voidResultDecoder,execute:this.bundleItem.bind(this)},hibernateWorkspace:{name:"hibernateWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.hibernateWorkspace.bind(this)},resumeWorkspace:{name:"resumeWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.resumeWorkspace.bind(this)},getWorkspacesConfig:{name:"getWorkspacesConfig",resultDecoder:workspacesConfigDecoder,execute:this.getWorkspacesConfiguration.bind(this)},lockWorkspace:{name:"lockWorkspace",dataDecoder:lockWorkspaceDecoder,resultDecoder:voidResultDecoder,execute:this.lockWorkspace.bind(this)},lockWindow:{name:"lockWindow",dataDecoder:lockWindowDecoder,resultDecoder:voidResultDecoder,execute:this.lockWindow.bind(this)},lockContainer:{name:"lockContainer",dataDecoder:lockContainerDecoder,resultDecoder:voidResultDecoder,execute:this.lockContainer.bind(this)},pinWorkspace:{name:"pinWorkspace",dataDecoder:pinWorkspaceDecoder,resultDecoder:voidResultDecoder,execute:this.pinWorkspace.bind(this)},unpinWorkspace:{name:"unpinWorkspace",dataDecoder:workspaceSelectorDecoder,resultDecoder:voidResultDecoder,execute:this.unpinWorkspace.bind(this)},getWorkspaceIcon:{name:"getWorkspaceIcon",dataDecoder:workspaceSelectorDecoder,resultDecoder:workspaceIconDecoder,execute:this.getWorkspaceIcon.bind(this)},setWorkspaceIcon:{name:"setWorkspaceIcon",dataDecoder:setWorkspaceIconDecoder,resultDecoder:voidResultDecoder,execute:this.setWorkspaceIcon.bind(this)},checkStarted:{name:"checkStarted",execute:this.handleCheckStarted.bind(this)},getPlatformFrameId:{name:"getPlatformFrameId",execute:this.handleGetPlatformFrameId.bind(this)},getWorkspacesLayouts:{name:"getWorkspacesLayouts",dataDecoder:getWorkspacesLayoutsConfigDecoder,resultDecoder:getWorkspacesLayoutsResponseDecoder,execute:this.handleGetWorkspacesLayouts.bind(this)},getWorkspaceWindowsOnLayoutSaveContext:{name:"getWorkspaceWindowsOnLayoutSaveContext",dataDecoder:getWorkspaceWindowsOnLayoutSaveContextConfigDecoder,resultDecoder:getWorkspaceWindowsOnLayoutSaveContextResult,execute:this.handleGetWorkspaceWindowsOnLayoutSaveContext.bind(this)},setMaximizationBoundary:{name:"setMaximizationBoundary",dataDecoder:setMaximizationBoundaryConfigDecoder,resultDecoder:voidResultDecoder,execute:this.handleSetMaximizationBoundary.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},getWorkspaceWindowFrameBounds:{name:"getWorkspaceWindowFrameBounds",resultDecoder:frameBoundsResultDecoder,dataDecoder:simpleItemConfigDecoder,execute:this.getWorkspaceWindowFrameBounds.bind(this)},focusChange:{name:"focusChange",dataDecoder:focusEventDataDecoder,execute:this.handleFocusEvent.bind(this)},bringBackToWorkspace:{name:"bringBackToWorkspace",dataDecoder:bringBackToWorkspaceDataDecoder,execute:this.handleBringBackToWorkspace.bind(this)},showChannelsLink:{name:"showChannelsLink",dataDecoder:showChannelsLinkDecoder,resultDecoder:voidResultDecoder,execute:this.showChannelsLink.bind(this)}};constructor(e,t,r,n,i,o,s){this.framesController=e,this.glueController=t,this.stateController=r,this.hibernationWatcher=n,this.sequelizer=i,this.sessionStorageController=o,this.ioc=s}get started(){return this._started}set started(e){this._started=e}handlePlatformShutdown(){this.started=!1,this.hibernationWatcher.stop(),this.framesController.stop()}async start(e){e.workspaces?(this.connectionConfig=e.connection,this.settings=this.applyDefaults(e.workspaces),this.defaultWindowOpenBounds=e.windows.defaultWindowOpenBounds,this.settings.hibernation&&this.hibernationWatcher.start(this,this.settings.hibernation),await Promise.all([this.glueController.createWorkspacesStream(),this.glueController.createWorkspacesEventsReceiver(this.bridgeWorkspaceEvent.bind(this))]),this.started=!0):this.started=!1}async configurePostStart(){await this.framesController.start(this.settings,this.defaultWindowOpenBounds,this.operations.getFrameSummary),this.stateController.onWindowDisappeared(e=>this.framesController.handleFrameDisappeared(e))}get logger(){return logger.get("workspaces.controller")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this workspaces control message, because the controller has not been started");const t=e.data,r=e.commandId,n=workspacesOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This workspace request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Workspace request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Workspace request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(e,t){this.logger?.trace(`handling unloading of ${e}`),t&&!t.closed||(this.logger?.trace(`${e} detected as closed, checking if frame and processing close`),this.framesController.handleFrameDisappeared(e))}bridgeWorkspaceEvent(e){if(this.glueController.pushWorkspacesMessage(e),"closed"===e.action&&"workspace"===e.type){const{workspaceSummary:t}=e.payload;this.glueController.clearContext(t.id,"workspace"),this.registry.execute("workspace-closed",{layoutName:t.config.name})}this.settings.hibernation&&this.hibernationWatcher.notifyEvent(e)}onWorkspaceClosed(e){return"function"!=typeof e?ioError.raiseError("onWorkspaceClosed requires a single argument of type function"):this.registry.add("workspace-closed",e)}async closeWorkspace(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] handling closeWorkspace request with config ${JSON.stringify(e)}`);const r=e.itemId,n=(await this.getAllWorkspacesSummaries({},t)).summaries,i=n.find(e=>e.id===r);if(!i)return ioError.raiseError(`Cannot close workspace with id: ${r}, because it is unknown to the platform`);const o=i.config.frameId,s=1===n.filter(e=>e.config.frameId===o).length,a=this.glueController.platformWindowId;if(s&&o===a&&this.logger?.info(`[${t}] this is the last workspace in the platform frame, cannot close the platform frame.`),s&&o!==a)return this.logger?.trace(`[${t}] this is the last workspace in frame ${o}, closing the frame`),await this.framesController.closeFrame(o),void this.logger?.trace(`[${t}] the frame window is closed`);this.logger?.trace(`[${t}] targeting frame ${o} for closing workspace ${r}`),await this.glueController.callFrame(this.operations.closeItem,e,o),this.logger?.trace(`[${t}] frame ${o} gave a success signal, responding to caller`)})}async closeFrame(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] handling closeFrame request with config ${JSON.stringify(e)}`),await this.framesController.closeFrame(e.itemId),this.logger?.trace(`[${t}] the frame window is closed`)})}async closeItem(e,t){this.logger?.trace(`[${t}] handling closeItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r)return await this.closeFrame(e,t);const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${n.windowId}`),await this.glueController.callFrame(this.operations.closeItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async setItemTitle(e,t){this.logger?.trace(`[${t}] handling setItemTitle request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setItemTitle,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async hibernateWorkspace(e,t){this.logger?.trace(`[${t}] handling hibernateWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.preserveAllWorkspaceWindowsContext(e.workspaceId),await this.glueController.callFrame(this.operations.hibernateWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async getWorkspacesConfiguration(e,t){return this.logger?.trace(`[${t}] handling getWorkspacesConfiguration request`),this.settings}async getWorkspaceWindowFrameBounds(e,t){this.logger?.trace(`[${t}] handling getWorkspaceWindowFrameBounds request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId}),n=await this.glueController.callWindow("windows",this.ioc.windowsController.getFrameBoundsOperation,{windowId:r.windowId},{windowId:r.windowId});return this.logger?.trace(`[${t}] getWorkspaceWindowFrameBounds completed`),{bounds:n.bounds}}async getAllFramesSummaries(e,t){if(this.logger?.trace(`[${t}] handling getAllFramesSummaries request`),!this.started)return{summaries:[]};const r=await this.framesController.getAll();this.logger?.trace(`[${t}] sending getFrameSummary to all known frames: ${r.join(", ")}`);const n=(await Promise.all(r.map(e=>this.glueController.callFrame(this.operations.getFrameSummary,{itemId:e.windowId},e.windowId)))).filter(e=>"none"!==e.id);return this.logger?.trace(`[${t}] all frames responded, returning to caller`),{summaries:n}}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleFrameHello(e,t){this.logger?.trace(`[${t}] handling handleFrameHello command with config: ${JSON.stringify(e)}`),e.windowId&&this.framesController.processNewHello(e.windowId)}async isWindowInWorkspace(e,t){this.logger?.trace(`[${t}] handling isWindowInWorkspace command with config: ${JSON.stringify(e)}`);const r=this.framesController.getAll();this.logger?.trace(`[${t}] sending isWindowInWorkspace to all known frames: ${JSON.stringify(r.join(", "))}`);const n=(await Promise.all(r.map(t=>this.glueController.callFrame(this.operations.isWindowInWorkspace,e,t.windowId)))).some(e=>e.inWorkspace);return this.logger?.trace(`[${t}] all frames responded, returning ${n} to the caller`),{inWorkspace:n}}async createWorkspace(e,t){this.logger?.trace(`[${t}] handling createWorkspace command`);const r=this.getBlockedAppNames(e.children??[],t);if(r.length)return ioError.raiseError(`Cannot complete 'createWorkspace' operation because there're app origins blocked by the Platform. Blocked names: ${JSON.stringify(r)}`);const n={frameId:e.frame?.reuseFrameId,newFrame:e.frame?.newFrame,itemId:e.config?.reuseWorkspaceId},i=await this.framesController.getFrameInstance(n);this.logger?.trace(`[${t}] calling frame: ${i.windowId}, based on selection config: ${JSON.stringify(n)}`);const o=await this.glueController.callFrame(this.operations.createWorkspace,e,i.windowId);return this.logger?.trace(`[${t}] frame ${i.windowId} responded with a valid snapshot, returning to caller`),o}async createFrame(e,t){this.logger?.trace(`[${t}] handling createFrame command`);const r=await this.framesController.openFrame(e.frameConfig,e.layoutComponentId);this.logger?.trace(`[${t}] calling frame: ${r.windowId}}`);const n=await this.glueController.callFrame(this.operations.createFrame,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded returning to caller`),n}async initFrame(e,t){this.logger?.trace(`[${t}] handling initFrame command`);const r={frameId:e.frameId},n=await this.framesController.getFrameInstance(r);this.logger?.trace(`[${t}] calling frame: ${n.windowId}, based on selection config: ${JSON.stringify(r)}`);const i=await this.filterWorkspacesWithInstanceRestrictions(e.workspaces,t),o={...e,workspaces:i};await this.glueController.callFrame(this.operations.initFrame,o,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} responded returning to caller`)}async getFrameSummary(e,t){this.logger?.trace(`[${t}] handling getFrameSummary request for config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] forwarding getFrameSummary to frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getFrameSummary,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid summary, returning to caller`),n}async getAllWorkspacesSummaries(e,t){this.logger?.trace(`[${t}] handling getAllWorkspacesSummaries request`);const r=this.framesController.getAll();this.logger?.trace(`[${t}] sending getAllWorkspacesSummaries to all known frames: ${r.join(", ")}`);const n=(await Promise.all(r.map(e=>this.glueController.callFrame(this.operations.getAllWorkspacesSummaries,{},e.windowId)))).reduce((e,t)=>(e.push(...t.summaries),e),[]);return this.logger?.trace(`[${t}] all frames responded, results were aggregated, returning to caller`),{summaries:n}}async getWorkspaceSnapshot(e,t){this.logger?.trace(`[${t}] handling getWorkspaceSnapshot for config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getWorkspaceSnapshot,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid snapshot, retuning to caller`),n}async handleCheckStarted(e,t){return this.logger?.trace(`[${t}] handling handleCheckStarted request`),this.logger?.trace(`[${t}] the controller has been started, responding to caller`),{started:!0}}async handleGetPlatformFrameId(e,t){this.logger?.trace(`[${t}] handling GetPlatformFrameId request`);const r=this.framesController.getPlatformFrameSessionData();return this.logger?.trace(`[${t}] GetPlatformFrameId completed, responding to caller`),{id:r?.windowId}}async getFrameSessionData(e,t){this.logger?.trace(`[${t}] handling getFrameSessionData request`);const r=this.framesController.getFrameConfig(e.frameId);return this.logger?.trace(`[${t}] getFrameSessionData completed, responding to caller`),r}async handleGetWorkspacesLayouts(e,t){this.logger?.trace(`[${t}] handling handleGetWorkspacesLayouts request for frame: ${e.frameId} for layout: ${e.layoutName} of type: ${e.layoutType} and config: ${JSON.stringify(e)}`);const r=await this.glueController.callFrame(this.operations.getWorkspacesLayouts,e,e.frameId);if(this.logger?.trace(`[${t}] handleGetWorkspacesLayouts request completed for frame: ${e.frameId} for layout: ${e.layoutName} of type: ${e.layoutType} and config: ${JSON.stringify(e)}`),!e.ignoreContexts)return this.logger?.info(`[${t}] 'ignoreContexts' flag not set on layout save request, returning workspace and window contexts as received from frame ${e.frameId}`),r;return await this.checkIsIgnoreContextsOnLayoutSaveSupported(e.frameId,t)?(this.logger?.info(`[${t}] Returning workspaces layouts response as received from frame ${e.frameId}.`),r):(this.clearWorkspaceAndWindowsContexts(r.workspaces),this.logger?.info(`[${t}] Returning workspaces layouts response after clearing workspace and window contexts in the Platform`),r)}async getFrameBounds(e,t){this.logger?.trace(`[${t}] handling getFrameBounds request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({frameId:e.itemId}),n=await this.glueController.callWindow("windows",this.ioc.windowsController.getFrameBoundsOperation,{windowId:r.windowId},{windowId:r.windowId});return this.logger?.trace(`[${t}] getFrameBounds completed`),{bounds:n.bounds}}async showChannelsLink(e,t){this.logger?.trace(`[${t}] - received 'showChannelsLink' signal for windowId ${e.windowId}`);const r=await this.framesController.getFrameInstance({frameId:e.frameId});if(!r)return ioError.raiseError(`[${t}] - frame ${e.frameId} not found, cannot show channels link`);await this.glueController.callFrame(this.operations.showChannelsLink,e,r.windowId),this.logger?.trace(`[${t}] - frame ${r.windowId} gave a success signal, responding to caller`)}async getAllLayoutsSummaries(e,t){this.logger?.trace(`[${t}] handling getAllLayoutsSummaries command`);const r=(await this.ioc.layoutsController.handleGetAll({type:"Workspace"},t)).summaries.map(e=>({name:e.name}));return this.logger?.trace(`[${t}] all layouts retrieved and mapped, returning to caller`),{summaries:r}}async openWorkspace(e,t){this.logger?.trace(`[${t}] handling openWorkspace command for name: ${e.name}`);const r={frameId:e.restoreOptions?.frameId,newFrame:e.restoreOptions?.newFrame,itemId:e.restoreOptions?.reuseWorkspaceId},n=new Date,i=await this.tryFocusExistingWorkspace(e.name,t),o=await this.framesController.getFrameInstance(r),s=i?await this.getWorkspaceSnapshot({itemId:i},t):await this.glueController.callFrame(this.operations.openWorkspace,e,o.windowId),a=new Date;return this.registry.execute("workspace-restored",{layoutName:e.name,startTime:n,endTime:a}),s}onWorkspaceRestored(e){return this.registry.add("workspace-restored",e)}async deleteLayout(e,t){this.logger?.trace(`[${t}] handling deleteLayout request for name: ${e.name}`),await this.ioc.layoutsController.handleRemove({name:e.name,type:"Workspace"},t),this.logger?.trace(`[${t}] layouts reported this layout as deleted, responding to caller`)}async saveLayout(e,t){this.logger?.trace(`[${t}] handling saveLayout request for workspace ${e.workspaceId} and name ${e.name}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] forwarding request to frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.saveLayout,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} responded with a valid layout, returning to caller`),n}async importLayout(e,t){this.logger?.trace(`[${t}] handling importLayout command for layout ${e.layout.name}`),await this.ioc.layoutsController.handleImport({layouts:[e.layout],mode:e.mode},t),this.logger?.trace(`[${t}] the layouts controller successfully imported the layout, responding to caller`)}async exportAllLayouts(e,t){this.logger?.trace(`[${t}] handling exportAllLayouts request`);return await this.ioc.layoutsController.handleExport({type:"Workspace"},t)}async restoreItem(e,t){this.logger?.trace(`[${t}] handling restoreItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.restoreItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async maximizeItem(e,t){this.logger?.trace(`[${t}] handling maximizeItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.maximizeItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async focusItem(e,t){this.logger?.trace(`[${t}] handling focusItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r)return this.logger?.trace(`[${t}] this is targeted at a frame, focusing the frame`),void window.open(void 0,r.windowId);const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${n.windowId}`),await this.glueController.callFrame(this.operations.focusItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async resizeItem(e,t){this.logger?.trace(`[${t}] handling resizeItem request with config ${JSON.stringify(e)}`);const r=this.framesController.getAll().find(t=>t.windowId===e.itemId);if(r){this.logger?.trace(`[${t}] detected targeted item is frame, building window resize config`);const n={windowId:e.itemId,width:e.width,height:e.height,relative:e.relative};return await this.glueController.callWindow("windows",this.ioc.windowsController.moveResizeOperation,n,{windowId:r.windowId}),void this.logger?.trace(`[${t}] window resize responded with success, returning to caller`)}const n=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeted item is not a frame, it is located in frame ${n.windowId}`),await this.glueController.callFrame(this.operations.resizeItem,e,n.windowId),this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal, responding to caller`)}async getFrameSnapshot(e,t){this.logger?.trace(`[${t}] handling getFrameSnapshot request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getFrameSnapshot,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async forceLoadWindow(e,t){this.logger?.trace(`[${t}] handling forceLoadWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.forceLoadWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async ejectWindow(e,t){this.logger?.trace(`[${t}] handling ejectWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);e.windowId&&this.sessionStorageController.addEjectedWindowId(e.windowId),this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.ejectWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async moveWindowTo(e,t){this.logger?.trace(`[${t}] handling moveWindowTo request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.moveWindowTo,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async addWindow(e,t){if(this.logger?.trace(`[${t}] handling addWindow request with config ${JSON.stringify(e)}`),e.definition.appName&&this.checkIfOriginBlockedByAppName(e.definition.appName))return ioError.raiseError(`Cannot complete 'addWindow' operation - origin of app '${e.definition.appName}' is blocked by the Platform`);const r=await this.framesController.getFrameInstance({itemId:e.parentId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.addWindow,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal: ${JSON.stringify(n)}, responding to caller`),n}checkIfOriginBlockedByAppName(e){const t=this.glueController.getAllApplications().find(t=>t.name===e);return t?checkIsOriginBlocked(t.userProperties.details.url,this.connectionConfig.blockList):ioError.raiseError(`Application with name: ${e} does not exist`)}extractAppNamesFromConfig(e,t=[]){if("window"===e.type&&e.appName)return t.push(e.appName),t;for(const r of e.children||[])this.extractAppNamesFromConfig(r,t);return t}getBlockedAppNames(e,t){const r=[];for(const t of e)this.extractAppNamesFromConfig(t,r);this.logger?.trace(`[${t}] filtering blocked apps from all gathered appNames: ${JSON.stringify(r)}`);const n=r.filter(e=>this.checkIfOriginBlockedByAppName(e));return this.logger?.trace(`[${t}] blocked app names: ${JSON.stringify(n)}`),n}async addContainer(e,t){this.logger?.trace(`[${t}] handling addContainer request with config ${JSON.stringify(e)}`);const r=this.getBlockedAppNames(e.definition.children??[],t);if(r.length)return ioError.raiseError(`Cannot complete 'addContainer' operation because there're app origins blocked by the Platform. Blocked names: ${JSON.stringify(r)}`);const n=await this.framesController.getFrameInstance({itemId:e.parentId});this.logger?.trace(`[${t}] targeting frame ${n.windowId}`);const i=await this.glueController.callFrame(this.operations.addContainer,e,n.windowId);return this.logger?.trace(`[${t}] frame ${n.windowId} gave a success signal: ${JSON.stringify(i)}, responding to caller`),i}async bundleWorkspace(e,t){this.logger?.trace(`[${t}] handling bundleWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.bundleWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async bundleItem(e,t){this.logger?.trace(`[${t}] handling bundleItem request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.bundleItem,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async resumeWorkspace(e,t){this.logger?.trace(`[${t}] handling resumeWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.resumeWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockWorkspace(e,t){this.logger?.trace(`[${t}] handling lockWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockContainer(e,t){this.logger?.trace(`[${t}] handling lockContainer request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.itemId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockContainer,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async lockWindow(e,t){this.logger?.trace(`[${t}] handling lockWindow request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.windowPlacementId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.lockWindow,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async pinWorkspace(e,t){this.logger?.trace(`[${t}] handling pinWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.pinWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async unpinWorkspace(e,t){this.logger?.trace(`[${t}] handling unpinWorkspace request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.unpinWorkspace,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async getWorkspaceIcon(e,t){this.logger?.trace(`[${t}] handling getWorkspaceIcon request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`);const n=await this.glueController.callFrame(this.operations.getWorkspaceIcon,e,r.windowId);return this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`),n}async setWorkspaceIcon(e,t){this.logger?.trace(`[${t}] handling setWorkspaceIcon request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({itemId:e.workspaceId});this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setWorkspaceIcon,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async handleGetWorkspaceWindowsOnLayoutSaveContext(e,t){this.logger?.trace(`[${t}] handling GetWorkspaceWindowsOnLayoutSaveContext request with config: ${JSON.stringify(e)}`);const r=await Promise.all(e.windowIds.map(async t=>({windowId:t,windowContext:await this.getWorkspaceWindowOnLayoutSaveData(t,e)})));return this.logger?.trace(`[${t}] operation GetWorkspaceWindowsOnLayoutSaveContext completed responding`),{windowsOnSaveData:r}}async handleSetMaximizationBoundary(e,t){this.logger?.trace(`[${t}] handling setMaximizationBoundary request with config ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance(e);this.logger?.trace(`[${t}] targeting frame ${r.windowId}`),await this.glueController.callFrame(this.operations.setMaximizationBoundary,e,r.windowId),this.logger?.trace(`[${t}] frame ${r.windowId} gave a success signal, responding to caller`)}async changeFrameState(e,t){return ioError.raiseError("Frame states are not supported in Glue42 Core")}async getFrameState(e,t){return ioError.raiseError("Frame states are not supported in Glue42 Core")}async handleFocusEvent(e,t){this.logger?.trace(`[${t}] handling focus event from frame id: ${e.windowId} and hasFocus: ${e.hasFocus}`);try{await this.framesController.getFrameInstance({frameId:e.windowId})}catch(r){return void this.logger?.trace(`[${t}] ignoring focus event for unrecognized frame with id: ${e.windowId}`)}const r={type:"frame",action:"focus",payload:{frameSummary:{id:e.windowId,isFocused:e.hasFocus}}};this.bridgeWorkspaceEvent(r),this.logger?.trace(`[${t}] focus event from frame id: ${e.windowId} and hasFocus: ${e.hasFocus} handled`)}async moveFrame(e,t){this.logger?.trace(`[${t}] handling moveFrame command with config: ${JSON.stringify(e)}`);const r=await this.framesController.getFrameInstance({frameId:e.itemId}),n={windowId:e.itemId,top:e.top,left:e.left,relative:e.relative};await this.glueController.callWindow("windows",this.ioc.windowsController.moveResizeOperation,n,{windowId:r.windowId}),this.logger?.trace(`[${t}] frame with id ${r.windowId} was successfully moved, responding to caller`)}applyDefaults(e){const t=e?.hibernation||{},r=deepMerge(defaultLoadingConfig,e?.loadingStrategy||{});return{...e,loadingStrategy:r,hibernation:t}}async getWorkspaceWindowOnLayoutSaveData(e,t){if(this.ioc.sessionController.getAllNonGlue().some(t=>t.windowId===e))return{};if(!this.ioc.sessionController.getWorkspaceClientById(e))return ioError.raiseError(`Cannot ask window: ${e} for on layout save request, because it is not a known workspace window`);const r=`Cannot fetch the on layout save context from: ${e}, because of timeout`,n=await PromiseWrap(async()=>{try{return await this.glueController.callWindow("layouts",{name:"clientSaveRequest",execute:async()=>{}},t,{windowId:e})}catch(e){return{}}},15e3,r);return n?.windowContext??{}}async handleBringBackToWorkspace({windowId:e},t){this.logger?.trace(`[${t}] - received 'bringBackToWorkspace' signal for windowId ${e}`);if(!this.glueController.getWindowById(e))return ioError.raiseError(`Cannot bring back window with id ${e} to workspace because it is not known by the platform`);this.sessionStorageController.addEjectedWindowId(e);const r=await this.glueController.clientGlue.contexts.get(`___window___${e}`);if(!r||!Object.keys(r).length||!r.___io___?.ejectedWindow)return ioError.raiseError(`Cannot bring back window with id ${e} to workspace because it was never a part from one`);const{___io___:{ejectedWindow:n}}=r,i=await this.framesController.getFrameInstance({itemId:n.frameId}),o={definition:{type:"group",children:[{windowId:e,type:"window"}]},parentType:"workspace",parentId:n.workspaceId},s=await this.glueController.callFrame(this.operations.addContainer,o,i.windowId);this.logger?.trace(`[${t}] - frame ${i.windowId} gave a success signal: ${JSON.stringify(s)}`)}async tryFocusExistingWorkspace(e,t){const r=await this.ioc.layoutsController.handleGetLayout({name:e,type:"Workspace"},t);if(!this.hasInstanceRestriction(r.layout))return;const n=(await this.getAllWorkspacesSummaries({},t)).summaries.find(t=>t.config.layoutName===e);return n?(await this.focusItem({itemId:n.id},t),n.id):void 0}hasInstanceRestriction(e){if(!e)return!1;const t=e.components[0];return!1===t.state?.config?.allowMultiple}async filterWorkspacesWithInstanceRestrictions(e,t){const r=await this.getAllWorkspacesSummaries({},t),n=await Promise.all(e.map(e=>e).filter(e=>e.name).map(e=>this.ioc.layoutsController.handleGetLayout({name:e.name,type:"Workspace"},t))),i=e.filter((e,t,i)=>{if(!this.isRestoreWorkspaceDefinition(e))return!0;const o=n.find(t=>t.layout?.name===e.name)?.layout;if(!this.hasInstanceRestriction(o))return!0;const s=r.summaries.find(t=>t.config.layoutName===e.name),a=e!==i.find(t=>this.isRestoreWorkspaceDefinition(t)&&t.name===e.name);return!s&&!a},[]);return i}isRestoreWorkspaceDefinition(e){return!!e.name}async checkIsIgnoreContextsOnLayoutSaveSupported(e,t){const r=await this.glueController.isFrameOperationSupported("isIgnoreContextsOnLayoutSaveSupported",e);return this.logger?.info(`[${t}] Frame ${e} ${r?"supports":"does NOT support"} 'ignoreContexts' flag on layout save requests`),r}clearWorkspaceAndWindowsContexts(e){e.forEach(e=>{e.context={},this.clearWorkspaceChildrenContexts(e.children)})}clearWorkspaceChildrenContexts(e){e.forEach(e=>{"window"!==e.type?this.clearWorkspaceChildrenContexts(e.children):e.config.context={}})}}const INTENTS_RESOLVER_INTEROP_PREFIX="T42.Intents.Resolver.Control.",INTENTS_RESOLVER_WIDTH=400,INTENTS_RESOLVER_HEIGHT=400,DEFAULT_METHOD_RESPONSE_TIMEOUT_MS=6e4,DEFAULT_RAISE_TIMEOUT_MS=9e4,DEFAULT_PICK_HANDLER_BY_TIMEOUT_MS=9e4,ERRORS=errors.intents;class IntentsController{glueController;legacyResolverController;appDirectory;windowsController;prefsController;uiController;operations={getIntents:{name:"getIntents",resultDecoder:wrappedIntentsDecoder,execute:this.getWrappedIntents.bind(this)},findIntent:{name:"findIntent",dataDecoder:wrappedIntentFilterDecoder,resultDecoder:wrappedIntentsDecoder,execute:this.findIntent.bind(this)},raise:{name:"raise",dataDecoder:raiseIntentRequestDecoder,resultDecoder:intentResultDecoder,execute:this.raise.bind(this)},filterHandlers:{name:"filterHandlers",dataDecoder:filterHandlersWithResolverConfigDecoder,resultDecoder:filterHandlersResultDecoder,execute:this.filterHandlers.bind(this)},getIntentsByHandler:{name:"getIntentsByHandler",dataDecoder:intentHandlerDecoder,resultDecoder:getIntentsResultDecoder,execute:this.getIntentsByHandler.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};started=!1;isIntentsSharingEnabledViaBridge=!1;constructor(e,t,r,n,i,o){this.glueController=e,this.legacyResolverController=t,this.appDirectory=r,this.windowsController=n,this.prefsController=i,this.uiController=o}get logger(){return logger.get("intents.controller")}handlePlatformShutdown(){this.started=!1}async start(e){this.started=!0;const t=e.gateway?.bridge;this.isIntentsSharingEnabledViaBridge=!!t?.url&&!1!==t.intents?.enabled}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this intents control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=e.callerType,o=intentsOperationTypesDecoder.run(e.operation);if(!o.ok)return ioError.raiseError(`This intents request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(o.error)}`);const s=o.result,a=this.operations[s].dataDecoder?.run(t);if(a&&!a.ok)return ioError.raiseError(`Intents request for ${s} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(a.error)}`);this.logger?.debug(`[${r}] ${s} command is valid with data: ${JSON.stringify(t)}`);const c=await this.operations[s].execute(t,r,n,i),l=this.operations[s].resultDecoder?.run(c);return l&&!l.ok?ioError.raiseError(`Intents request for ${s} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(l.error)}`):(this.logger?.trace(`[${r}] ${s} command was executed successfully`),c)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}extractAppIntents(e){const t={},r=e.filter(e=>e.intents.length>0);for(const e of r)for(const r of e.intents){t[r.name]||(t[r.name]=[]);const n={applicationName:e.name,applicationTitle:e.title,applicationDescription:e.caption,displayName:r.displayName,contextTypes:r.contexts,applicationIcon:e.icon,type:"app",resultType:r.resultType,customConfig:r.customConfig};t[r.name].push(n)}return t}async getInstanceIntents(e,t){const r={},n=this.isIntentsSharingEnabledViaBridge?this.glueController.getServers():this.glueController.getLocalServers();for(const i of n){const n=(i.getMethods?.()||[]).filter(e=>e.name.startsWith(GlueWebIntentsPrefix));await Promise.all(n.map(async n=>{const o=n.name.replace(GlueWebIntentsPrefix,"");r[o]=r[o]??[];const s={apps:e,server:i,method:n,commandId:t,intentName:o},a=this.glueController.isValidWindowId(s.server.windowId)?await this.getInstanceIntentHandler(s):this.getInstanceIntentHandlerWithInvalidWindowId(s);r[o].push(a)}))}return r}getInstanceIntentHandlerWithInvalidWindowId({server:e,method:t,apps:r,intentName:n}){const i=this.glueController.clientGlue.appManager.instances().find(t=>t.id===e.instance),o=t.flags.intent;if(!i)return{instanceId:e.instance,applicationName:e.application??e.applicationName??"",applicationIcon:o.icon,applicationTitle:"",applicationDescription:o.description,displayName:o.displayName,contextTypes:o.contextTypes,instanceTitle:e.instance,type:"instance",resultType:o.resultType,customConfig:o.customConfig};const{application:s}=i,a=r.find(e=>e.name===s.name)?.intents?.find(e=>e.name===n);return{instanceId:e.instance,applicationName:s.name,applicationIcon:o.icon??s.icon,applicationTitle:s.title??"",applicationDescription:o.description??s.caption,displayName:o.displayName??a?.displayName,contextTypes:o.contextTypes??a?.contexts,instanceTitle:"",type:"instance",resultType:o.resultType??a?.resultType}}async getInstanceIntentHandler({apps:e,intentName:t,server:r,method:n,commandId:i}){const o=e.find(e=>e.name===r.application),s=o?.intents?.find(e=>e.name===t)||void 0,a=n.flags.intent,c=await this.windowsController.getWindowTitle(r.windowId??"",i);return{instanceId:r.windowId||r.instance,applicationName:r.application||"",applicationIcon:a.icon||o?.icon,applicationTitle:o?.title||"",applicationDescription:a.description||o?.caption,displayName:a.displayName||s?.displayName,contextTypes:a.contextTypes||s?.contexts,instanceTitle:c,type:"instance",resultType:s?.resultType||a.resultType,customConfig:a.customConfig}}mergeIntentStores(e,t){const r={};for(const n of new Set([...Object.keys(e),...Object.keys(t)]))r[n]=[...e[n]||[],...t[n]||[]];return r}wrapIntents(e){return{intents:e}}async getIntents(e){const t=(await this.appDirectory.getAll()).map(e=>({name:e.name,title:e.title||"",icon:e.icon,caption:e.caption,intents:e.userProperties.intents??[]})),r=this.extractAppIntents(t);this.logger?.trace(`[${e}] got app intents`);const n=await this.getInstanceIntents(t,e);this.logger?.trace(`[${e}] got instance intents`);const i=this.mergeIntentStores(r,n);return Object.keys(i).map(e=>({name:e,handlers:i[e]}))}async getWrappedIntents(e){this.logger?.trace(`[${e}] handling getIntents command`);const t=await this.getIntents(e);return this.logger?.trace(`[${e}] getIntents command completed`),this.wrapIntents(t)}async findIntent(e,t){this.logger?.trace(`[${t}] handling findIntent command`);const r=e.filter;let n=await this.getIntents(t);if(!r)return this.wrapIntents(n);if("string"==typeof r)return this.wrapIntents(n.filter(e=>e.name===r));if(r.contextType){const e=r.contextType.toLowerCase();n=n.filter(t=>t.handlers.some(t=>t.contextTypes?.some(t=>t.toLowerCase()===e)))}if(r.name&&(n=n.filter(e=>e.name===r.name)),r.resultType){const e=r.resultType.toLowerCase();n=n.filter(t=>t.handlers.some(t=>t.resultType?.toLowerCase()===e))}return this.logger?.trace(`[${t}] findIntent command completed`),this.wrapIntents(n)}async getIntent(e,t){return(await this.getIntents(t)).find(t=>t.name===e)}async startApp(e,t){const r={...t.options??{},originIntentRequest:t};return(await this.glueController.clientGlue.appManager.application(e).start(t.context,r)).id}async raiseIntent(e,t,r,n){this.logger?.trace(`[${t}] handling raiseIntent command with intentRequest: ${JSON.stringify(e)}`);const i=e.intent,o=await this.getIntent(i,t);if(!o)return ioError.raiseError(`Intent ${i} not found!`);this.logger?.trace(`Raised intent definition: ${JSON.stringify(o)}`);const s=e.handlers?this.findHandlerByFilter(e.handlers,{type:"app"}):this.findHandlerByFilter(o.handlers,{type:"app"}),a=e.handlers?this.findHandlerByFilter(e.handlers,{type:"instance"}):this.findHandlerByFilter(o.handlers,{type:"instance"});let c;if(e.target&&"reuse"!==e.target||(c=a||s),"startNew"===e.target&&(c=s),"object"==typeof e.target&&e.target.app&&(c=this.findHandlerByFilter(o.handlers,{app:e.target.app})),"object"==typeof e.target&&e.target.instance&&(c=this.findHandlerByFilter(o.handlers,{instance:e.target.instance,app:e.target.app})),!c)return ioError.raiseError(`Can not raise intent for request ${JSON.stringify(e)} - can not find intent handler!`);return await this.raiseIntentToTargetHandler({request:e,handler:c,commandId:t,callerId:r,timeout:n})}findHandlerByFilter(e,t){return t.type?e.find(e=>e.type===t.type):t.instance?e.find(e=>t.app?e.applicationName===t.app&&e.instanceId===t.instance:e.instanceId===t.instance):t.app?e.find(e=>e.applicationName===t.app):void 0}async raiseIntentToTargetHandler({handler:e,request:t,callerId:r,commandId:n,timeout:i}){this.logger?.trace(`Raising intent to target handler:${JSON.stringify(e)}`);const o=e.instanceId?Promise.resolve(e.instanceId):this.startApp(e.applicationName,t).catch(e=>{const t=e instanceof Error||"string"==typeof e?e:JSON.stringify(e);return ioError.raiseError(`${ERRORS.TARGET_INSTANCE_UNAVAILABLE}. Reason: ${t}`)}),s=await o,a=`${GlueWebIntentsPrefix}${t.intent}`;this.logger?.trace(`Searching for interop server offering method ${a}`);const c={methodResponseTimeoutMs:i?i+1e3:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS,waitTimeoutMs:i?i+1e3:DEFAULT_METHOD_RESPONSE_TIMEOUT_MS},l=this.glueController.invokeMethod(a,{...t.context,_initialCallerId:r},{instance:s},c).catch(e=>ioError.raiseError(`${ERRORS.INTENT_HANDLER_REJECTION}. Reason: ${e instanceof Error?e:JSON.stringify(e)}`)),u=await l;return this.logger?.trace(`[${n}] raiseIntent command completed. Returning result: ${JSON.stringify(u)}`),{request:t,handler:{...e,instanceId:s,type:"instance"},result:u.returned}}async raise(e,t,r,n){if(this.logger?.trace(`[${t}] Receive raise command with config: ${JSON.stringify(e)}`),!r)return ioError.raiseError(`${ERRORS.CALLER_NOT_DEFINED} for 'raise' command with request ${JSON.stringify(e)}`);const i=e.intentRequest.timeout||DEFAULT_RAISE_TIMEOUT_MS,o={instanceId:void 0},s=this.coreRaiseIntent.bind(this,{request:e,resolverInstance:o,timeout:i,commandId:t,callerId:this.getCallerIdByCallerType(r,n)});return e.intentRequest.waitUserResponseIndefinitely?s():PromiseWrap(s,i,`${ERRORS.TIMEOUT_HIT} - waited ${i}ms for 'raise' to resolve`)}async handleRaiseWithEmbeddedResolver({intentRequest:e,initialCaller:t,timeout:r,commandId:n}){this.logger?.trace(`[${n}] handling raise command with embedded resolver`);const i=e.waitUserResponseIndefinitely?MAX_SET_TIMEOUT_DELAY:r,o={commandId:n,config:{intentRequest:e,timeout:i},methodResponseTimeoutMs:i,initialCaller:t},s=await this.uiController.openResolver(o);s.isClosed&&ioError.raiseError(`${ERRORS.USER_CANCELLED}`),s.isExpired&&ioError.raiseError(`${ERRORS.TIMEOUT_HIT} - waited ${r}ms for user to choose an intent handler`);const a=s.userChoice?.handler;if(!a)return ioError.raiseError(`${ERRORS.HANDLER_NOT_FOUND}`);if(!!s.userChoice?.userSettings.preserveChoice)try{this.logger?.trace(`[${n}] - User wants to preserve the chosen of handler: ${JSON.stringify(a)}`),await this.preserveUserChoice({initialCaller:t,commandId:n,handler:a,intentName:e.intent})}catch(e){this.logger?.warn(`[${n}] - Prefs API threw the following error: ${e}. Handler won't be preserved`)}return this.handleRaiseToTargetHandler(e,a,n,t.instanceId,r)}async coreRaiseIntent({request:e,resolverInstance:t,timeout:r,commandId:n,callerId:i}){const{resolverConfig:o,intentRequest:s,embeddedResolverConfig:a}=e,c=(await this.findIntent({filter:{name:s.intent}},n)).intents.find(e=>e.name===s.intent);if(!c)return ioError.raiseError(`${ERRORS.INTENT_NOT_FOUND} with name ${s.intent}`);this.logger?.trace(`[${n}] Intent to be handled: ${JSON.stringify(c)}`);const{open:l,reason:u}=this.checkIfResolverShouldBeOpenedForRaise(c,s,o,a);if(!l)return this.logger?.trace(`[${n}] Intent Resolver UI won't be used. Reason: ${u}`),this.handleRaiseWithoutResolver({request:e,commandId:n,callerId:i,timeout:r});if(this.logger?.trace(`[${n}] Starting Intent Resolver app for intent request: ${JSON.stringify(e)}`),a?.enabled)return this.logger?.trace(`[${n}] Handling 'raise' with embedded intent resolver`),this.handleRaiseWithEmbeddedResolver({intentRequest:s,initialCaller:a.initialCaller,timeout:r,commandId:n});if(o){this.logger?.trace(`[${n}] Handling 'raise' with legacy intent resolver`);const o=this.handleRaiseWithLegacyResolver({request:e,commandId:n,resolverInstance:t,callerId:i,timeout:r});return o.catch(()=>t.instanceId&&this.legacyResolverController.stopResolverInstance(t.instanceId)),o}return ioError.raiseError(`Couldn't complete 'raise' operation with request: ${JSON.stringify(s)}`)}async handleRaiseToTargetHandler(e,t,r,n,i){const o=`with timeout of ${e.timeout??DEFAULT_RAISE_TIMEOUT_MS}ms`;if(this.logger?.trace(`Raising intent to target handler: ${JSON.stringify(t)} ${o}`),e.waitUserResponseIndefinitely)return PromiseWrap(()=>this.raiseIntentToTargetHandler({request:e,handler:{...t,type:t.instanceId?"instance":"app"},commandId:r,timeout:i,callerId:n}),i,`${ERRORS.INTENT_DELIVERY_FAILED} - waited ${i}ms for client to handle the raised intent`);const s=await this.raiseIntentToTargetHandler({request:e,handler:{...t,type:t.instanceId?"instance":"app"},commandId:r,callerId:n,timeout:i});return this.logger?.trace(`Result from raise() method for intent ${JSON.stringify(e.intent)}: ${JSON.stringify(s)}`),s}async handleRaiseWithoutResolver({request:e,commandId:t,callerId:r,timeout:n}){const{intentRequest:i}=e;return i.waitUserResponseIndefinitely?PromiseWrap(()=>this.raiseIntent(i,t,r,n),n,`${ERRORS.TIMEOUT_HIT} - waited ${n}ms for 'raise' to resolve`):this.raiseIntent(i,t,r,n)}async handleRaiseWithLegacyResolver(e){const{request:t,callerId:r,commandId:n,resolverInstance:i,timeout:o}=e,s=await this.legacyResolverController.startResolverApp({request:t.intentRequest,resolverConfig:t.resolverConfig,callerId:r,commandId:n,resolverInstance:i,method:"raise"});return this.handleRaiseToTargetHandler(t.intentRequest,s,n,r,o)}async preserveUserChoice({initialCaller:e,commandId:t,filter:r,intentName:n,handler:i}){const o=e.instanceId===this.glueController.me.instance?this.prefsController.platformAppName:this.glueController.getAppNameByInstanceId(e.instanceId);if(!o)return;this.logger?.info(`[${t}] - Saving user's choice of handler for '${o}' app`);const s=await this.prefsController.get({app:o},t),a=s.prefs.data?.intents??{},c={...s.prefs.data,intents:{...a,[n]:{handler:i,filter:r}}};await this.prefsController.update({app:o,data:c},t)}checkIfIntentHasMoreThanOneHandler(e,t){const r=t.handlers||e.handlers;if(!t.target)return r.length>1;if("reuse"===t.target)return r.filter(e=>"instance"===e.type&&e.instanceId).length>1||e.handlers.filter(e=>"app"===e.type).length>1;if("startNew"===t.target)return r.filter(e=>"app"===e.type).length>1;if(t.target.instance)return!1;if(t.target.app){const e=t.target.app;return r.filter(t=>t.applicationName===e&&t.instanceId).length>1}return!1}checkIfResolverShouldBeOpenedForRaise(e,t,r,n){if(!this.checkIfIntentHasMoreThanOneHandler(e,t))return{open:!1,reason:"Raised intent has only one handler"};if(n?.enabled)return{open:!0};const i=this.checkIfResolverShouldBeOpenByResolverConfig(r);return i.open?{open:!0}:i}checkIfResolverShouldBeOpenedForFilterHandlers(e,t,r,n){return 1===e.length?{open:!1,reason:`There's only one valid intent handler for filter ${JSON.stringify(t)}`}:!1===t.openResolver?{open:!1,reason:"Intents resolver is disabled by IntentHandler filter"}:n?.enabled?{open:!0}:this.checkIfResolverShouldBeOpenByResolverConfig(r)}checkIfResolverShouldBeOpenByResolverConfig(e){if(!e.enabled)return{open:!1,reason:"Intent Resolver is disabled. Raising intent to first found handler"};return this.glueController.clientGlue.appManager.application(e.appName)?{open:!0}:{open:!1,reason:`Application with name ${e.appName} not found`}}async filterHandlers(e,t,r,n){if(this.logger?.trace(`[${t}] Receive 'filterHandlers' command with request: ${JSON.stringify(e)}`),!r)return ioError.raiseError("Cannot preform 'filterHandlers' - callerId is not defined");const{filterHandlersRequest:i,resolverConfig:o,embeddedResolverConfig:s}=e,a=await this.getIntents(t),c=this.filterHandlersBy(a,i);if(!c?.length)return{handlers:[]};const{open:l,reason:u}=this.checkIfResolverShouldBeOpenedForFilterHandlers(c,i,o,s);if(!l)return this.logger?.trace(`[${t}] Intent Resolver UI won't be used. Reason: ${u}`),{handlers:c};const d=i.timeout||DEFAULT_PICK_HANDLER_BY_TIMEOUT_MS;if(s?.enabled)return this.logger?.trace(`[${t}] Handling 'filterHandlers' with embedded intent resolver`),PromiseWrap(()=>this.handleFilterHandlersWithEmbeddedResolver({commandId:t,handlerFilter:i,initialCaller:s.initialCaller,timeout:d}),d,`${ERRORS.TIMEOUT_HIT} - waited ${d}ms for 'filterHandlers' to resolve`);const h={instanceId:void 0};return{handlers:[await PromiseWrap(()=>this.legacyResolverController.startResolverApp({request:i,resolverConfig:o,commandId:t,callerId:this.getCallerIdByCallerType(r,n),resolverInstance:h,method:"filterHandlers"}),d,`Timeout of ${d}ms hit for 'filterHandlers' request with filter: ${JSON.stringify(e.filterHandlersRequest)}`)]}}async handleFilterHandlersWithEmbeddedResolver({commandId:e,handlerFilter:t,initialCaller:r,timeout:n}){const i={commandId:e,config:{handlerFilter:t,timeout:n},methodResponseTimeoutMs:n,initialCaller:r},o=await this.uiController.openResolver(i);o.isClosed&&ioError.raiseError(`${ERRORS.USER_CANCELLED}`),o.isExpired&&ioError.raiseError(`${ERRORS.TIMEOUT_HIT} - waited ${n}ms for user to choose an intent handler`);const{handler:s,intent:a}=o.userChoice??{};if(!s)return ioError.raiseError(`${ERRORS.HANDLER_NOT_FOUND}`);if(!a)return ioError.raiseError(`${ERRORS.INTENT_NOT_FOUND} for handlerFilter: ${JSON.stringify(t)}`);if(!!o.userChoice?.userSettings.preserveChoice)try{this.logger?.trace(`[${e}] - User wants to preserve the chosen of handler: ${JSON.stringify(s)}`);const n={applicationNames:t.applicationNames,contextTypes:t.contextTypes,resultType:t.resultType};await this.preserveUserChoice({initialCaller:r,commandId:e,handler:s,intentName:a,filter:n})}catch(t){this.logger?.warn(`[${e}] - Prefs API threw the following error: ${t}. Handler won't be preserved`)}return{handlers:[s]}}filterHandlersBy(e,t){const r=e.filter(e=>{if(!t.intent||t.intent===e.name){if(t.excludeList&&(e.handlers=this.excludeIntentHandlers(e,t.excludeList)),t.resultType){const r=e.handlers.filter(e=>e.resultType&&e.resultType===t.resultType);if(!r.length)return;e.handlers=r}if(t.contextTypes){const r=e.handlers.filter(e=>t.contextTypes?.every(t=>e.contextTypes?.includes(t)));if(!r.length)return;e.handlers=r}if(t.applicationNames){const r=e.handlers.filter(e=>t.applicationNames?.includes(e.applicationName));if(!r.length)return;e.handlers=r}return e}}),n=r.map(e=>e.handlers).flat(1);return n.filter((e,t)=>t===n.findIndex(t=>e.instanceId?e.instanceId===t.instanceId:!t.instanceId&&t.applicationName===e.applicationName))}excludeIntentHandlers(e,t){return e.handlers.filter(e=>!t.some(t=>"applicationName"in t?t.applicationName===e.applicationName:"instanceId"in t&&t.instanceId===e.instanceId))}async getIntentsByHandler(e,t){this.logger?.log(`[${t}] - Receive 'getIntents' command with request: ${JSON.stringify(e)}`);const r=runDecoderWithIOError(intentHandlerDecoder,e),n=await this.getIntents(t);clearNullUndefined(r),this.logger?.info(`[${t}] - extracting valid intents for the passed handler`);const i=this.extractIntentsWithInfoByHandler(n,r);return this.logger?.info(`[${t}] - returning intents for handler ${JSON.stringify(e)}`),{intents:i}}isHandlerValid(e,t){return Object.keys(e).every(r=>"contextTypes"===r?e.contextTypes?.every(e=>t.contextTypes?.includes(e)):t[r]===e[r])}extractIntentsWithInfoByHandler(e,t){return e.reduce((e,r)=>(r.handlers.forEach(n=>{if(!this.isHandlerValid(t,n))return;const i={intent:r.name,contextTypes:n.contextTypes,description:n.applicationDescription,displayName:n.displayName,icon:n.applicationIcon,resultType:n.resultType};e.push(i)}),e),[])}getCallerIdByCallerType(e,t){return"plugin"===t?this.glueController.me.instance??"":e}}const channelOperationDecoder=oneOf$1(constant$2("appHello"),constant$2("addChannel"),constant$2("removeChannel"),constant$2("operationCheck"),constant$2("getMyChannel"),constant$2("getWindowIdsOnChannel"),constant$2("getWindowIdsWithChannels"),constant$2("joinChannel"),constant$2("restrict"),constant$2("getRestrictions"),constant$2("restrictAll"),constant$2("notifyChannelsChanged"),constant$2("leaveChannel"),constant$2("requestChannelSelector"),constant$2("getMode")),leaveChannelDecoder=object$3({windowId:nonEmptyStringDecoder$2,channelName:optional$3(nonEmptyStringDecoder$2)}),channelsChangedDecoder=object$3({windowId:nonEmptyStringDecoder$2,channelNames:array$3(nonEmptyStringDecoder$2)}),modeDecoder=oneOf$1(constant$2("single"),constant$2("multi")),getChannelsModeDecoder=object$3({mode:modeDecoder}),channelFDC3DisplayMetadataDecoder=object$3({color:optional$3(nonEmptyStringDecoder$2),icon:optional$3(nonEmptyStringDecoder$2),name:optional$3(nonEmptyStringDecoder$2),glyph:optional$3(nonEmptyStringDecoder$2)}),channelFdc3MetaDecoder=object$3({id:nonEmptyStringDecoder$2,displayMetadata:optional$3(channelFDC3DisplayMetadataDecoder)}),channelMetaDecoder=object$3({color:nonEmptyStringDecoder$2,fdc3:optional$3(channelFdc3MetaDecoder)}),channelDefinitionDecoder=object$3({name:nonEmptyStringDecoder$2,meta:channelMetaDecoder,data:optional$3(anyJson$2())}),removeChannelDataDecoder=object$3({name:nonEmptyStringDecoder$2}),getMyChanelResultDecoder=object$3({channel:optional$3(nonEmptyStringDecoder$2)}),getWindowIdsOnChannelDataDecoder=object$3({channel:nonEmptyStringDecoder$2}),getWindowIdsOnChannelResultDecoder=object$3({windowIds:array$3(nonEmptyStringDecoder$2)}),getWindowIdsWithChannelsResultDecoder=object$3({windowIdsWithChannels:array$3(object$3({application:nonEmptyStringDecoder$2,channel:optional$3(nonEmptyStringDecoder$2),windowId:nonEmptyStringDecoder$2}))}),windowWithChannelFilterDecoder=object$3({application:optional$3(nonEmptyStringDecoder$2),channels:optional$3(array$3(nonEmptyStringDecoder$2)),windowIds:optional$3(array$3(nonEmptyStringDecoder$2))}),wrappedWindowWithChannelFilterDecoder=object$3({filter:optional$3(windowWithChannelFilterDecoder)}),joinChannelDataDecoder=object$3({channel:nonEmptyStringDecoder$2,windowId:nonEmptyStringDecoder$2}),channelRestrictionConfigWithWindowIdDecoder=object$3({name:nonEmptyStringDecoder$2,read:boolean$4(),write:boolean$4(),windowId:nonEmptyStringDecoder$2}),restrictionConfigDataDecoder=object$3({config:channelRestrictionConfigWithWindowIdDecoder}),getRestrictionsDataDecoder=object$3({windowId:nonEmptyStringDecoder$2}),restrictionsConfigDecoder=object$3({read:boolean$4(),write:boolean$4(),windowId:nonEmptyStringDecoder$2}),restrictAllDataDecoder=object$3({restrictions:restrictionsConfigDecoder}),channelRestrictionsDecoder=object$3({name:nonEmptyStringDecoder$2,read:boolean$4(),write:boolean$4(),windowId:optional$3(nonEmptyStringDecoder$2)}),restrictionsDecoder=object$3({channels:array$3(channelRestrictionsDecoder)}),requestChannelSelectorConfigDecoder=object$3({windowId:nonEmptyStringDecoder$2,channelsNames:array$3(nonEmptyStringDecoder$2)}),appHelloDataDecoder=object$3({windowId:nonEmptyStringDecoder$2}),appHelloSuccessDecoder=object$3({mode:modeDecoder,channels:array$3(nonEmptyStringDecoder$2),restrictions:array$3(channelRestrictionsDecoder)});class ChannelsController{glueController;sessionController;workspacesController;mode;operations={appHello:{name:"appHello",dataDecoder:appHelloDataDecoder,execute:this.handleAppHello.bind(this),resultDecoder:appHelloSuccessDecoder},addChannel:{name:"addChannel",execute:this.addChannel.bind(this),dataDecoder:channelDefinitionDecoder},removeChannel:{name:"removeChannel",execute:this.removeChannel.bind(this),dataDecoder:removeChannelDataDecoder},getMyChannel:{name:"getMyChannel",execute:async()=>{},resultDecoder:getMyChanelResultDecoder},getWindowIdsOnChannel:{name:"getWindowIdsOnChannel",execute:this.handleGetWindowIdsOnChannel.bind(this),dataDecoder:getWindowIdsOnChannelDataDecoder,resultDecoder:getWindowIdsOnChannelResultDecoder},getWindowIdsWithChannels:{name:"getWindowIdsWithChannels",execute:this.handleGetWindowIdsWithChannels.bind(this),dataDecoder:wrappedWindowWithChannelFilterDecoder,resultDecoder:getWindowIdsWithChannelsResultDecoder},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},joinChannel:{name:"joinChannel",dataDecoder:joinChannelDataDecoder,execute:this.handleJoinChannel.bind(this)},restrict:{name:"restrict",dataDecoder:restrictionConfigDataDecoder,execute:this.restrict.bind(this)},getRestrictions:{name:"getRestrictions",dataDecoder:getRestrictionsDataDecoder,execute:this.getRestrictions.bind(this),resultDecoder:restrictionsDecoder},restrictAll:{name:"restrictAll",dataDecoder:restrictAllDataDecoder,execute:this.restrictAll.bind(this)},notifyChannelsChanged:{name:"notifyChannelsChanged",execute:this.handleChannelsChanged.bind(this),dataDecoder:channelsChangedDecoder},leaveChannel:{name:"leaveChannel",dataDecoder:leaveChannelDecoder,execute:this.handleLeaveChannel.bind(this)},requestChannelSelector:{name:"requestChannelSelector",dataDecoder:requestChannelSelectorConfigDecoder,execute:this.handleRequestChannelSelector.bind(this)},getMode:{name:"getMode",resultDecoder:getChannelsModeDecoder,execute:this.handleGetMode.bind(this)}};constructor(e,t,r){this.glueController=e,this.sessionController=t,this.workspacesController=r}get logger(){return logger.get("channels.controller")}async start(e){const t=e.channels.definitions;this.logger?.trace("initializing channels"),this.mode=e.channels.mode,this.logger?.trace(`initializing channels with mode: ${this.mode}`),await this.setupChannels(t),this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){const t=e.data,r=e.commandId,n=e.callerId,i=channelOperationDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This channels request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`Channels request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`Channels request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}handleClientUnloaded(e,t){this.logger?.trace(`[${e}] - Received client unloaded event for windowId: ${e}`);this.sessionController.getEjectedWindowIds().includes(e)?this.logger?.trace(`[${e}] - A workspace window with ID ${e} is being ejected or brought back to workspace. Keeping track of it.`):t&&!t.closed||(this.sessionController.removeEjectedWindowId(e),this.sessionController.removeWindowChannelData(e),this.logger?.trace(`[${e}] - Client unloaded event processed. Removed from Session Storage successfully`))}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleAppHello({windowId:e},t){this.logger?.trace(`[${t}] - Received 'appHello' message for window with ID: ${e}`);this.checkIfValidWindowOrInteropInstanceId(e)||ioError.raiseError(`[${t}] - Cannot complete 'appHello' operation - received invalid window ID: ${e}`);const r=this.sessionController.getWindowChannelData(e);return this.logger?.trace(`[${t}] - Session data for window with ID ${e}: ${JSON.stringify(r)}`),{mode:this.mode,channels:r?.channels||[],restrictions:r?.restrictions||[]}}async handleLeaveChannel(e,t){this.trace(`[${t}] handling leaveChannel command with windowId: ${e.windowId}`,t);this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'leaveChannel' operation - received invalid window ID: ${e.windowId}`),this.removeChannelsFromSessionStorage(e.windowId,e.channelName),await this.glueController.callWindow("channels",this.operations.leaveChannel,e,{instance:e.windowId}),this.trace(`[${t}] successfully left the channel on window with ID "${e.windowId}"`,t)}removeChannelsFromSessionStorage(e,t){const r=this.sessionController.getWindowChannelData(e);if(!r?.channels?.length)return void this.logger?.trace(`No channels data found for window with id: ${e}, nothing to remove`);const n=t?r.channels.filter(e=>e!==t):[];this.sessionController.setChannelsForWindow(e,n)}async setupChannels(e){await Promise.all(e.map(e=>this.addChannel(e)))}async addChannel(e,t){this.trace(`[${t}] handling addChannel command with a valid name: ${e.name}, color: ${e.meta.color} and data: ${JSON.stringify(e.data)}`,t);const r={name:e.name,meta:e.meta,data:e.data||{}},n=this.createContextName(r.name);this.trace(`[${t}] setting a new channel context with name: ${n}`,t),await this.glueController.setContext(n,r),this.trace(`[${t}] channel context with name: ${n} created successfully`,t)}async removeChannel({name:e},t){this.trace(`[${t}] handling removeChannel command with a valid name: ${e}`,t);const r=this.createContextName(e);await this.glueController.destroyContext(r),this.trace(`[${t}] channel context with name: ${r} destroyed successfully`,t)}async getWindowChannel(e,t){if(!await this.checkIfAppHelloSupported(e))return this.trace(`[${t}] client is outdated and does not support platform session storage, falling back to window call`,t),this.glueController.callWindow("channels",this.operations.getMyChannel,{},{instance:e});const r=this.sessionController.getWindowChannelData(e),n=r?.channels?.[0];return{channel:n}}async handleGetWindowIdsOnChannel({channel:e},t){this.trace(`[${t}] handling getWindowIdsOnChannel command with channel: ${e}`,t);const r=this.glueController.getLocalServers().reduce((e,{windowId:t})=>t?[...e,t]:e,[]);this.trace(`[${t}] compiled a list of the IDs of all the windows that will be called: [${r.join(", ")}]`,t);const n=await Promise.all(r.map(async e=>{const{channel:r}=await this.getWindowChannel(e,t);return{channel:r,windowId:e}})),i=n.filter(t=>t.channel===e).map(({windowId:e})=>e);return this.trace(`[${t}] compiled a list of all windowIds that are on the "${e}" channel and returning it to the caller: [${i.join(", ")}]`,t),{windowIds:i}}async handleGetWindowIdsWithChannels({filter:e},t){this.trace(`[${t}] handling getWindowIdsWithChannels command with filter: ${JSON.stringify(e)}`,t);const r=this.glueController.getLocalServers(),n=this.glueController.getAllApplicationNames(),i=r.filter(({windowId:e})=>e);this.trace(`[${t}] compiled a list of the IDs of all the windows that will be called: [${i.map(({windowId:e})=>e).join(", ")}]`,t);const o=await Promise.all(i.map(async({applicationName:e,windowId:r})=>{const{channel:i}=await this.getWindowChannel(r,t);return{application:e&&n.includes(e)?e:"no-app-window",...i?{channel:i}:{},windowId:r}}));let s=o;return e?(e.application&&(this.trace(`[${t}] filtering windows by application: ${e.application}`,t),s=s.filter(({application:t})=>t===e.application)),e.channels&&(this.trace(`[${t}] filtering windows by channels: [${e.channels.join(", ")}]`,t),s=s.filter(({channel:t})=>t&&e.channels?.includes(t))),e.windowIds&&(this.trace(`[${t}] filtering windows by windowIds: [${e.windowIds.join(", ")}]`,t),s=s.filter(({windowId:t})=>e.windowIds?.includes(t))),this.trace(`[${t}] compiled a list of all windowIds with channels and returning it to the caller: ${JSON.stringify(s)}`,t),{windowIdsWithChannels:s}):(this.trace(`[${t}] compiled a list of all windowIds with channels and returning it to the caller: ${JSON.stringify(s)}`,t),{windowIdsWithChannels:s})}async handleChannelsChanged(e,t){this.trace(`[${t}] handling notifyChannelsChanged command with data: ${JSON.stringify(e)}`,t),this.glueController.pushSystemMessage("windows","notifyChannelsChanged",e),this.trace(`[${t}] successfully notified all windows about the channel change`,t)}async handleRequestChannelSelector(e,t){this.trace(`[${t}] handling requestChannelSelector command with windowId: ${e.windowId} and initial channels: ${e.channelsNames?.join(", ")}`,t);const r=this.sessionController.getWorkspaceClientById(e.windowId);if(!r)return ioError.raiseError(`Failed to display channel selector on window with ID "${e.windowId}", because the provided windowId is not a workspace window.`);await this.workspacesController.showChannelsLink({windowId:r.windowId,frameId:r.frameId,channelsNames:e.channelsNames},t),this.trace(`[${t}] successfully notified all windows about the channel change`,t)}async handleGetMode(){return{mode:this.mode}}async handleJoinChannel({channel:e,windowId:t},r){this.trace(`[${r}] handling joinChannel command with channel: ${e} and windowId: ${t}`,r);this.checkIfValidWindowOrInteropInstanceId(t)||ioError.raiseError(`[${r}] - Cannot complete 'joinChannel' operation - received invalid window ID: ${t}`),"single"===this.mode?this.sessionController.setChannelsForWindow(t,[e]):this.sessionController.setAdditionalChannelForWindow(t,e),await this.glueController.callWindow("channels",this.operations.joinChannel,{channel:e,windowId:t},{instance:t}),this.trace(`[${r}] successfully joined "${e}" channel on window with ID "${t}"`,r)}createContextName(e){return`${ChannelContextPrefix}${e}`}trace(e,t){t&&this.logger?.trace(e)}async restrict({config:e},t,r){this.trace(`[${t}] received restrict command with config ${JSON.stringify(e)} from callerId: ${r}`,t);this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'restrict' operation - received invalid window ID: ${e.windowId}`),this.sessionController.addChannelRestrictionsByWindowId(e.windowId,e),await this.glueController.callWindow("channels",this.operations.restrict,{config:e},{instance:e.windowId})}async getRestrictions({windowId:e},t,r){this.trace(`[${t}] received getRestrictions command for window with id ${e} from callerId: ${r}`,t);this.checkIfValidWindowOrInteropInstanceId(e)||ioError.raiseError(`[${t}] - Cannot complete 'getRestrictions' operation - received invalid window ID: ${e}`);if(!await this.checkIfAppHelloSupported(e))return this.logger?.trace(`[${t}] - Client's restrictions are saved in its own session storage. Calling it to get restrictions.`),this.glueController.callWindow("channels",this.operations.getRestrictions,{windowId:e},{instance:e});const n=this.sessionController.getWindowChannelData(e);return{channels:n?.restrictions||[]}}async restrictAll({restrictions:e},t,r){this.trace(`[${t}] received restrictAll command with config ${JSON.stringify(e)} from callerId: ${r}`,t);return this.checkIfValidWindowOrInteropInstanceId(e.windowId)||ioError.raiseError(`[${t}] - Cannot complete 'restrictAll' operation - received invalid window ID: ${e.windowId}`),this.addAllChannelRestrictionsInSessionStorage(e.windowId,e),this.glueController.callWindow("channels",this.operations.restrictAll,{restrictions:e},{instance:e.windowId})}addAllChannelRestrictionsInSessionStorage(e,t){const r=this.glueController.getAllContexts().filter(e=>e.startsWith(ChannelContextPrefix)).map(e=>e.replace(ChannelContextPrefix,"")),n=r.map(e=>({name:e,...t}));this.sessionController.addAllChannelsRestrictionsByWindowId(e,n)}checkIfValidWindowOrInteropInstanceId(e){if(this.glueController.isValidWindowId(e))return!0;if(this.glueController.platformWindowId===e)return!0;return!!this.glueController.getLocalServers().some(t=>t.instance===e)}async checkIfAppHelloSupported(e){try{return(await this.glueController.checkClientOperationSupport("channels",this.operations.appHello,{instance:e})).isSupported}catch(t){return this.logger?.trace(`Client with windowId: ${e} does NOT support 'appHello' message.`),!1}}}class FramesController{sessionController;glueController;ioc;config;defaultBounds;frameSummaryOperation;locks={};defaultFrameHelloTimeoutMs=15e3;_handleUnload;constructor(e,t,r){this.sessionController=e,this.glueController=t,this.ioc=r}get myFrameId(){return this.glueController.platformWindowId}stop(){this._handleUnload&&window.removeEventListener("pagehide",this._handleUnload)}async start(e,t,r){this.config=e,this.defaultBounds=t,this.frameSummaryOperation=r}async openFrame(e,t){const r="object"==typeof e?e.bounds??{}:{},n=r.top??this.defaultBounds.top,i=r.left??this.defaultBounds.left,o=r.width??this.defaultBounds.width,s=r.height??this.defaultBounds.height,a="object"==typeof e&&e?.frameId?e.frameId:`g42-${nanoid$5(10)}`;if(this.sessionController.getAllFrames().some(e=>e.windowId===a))return ioError.raiseError(`Cannot open a frame with id: ${a}, because a frame with this id already exists`);const c={windowId:a,active:!1,isPlatform:!1,layoutComponentId:t},l=`left=${i},top=${n},width=${o},height=${s}`,u=(await this.getWorkspacesUrls()).workspacesUrl.current,d=u.includes("?")?`${u}&emptyFrame=true`:`${u}?emptyFrame=true`;if(!window.open(d,c.windowId,l))return ioError.raiseError("Cannot open a new workspace frame, because the user has not allowed popups or uses a blocker");this.sessionController.saveFrameData(c);try{return await this.waitHello(c.windowId),{windowId:c.windowId}}catch(e){return delete this.locks[c.windowId],ioError.raiseError("Cannot open a new frame, because the workspace frame app did not send a hello in time")}}async closeFrame(e){if(this.myFrameId===e)return ioError.raiseError("Cannot close the platform frame, because it is the current frame");this.sessionController.getFrameData(e)&&(this.handleFrameDisappeared(e),window.open(void 0,e)?.close())}processNewHello(e){this.sessionController.getFrameData(e)&&(this.sessionController.setFrameActive(e),this.locks[e]?.lift())}handleFrameDisappeared(e){this.sessionController.getFrameData(e)&&(this.sessionController.removeFrameData(e),this.clearAllWorkspaceWindows(e))}getAll(){return this.sessionController.getAllFrames().filter(e=>e.active).map(e=>({windowId:e.windowId}))}async getFrameInstance(e){if(e){if(["frameId","itemId","newFrame"].reduce((t,r)=>(e[r]&&t.push(r),t),[]).length>1)return ioError.raiseError(`Cannot retrieve the frame, because of over-specification: the provided selection object must have either 1 or none of the possible properties: ${JSON.stringify(e)}`)}const t=this.getAll();if(e?.frameId){const r=t.find(t=>t.windowId===e.frameId);return r||ioError.raiseError(`Cannot retrieve a frame with Id: ${e.frameId}, because it is not known by the platform`)}return e?.itemId?this.getFrameByItemId(e.itemId,t):e?.newFrame?this.openFrame(e.newFrame):t.length?this.getLastOpenedFrame():this.openFrame()}getPlatformFrameSessionData(){return this.sessionController.getAllFrames().find(e=>e.isPlatform)}getFrameConfig(e){return this.sessionController.getAllFrames().find(t=>t.windowId===e)}clearAllWorkspaceWindows(e){this.sessionController.pickWorkspaceClients(t=>t.frameId===e).forEach(e=>{this.ioc.applicationsController.unregisterWorkspaceApp({windowId:e.windowId})})}async waitHello(e){return PromisePlus(t=>{this.locks[e]={lift:t}},this.defaultFrameHelloTimeoutMs,"Frame hello timed out")}getLastOpenedFrame(){const e=this.sessionController.getAllFrames().filter(e=>e.active);return e[e.length-1]}async getFrameByItemId(e,t){if(!t.length)return ioError.raiseError(`Cannot get frame by item id for: ${e}, because not frames were found`);for(const r of t){if("none"!==(await this.glueController.callFrame(this.frameSummaryOperation,{itemId:e},r.windowId)).id)return r}return ioError.raiseError(`Cannot find frame for item: ${e}`)}getWorkspacesUrls(){return new URL(window.location.href).protocol.includes("extension")?new Promise(e=>{chrome.storage.local.get("workspacesUrl",t=>{e(t)})}):Promise.resolve({workspacesUrl:{current:this.config.src,default:this.config.src}})}}class WorkspaceHibernationWatcher{session;sequelizer;workspacesController;settings;running;constructor(e,t){this.session=e,this.sequelizer=t}get logger(){return logger.get("workspaces.hibernation")}stop(){this.running=!1}start(e,t){this.logger?.trace(`starting the hibernation watcher with following settings: ${JSON.stringify(this.settings)}`),this.running=!0,this.workspacesController=e,this.settings=t;const r=this.session.exportClearTimeouts();this.settings?.idleWorkspaces?.idleMSThreshold&&r.forEach(e=>this.buildTimer(e.workspaceId)),this.logger?.trace("The hibernation watcher has started successfully")}notifyEvent(e){"window"===e.type&&this.handleWorkspaceWindowEvent(e),"workspace"===e.type&&this.handleWorkspaceEvent(e)}handleWorkspaceWindowEvent(e){("opened"===e.action||"added"===e.action)&&(this.sequelizer.enqueue(()=>this.checkMaximumAmountCore()),this.addTimersForWorkspacesInFrame(e.payload.windowSummary.config.frameId))}handleWorkspaceEvent(e){const t="selected"===e.action,r="lock-configuration-changed"===e.action,n=e.payload;if(!("selected"===e.action||"opened"===e.action||"lock-configuration-changed"===e.action))return;this.sequelizer.enqueue(()=>this.checkMaximumAmountCore());const i=n.workspaceSummary.config.allowSystemHibernation;if(!(t||r&&i))return;const o=this.session.getTimeout(n.workspaceSummary.id);o&&(clearTimeout(o),this.session.removeTimeout(n.workspaceSummary.id)),this.addTimersForWorkspacesInFrame(n.frameSummary.id)}compare(e,t){return e.config.lastActive>t.config.lastActive?1:e.config.lastActivethis.workspacesController.getWorkspaceSnapshot({itemId:e.id},t)),n=(await Promise.all(r)).filter(e=>!this.isWorkspaceHibernated(e.config)&&!this.isWorkspaceEmpty(e)),i=n.filter(e=>this.isSystemHibernationAllowed(e));if(n.length<=e)return;this.logger?.trace(`Found ${i.length} eligible for hibernation workspaces`);const o=i.sort(this.compare).slice(0,n.length-e).map(e=>this.tryHibernateWorkspace(e.id));await Promise.all(o)}async tryHibernateWorkspace(e){try{const t=await this.workspacesController.getWorkspaceSnapshot({itemId:e},nanoid$5(10));if(!this.canBeHibernated(t))return;this.logger?.trace(`trying to hibernate workspace ${e}`),await this.workspacesController.hibernateWorkspace({workspaceId:e},nanoid$5(10)),this.logger?.trace(`workspace ${e} was hibernated successfully`)}catch(e){this.logger?.trace(e)}}canBeHibernated(e){const t=this.isWorkspaceHibernated(e.config),r=this.isWorkspaceSelected(e.config),n=this.isWorkspaceEmpty(e),i=this.isSystemHibernationAllowed(e);return!t&&!r&&!n&&i}isWorkspaceHibernated(e){return e.isHibernated}isWorkspaceSelected(e){return e.isSelected}isWorkspaceEmpty(e){return!e.children.length}isSystemHibernationAllowed(e){const{allowSystemHibernation:t}=e.config;return"boolean"!=typeof t||t}async getWorkspacesInFrame(e){const t=(await this.workspacesController.getAllWorkspacesSummaries({},nanoid$5(10))).summaries.reduce((t,r)=>(r.config.frameId===e&&t.push(this.workspacesController.getWorkspaceSnapshot({itemId:r.id},nanoid$5(10))),t),[]);return await Promise.all(t)}async addTimersForWorkspacesInFrame(e){if(!this.settings?.idleWorkspaces?.idleMSThreshold)return;(await this.getWorkspacesInFrame(e)).forEach(e=>{this.canBeHibernated(e)&&!this.session.getTimeout(e.id)&&(this.buildTimer(e.id),this.logger?.trace(`Starting workspace idle timer ( ${this.settings?.idleWorkspaces?.idleMSThreshold}ms ) for workspace ${e.id}`))})}buildTimer(e){const t=window.setTimeout(()=>{this.running&&(this.logger?.trace(`Timer triggered will try to hibernated ${e}`),this.tryHibernateWorkspace(e),this.session.removeTimeout(e))},this.settings?.idleWorkspaces?.idleMSThreshold);this.session.saveTimeout(e,t)}}class SystemController{session;workspacesController;glueController;pluginsController;profileData;environment;base={};started=!1;errorPort=errorChannel.port2;registry=CallbackRegistryFactory$2();platformOperations=["cleanupClientsOnWorkspaceFrameUnregister"];operations={getEnvironment:{name:"getEnvironment",resultDecoder:anyDecoder,execute:this.handleGetEnvironment.bind(this)},getBase:{name:"getBase",resultDecoder:anyDecoder,execute:this.handleGetBase.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},workspacesInitCheck:{name:"workspacesInitCheck",resultDecoder:workspacesInitCheckResultDecoder,execute:this.handleWorkspacesInitCheck.bind(this)},clientError:{name:"clientError",dataDecoder:clientErrorDataDecoder,execute:this.handleClientError.bind(this)},systemHello:{name:"systemHello",resultDecoder:systemHelloSuccessDecoder,execute:this.handleSystemHello.bind(this)},getProfileData:{name:"getProfileData",execute:this.handleGetProfileData.bind(this)}};constructor(e,t,r,n){this.session=e,this.workspacesController=t,this.glueController=r,this.pluginsController=n}get logger(){return logger.get("system.controller")}handlePlatformShutdown(){this.started=!1,this.registry.clear()}async start(e){this.environment=e.environment,this.base={workspaces:{frameCache:e.workspacesFrameCache},workspacesFrameCache:e.workspacesFrameCache,communicationId:this.session.getSystemSettings()?.systemInstanceId,platformVersion:version$1,connectionProtocolVersion:connectionProtocolVersion,fdc3:{webProxyUrl:FDC3ProxyUrl}},this.profileData=e.profileData,this.errorPort.onmessage=e=>{this.registry.execute("platform-error",{message:e.data})},this.started=!0}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this system control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=systemOperationTypesDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This system request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`System request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`System request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}onPlatformError(e){return this.registry.add("platform-error",e)}onClientError(e){return this.registry.add("client-error",e)}setProfileData(e){this.profileData=e}async handleOperationCheck(e){const t=Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase()),r=this.platformOperations.some(t=>t.toLowerCase()===e.operation.toLowerCase());return{isSupported:t||r}}async handleGetEnvironment(){return this.environment}async handleGetProfileData(){if(!this.profileData)return;return{...this.profileData,plugins:this.pluginsController.registeredPlugins.map(e=>({name:e.name,version:e.version}))}}async handleGetBase(){return this.base}async handleWorkspacesInitCheck(){return{initialized:this.workspacesController.started}}async handleClientError({message:e},t,r){this.logger?.trace(`[${t}] received clientError command with message ${e} from callerId: ${r}`),this.glueController.clientGlue?r&&r===this.glueController.me.instance?this.registry.execute("platform-error",{message:e}):this.registry.execute("client-error",{message:e,callerId:r}):this.registry.execute("platform-error",{message:e})}async handleSystemHello(){return{isClientErrorOperationSupported:!0}}}class AppDirectory{remoteWatcher;manager;cache;unsubFuncs=[];maxAllowedApplicationsInStore=1e4;baseEventFlushDurationMs=10;appsStateChange;sequelizer;isManagerConfigured;constructor(e,t,r){this.remoteWatcher=e,this.manager=t,this.cache=r}stop(){this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[]}async start(e){if(this.logger?.trace("Starting the application directory"),this.appsStateChange=e.appsStateChange,this.sequelizer=e.sequelizer,await this.cache.start(e.config.remote),e.config.local?.length&&(this.logger?.trace("Detected local applications, parsing..."),await this.processAppDefinitions(e.config.local,{type:"inmemory",mode:"merge"})),e.isManagerConfigured&&(this.isManagerConfigured=e.isManagerConfigured,this.setupManagerListeners(),this.logger?.trace("Detected manager configuration, starting the watcher...")),e.config.remote){this.logger?.trace("Detected remote app store configuration, starting the watcher...");try{await this.remoteWatcher.start(e.config.remote,e=>this.processAppDefinitions(e,{type:"remote",mode:"replace"}))}catch(e){return this.handleRemoteConnectionFailure(e)}}}processAppDefinitions(e,t){return this.sequelizer.enqueue(async()=>{const r=e.map(e=>this.parseDefinition(e)),n=[...await this.cache.getAllRemoteApps(),...await this.cache.getAllMemoryApps()],i=this[t.mode](n,r);if(i.readyApps.length>this.maxAllowedApplicationsInStore)return ioError.raiseError("Cannot save the app definitions, because the total number exceeds 10000, which is the limit.");const o="remote"===t.type?this.cache.saveRemoteApps.bind(this.cache):this.cache.saveMemoryApps.bind(this.cache);await o(i.readyApps),await this.announceApps(i)})}getAll(){return this.sequelizer.enqueue(async()=>{const e=new Map,t=await this.cache.getAllMemoryApps(),r=await this.cache.getAllRemoteApps(),n=this.isManagerConfigured?this.manager.getAllApps().map(this.parseDefinition):[];return r.forEach(t=>e.set(t.name,t)),n.forEach(t=>e.set(t.name,t)),t.forEach(t=>e.set(t.name,t)),Array.from(e.values())})}exportInMemory(){return this.sequelizer.enqueue(async()=>(await this.cache.getAllMemoryApps()).map(this.reverseParseDefinition))}removeInMemory(e){return this.sequelizer.enqueue(async()=>this.cache.removeMemoryApp(e))}merge(e,t){const r={readyApps:[],addedApps:[],changedApps:[],removedApps:[]},n=e.reduce((e,t)=>(e[t.name]=t,e),{});return t.forEach(e=>n[e.name]&&!objEqualFast(e,n[e.name])?(n[e.name]=e,void r.changedApps.push(e)):n[e.name]?void 0:(n[e.name]=e,void r.addedApps.push(e))),r.readyApps=Object.values(n),r}replace(e,t){const r={readyApps:[],addedApps:[],changedApps:[],removedApps:[]},n=e.reduce((e,t)=>(e[t.name]=t,e),{});return t.forEach(e=>{n[e.name]||r.addedApps.push(e),n[e.name]&&!objEqualFast(e,n[e.name])&&r.changedApps.push(e),n[e.name]&&(n[e.name].isChecked=!0)}),r.removedApps=e.filter(e=>!e.isChecked),r.readyApps=t,r}reverseParseDefinition(e){const t=e.userProperties.details,{details:r,...n}=e.userProperties,i={name:e.name,type:e.type||"window",title:e.title,version:e.version,icon:e.icon,caption:e.caption,details:t,customProperties:n};return e.fdc3&&(i.fdc3=e.fdc3),i}parseDefinition(e){const t=["name","title","version","customProperties","icon","caption","type"],r=Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e))),{isFdc3:n}=fdc3.isFdc3Definition(e);let i;if(n)i=fdc3.parseToBrowserBaseAppData(e);else{const t=e.details;i={createOptions:t,type:e.type||"window",name:e.name,title:e.title,version:e.version,icon:e.icon,caption:e.caption,userProperties:{...r,...e.customProperties}},i.userProperties.details||(i.userProperties.details=t)}return Object.keys(i).forEach(e=>void 0===i[e]&&delete i[e]),i}get logger(){return logger.get("applications.remote.directory")}async announceApps(e){const t={appsAdded:e.addedApps,appsChanged:e.changedApps,appsRemoved:e.removedApps};this.logger?.trace(`announcing a change in the app directory state: ${JSON.stringify(t)}`),this.appsStateChange(t),await this.waitEventFlush()}setupManagerListeners(){const e=this.manager.onAppsAdded(e=>{this.announceApps({addedApps:e.map(this.parseDefinition),changedApps:[],removedApps:[],readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),t=this.manager.onAppsDeleted(e=>{this.announceApps({addedApps:[],changedApps:[],removedApps:e.map(this.parseDefinition),readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))}),r=this.manager.onAppsChanged(e=>{this.announceApps({addedApps:[],changedApps:e.map(this.parseDefinition),removedApps:[],readyApps:[]}).catch(e=>this.logger?.warn(extractErrorMsg$1(e)))});this.unsubFuncs.push(e,t,r)}waitEventFlush(){return new Promise(e=>setTimeout(e,this.baseEventFlushDurationMs))}async handleRemoteConnectionFailure(e){const t=await this.cache.getAllRemoteApps();if(!t?.length)return ioError.raiseError(`The connection to the remote app store failed and there are no cached entries, cannot continue. Error: ${extractErrorMsg$1(e)}`);this.logger?.warn(`The connection to the remote app store failed, but there are cached entries, continuing with the cached apps. Error: ${extractErrorMsg$1(e)}`)}}const defaultRemoteWatcherHeaders={"Content-Type":"application/json",Accept:"application/json"},defaultRemoteWatcherRequestTimeoutMS=3e3,fetchTimeout=(e,t=defaultFetchTimeoutMs,r=new AbortController)=>new Promise((n,i)=>{const o={signal:r.signal};let s=!1;const a=setTimeout(()=>{s=!0,i(new Error(`Fetch request for: ${JSON.stringify(e)} timed out at: ${t} milliseconds`)),r.abort()},t);fetch(e,o).then(e=>{s||(clearTimeout(a),n(e))}).catch(e=>{s||(clearTimeout(a),i(e))})});class RemoteWatcher{scheduler;handleApps;config;constructor(e){this.scheduler=e}async start(e,t){this.handleApps=t,this.config=this.prepareConfig(e);const r=this.doInitialRequest();if(this.configureScheduler(),this.config.waitInitialResponse)return this.logger?.info("Waiting for the initial response from the remote app store before proceeding"),void await r;r.catch(e=>this.logger?.error("The initial request to the remote app store failed",e))}getRequest(){const e=new Headers;for(const t in defaultRemoteWatcherHeaders)e.append(t,defaultRemoteWatcherHeaders[t]);for(const t in this.config.customHeaders)this.logger?.trace("Custom headers detected and set"),e.append(t,this.config.customHeaders[t]);const t={method:"GET",headers:e,mode:"cors",cache:"default"},r=this.config.getRequestInit?.({url:this.config.url,requestInit:t});return new Request(this.config.url,{...t,...r})}get logger(){return logger.get("applications.remote.directory")}prepareConfig(e){const t={...e,requestTimeout:e.requestTimeout??defaultRemoteWatcherRequestTimeoutMS,customHeaders:e.customHeaders??{},getRequestInit:e.getRequestInit??(()=>({})),waitInitialResponse:e.waitInitialResponse??!0};return t.cache?.enabled&&!t.pollingInterval?ioError.raiseError("Polling interval is required when cache is enabled"):t.pollingInterval&&t.pollingInterval<5e3?ioError.raiseError("Polling interval must be at least 5000ms"):t}configureScheduler(){if(!this.config.pollingInterval)return void this.logger?.info("Polling interval is not set, skipping scheduler setup");const e="applications:get:all";if(this.scheduler.checkEntryExists(e))return;const t={key:e,getRequest:()=>this.getRequest(),timeout:this.config.requestTimeout,refreshIntervalMS:this.config.pollingInterval,onData:this.processGetAllAppsUpdate.bind(this),onError:e=>this.logger?.error("Error during get all application definitions from scheduler",e)};this.scheduler.register(t)}async processGetAllAppsUpdate(e){if(!e||!Array.isArray(e.applications))return this.logger?.warn("The remote response was either empty or did not contain an applications collection");this.logger?.trace("There is a valid response from the app store, processing definitions...");const t=e.applications.reduce((e,t)=>{const r=allApplicationDefinitionsDecoder.run(t);return r.ok?e.push(t):this.logger?.warn(`Removing applications definition with name: ${t.name} from the remote response, because of validation error: ${JSON.stringify(r.error)}`),e},[]);await this.handleApps(t)}async doInitialRequest(){try{const e=this.getRequest(),t=await fetchTimeout(e,this.config.requestTimeout),r=await t.json();await this.processGetAllAppsUpdate(r)}catch(e){return ioError.raiseError("Error during initial request to get all applications",e)}}}class ServiceWorkerController{idbController;registry=CallbackRegistryFactory$2();_serviceWorkerRegistration;channel;_broadcastMessageHandler;constructor(e){this.idbController=e}get logger(){return logger.get("service.worker.web.platform")}get serviceWorkerRegistration(){return this._serviceWorkerRegistration?this._serviceWorkerRegistration:ioError.raiseError("Accessing missing service worker registration object. This is caused because the application is trying to raise a persistent notification, which requires a service worker. Please provide a service worker config when initializing GlueWebPlatform.")}shutdown(){this.channel?.removeEventListener("message",this._broadcastMessageHandler),this.registry.clear()}async connect(e){if(e.serviceWorker){if(this.logger?.info("Detected service worker definition, connecting..."),!e.serviceWorker.url&&void 0===e.serviceWorker.registrationPromise)return ioError.raiseError("The service worker config is defined, but it is missing a url or a registration promise, please provide one or the other");if(e.serviceWorker.url&&void 0!==e.serviceWorker.registrationPromise)return ioError.raiseError("The service worker is over-specified, there is both defined url and a registration promise, please provide one or the other");await this.prepareSwDb(),this._serviceWorkerRegistration=e.serviceWorker.url?await this.registerWorker(e.serviceWorker.url):await this.waitRegistration(e.serviceWorker.registrationPromise),this._serviceWorkerRegistration&&this.setUpBroadcastChannelConnection(),this.logger?.info("Service worker connection completed.")}}async showNotification(e,t){const r=Object.assign({},e,{title:void 0,clickInterop:void 0,actions:void 0});r.actions=e.actions?.map(e=>({action:e.action,title:e.title,icon:e.icon}));const n={focusPlatformOnDefaultClick:e.focusPlatformOnDefaultClick,clickInterop:e.clickInterop,actions:e.actions,id:t};r.data?r.data.glueData=n:r.data={glueData:n},await this.serviceWorkerRegistration.showNotification(e.title,r)}notifyReady(){this._serviceWorkerRegistration&&this.channel.postMessage({platformStarted:!0})}onNotificationClick(e){return this.registry.add("notification-click",e)}onNotificationClose(e){return this.registry.add("notification-close",e)}setUpBroadcastChannelConnection(){this.channel=new BroadcastChannel(serviceWorkerBroadcastChannelName),this._broadcastMessageHandler=this.broadcastMessageHandler.bind(this),this.channel.addEventListener("message",this._broadcastMessageHandler)}broadcastMessageHandler(e){const t=e.data,r=t?.messageType;if(r)if("ping"!==r){if("notificationClick"===r){const e=t.action,r=t.glueData;return void this.registry.execute("notification-click",{action:e,glueData:r})}if("notificationClose"===r){const e=t.action,r=t.glueData;return void this.registry.execute("notification-close",{action:e,glueData:r})}"notificationError"!==r||this.logger?.error(`Service worker error when raising notification: ${t.error}`)}else this.channel.postMessage({pong:!0})}async registerWorker(e){if("serviceWorker"in navigator)try{return await navigator.serviceWorker.register(e)}catch(e){const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(t)}else this.logger?.warn(`A defined service worker has not been registered at ${e} because this browser does not support it.`)}async waitRegistration(e){if("function"!=typeof e.then||"function"!=typeof e.catch)return ioError.raiseError("The provided service worker registration promise is not a promise");const t=await e;return"function"!=typeof t.showNotification?ioError.raiseError("The provided registration promise is a promise, but it resolved with an object which does not appear to be a ServiceWorkerRegistration"):t}async prepareSwDb(){await this.idbController.clearServiceWorker(),await this.idbController.storeServiceWorker({platformUrl:window.location.href})}}const setNotificationDefaults=e=>{e.showToast="boolean"!=typeof e.showToast||e.showToast,e.showInPanel="boolean"!=typeof e.showInPanel||e.showInPanel,e.timestamp=void 0===e.timestamp?Date.now():e.timestamp,e.state=void 0===e.state?"Active":e.state},notificationsOperationDecoder=oneOf$1(constant$2("raiseNotification"),constant$2("requestPermission"),constant$2("getPermission"),constant$2("operationCheck"),constant$2("list"),constant$2("clear"),constant$2("click"),constant$2("clearAll"),constant$2("configure"),constant$2("getConfiguration"),constant$2("setState"),constant$2("clearOld"),constant$2("getActiveCount")),interopActionSettingsDecoder=object$3({method:nonEmptyStringDecoder$2,arguments:optional$3(anyJson$2()),target:optional$3(oneOf$1(constant$2("all"),constant$2("best")))}),glue42NotificationActionDecoder=object$3({action:string$5(),title:nonEmptyStringDecoder$2,icon:optional$3(string$5()),interop:optional$3(interopActionSettingsDecoder)}),notificationStateDecoder=oneOf$1(constant$2("Active"),constant$2("Acknowledged"),constant$2("Seen"),constant$2("Closed"),constant$2("Stale"),constant$2("Snoozed"),constant$2("Processing")),glue42NotificationOptionsDecoder=object$3({title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$4()),badge:optional$3(string$5()),body:optional$3(string$5()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$5()),image:optional$3(string$5()),lang:optional$3(string$5()),renotify:optional$3(boolean$4()),requireInteraction:optional$3(boolean$4()),silent:optional$3(boolean$4()),tag:optional$3(string$5()),timestamp:optional$3(nonNegativeNumberDecoder$2),vibrate:optional$3(array$3(number$5())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:optional$3(boolean$4()),showInPanel:optional$3(boolean$4()),state:optional$3(notificationStateDecoder)}),glue42NotificationOptionsWithDefaultsDecoder=object$3({title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$4()),badge:optional$3(string$5()),body:optional$3(string$5()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$5()),image:optional$3(string$5()),lang:optional$3(string$5()),renotify:optional$3(boolean$4()),requireInteraction:optional$3(boolean$4()),silent:optional$3(boolean$4()),tag:optional$3(string$5()),timestamp:nonNegativeNumberDecoder$2,vibrate:optional$3(array$3(number$5())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:boolean$4(),showInPanel:boolean$4(),state:optional$3(notificationStateDecoder)}),raiseNotificationDecoder=object$3({settings:glue42NotificationOptionsDecoder,id:nonEmptyStringDecoder$2}),raiseNotificationResultDecoder=object$3({settings:glue42NotificationOptionsWithDefaultsDecoder}),permissionRequestResultDecoder=object$3({permissionGranted:boolean$4()}),permissionQueryResultDecoder=object$3({permission:oneOf$1(constant$2("default"),constant$2("granted"),constant$2("denied"))}),simpleNotificationSelectDecoder=object$3({id:nonEmptyStringDecoder$2}),notificationClickConfigDecoder=object$3({id:nonEmptyStringDecoder$2,action:optional$3(nonEmptyStringDecoder$2)}),notificationsDataDecoder=object$3({id:nonEmptyStringDecoder$2,title:nonEmptyStringDecoder$2,clickInterop:optional$3(interopActionSettingsDecoder),actions:optional$3(array$3(glue42NotificationActionDecoder)),focusPlatformOnDefaultClick:optional$3(boolean$4()),badge:optional$3(string$5()),body:optional$3(string$5()),data:optional$3(anyJson$2()),dir:optional$3(oneOf$1(constant$2("auto"),constant$2("ltr"),constant$2("rtl"))),icon:optional$3(string$5()),image:optional$3(string$5()),lang:optional$3(string$5()),renotify:optional$3(boolean$4()),requireInteraction:optional$3(boolean$4()),silent:optional$3(boolean$4()),tag:optional$3(string$5()),timestamp:optional$3(nonNegativeNumberDecoder$2),vibrate:optional$3(array$3(number$5())),severity:optional$3(oneOf$1(constant$2("Low"),constant$2("None"),constant$2("Medium"),constant$2("High"),constant$2("Critical"))),showToast:optional$3(boolean$4()),showInPanel:optional$3(boolean$4()),state:optional$3(notificationStateDecoder)}),allNotificationsDataDecoder=object$3({notifications:array$3(notificationsDataDecoder)}),notificationsConfigurationDecoder=object$3({enable:optional$3(boolean$4()),enableToasts:optional$3(boolean$4()),sourceFilter:optional$3(notificationFilterDecoder),showNotificationBadge:optional$3(boolean$4())}),notificationsConfigurationProtocolDecoder=object$3({configuration:notificationsConfigurationDecoder}),notificationsActiveCountDecoder=object$3({count:number$5()}),notificationSetStateRequestDecoder=object$3({id:nonEmptyStringDecoder$2,state:notificationStateDecoder}),prefsNotificationsDecoder=object$3({config:notificationsConfigurationDecoder});class NotificationsController{glueController;serviceWorkerController;session;localStorage;prefsController;started=!1;isInExtension=!1;clearNotificationOnClick;extNotificationConfig;systemUnsubFuncs=[];_chromeClickedHandler;_chromeButtonClickedHandler;_chromeClosedHandler;operations={raiseNotification:{name:"raiseNotification",execute:this.handleRaiseNotification.bind(this),dataDecoder:raiseNotificationDecoder,resultDecoder:raiseNotificationResultDecoder},requestPermission:{name:"requestPermission",resultDecoder:permissionRequestResultDecoder,execute:this.handleRequestPermission.bind(this)},getPermission:{name:"getPermission",resultDecoder:permissionQueryResultDecoder,execute:this.handleGetPermission.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},list:{name:"list",resultDecoder:allNotificationsDataDecoder,execute:this.handleList.bind(this)},click:{name:"click",dataDecoder:notificationClickConfigDecoder,execute:this.handleClick.bind(this)},clear:{name:"clear",dataDecoder:simpleNotificationSelectDecoder,execute:this.handleClear.bind(this)},clearAll:{name:"clearAll",execute:this.handleClearAll.bind(this)},configure:{name:"configure",dataDecoder:notificationsConfigurationProtocolDecoder,execute:this.handleConfigure.bind(this)},getActiveCount:{name:"getActiveCount",resultDecoder:notificationsActiveCountDecoder,execute:this.handleGetActiveCount.bind(this)},getConfiguration:{name:"getConfiguration",resultDecoder:notificationsConfigurationProtocolDecoder,execute:this.handleGetConfiguration.bind(this)},setState:{name:"setState",dataDecoder:notificationSetStateRequestDecoder,execute:this.handleSetState.bind(this)},clearOld:{name:"clearOld",execute:this.handleClearOld.bind(this)}};constructor(e,t,r,n,i){this.glueController=e,this.serviceWorkerController=t,this.session=r,this.localStorage=n,this.prefsController=i}get logger(){return logger.get("notifications.controller")}get config(){const e=this.localStorage.getNotificationsConfig();return e||ioError.raiseError("The notifications configuration has not been set.")}get currentActiveCount(){return this.session.getAllNotifications().reduce((e,t)=>"Active"===t.state?e+1:e,0)}handlePlatformShutdown(){this.started=!1;new URL(window.location.href).protocol.includes("extension")&&this.removeExtensionNotificationsListeners(),this.systemUnsubFuncs.forEach(e=>e()),this.systemUnsubFuncs=[]}async start(){this.clearNotificationOnClick=this.config.clearNotificationOnClick;new URL(window.location.href).protocol.includes("extension")&&await this.setupExtensionNotifications(),this.listenForServiceWorkerNotificationEvents(),this.started=!0}async setupInitialConfig(){const e=this.prefsController.storeType;if(!e||"local"===e)return void this.logger?.info("The notifications service will use the local storage for the notifications configuration");let t;try{t=await this.glueController.clientGlue.prefs.get(systemPrefsAppName)}catch(e){return void this.logger?.warn(`Failed to get the system preferences for the notifications service: ${e}, falling back to local storage`)}const r=t?.data[notificationsPrefsKey];if(!r)return void this.logger?.info("The system preferences for the notifications service are not set in prefs, falling back to local storage");const n=prefsNotificationsDecoder.run(r);if(!n.ok)return void this.logger?.error(`The system preferences from Prefs for the notifications service did not pass validation: ${JSON.stringify(n.error)}, falling back to local storage`);const i=n.result.config;this.localStorage.updateNotificationsConfig(i)}ready(){return Promise.resolve()}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this notifications control message, because the controller has not been started");const t=e.data,r=e.commandId,n=e.callerId,i=notificationsOperationDecoder.run(e.operation);if(!i.ok)return ioError.raiseError(`This notifications request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(i.error)}`);const o=i.result,s=this.operations[o].dataDecoder?.run(t);if(s&&!s.ok)return ioError.raiseError(`Notifications request for ${o} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(s.error)}`);this.logger?.debug(`[${r}] ${o} command is valid with data: ${JSON.stringify(t)}`);const a=await this.operations[o].execute(t,r,n),c=this.operations[o].resultDecoder?.run(a);return c&&!c.ok?ioError.raiseError(`Notifications request for ${o} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(c.error)}`):(this.logger?.trace(`[${r}] ${o} command was executed successfully`),a)}async handleConfigure({configuration:e},t,r=""){if(this.logger?.trace(`[${t}] handling a notification configure message with data: ${JSON.stringify(e)}`),this.validateServiceAccess(r,!0),this.localStorage.updateNotificationsConfig(e),this.glueController.pushSystemMessage("notifications","configurationChanged",{configuration:this.config}),"local"!==this.prefsController.storeType){const e={config:this.config};this.glueController.clientGlue.prefs.update({[notificationsPrefsKey]:e},{app:systemPrefsAppName}).catch(e=>{this.logger?.warn(`Failed to update the notifications configuration in prefs: ${e} - the settings are only updated in the local storage`)})}this.logger?.trace(`[${t}] handling a notification configure message completed`)}async handleGetActiveCount(e,t){return this.logger?.trace(`[${t}] handling a get active count message`),{count:this.currentActiveCount}}async handleGetConfiguration(e,t){this.logger?.trace(`[${t}] handling a get notification configure message`);const r={...this.config};return this.logger?.trace(`[${t}] handling a get notification configure message completed`),{configuration:r}}async handleList(e,t){this.logger?.trace(`[${t}] handling a list notification message`);const r=this.session.getAllNotifications();return this.logger?.trace(`[${t}] list notification message completed`),{notifications:r}}async handleSetState({id:e,state:t},r){this.logger?.trace(`[${r}] handling a set state notification message with data: ${JSON.stringify({id:e,state:t})}`);const n=this.session.getNotification(e);if(!n)return ioError.raiseError(`Cannot set state of a notification: ${e}, because it doesn't exist`);const i=this.currentActiveCount;n.state=t,this.session.updateNotification(n),this.glueController.pushSystemMessage("notifications","stateChange",{id:e,state:t}),this.syncActiveCount(i)}async handleClick(e,t){this.logger?.trace(`[${t}] handling a click notification message with data: ${JSON.stringify(e)}`);const r=this.session.getNotification(e.id);return r?e.action&&r.actions?.every(t=>t.action!==e.action)?ioError.raiseError(`Cannot click action ${e.action} of ${e.id}, because that notification does not have that action`):(this.handleNotificationClick({notification:r,action:e.action}),void this.logger?.trace(`[${t}] handling a click notification message completed`)):ioError.raiseError(`Cannot click a notification: ${e.id}, because it doesn't exist`)}async handleClear(e,t){this.logger?.trace(`[${t}] handling a clear notification message with data: ${JSON.stringify(e)}`);const r=this.currentActiveCount;this.removeNotification(e.id),this.syncActiveCount(r),this.logger?.trace(`[${t}] handling a clear notification message completed`)}async handleClearAll(e,t){this.logger?.trace(`[${t}] handling a clearAll notifications message`);const r=this.session.getAllNotifications(),n=r.reduce((e,t)=>"Active"===t.state?e+1:e,0);r.forEach(e=>this.removeNotification(e.id)),this.syncActiveCount(n),this.logger?.trace(`[${t}] handling a clearAll notification message completed`)}async handleClearOld(e,t){this.logger?.trace(`[${t}] handling a clearOld notifications message`);const r=this.session.getAllNotifications(),n=r.reduce((e,t)=>"Active"===t.state?e+1:e,0);r.filter(e=>"Active"!==e.state).forEach(e=>this.removeNotification(e.id)),this.syncActiveCount(n),this.logger?.trace(`[${t}] handling a clearOld notification message completed`)}async handleRaiseNotification({settings:e,id:t},r,n=""){if(this.logger?.trace(`[${r}] handling a raise notification message with a title: ${e.title}`),!this.config.enable)return ioError.raiseError("Cannot raise a notification, because the notifications service is disabled");this.validateServiceAccess(n);const i=this.currentActiveCount;setNotificationDefaults(e),this.processNewNotification(e,t);const o=this.config.enableToasts?!!e.showToast:this.config.enableToasts;await this.showToast({settings:e,id:t},o,r);const s={definition:Object.assign({},e,{title:void 0,clickInterop:void 0,actions:void 0}),id:t};return setTimeout(()=>this.glueController.pushSystemMessage("notifications","notificationShow",s),0),this.logger?.trace(`[${r}] notification with a title: ${e.title} was successfully raised`),this.syncActiveCount(i),{settings:e}}async showToast({settings:e,id:t},r,n){if(!r)return;if(this.isInExtension)return void await this.raiseExtensionToast(e,t,n);e.actions&&e.actions.length?await this.raiseActionsToast(e,t,n):this.raiseSimpleToast(e,t,n)}async handleGetPermission(e,t){this.logger?.trace(`[${t}] handling a get permission message`);const r=Notification.permission;return this.logger?.trace(`[${t}] permission for raising notifications is: ${r}`),{permission:r}}async handleRequestPermission(e,t){this.logger?.trace(`[${t}] handling a request permission message`);let r=Notification.permission;"granted"!==r&&(r=await Notification.requestPermission());const n="granted"===r;return this.logger?.trace(`[${t}] permission for raising notifications is: ${r}`),{permissionGranted:n}}validateServiceAccess(e,t){const r=this.glueController.getAppNameByInstanceId(e)||"";if(t&&e===this.glueController.me.instance)return;if(this.config.sourceFilter.blocked.includes(r))return ioError.raiseError(`Cannot complete the notifications operation, because the caller app: ${r} is blocked from the notifications service`);const n=this.config.sourceFilter.allowed.includes("*"),i=this.config.sourceFilter.allowed.includes(r);return n||i?void 0:ioError.raiseError(`Cannot complete the notifications operation, because the caller app: ${r} is not present in the allowed list of the notifications service`)}async raiseSimpleToast(e,t,r){this.logger?.trace(`[${r}] notification with a title: ${e.title} was found to be non-persistent and therefore will be raised with the native notifications API`);const n=Object.assign({},e,{title:void 0,clickInterop:void 0}),i=new Notification(e.title,n);i.onclick=()=>{e.focusPlatformOnDefaultClick&&window.focus();const r=this.session.getNotification(t);r&&this.handleNotificationClick({action:"",notification:r})},i.onclose=()=>{const e=this.currentActiveCount;this.removeNotification(t),this.syncActiveCount(e)}}async raiseActionsToast(e,t,r){this.logger?.trace(`[${r}] notification with a title: ${e.title} was found to be persistent and therefore the service worker will be instructed to raise it.`),await this.serviceWorkerController.showNotification(e,t)}raiseExtensionToast(e,t,r){return new Promise((n,i)=>{if(this.logger?.trace(`[${r}] notification with a title: ${e.title} will be raised with the native extension notifications API, because the platform is running in extension mode`),!this.extNotificationConfig)return i("Cannot raise a notification, because the environment settings for the extension mode are missing.");const o=e.actions?e.actions.map(e=>({title:e.title,iconUrl:e.icon})):void 0,s={type:"basic",iconUrl:e.icon||this.extNotificationConfig.defaultIcon,title:e.title,message:e.body||this.extNotificationConfig.defaultMessage,silent:e.silent,requireInteraction:e.requireInteraction,imageUrl:e.image,buttons:o};chrome.notifications.create(t,s,()=>n())})}async setupExtensionNotifications(){this.isInExtension=!0,this.extNotificationConfig=(await this.getExtNotificationsConfig()).notifications,this.listenForExtensionNotificationsEvents()}listenForExtensionNotificationsEvents(){this._chromeClickedHandler=this.chromeClickedHandler.bind(this),chrome.notifications.onClicked.addListener(this._chromeClickedHandler),this._chromeButtonClickedHandler=this.chromeButtonClickedHandler.bind(this),chrome.notifications.onButtonClicked.addListener(this._chromeButtonClickedHandler),this._chromeClosedHandler=this.chromeClosedHandler.bind(this),chrome.notifications.onClosed.addListener(this._chromeClosedHandler)}removeExtensionNotificationsListeners(){chrome.notifications.onClicked.removeListener(this._chromeClickedHandler),chrome.notifications.onButtonClicked.removeListener(this._chromeButtonClickedHandler),chrome.notifications.onClosed.removeListener(this._chromeClosedHandler)}chromeClickedHandler(e){const t=this.session.getNotification(e);t&&this.handleNotificationClick({notification:t})}chromeButtonClickedHandler(e,t){const r=this.session.getNotification(e);if(!r)return;if(!r.actions)return;const n=r.actions[t].action;this.handleNotificationClick({action:n,notification:r})}chromeClosedHandler(e){const t=this.currentActiveCount;this.removeNotification(e),this.syncActiveCount(t)}listenForServiceWorkerNotificationEvents(){const e=this.serviceWorkerController.onNotificationClick(e=>{const t=this.session.getNotification(e.glueData.id);t&&this.handleNotificationClick({action:e.action,notification:t})}),t=this.serviceWorkerController.onNotificationClose(e=>{const t=this.currentActiveCount;this.removeNotification(e.glueData.id),this.syncActiveCount(t)});this.systemUnsubFuncs.push(e),this.systemUnsubFuncs.push(t)}getExtNotificationsConfig(){return new Promise(e=>{chrome.storage.local.get("notifications",t=>{e(t)})})}handleNotificationClick(e){!e.action&&e.notification.clickInterop&&this.callDefinedInterop(e.notification.clickInterop);const t=e.action?e.notification.actions?.find(t=>t.action===e.action):null;t&&t.interop&&this.callDefinedInterop(t.interop),e.notification.data?.glueData&&delete e.notification.data.glueData;const r={definition:e.notification,action:e.action,id:e.notification.id};if(this.clearNotificationOnClick){const t=this.currentActiveCount;this.removeNotification(e.notification.id),this.syncActiveCount(t)}this.glueController.pushSystemMessage("notifications","notificationClick",r)}callDefinedInterop(e){const t=e.method,r=e.arguments,n=e.target;this.glueController.invokeMethod(t,r,n).catch(e=>{const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(`The interop invocation defined in the clickInterop was rejected, reason: ${t}`)})}processNewNotification(e,t){const r={id:t,...e};this.session.saveNewNotification(r),this.glueController.pushSystemMessage("notifications","notificationRaised",{notification:r})}removeNotification(e){this.session.removeNotification(e),this.glueController.pushSystemMessage("notifications","notificationClosed",{id:e})}syncActiveCount(e){const t=this.currentActiveCount;e!==t&&this.glueController.pushSystemMessage("notifications","activeCountChange",{count:t})}}const extensionOperationTypesDecoder=oneOf$1(constant$2("clientHello"),constant$2("operationCheck")),clientHelloResponseDecoder=object$3({widget:object$3({inject:boolean$4()})}),clientHelloDecoder=object$3({windowId:optional$3(nonEmptyStringDecoder$2)});class ExtensionController{session;started=!1;operations={clientHello:{name:"appHello",resultDecoder:clientHelloResponseDecoder,dataDecoder:clientHelloDecoder,execute:this.handleClientHello.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e){this.session=e}get logger(){return logger.get("extension.controller")}handlePlatformShutdown(){this.started=!1}async start(){this.started=!0,this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this extension control message, because the controller has not been started");const t=e.data,r=e.commandId,n=extensionOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This extension request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Extension request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Extension request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleClientHello(e,t){this.logger?.trace(`[${t}] handling client hello command`);const r=(await this.getWidgetConfig()).widget,n={widget:{inject:!(!!e.windowId&&!!this.session.getFrameData(e.windowId))&&(!!r&&r.enable)}};return this.logger?.trace(`[${t}] responding to client hello command with: ${JSON.stringify(n)}`),n}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}getWidgetConfig(){return new URL(window.location.href).protocol.includes("extension")?new Promise(e=>{chrome.storage.local.get("widget",t=>{e(t)})}):Promise.resolve({widget:{enable:!1}})}}class AsyncSequelizer{minSequenceInterval;queue=[];isExecutingQueue=!1;constructor(e=0){this.minSequenceInterval=e}enqueue(e){return new Promise((t,r)=>{this.queue.push({action:e,resolve:t,reject:r}),this.executeQueue()})}async executeQueue(){if(!this.isExecutingQueue){for(this.isExecutingQueue=!0;this.queue.length;){const e=this.queue.shift();if(!e)return void(this.isExecutingQueue=!1);try{const t=await e.action();e.resolve(t)}catch(t){e.reject(t)}await this.intervalBreak()}this.isExecutingQueue=!1}}intervalBreak(){return new Promise(e=>setTimeout(e,this.minSequenceInterval))}}class PreferredConnectionController{glueController;portsBridge;sequelizer;registry=CallbackRegistryFactory$2();unsub;discoveryInterval;shouldForceTransfer;preferredUrl;preferredAuth;stopped=!1;constructor(e,t,r){this.glueController=e,this.portsBridge=t,this.sequelizer=r}get logger(){return logger.get("preferred.connection.controller")}shutdown(){this.stopped=!0,this.registry.clear()}async start(e){this.logger?.trace(`Starting the preferred connection with config: ${JSON.stringify(e)}`),this.stopped=!1,this.portsBridge.setPreferredActivated(),e.preferred&&(this.preferredUrl=e.preferred.url,this.preferredAuth=Object.assign({},{provider:"core"},e.preferred.auth),this.shouldForceTransfer="boolean"==typeof e.preferred.forceIncompleteSwitch&&e.preferred.forceIncompleteSwitch,this.discoveryInterval="number"==typeof e.preferred.discoveryIntervalMS?e.preferred.discoveryIntervalMS:defaultPreferredDiscoveryIntervalMS,this.logger?.trace("Starting the initial preferred connection check"),await this.connectPreferred(),this.logger?.trace("The preferred connection controller initiated."))}onReconnect(e){return this.registry.add("system-reconnect",e)}async connectPreferred(e,t,r){if(this.stopped&&!e)return;const n=await this.checkPreFlight(t);if(!n.ready&&e)return ioError.raiseError("The provided preferred connection is not ready.");if(!n.ready)return this.logger?.trace("The preflight is not ready, restarting the preferred tracking."),void wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r));const i={type:"secondary",transportConfig:Object.assign({url:t||this.preferredUrl},{auth:r||this.preferredAuth})};if(this.logger?.trace("Switching the system glue."),this.stopped)return;if(!(await this.glueController.switchTransport(i,"system")).success)return this.logger?.trace("The switch attempt was not successful, revered to default."),void wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r));this.portsBridge.setActivePreferredTransportConfig(i),this.logger?.trace("The switch to the preferred connection was successful, transferring all children.");try{await this.changeClientsConnection(i)}catch(n){return this.logger?.warn(`Some platform clients could not connect to the preferred connection, reverting all to the default connection. Reason: ${JSON.stringify(n)}`),void this.fullDefaultRevert().then(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r))).catch(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred(e,t,r)))}this.logger?.trace("The platform is now fully connected to the preferred connection, hooking up disconnection logic."),this.registry.execute("system-reconnect");const o=this.glueController.onDisconnected(()=>this.handleDisconnected(o,e));this.unsub=o}async revertToDefault(){this.unsub&&(this.unsub(),delete this.unsub),await this.fullDefaultRevert()}async fullDefaultRevert(){await this.glueController.switchTransport({type:"default"},"system"),this.portsBridge.setActivePreferredTransportConfig({type:"default"}),await this.changeClientsConnection({type:"default"})}handleDisconnected(e,t){this.logger?.trace("The platform has been disconnected from the preferred transport, reverting all to the default one."),e(),this.fullDefaultRevert().then(()=>{this.registry.execute("system-reconnect"),this.logger?.trace("The platform reversion to default completed, restarting the preferred tracking."),t||wait(this.discoveryInterval).then(()=>this.connectPreferred())}).catch(()=>wait(this.discoveryInterval).then(()=>this.connectPreferred()))}changeClientsConnection(e){return this.sequelizer.enqueue(async()=>{try{await Promise.all([this.glueController.switchTransport(e,"client"),this.portsBridge.switchAllClientsTransport(e)])}catch(e){if(this.logger?.trace(`Some clients could not connect to the preferred transport with error: ${JSON.stringify(e)}`),!this.shouldForceTransfer)return this.logger?.trace("The platform is not forcing a transfer in cases of errors, re-throwing."),ioError.raiseError(e);this.logger?.trace("The platform is forcing a transfer regardless of the errors.")}await this.glueController.switchTransport(e,"contextsTrack")})}checkPreferredConnection(e){return new Promise(t=>{const r=new WebSocket(e);r.onerror=()=>t({live:!1}),r.onopen=()=>{r.close(),t({live:!0})}})}async checkPreFlight(e){this.logger?.trace("Starting the preflight check");if(!(await this.checkPreferredConnection(e||this.preferredUrl)).live)return this.logger?.trace("The preferred connection is not live."),{ready:!1};this.logger?.trace(`Found a live preferred connection at: ${e||this.preferredUrl}, testing the availability of transport switching logic in all current clients`);const t=await this.portsBridge.checkClientsPreferredLogic();if(this.logger?.trace(`The logic check returned: ${JSON.stringify(t)}`),!t.success&&!this.shouldForceTransfer)return this.logger?.trace("The preflight check is marked as not ready"),{ready:!1};this.logger?.trace("Checking the possibility of all clients to connect to the preferred connection");const r=await this.portsBridge.checkClientsPreferredConnection(e||this.preferredUrl);return this.logger?.trace(`The connection check returned: ${JSON.stringify(r)}`),r.success||this.shouldForceTransfer?(this.logger?.trace("The preflight check is marked as ready"),{ready:!0}):(this.logger?.trace("The preflight check is marked as not ready"),{ready:!1})}}class TransactionsController{transactionLocks={};get logger(){return logger.get("transactions.controller")}completeTransaction(e,t){if("string"!=typeof e)return ioError.raiseError(`Cannot complete the transaction, because the provided id is not a string: ${JSON.stringify(e)}`);const r=this.transactionLocks[e];r?r.lift(t):this.logger?.warn(`Cannot mark a transaction as complete, because there is not lock with id ${e}`)}failTransaction(e,t){const r=this.transactionLocks[e];r?r.fail(t):this.logger?.warn(`Cannot mark a transaction as failed, because there is not lock with id ${e}`)}createTransaction(e,t){const r={},n=nanoid$5(10),i=new Promise((i,o)=>{let s=!0;r.lift=e=>{s=!1,delete this.transactionLocks[n],i(e)},r.fail=e=>{s=!1,delete this.transactionLocks[n],o(e)},setTimeout(()=>{s&&(s=!1,this.logger?.warn(`Transaction for operation: ${e} timed out.`),delete this.transactionLocks[n],o(`Transaction for operation: ${e} timed out.`))},t)});return r.lock=i,r.id=n,this.transactionLocks[n]=r,r}}class InterceptionController{interceptions=[];shutdown(){this.interceptions=[]}async registerInterceptor(e,t){runDecoderWithIOError(interceptorRegistrationRequestDecoder,e),runDecoderWithIOError(nonEmptyStringDecoder$2,t);const r=e.interceptions.reduce((e,t)=>(this.interceptions.some(e=>e.domain===t.domain&&e.operation===t.operation)&&e.push({domain:t.domain,operation:t.operation}),e),[]);if(r.length){const e=r.map(e=>`${e.domain} - ${e.operation}`).join(", ");return ioError.raiseError(`Interception registration is rejected, because the following collisions where found: ${e}`)}e.interceptions.forEach(r=>{this.interceptions.push({domain:r.domain,operation:r.operation,callInterceptor:e.callInterceptor,registrantName:t})})}getOperationInterceptor(e){const t=this.interceptions.find(t=>t.domain===e.domain&&t.operation===e.operation);if(t)return{name:t.registrantName,intercept:t.callInterceptor}}}class PluginsController{interceptionController;glueController;handlePluginMessage;platformApi;allPlugins;registeredPlugins=[];constructor(e,t){this.interceptionController=e,this.glueController=t}get logger(){return logger.get("plugins.controller")}async shutdown(){this.logger?.debug(`starting plugins shutdown for all plugins: [${this.allPlugins.map(e=>e.name).join(", ")}]`),this.allPlugins.forEach(e=>{if(e.stop)try{e.stop()}catch(t){this.logger?.warn(`Plugin: ${e.name} threw while onPlatformShutdown -> ${extractErrorMsg$1(t)}`)}}),this.allPlugins=[],this.registeredPlugins=[],this.logger?.debug("plugins shutdown completed")}async start(e){if(this.logger?.debug(`initializing plugins with ${JSON.stringify((e.plugins??[]).map(e=>e.name))} plugins`),!e.plugins)return;if(this.allPlugins=e.plugins,this.handlePluginMessage=e.handlePluginMessage,this.platformApi=e.api,!e.plugins||!e.plugins.length)return;const t=[],r=[];for(const n of e.plugins){const e=this.startPlugin(n);n.critical&&(t.push(e),r.push(n.name))}this.logger?.debug(`waiting for ${t.length} critical plugins to start: [${r.join(", ")}]`),await Promise.all(t),this.logger?.debug(`all critical plugins started successfully [${r.join(", ")}]`)}async startPlugin(e){this.logger?.debug(`starting plugin with definition: ${JSON.stringify(e)}`);try{const t=this.buildPlatformControls(e.name,this.platformApi);this.validatePlugin(e.name),await e.start(this.glueController.clientGlue,e.config,t),this.registerPlugin(e.name,e.version??"N/A"),this.logger?.debug(`plugin '${e.name}' started successfully`)}catch(t){this.logger?.error(`plugin '${e.name}' failed to start with error: ${extractErrorMsg$1(t)}`);const r="string"==typeof t?t:JSON.stringify(t.message),n=`Plugin: ${e.name} threw while initiating: ${r}`;if(e.critical)return ioError.raiseError(n);this.logger?.warn(n)}}buildPlatformControls(e,t){return{control:t=>this.handlePluginMessage(t,e),logger:logger.get(e),platformApi:t,interception:{register:t=>this.interceptionController.registerInterceptor(t,e)},system:{sendControl:t=>this.handlePluginMessage(t,e)}}}validatePlugin(e){if(this.registeredPlugins.some(t=>t.name===e))throw new Error(`Plugin: ${e} is already registered`)}registerPlugin(e,t){this.registeredPlugins.push({name:e,version:t})}}class DomainsController{systemController;windowsController;applicationsController;layoutsController;workspacesController;intentsController;channelsController;notificationsController;extensionController;searchController;themesController;managerController;prefsController;otelController;uiController;defaultDomainNames=["system","windows","appManager","layouts","workspaces","intents","channels","notifications","extension","search","themes","prefs","otel","ui"];domains;constructor(e,t,r,n,i,o,s,a,c,l,u,d,h,p,g){this.systemController=e,this.windowsController=t,this.applicationsController=r,this.layoutsController=n,this.workspacesController=i,this.intentsController=o,this.channelsController=s,this.notificationsController=a,this.extensionController=c,this.searchController=l,this.themesController=u,this.managerController=d,this.prefsController=h,this.otelController=p,this.uiController=g,this.setDomains()}setDomains(){this.domains={system:{name:"system",libController:this.systemController},windows:{name:"windows",libController:this.windowsController},appManager:{name:"appManager",libController:this.applicationsController},layouts:{name:"layouts",libController:this.layoutsController},workspaces:{name:"workspaces",libController:this.workspacesController},intents:{name:"intents",libController:this.intentsController},channels:{name:"channels",libController:this.channelsController},notifications:{name:"notifications",libController:this.notificationsController},extension:{name:"extension",libController:this.extensionController},search:{name:"search",libController:this.searchController},themes:{name:"themes",libController:this.themesController},manager:{name:"manager",libController:this.managerController},prefs:{name:"prefs",libController:this.prefsController},otel:{name:"otel",libController:this.otelController},ui:{name:"ui",libController:this.uiController}}}get logger(){return logger.get("domains.controller")}shutdown(){Object.values(this.domains).forEach(e=>e.libController.handlePlatformShutdown?e.libController.handlePlatformShutdown():null),this.domains={system:{name:"system",libController:this.systemController},windows:{name:"windows",libController:this.windowsController},appManager:{name:"appManager",libController:this.applicationsController},layouts:{name:"layouts",libController:this.layoutsController},workspaces:{name:"workspaces",libController:this.workspacesController},intents:{name:"intents",libController:this.intentsController},channels:{name:"channels",libController:this.channelsController},notifications:{name:"notifications",libController:this.notificationsController},extension:{name:"extension",libController:this.extensionController},search:{name:"search",libController:this.searchController},themes:{name:"themes",libController:this.themesController},prefs:{name:"prefs",libController:this.prefsController},otel:{name:"otel",libController:this.otelController},ui:{name:"ui",libController:this.uiController}}}setProfileData(e){this.systemController.setProfileData(e)}async setNotificationsData(){await this.notificationsController.setupInitialConfig()}validateDomain(e){const t=this.domains[e];if(!t)return ioError.raiseError(`Accessing a missing domain: ${e}.`);const r=t.domainNameDecoder?t.domainNameDecoder:libDomainDecoder;runDecoderWithIOError(r,e)}async startAllDomains(e){this.logger?.trace("Starting all domains lib controllers"),await Promise.all(Object.values(this.domains).map(t=>t.libController.start(e))),this.logger?.trace("All domains have been initialized")}async configurePostStartAllDomains(){this.logger?.trace("Starting all domains lib controllers"),await Promise.all(Object.values(this.domains).filter(e=>!!e.libController.configurePostStart).map(e=>e.libController.configurePostStart&&e.libController.configurePostStart())),this.logger?.trace("All domains have been initialized")}notifyDomainsClientUnloaded(e){this.logger?.trace(`detected unloading of client: ${e.windowId}, notifying all controllers`),Object.values(this.domains).forEach(t=>{try{t.libController.handleClientUnloaded?.(e.windowId,e.win)}catch(r){const n="string"==typeof r?r:JSON.stringify(r.message),i=t.name;this.logger?.error(`${i} controller threw when handling unloaded client ${e.windowId} with error message: ${n}`)}})}executeControlMessage(e){const t=this.domains[e.domain];return t?t.libController.handleControl(e):ioError.raiseError(`Cannot process message for domain: ${e.domain} and operation ${e.operation}, because no domain can service it.`)}registerDynamicDomain(e){return Object.values(this.domains).map(e=>e.name).some(t=>t===e.name)?ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it is already registered`):e.libController&&e.libController.start&&e.libController.handleControl&&e.libController.handleClientUnloaded?e.domainNameDecoder?void(this.domains[e.name]=e):ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it does not have a domain decoder`):ioError.raiseError(`Cannot register a domain with name: ${e.name}, because it does not have a valid libController`)}unregisterDynamicDomain(e){if(this.defaultDomainNames.some(t=>t===e))return ioError.raiseError(`Cannot unregister a domain: ${e}, because it is a reserved default domain`);delete this.domains[e]}async domainsReady(){this.logger?.trace("Verifying all domains lib controllers ready"),await Promise.all(Object.values(this.domains).map(e=>e.libController.ready())),this.logger?.trace("All domains have signaled ready")}}class LegacyResolverController{glueController;workspacesController;windowsController;prefsController;intentsResolverResponsePromises={};constructor(e,t,r,n){this.glueController=e,this.workspacesController=t,this.windowsController=r,this.prefsController=n}get logger(){return logger.get("intents.resolver.controller")}async startResolverApp({request:e,resolverConfig:t,commandId:r,callerId:n,resolverInstance:i,method:o}){this.logger?.trace(`[${r}] Intents Resolver UI with app name ${t.appName} will be used for request: ${JSON.stringify(e)}`);const s=await this.registerResponseMethod();this.logger?.trace(`[${r}] Registered interop method ${s}`);const a=this.buildStartContext(o,e,s,n),c=await this.buildStartOptions(n,r);this.logger?.trace(`[${r}] Starting Intents Resolver UI with context: ${JSON.stringify(a)} and options: ${c}`);const l=this.glueController.clientGlue.appManager.application(t.appName).start(a,c).catch(e=>ioError.raiseError(`${ERRORS.RESOLVER_UNAVAILABLE}. Reason: ${e instanceof Error||"string"==typeof e?e:JSON.stringify(e)}`)),u=await l;i.instanceId=u.id,this.logger?.trace(`[${r}] Intents Resolver instance with id ${u.id} opened`),this.subscribeOnInstanceStopped(u,o);const d="raise"===o?`for intent request ${JSON.stringify(e)}`:`for '${o}' method with filter ${JSON.stringify(e)}`,h=`${ERRORS.RESOLVER_TIMEOUT} - waited ${t.waitResponseTimeout}ms for the user the choose a handler ${d}`;this.createResponsePromise({intent:"raise"===o?e.intent:void 0,instanceId:u.id,responseMethodName:s,timeout:t.waitResponseTimeout,errorMsg:h});try{return await this.handleInstanceResponse({request:e,instanceId:u.id,method:o,commandId:r,caller:a.initialCaller})}catch(e){return this.stopResolverInstance(i.instanceId),ioError.raiseError(e)}}stopResolverInstance(e){const t=this.glueController.clientGlue.appManager.instances().find(t=>t.id===e);t&&t.stop().catch(e=>this.logger?.warn(e))}async handleInstanceResponse({method:e,caller:t,commandId:r,instanceId:n,request:i}){const o=await this.intentsResolverResponsePromises[n].promise,s="raise"===e?`for intent ${o.intent} `:"";if(this.logger?.trace(`[${r}] Intent handler chosen ${s}: ${JSON.stringify(o.handler)}. Stopping resolver instance with id ${n}`),this.stopResolverInstance(n),this.logger?.trace(`[${r}] Instance with id ${n} successfully stopped`),!o?.userSettings?.preserveChoice)return o.handler;try{await this.saveUserChoice({intent:o.intent,handler:o.handler,filter:"filterHandlers"===e?{applicationNames:i.applicationNames,contextTypes:i.contextTypes,resultType:i.resultType}:void 0,caller:t},r)}catch(e){this.logger?.warn(`[${r}] - Prefs API threw the following error: ${e}`)}return o.handler}async registerResponseMethod(){const e=INTENTS_RESOLVER_INTEROP_PREFIX+nanoid$5(10);return await this.glueController.clientGlue.interop.register(e,(e,t)=>this.responseHandler(e,t)),e}createResponsePromise({instanceId:e,intent:t,responseMethodName:r,timeout:n,errorMsg:i}){let o=()=>{},s=()=>{};const a=PromisePlus((e,t)=>{o=e,s=t},n,i);this.intentsResolverResponsePromises[e]={intent:t,resolve:o,reject:s,promise:a,methodName:r}}buildStartContext(e,t,r,n){const i={callerId:this.glueController.clientGlue.interop.instance.instance,methodName:r,resolverApi:"1.0"},o=this.glueController.getLocalServers().find(e=>e.instance===n);if(!o)throw new Error(`Cannot find window with id: ${n} - the client which sent the "raise" command is no longer opened`);const s=o.application??o.applicationName,a={applicationName:s,applicationTitle:s?this.glueController.clientGlue.appManager.application(s)?.title:"",id:n};return"raise"===e?{...i,initialCaller:a,intent:t}:{...i,initialCaller:a,handlerFilter:t}}async buildStartOptions(e,t){const r=await this.getTargetBounds(e,t);return r?{top:(r.height-INTENTS_RESOLVER_HEIGHT)/2+r.top,left:(r.width-INTENTS_RESOLVER_WIDTH)/2+r.left,width:INTENTS_RESOLVER_WIDTH,height:INTENTS_RESOLVER_HEIGHT}:ioError.raiseError(`[${t}] Cannot find window with id: ${e} - the client which sent the "raise" command is no longer opened`)}async getTargetBounds(e,t){const r=await this.tryGetWindowBasedBounds(e,t)??await this.tryGetWorkspaceBasedBounds(e,t);if(r)return this.logger?.trace(`[${t}] Opening Intents Resolver UI with bounds: ${JSON.stringify(r)}`),r;const n={top:window.screen.availTop??0,left:window.screen.availLeft??0,width:window.screen.width,height:window.screen.height};return this.logger?.trace(`[${t}] Opening Intents Resolver UI relative to my screen bounds: ${JSON.stringify(n)}`),n}async tryGetWindowBasedBounds(e,t){const r=this.glueController.clientGlue.windows.findById(e),n=this.getServerInstanceByWindowId(e);if(!r&&!n)return ioError.raiseError(`Client with id "${e}" does not exist`);if(!r&&n)return this.getWindowBoundsByServerInstance(n,e,t);if(!r)return ioError.raiseError(`Client with id "${e}" does not exist`);try{const n=await r.getBounds();return this.logger?.trace(`[${t}] Opening the resolver UI with bounds: ${JSON.stringify(n)}, relative to a window with id: ${e}`),n}catch(r){return void this.logger?.trace(`[${t}] Failure to get bounds of a window with id ${e}. Error: ${JSON.stringify(r)}`)}}getServerInstanceByWindowId(e){return this.glueController.getLocalServers().find(t=>t.instance===e)}async getWindowBoundsByServerInstance(e,t,r){try{const{bounds:r}=await this.glueController.callWindow("windows",this.windowsController.getBoundsOperation,{windowId:t},{instance:e.instance});return r}catch(t){this.logger?.trace(`[${r}] Failure to get bounds of a window with instance ${e.instance}. Error: ${JSON.stringify(t)}`)}}async tryGetWorkspaceBasedBounds(e,t){try{const{bounds:r}=await this.workspacesController.getWorkspaceWindowFrameBounds({itemId:e},t);return this.logger?.trace(`[${t}] Opening the resolver UI relative to my workspace frame window bounds: ${JSON.stringify(r)}`),r}catch(e){this.logger?.trace(`[${t}] Failure to get my workspace frame window bounds. Error: ${JSON.stringify(e)}`)}}responseHandler(e,t){const r=resolverResponseDecoder.run(e),n=t.instance;return n?r.ok?(this.logger?.trace(`Intent Resolver instance with id ${n} send a valid response: ${JSON.stringify(r.result)}`),this.intentsResolverResponsePromises[n].resolve(e)):(this.logger?.trace(`Intent Resolver instance with id ${n} sent an invalid response. Error: ${JSON.stringify(r.error)}`),this.intentsResolverResponsePromises[n].reject(r.error.message),void this.stopResolverInstance(n)):ioError.raiseError("Cannot find instance id for the response of the intent resolver")}subscribeOnInstanceStopped(e,t){const{application:r}=e,n=r.onInstanceStopped(r=>{if(r.id!==e.id)return;const i=this.intentsResolverResponsePromises[r.id];if(!i)return n();const o="raise"===t?`raised intent ${i.intent}`:`'${t}' method`,s=`${ERRORS.USER_CANCELLED} for ${o}`;i.reject(s),this.cleanUpIntentResolverPromise(r.id),n()})}async cleanUpIntentResolverPromise(e){const t=this.intentsResolverResponsePromises[e];if(!t)return;this.glueController.clientGlue.interop.unregister(t.methodName).catch(e=>this.logger?.warn(e)),delete this.intentsResolverResponsePromises[e]}async saveUserChoice({intent:e,handler:t,filter:r,caller:n},i){const o="Platform"===n.applicationName?this.prefsController.platformAppName:n.applicationName;this.logger?.info(`[${i}] - Saving user's choice of handler for '${o}' app`);const s=await this.prefsController.get({app:o},i),a=s.prefs.data?.intents??{},c={...s.prefs.data,intents:{...a,[e]:{handler:t,filter:r}}};await this.prefsController.update({app:o,data:c},i)}}class LicenseController{verifyLicense(e){if(!e||"string"!=typeof e)return{valid:!1};const t=KEYUTIL_1.getKey(publicLicKey);return{valid:KJUR_1.jws.JWS.verifyJWT(e,t,{alg:["RS256"]})}}getLicensePayload(e){if(!e)return ioError.raiseError("No license key was provided");const t=KJUR_1.jws.JWS.readSafeJSONString(b64utoutf8_1(e.split(".")[1]));return t&&"string"==typeof t.type&&"number"==typeof t.expiration?(t.type=t.type.toLowerCase(),t):ioError.raiseError("The license key payload is invalid")}isPlatformOriginAllowed(e,t=[]){if(!t.length||t.includes("*"))return!0;if("localhost"===e.hostname)return!0;return t.some(t=>pm(t)(e.origin))}checkExpired(e){return!(!e||"number"!=typeof e)&&e<=Date.now()}}class Builder{glueController;sessionStore;windowsController;workspacesController;constructor(e,t,r,n){this.glueController=e,this.sessionStore=t,this.windowsController=r,this.workspacesController=n}get logger(){return logger.get("layouts.builder")}async saveGlobalLayout(e,t){const r=await this.getRawWindowsLayoutData({layoutType:"Global",layoutName:e.layout.name,context:e.layout.context,instances:e.layout.instances,ignoreInstances:e.layout.ignoreInstances,ignoreContexts:e.layout.ignoreContexts},t);this.logger?.trace(`[${t}] received valid data for the eligible windows`);const n=await this.glueController.getLayout(e.layout.name),i=n?await this.updateLayout(n,e.layout,r.windows,t):await this.buildNewLayout(e.layout,r.windows,t);return this.logger?.trace(`[${t}] the layout object was constructed, importing.`),await this.glueController.importLayout(i),this.logger?.trace(`[${t}] the import for layout: ${i.name} was completed, responding.`),i}async updateLayout(e,t,r,n){this.logger?.trace(`[${n}] updating an existing layout with name ${t.name}`),e.context=t.context??{},e.metadata=t.metadata??{},e.token=e.token??generateLayoutToken();const i=r.filter(e=>!!e.layoutComponentId).map(e=>e.layoutComponentId),o=this.getLayoutIdOccurrenceMap(i),s=r.map(t=>this.generateWindowComponent(e,t,o,n));this.logger?.trace(`[${n}] the window components are completed, we have ${s.length} windows for the layout`);const a={layoutName:t.name,layoutType:"Global",context:t.context,ignoreContexts:t.ignoreContexts},c=e.components.filter(e=>"workspaceFrame"===e.type),l=await this.compileWorkspacesFrameComponents(c,a,n);return this.logger?.trace(`[${n}] the workspaces frame components are completed, we have ${l.length} frames for the layout`),e.components=[],e.components.push(...s),e.components.push(...l),e}async buildNewLayout(e,t,r){this.logger?.trace(`[${r}] build a brand new layout with name ${e.name}`);const n={name:e.name,type:"Global",context:e.context??{},metadata:e.metadata??{},components:[],token:generateLayoutToken(),version:2},i=t.map(e=>this.buildNewWindowComponent(e,r));this.logger?.trace(`[${r}] the window components are completed, we have ${i.length} windows for the layout`);const o={layoutName:e.name,layoutType:"Global",context:e.context,ignoreContexts:e.ignoreContexts},s=await this.compileWorkspacesFrameComponents([],o,r);return this.logger?.trace(`[${r}] the workspaces frame components are completed, we have ${s.length} frames for the layout`),n.components.push(...i),n.components.push(...s),n}async getRawWindowsLayoutData(e,t){this.logger?.trace(`[${t}] handling send save requests for layout: ${e.layoutName} to instances: ${e.instances?.join(", ")}`);const r={windows:[...await Promise.all(this.getEligibleGlueWindows(e.instances,e.ignoreInstances).map(r=>this.buildRawGlueWindowData(r,e,t))),...await Promise.all(this.getEligibleNonGlueWindows(e.instances,e.ignoreInstances).map(t=>this.buildRawNonGlueWindowData(t,e)))]};return this.logger?.trace(`[${t}] request completed, responding to the caller`),r}async buildRawGlueWindowData(e,t,r){if(!e.initialUrl)return ioError.raiseError(`Missing URL for client: ${e.name}`);const n=await this.getClientWindowContextOnSaveRequest(t,e),i=this.sessionStore.getAllInstancesData().find(t=>t.id===e.windowId),o=await this.windowsController.getWindowBounds(e.windowId,r),s=await this.glueController.callWindow("channels",{name:"getMyChannel",execute:async()=>{}},{},{windowId:e.windowId});return{bounds:o,windowContext:n,url:e.initialUrl,name:e.name,application:i?i.applicationName:defaultNoAppWindowComponentAppName,initialContext:t.ignoreContexts?{}:e.initialContext,windowId:e.windowId,layoutComponentId:e.layoutComponentId,channelId:s.channel}}async getClientWindowContextOnSaveRequest(e,t){if(e.ignoreContexts)return{};const r=`Cannot fetch the layout save data from: ${t.name} with id: ${t.windowId}`;return(await PromiseWrap(async()=>{try{return await this.glueController.callWindow("layouts",{name:"clientSaveRequest",execute:async()=>{}},e,{windowId:t.windowId})}catch(e){return{}}},15e3,r)).windowContext??{}}async buildRawNonGlueWindowData(e,t){if(!e.initialUrl)return ioError.raiseError(`Missing URL for client: ${e.name}`);const r=this.sessionStore.getAllInstancesData().find(t=>t.id===e.windowId);return{bounds:e.initialBounds??defaultPlatformConfig.windows.defaultWindowOpenBounds,windowContext:{},url:e.initialUrl,name:e.name,application:r?r.applicationName:defaultNoAppWindowComponentAppName,initialContext:t.ignoreContexts?{}:e.initialContext,windowId:e.windowId,layoutComponentId:e.layoutComponentId}}getEligibleNonGlueWindows(e,t){const r=this.getAllEligibleWindows(e,t),n=this.sessionStore.getAllNonGlue(),i=this.sessionStore.pickWorkspaceClients(()=>!0);return r.filter(e=>n.some(t=>t.windowId===e.windowId)&&i.every(t=>t.windowId!==e.windowId))}getEligibleGlueWindows(e,t){const r=this.getAllEligibleWindows(e,t),n=this.sessionStore.getAllNonGlue(),i=this.sessionStore.pickWorkspaceClients(()=>!0);return r.filter(e=>i.every(t=>t.windowId!==e.windowId)&&n.every(t=>t.windowId!==e.windowId))}getAllEligibleWindows(e,t){let r=this.sessionStore.getAllWindowsData().filter(e=>"Platform"!==e.name);if(e&&e.length){const t=this.glueController.getLocalServers().filter(t=>e.some(e=>t.instance===e));r=r.filter(e=>t.some(t=>t.windowId===e.windowId))}if(t&&t.length){const e=this.glueController.getLocalServers().filter(e=>t.some(t=>e.instance===t));r=r.filter(t=>e.every(e=>e.windowId!==t.windowId))}return r}updateExistingWindowComponent(e,t,r){return this.logger?.trace(`[${r}] performing a soft update on am existing component ${e.application} with id ${e.state.instanceId}`),e.state.context=t.windowContext?t.windowContext:e.state.context,e.state.bounds=t.bounds,e.state.createArgs.context=t.initialContext?t.initialContext:e.state.createArgs?.context,e.state.instanceId=e.state.instanceId?e.state.instanceId:t.windowId,e.state.channelId=t.channelId,e}buildNewWindowComponent(e,t){return this.logger?.trace(`[${t}] building a brand new component ${e.application} with id ${e.windowId}`),{type:"window",componentType:"application",application:e.application,state:{context:e.windowContext??{},bounds:e.bounds,createArgs:{name:e.name,url:e.url,context:e.initialContext??{}},windowState:"Normal",restoreState:"Normal",restoreSettings:{groupId:"glue_42_core",groupZOrder:0},instanceId:e.windowId,isSticky:!0,isCollapsed:!1,channelId:e.channelId}}}async compileWorkspacesFrameComponents(e,t,r){this.logger?.trace(`[${r}] requesting information about all running workspaces frames`);const n=await this.getAllFramesSnapshotsWithBounds(t,r);this.logger?.trace(`[${r}] got information on ${n.length} frames, composing the frame components`);const i=n.filter(e=>!!e.config?.layoutComponentId).map(e=>e.config.layoutComponentId),o=this.getLayoutIdOccurrenceMap(i);return n.map(t=>this.generateFrameComponent(t,e,o,r))}getLayoutIdOccurrenceMap(e){const t={};return e.forEach(e=>{t[e]?t[e]=1+t[e]:t[e]=1}),t}softUpdateFrameComponent(e,t,r,n){return this.logger?.trace(`[${n}] performing a soft update on am existing frame component ${e.state.instanceId}`),e.state.bounds=t.bounds,e.state.selectedWorkspace=-1===r?0:r,e.state.workspaces=t.snapshot.workspaces,e.state.context=Object.assign({},e.state.context,{isPlatform:t.config.isPlatform}),e}createNewFrameComponent(e,t,r){return this.logger?.trace(`[${r}] building a new frame component ${e.snapshot.id}`),{type:"workspaceFrame",application:"workspaces-demo",componentType:"application",state:{context:{isPlatform:e.config.isPlatform},bounds:e.bounds,instanceId:e.snapshot.id,selectedWorkspace:-1===t?0:t,workspaces:e.snapshot.workspaces,restoreState:"Normal",windowState:"Normal"}}}generateWindowComponent(e,t,r,n){const i=e.components.find(e=>"window"===e.type&&e.state.instanceId===t.layoutComponentId),o=t.layoutComponentId?r[t.layoutComponentId]:0;return i&&o<2?this.updateExistingWindowComponent(i,t,n):this.buildNewWindowComponent(t,n)}generateFrameComponent(e,t,r,n){const i=e.snapshot.workspaces.findIndex(e=>e?.config?.isSelected),o=t.find(t=>t.state.instanceId===e.config.layoutComponentId),s=e.config.layoutComponentId?r[e.config.layoutComponentId]:0;return o&&s<2?this.softUpdateFrameComponent(o,e,i,n):this.createNewFrameComponent(e,i,n)}async getAllFramesSnapshotsWithBounds(e,t){const r=(await this.workspacesController.getAllFramesSummaries(void 0,t)).summaries||[];return await Promise.all(r.map(async r=>{const n=await this.workspacesController.handleGetWorkspacesLayouts({frameId:r.id,...e},t),i=await this.workspacesController.getFrameSessionData({frameId:r.id},t);return{bounds:(await this.workspacesController.getFrameBounds({itemId:r.id},t)).bounds,snapshot:{id:r.id,workspaces:n.workspaces,config:{}},config:{isPlatform:i?.isPlatform,layoutComponentId:i?.layoutComponentId}}}))}}class Restorer{glueController;validator;resetter;workspacesController;sessionStore;constructor(e,t,r,n,i){this.glueController=e,this.validator=t,this.resetter=r,this.workspacesController=n,this.sessionStore=i}get logger(){return logger.get("layouts.restorer")}async restoreGlobalLayout(e,t,r,n){const i=await this.glueController.getLayout(e.layout.name);if(!i)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because it was not found in this platform`);if("Global"!==i.type)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because it is not a Global Layout`);if(!r||!n)return ioError.raiseError(`Cannot restore layout: ${e.layout.name}, because the callerId or callerType are missing`);await this.validator.doInitialValidation(i,t),this.logger?.trace(`[${t}] the initial validation of the compliancy of the layout was completed`),await this.closeInstances(n,r,t,e.layout.closeMe,e.layout.closeRunningInstances),this.logger?.trace(`[${t}] closed all necessary running instances`),await this.restore(i,e,t);const o=this.sessionStore.getLayoutsSystemData();o.currentLayoutName=i.name,this.sessionStore.setLayoutsSystemData(o),this.logger?.trace(`[${t}] the layout ${i.name} was restored`)}async closeInstances(e,t,r,n,i){(void 0===i||i)&&await this.resetter.closeAllExceptCaller(t,r);(n||void 0===n&&void 0===i||void 0===n&&i)&&await this.resetter.closeCaller(e,t,r)}async restore(e,t,r){this.logger?.trace(`[${r}] starting the restore process of ${e.name}`);const n=await this.canPlatformFrameAcceptComponent(r)?this.pickComponentForPlatformFrame(e.components.filter(e=>"workspaceFrame"===e.type)):null,i=Promise.all(e.components.map(i=>{if("window"===i.type)return this.restoreWindowComponent(i,r,e.context,t.layout.context);if("workspaceFrame"===i.type){const o=n===i;return this.restoreWorkspaceFrameComponent(i,r,e.context,t.layout.context,o)}}));await i}async restoreWindowComponent(e,t,r,n){this.logger?.trace(`[${t}] restoring window component ${e.application} with id ${e.state.instanceId} and bounds: ${JSON.stringify(e.state.bounds)}`);const i=Object.assign({},r,e.state.context,e.state.createArgs.context,n),o=e.state.channelId,s=e.state.bounds,a=await this.checkTargetBoundsPossible(s);a.isPossible||this.logger?.warn(`Restoring ${e.application} not possible with the saved bounds, falling back to default bounds`);const c=a.isPossible?s:void 0;this.logger?.trace(`[${t}] calling the respective glue open/start method`);const l=e.application===defaultNoAppWindowComponentAppName?this.glueController.openWindow({name:e.state.createArgs.name,url:e.state.createArgs.url,layoutComponentId:e.state.instanceId,context:i,bounds:c}):this.glueController.startApp({name:e.application,layoutComponentId:e.state.instanceId,context:i,bounds:c});this.logger?.trace(`[${t}] the component was started`);const u=await l;o&&await this.glueController.callWindow("channels",{name:"joinChannel",execute:async()=>{}},{windowId:u.id,channel:o},{instance:u.id}).catch(console.error)}async restoreWorkspaceFrameComponent(e,t,r,n,i){this.logger?.trace(`[${t}] restoring workspace frame component $with id ${e.state.instanceId} and bounds: ${JSON.stringify(e.state.bounds)}`);const o=i?(await this.getPlatformFrame(t))?.id:void 0,s=await this.createFrameWithWorkspaceComponents(e,o);this.logger?.trace(`[${t}] the frame was restored, selecting the correct workspace`);const a=await s.workspaces();await(a[e.state.selectedWorkspace]?.focus()),this.logger?.trace(`[${t}] the correct workspace was selected, restoring the workspaces context`);const c=Object.assign({},r,n);await Promise.all(a.map(e=>e.updateContext(c))),this.logger?.trace(`[${t}] the frame component ${e.state.instanceId} is restored`)}async canPlatformFrameAcceptComponent(e){const t=await this.getPlatformFrame(e);if(!t)return!1;const r=await t.workspaces();return 1===r.length&&0===r[0].getAllWindows().length}pickComponentForPlatformFrame(e){if(0===e.length)return;return e.find(e=>e.state.context?.isPlatform)||e[0]}async checkTargetBoundsPossible(e){if(window.gtf)return{isPossible:!0};return(await window.getScreenDetails()).screens.find(t=>{const r=e.left>=t.left&&e.left<=t.left+t.width,n=e.top>=t.top&&e.top<=t.top+t.height;return r&&n})?{isPossible:!0}:{isPossible:!1}}async getPlatformFrame(e){if(!this.glueController.isWorkspacesEnabled)return;if(!await this.workspacesController.handleCheckStarted(void 0,e))return;const t=(await this.workspacesController.handleGetPlatformFrameId({},e)).id;return t?this.glueController.getOrCreateWorkspaceFrame({frameId:t}):void 0}async createFrameWithWorkspaceComponents(e,t){const r=await this.glueController.getOrCreateWorkspaceFrame({frameId:t,bounds:e.state.bounds,layoutComponentId:e.state.instanceId});return await this.glueController.invokeMethod(GlueWorkspaceFrameClientControlName,{operation:"initFrameFromSnapshot",operationArguments:{workspaces:e.state.workspaces,keepWorkspaces:[]}},{windowId:r.id}),r}}class LayoutValidator{glueController;workspacesController;constructor(e,t){this.glueController=e,this.workspacesController=t}async doInitialValidation(e,t){this.validateRequiredApplicationsExistence(e),await this.validateWorkspaceConfigurationInPlatform(e,t),this.validateNoAppNameAndUrl(e)}async doFinalValidation(e){this.validateWindowNamesCollision(e),this.validateInstanceIdCollision(e),await this.validateWorkspaceFramesIdCollisions(e)}validateWindowNamesCollision(e){const t=e.components.filter(e=>"window"===e.type&&e.application===defaultNoAppWindowComponentAppName&&!!e.state.createArgs.name).map(e=>e.state.createArgs.name),r=this.glueController.getAllWindowNames(),n=t.filter(e=>r.some(t=>e===t));if(n.length)return ioError.raiseError(`Cannot restore layout: ${e.name}, because there are window names collisions: ${n.join(", ")}`)}validateInstanceIdCollision(e){const t=e.components.filter(e=>"window"===e.type&&!!e.state.instanceId).map(e=>e.state.instanceId),r=this.glueController.getAllOpenedIds(),n=t.filter(e=>r.some(t=>e===t));if(n.length)return ioError.raiseError(`Cannot restore layout: ${e.name}, because there are instances ids collisions: ${n.join(", ")}`)}async validateWorkspaceFramesIdCollisions(e){if(e.components.every(e=>"workspaceFrame"!==e.type))return;const t=await this.glueController.getAllOpenedFrameIds(),r=e.components.filter(e=>"workspaceFrame"===e.type).map(e=>e.state.instanceId).filter(e=>t.some(t=>e===t));return r.length?ioError.raiseError(`Cannot restore layout: ${e.name}, because there are frame ids collisions: ${r.join(", ")}`):void 0}validateNoAppNameAndUrl(e){const t=e.components.filter(e=>"window"===e.type&&e.application===defaultNoAppWindowComponentAppName).filter(e=>!("window"!==e.type||e.state.createArgs.name&&e.state.createArgs.url));if(!t.length)return;const r=t.map(e=>JSON.stringify(e.state.createArgs)).join(", ");return ioError.raiseError(`Cannot restore layout: ${e.name}, because it has window components, which are not defined applications and are missing name or url, provided insufficient createArgs are: ${r}`)}validateRequiredApplicationsExistence(e){const t=this.glueController.getAllApplicationNames(),r=e.components.filter(e=>"window"===e.type&&e.application!==defaultNoAppWindowComponentAppName).map(e=>e.application);if(r.push(...this.getRequiredAppNamesFromWorkspaceFrameComponents(e)),!r.length)return;const n=r.filter(e=>t.every(t=>t!==e));return n.length?ioError.raiseError(`Cannot restore layout: ${e.name}, because some required applications are not registered with this platform: ${n.join(", ")}`):void 0}async validateWorkspaceConfigurationInPlatform(e,t){if(e.components.every(e=>"Workspace"!==e.type||"workspaceFrame"!==e.type))return;const r=(await this.workspacesController.handleCheckStarted({},t))?.started;return r?void 0:ioError.raiseError(`Cannot restore layout: ${e.name}, because this platform does not have a valid Workspaces configuration`)}getRequiredAppNamesFromWorkspaceFrameComponents(e){const t=[];for(const r of e.components)if("workspaceFrame"===r.type){const e=r.state.workspaces.reduce((e,t)=>(e.push(...this.getAllAppNamesFromChildren(t.children)),e),[]);t.push(...e)}return t}getAllAppNamesFromChildren(e){const t=e.filter(e=>"window"===e.type&&!!e.config.appName&&e.config.appName!==defaultNoAppWindowComponentAppName).map(e=>e.config.appName);for(const r of e)"window"!==r.type&&t.push(...this.getAllAppNamesFromChildren(r.children));return t}}class Resetter{glueController;workspacesController;constructor(e,t){this.glueController=e,this.workspacesController=t}get logger(){return logger.get("layouts.resetter")}async closeAllExceptCaller(e,t){const r=this.glueController.getAllOtherNonPlatformWindows(e);await Promise.all(r.map(async e=>{if(this.glueController.isWorkspacesEnabled){if(await this.glueController.getWorkspaceWindowById(e.id))return}return e.close()})),this.glueController.isWorkspacesEnabled&&await this.closeNecessaryWorkspacesFrames(e,t)}async closeCaller(e,t,r){if("plugin"===e)return;if(await this.glueController.getWorkspaceWindowById(t))return void await this.cleanupWorkspaceCaller(t,r);const n=this.glueController.getWindowById(t);n&&"Platform"!==n.name?await n.close():this.logger?.warn("The close caller was missing, is an iframe or is a platform")}async closeNecessaryWorkspacesFrames(e,t){const r=(await this.workspacesController.handleGetPlatformFrameId({},t)).id;let n=await this.glueController.getAllWorkspacesFrames();r&&(n=n.filter(e=>e.id!==r),await this.cleanUpFrameExceptCaller(r,e));const i=await this.glueController.getWorkspaceWindowById(e);i&&(n=n.filter(e=>e.id!==i.frameId),await this.cleanUpFrameExceptCaller(i.frameId,e)),await Promise.all(n.map(e=>e.close()))}async cleanUpFrameExceptCaller(e,t){const r=await this.glueController.getWorkspacesByFrameId(e),n=r.filter(e=>!e.getWindow(e=>e.id===t)),i=r.find(e=>e.getWindow(e=>e.id===t));await Promise.all(n.map(e=>e.close()));const o=i?i.getAllWindows(e=>e.id!==t):[];await Promise.all(o.map(e=>e.close()))}async cleanupWorkspaceCaller(e,t){const r=(await this.workspacesController.handleGetPlatformFrameId({},t)).id,n=await this.glueController.getWorkspaceWindowById(e);n&&(n.frameId!==r?await n.frame.close():await n.workspace.close())}}const searchOperationDecoder=oneOf$1(constant$2("operationCheck"));class SearchController{glueController;appsRepo;layoutsRepo;workspacesRepo;started=!1;repos=[];provider;activeQueries={};unsubFuncs=[];operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n){this.glueController=e,this.appsRepo=t,this.layoutsRepo=r,this.workspacesRepo=n}get logger(){return logger.get("notifications.controller")}get providerName(){return`io.Connect Browser Platform ${this.glueController.me.instance}`}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.repos=[],this.activeQueries={},this.provider?.unregister()}async configurePostStart(){if(this.repos.push(this.appsRepo),this.repos.push(this.layoutsRepo),!this.glueController.isWorkspacesEnabled)return;this.repos.push(this.workspacesRepo);const e=this.repos.map(e=>({name:e.type,displayName:e.displayType})),t={name:this.providerName,types:e};if(this.logger?.trace(`Registering the platform as a provider with name: ${t.name} and types: ${JSON.stringify(t.types?.join(", "))}.`),this.provider=await this.glueController.registerProvider(t),!this.provider)return ioError.raiseError("The platform was not registered successfully as a provider.");this.logger?.trace("The platform was registered successfully as a provider.");const r=this.provider.onQuery(e=>{this.processQuery(e).then(()=>this.markQueryDone(e)).catch(t=>this.markQueryError(e,t))}),n=this.provider.onQueryCancel(this.processQueryCancel.bind(this));this.unsubFuncs.push(r),this.unsubFuncs.push(n),this.started=!0,this.logger?.info("The module started successfully.")}async start(){this.logger?.info("Starting the Global Search provider.")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this search control message, because the controller has not been started");const t=e.data,r=e.commandId,n=searchOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This search request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Search request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Search request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async processQuery(e){this.logger?.info(`Processing a new query for: ${e.search}`),this.activeQueries[e.id]={allowedResultsCount:e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER};const t=e.types?this.repos.filter(t=>e.types?.some(e=>e.name===t.type)):this.repos;await Promise.all(t.map(t=>this.callRepo(t,e)))}async callRepo(e,t){const r=await this.getRepoResults(e,t);this.activeQueries[t.id]&&r&&this.sendResults(r,t)}async getRepoResults(e,t){try{return await e.getResults(t)}catch(e){return void this.markQueryError(t,e)}}sendResults(e,t){try{e.forEach(e=>{this.activeQueries[t.id]&&(this.activeQueries[t.id].allowedResultsCount?(--this.activeQueries[t.id].allowedResultsCount,t.sendResult(e)):this.markQueryDone(t))})}catch(e){this.logger?.warn(`Failed sending results for query: ${t.search} with an error: ${extractErrorMsg$1(e)}`)}}markQueryDone(e){this.activeQueries[e.id]&&(this.logger?.info(`The query for: ${e.search} is completed`),delete this.activeQueries[e.id],e.done())}markQueryError(e,t){this.activeQueries[e.id]&&(this.logger?.warn(`The query for: ${e.search} ended with an error: ${extractErrorMsg$1(t)}`),delete this.activeQueries[e.id],e.error(extractErrorMsg$1(t)))}processQueryCancel(e){delete this.activeQueries[e.id]}}class ApplicationsRepository{glueController;type="application";displayType="Applications";constructor(e){this.glueController=e}getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)},n=this.glueController.getAllApplications();if(n.filter(t=>checkMatch(r,()=>!!t.title?.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),!r.count)return Promise.resolve(this.transformApps(t));if(n.filter(t=>checkMatch(r,()=>!!t.caption?.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),!r.count)return Promise.resolve(this.transformApps(t));return n.filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),Promise.resolve(this.transformApps(t))}transformApps(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.title,description:r.caption,iconURL:r.icon});return t}}class LayoutsRepository{glueController;type="layout";displayType="Layouts";constructor(e){this.glueController=e}async getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)};return(await this.glueController.getAllLayoutsSummaries()).filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),this.transformLayouts(t)}transformLayouts(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.name});return t}}class WorkspacesRepository{glueController;type="workspace";displayType="Workspaces";constructor(e){this.glueController=e}async getResults(e){const t=new Set,r={count:Math.min(e.providerLimits?.maxResultsPerType||Number.MAX_SAFE_INTEGER,e.providerLimits?.maxResults||Number.MAX_SAFE_INTEGER)};return(await this.glueController.getAllWorkspacesSummaries()).filter(t=>checkMatch(r,()=>t.name.toLowerCase().includes(e.search.toLowerCase()))).forEach(e=>t.add(e)),this.transformWorkspaces(t)}transformWorkspaces(e){const t=[];for(const r of e.values())t.push({type:{name:this.type,displayName:this.displayType},id:r.name,displayName:r.name});return t}}class LocalStoreController{localStorage;defaultGlobalLayoutNamespace="g42_core_plus_default_global_layout";themesNamespace="g42_core_plus_themes";notificationsNamespace="g42_core_notifications_config";restSchedulerNamespace="g42_core_rest_scheduler";username="g42_public";constructor(){this.localStorage=window.localStorage}start(e){e?.id&&(this.username=e.id);if(!this.localStorage.getItem(this.username)){const e={[this.defaultGlobalLayoutNamespace]:{},[this.themesNamespace]:[],[this.restSchedulerNamespace]:{}};this.localStorage.setItem(this.username,JSON.stringify(e))}}stop(){this.username="g42_public"}saveThemeIfMissing(e){const t=this.getData(this.themesNamespace)||[];t.some(t=>t.theme.name===e.theme.name)||(t.push(e),this.saveData(this.themesNamespace,t))}getAllThemes(){return this.getData(this.themesNamespace)||[]}markThemeSelected(e,t){const r=this.getData(this.themesNamespace)||[],n=r.find(t=>t.theme.name===e);if(!n)return ioError.raiseError(`Cannot mark theme: ${e} as selected, because it doesn't exist`);r.forEach(e=>{e.selected=!1,e.isUserSelected=!1}),n.selected=!0,n.isUserSelected=!!t,this.saveData(this.themesNamespace,r)}getRestSchedulerEntry(e){return this.getAllRestSchedulerEntries()[e]}getAllRestSchedulerEntries(){return this.getData(this.restSchedulerNamespace)||{}}saveRestSchedulerEntry(e){const t=this.getAllRestSchedulerEntries();t[e.key]=e,this.saveData(this.restSchedulerNamespace,t)}clearRestSchedulerEntries(){this.saveData(this.restSchedulerNamespace,{})}deleteRestSchedulerEntry(e){const t=this.getAllRestSchedulerEntries();delete t[e],this.saveData(this.restSchedulerNamespace,t)}getDefaultGlobalLayoutName(){const e=this.getData(this.defaultGlobalLayoutNamespace);return e?.name}saveDefaultGlobalLayout(e){this.saveData(this.defaultGlobalLayoutNamespace,{name:e})}clearDefaultGlobalLayout(){this.saveData(this.defaultGlobalLayoutNamespace,{})}getNotificationsConfig(){return this.getData(this.notificationsNamespace)}setNotificationsConfig(e){this.saveData(this.notificationsNamespace,e)}updateNotificationsConfig(e){const t=this.getNotificationsConfig();if(!t)return ioError.raiseError("Cannot update notifications config, because it doesn't exist");this.setNotificationsConfig(deepMerge(t,e,{arrayMerge:(e,t)=>t}))}getData(e){const t=this.localStorage.getItem(this.username);return t?JSON.parse(t)[e]:ioError.raiseError(`Cannot get data for namespace: ${e}, because the user data is missing`)}saveData(e,t){const r=this.localStorage.getItem(this.username);if(!r)return ioError.raiseError(`Cannot set data for namespace: ${e}, because the user data is missing`);const n=JSON.parse(r);n[e]=t,this.localStorage.setItem(this.username,JSON.stringify(n))}}const themesOperationDecoder=oneOf$1(constant$2("getCurrent"),constant$2("list"),constant$2("select"),constant$2("operationCheck")),themeDecoder=object$3({displayName:nonEmptyStringDecoder$2,name:nonEmptyStringDecoder$2}),simpleThemeResponseDecoder=object$3({theme:themeDecoder}),allThemesResponseDecoder=object$3({themes:array$3(themeDecoder)}),selectThemeConfigDecoder=object$3({name:nonEmptyStringDecoder$2}),GlueCorePlusThemesStream="T42.Core.Plus.Themes.Stream",lightTheme={name:"light",displayName:"Light"},darkTheme={name:"dark",displayName:"Dark"};class ThemesController{glueController;localStore;started=!1;themesStream;operations={getCurrent:{name:"getCurrent",resultDecoder:simpleThemeResponseDecoder,execute:this.handleGetCurrent.bind(this)},list:{name:"list",resultDecoder:allThemesResponseDecoder,execute:this.handleList.bind(this)},select:{name:"select",dataDecoder:selectThemeConfigDecoder,execute:this.handleSelect.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t){this.glueController=e,this.localStore=t}get logger(){return logger.get("themes.controller")}async start(e){this.started=!0,this.localStore.saveThemeIfMissing({theme:lightTheme,selected:!1,isUserSelected:!1}),this.localStore.saveThemeIfMissing({theme:darkTheme,selected:!1,isUserSelected:!1}),this.themesStream=await this.glueController.createSystemStream(GlueCorePlusThemesStream);if(this.localStore.getAllThemes().some(e=>e.isUserSelected))return;const t="os"===e.themes?.defaultTheme?this.getOsTheme():"light"===e.themes?.defaultTheme?"light":"dark";this.localStore.markThemeSelected(t,!1);const r=this.localStore.getAllThemes().find(e=>e.selected)?.theme;this.themesStream.push({theme:r})}handlePlatformShutdown(){this.started=!1,this.themesStream.close()}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this themes control message, because the controller has not been started");const t=e.data,r=e.commandId,n=themesOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This themes request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Themes request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Themes request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}handleClientUnloaded(){}async handleGetCurrent(e,t){this.logger?.trace(`[${t}] handling a getCurrent message`);const r=this.localStore.getAllThemes().find(e=>e.selected);return r?{theme:r.theme}:ioError.raiseError("No selected theme found!")}async handleList(e,t){this.logger?.trace(`[${t}] handling a list message`);return{themes:this.localStore.getAllThemes().map(e=>e.theme)}}async handleSelect(e,t){this.logger?.trace(`[${t}] handling a select message`),this.localStore.markThemeSelected(e.name,!0);const r=this.localStore.getAllThemes().find(e=>e.selected)?.theme;if(!r)return ioError.raiseError("No selected theme found!");this.themesStream.push({theme:r})}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}getOsTheme(){return window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}}function bind(e,t){return function(){return e.apply(t,arguments)}}const{toString:toString}=Object.prototype,{getPrototypeOf:getPrototypeOf}=Object,{iterator:iterator,toStringTag:toStringTag}=Symbol,kindOf=(e=>t=>{const r=toString.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=e=>(e=e.toLowerCase(),t=>kindOf(t)===e),typeOfTest=e=>t=>typeof t===e,{isArray:isArray}=Array,isUndefined=typeOfTest("undefined");function isBuffer(e){return null!==e&&!isUndefined(e)&&null!==e.constructor&&!isUndefined(e.constructor)&&isFunction$1(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&isArrayBuffer(e.buffer),t}const isString=typeOfTest("string"),isFunction$1=typeOfTest("function"),isNumber=typeOfTest("number"),isObject$1=e=>null!==e&&"object"==typeof e,isBoolean=e=>!0===e||!1===e,isPlainObject$1=e=>{if("object"!==kindOf(e))return!1;const t=getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||toStringTag in e||iterator in e)},isEmptyObject=e=>{if(!isObject$1(e)||isBuffer(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=e=>isObject$1(e)&&isFunction$1(e.pipe),isFormData=e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||isFunction$1(e.append)&&("formdata"===(t=kindOf(e))||"object"===t&&isFunction$1(e.toString)&&"[object FormData]"===e.toString()))},isURLSearchParams=kindOfTest("URLSearchParams"),[isReadableStream,isRequest,isResponse,isHeaders]=["ReadableStream","Request","Response","Headers"].map(kindOfTest),trim=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,i;if("object"!=typeof e&&(e=[e]),isArray(e))for(n=0,i=e.length;n0;)if(n=r[i],t===n.toLowerCase())return n;return null}const _global="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,isContextDefined=e=>!isUndefined(e)&&e!==_global;function merge$1(){const{caseless:e,skipUndefined:t}=isContextDefined(this)&&this||{},r={},n=(n,i)=>{const o=e&&findKey(r,i)||i;isPlainObject$1(r[o])&&isPlainObject$1(n)?r[o]=merge$1(r[o],n):isPlainObject$1(n)?r[o]=merge$1({},n):isArray(n)?r[o]=n.slice():t&&isUndefined(n)||(r[o]=n)};for(let e=0,t=arguments.length;e(forEach(t,(t,n)=>{r&&isFunction$1(t)?Object.defineProperty(e,n,{value:bind(t,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),stripBOM=e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject=(e,t,r,n)=>{let i,o,s;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)s=i[o],n&&!n(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&getPrototypeOf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},endsWith=(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray=e=>{if(!e)return null;if(isArray(e))return e;let t=e.length;if(!isNumber(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},isTypedArray=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&getPrototypeOf(Uint8Array)),forEachEntry=(e,t)=>{const r=(e&&e[iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll=(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),hasOwnProperty=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),isRegExp=kindOfTest("RegExp"),reduceDescriptors=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};forEach(r,(r,i)=>{let o;!1!==(o=t(r,i,e))&&(n[i]=o||r)}),Object.defineProperties(e,n)},freezeMethods=e=>{reduceDescriptors(e,(t,r)=>{if(isFunction$1(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];isFunction$1(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet=(e,t)=>{const r={},n=e=>{e.forEach(e=>{r[e]=!0})};return isArray(e)?n(e):n(String(e).split(t)),r},noop=()=>{},toFiniteNumber=(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t;function isSpecCompliantForm(e){return!!(e&&isFunction$1(e.append)&&"FormData"===e[toStringTag]&&e[iterator])}const toJSONObject=e=>{const t=new Array(10),r=(e,n)=>{if(isObject$1(e)){if(t.indexOf(e)>=0)return;if(isBuffer(e))return e;if(!("toJSON"in e)){t[n]=e;const i=isArray(e)?[]:{};return forEach(e,(e,t)=>{const o=r(e,n+1);!isUndefined(o)&&(i[t]=o)}),t[n]=void 0,i}}return e};return r(e,0)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=e=>e&&(isObject$1(e)||isFunction$1(e))&&isFunction$1(e.then)&&isFunction$1(e.catch),_setImmediate=(setImmediateSupported="function"==typeof setImmediate,postMessageSupported=isFunction$1(_global.postMessage),setImmediateSupported?setImmediate:postMessageSupported?(token=`axios@${Math.random()}`,callbacks=[],_global.addEventListener("message",({source:e,data:t})=>{e===_global&&t===token&&callbacks.length&&callbacks.shift()()},!1),e=>{callbacks.push(e),_global.postMessage(token,"*")}):e=>setTimeout(e));var setImmediateSupported,postMessageSupported,token,callbacks;const asap="undefined"!=typeof queueMicrotask?queueMicrotask.bind(_global):_setImmediate,isIterable=e=>null!=e&&isFunction$1(e[iterator]);var utils$1={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isBoolean:isBoolean,isObject:isObject$1,isPlainObject:isPlainObject$1,isEmptyObject:isEmptyObject,isReadableStream:isReadableStream,isRequest:isRequest,isResponse:isResponse,isHeaders:isHeaders,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isRegExp:isRegExp,isFunction:isFunction$1,isStream:isStream,isURLSearchParams:isURLSearchParams,isTypedArray:isTypedArray,isFileList:isFileList,forEach:forEach,merge:merge$1,extend:extend$1,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,forEachEntry:forEachEntry,matchAll:matchAll,isHTMLForm:isHTMLForm,hasOwnProperty:hasOwnProperty,hasOwnProp:hasOwnProperty,reduceDescriptors:reduceDescriptors,freezeMethods:freezeMethods,toObjectSet:toObjectSet,toCamelCase:toCamelCase,noop:noop,toFiniteNumber:toFiniteNumber,findKey:findKey,global:_global,isContextDefined:isContextDefined,isSpecCompliantForm:isSpecCompliantForm,toJSONObject:toJSONObject,isAsyncFn:isAsyncFn,isThenable:isThenable,setImmediate:_setImmediate,asap:asap,isIterable:isIterable};let AxiosError$1=class e extends Error{static from(t,r,n,i,o,s){const a=new e(t.message,r||t.code,n,i,o);return a.cause=t,a.name=t.name,s&&Object.assign(a,s),a}constructor(e,t,r,n,i){super(e),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),i&&(this.response=i,this.status=i.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:utils$1.toJSONObject(this.config),code:this.code,status:this.status}}};AxiosError$1.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",AxiosError$1.ERR_BAD_OPTION="ERR_BAD_OPTION",AxiosError$1.ECONNABORTED="ECONNABORTED",AxiosError$1.ETIMEDOUT="ETIMEDOUT",AxiosError$1.ERR_NETWORK="ERR_NETWORK",AxiosError$1.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",AxiosError$1.ERR_DEPRECATED="ERR_DEPRECATED",AxiosError$1.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",AxiosError$1.ERR_BAD_REQUEST="ERR_BAD_REQUEST",AxiosError$1.ERR_CANCELED="ERR_CANCELED",AxiosError$1.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",AxiosError$1.ERR_INVALID_URL="ERR_INVALID_URL";var httpAdapter=null;function isVisitable(e){return utils$1.isPlainObject(e)||utils$1.isArray(e)}function removeBrackets(e){return utils$1.endsWith(e,"[]")?e.slice(0,-2):e}function renderKey(e,t,r){return e?e.concat(t).map(function(e,t){return e=removeBrackets(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}function isFlatArray(e){return utils$1.isArray(e)&&!e.some(isVisitable)}const predicates=utils$1.toFlatObject(utils$1,{},null,function(e){return/^is[A-Z]/.test(e)});function toFormData$1(e,t,r){if(!utils$1.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=utils$1.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!utils$1.isUndefined(t[e])})).metaTokens,i=r.visitor||l,o=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&utils$1.isSpecCompliantForm(t);if(!utils$1.isFunction(i))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(utils$1.isDate(e))return e.toISOString();if(utils$1.isBoolean(e))return e.toString();if(!a&&utils$1.isBlob(e))throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");return utils$1.isArrayBuffer(e)||utils$1.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,i){let a=e;if(e&&!i&&"object"==typeof e)if(utils$1.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(utils$1.isArray(e)&&isFlatArray(e)||(utils$1.isFileList(e)||utils$1.endsWith(r,"[]"))&&(a=utils$1.toArray(e)))return r=removeBrackets(r),a.forEach(function(e,n){!utils$1.isUndefined(e)&&null!==e&&t.append(!0===s?renderKey([r],n,o):null===s?r:r+"[]",c(e))}),!1;return!!isVisitable(e)||(t.append(renderKey(i,r,o),c(e)),!1)}const u=[],d=Object.assign(predicates,{defaultVisitor:l,convertValue:c,isVisitable:isVisitable});if(!utils$1.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!utils$1.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),utils$1.forEach(r,function(r,o){!0===(!(utils$1.isUndefined(r)||null===r)&&i.call(t,r,utils$1.isString(o)?o.trim():o,n,d))&&e(r,n?n.concat(o):[o])}),u.pop()}}(e),t}function encode$1(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function AxiosURLSearchParams(e,t){this._pairs=[],e&&toFormData$1(e,this,t)}const prototype=AxiosURLSearchParams.prototype;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function buildURL(e,t,r){if(!t)return e;const n=r&&r.encode||encode,i=utils$1.isFunction(r)?{serialize:r}:r,o=i&&i.serialize;let s;if(s=o?o(t,i):utils$1.isURLSearchParams(t)?t.toString():new AxiosURLSearchParams(t,i).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}prototype.append=function(e,t){this._pairs.push([e,t])},prototype.toString=function(e){const t=e?function(t){return e.call(this,t,encode$1)}:encode$1;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class InterceptorManager{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){utils$1.forEach(this.handlers,function(t){null!==t&&e(t)})}}var transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},URLSearchParams$1="undefined"!=typeof URLSearchParams?URLSearchParams:AxiosURLSearchParams,FormData$2="undefined"!=typeof FormData?FormData:null,Blob$1="undefined"!=typeof Blob?Blob:null,platform$1={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$1,FormData:FormData$2,Blob:Blob$1},protocols:["http","https","file","blob","url","data"]};const hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost";var utils=Object.freeze({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,navigator:_navigator,origin:origin}),platform={...utils,...platform$1};function toURLEncodedForm(e,t){return toFormData$1(e,new platform.classes.URLSearchParams,{visitor:function(e,t,r,n){return platform.isNode&&utils$1.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...t})}function parsePropPath(e){return utils$1.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}function arrayToObject(e){const t={},r=Object.keys(e);let n;const i=r.length;let o;for(n=0;n=e.length;if(o=!o&&utils$1.isArray(n)?n.length:o,a)return utils$1.hasOwnProp(n,o)?n[o]=[n[o],r]:n[o]=r,!s;n[o]&&utils$1.isObject(n[o])||(n[o]=[]);return t(e,r,n[o],i)&&utils$1.isArray(n[o])&&(n[o]=arrayToObject(n[o])),!s}if(utils$1.isFormData(e)&&utils$1.isFunction(e.entries)){const r={};return utils$1.forEachEntry(e,(e,n)=>{t(parsePropPath(e),n,r,0)}),r}return null}function stringifySafely(e,t,r){if(utils$1.isString(e))try{return(t||JSON.parse)(e),utils$1.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}const defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,i=utils$1.isObject(e);i&&utils$1.isHTMLForm(e)&&(e=new FormData(e));if(utils$1.isFormData(e))return n?JSON.stringify(formDataToJSON(e)):e;if(utils$1.isArrayBuffer(e)||utils$1.isBuffer(e)||utils$1.isStream(e)||utils$1.isFile(e)||utils$1.isBlob(e)||utils$1.isReadableStream(e))return e;if(utils$1.isArrayBufferView(e))return e.buffer;if(utils$1.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(e,this.formSerializer).toString();if((o=utils$1.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return toFormData$1(o?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||n?(t.setContentType("application/json",!1),stringifySafely(e)):e}],transformResponse:[function(e){const t=this.transitional||defaults.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(utils$1.isResponse(e)||utils$1.isReadableStream(e))return e;if(e&&utils$1.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e,this.parseReviver)}catch(e){if(r){if("SyntaxError"===e.name)throw AxiosError$1.from(e,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$1.forEach(["delete","get","head","post","put","patch"],e=>{defaults.headers[e]={}});const ignoreDuplicateOf=utils$1.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);var parseHeaders=e=>{const t={};let r,n,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),r=e.substring(0,i).trim().toLowerCase(),n=e.substring(i+1).trim(),!r||t[r]&&ignoreDuplicateOf[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t};const $internals=Symbol("internals");function normalizeHeader(e){return e&&String(e).trim().toLowerCase()}function normalizeValue(e){return!1===e||null==e?e:utils$1.isArray(e)?e.map(normalizeValue):String(e)}function parseTokens(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}const isValidHeaderName=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function matchHeaderValue(e,t,r,n,i){return utils$1.isFunction(n)?n.call(this,t,r):(i&&(t=r),utils$1.isString(t)?utils$1.isString(n)?-1!==t.indexOf(n):utils$1.isRegExp(n)?n.test(t):void 0:void 0)}function formatHeader(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}function buildAccessors(e,t){const r=utils$1.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(e,r,i){return this[n].call(this,t,e,r,i)},configurable:!0})})}let AxiosHeaders$1=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function i(e,t,r){const i=normalizeHeader(t);if(!i)throw new Error("header name must be a non-empty string");const o=utils$1.findKey(n,i);(!o||void 0===n[o]||!0===r||void 0===r&&!1!==n[o])&&(n[o||t]=normalizeValue(e))}const o=(e,t)=>utils$1.forEach(e,(e,r)=>i(e,r,t));if(utils$1.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(utils$1.isString(e)&&(e=e.trim())&&!isValidHeaderName(e))o(parseHeaders(e),t);else if(utils$1.isObject(e)&&utils$1.isIterable(e)){let r,n,i={};for(const t of e){if(!utils$1.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[n=t[0]]=(r=i[n])?utils$1.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}o(i,t)}else null!=e&&i(t,e,r);return this}get(e,t){if(e=normalizeHeader(e)){const r=utils$1.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return parseTokens(e);if(utils$1.isFunction(t))return t.call(this,e,r);if(utils$1.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=normalizeHeader(e)){const r=utils$1.findKey(this,e);return!(!r||void 0===this[r]||t&&!matchHeaderValue(this,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function i(e){if(e=normalizeHeader(e)){const i=utils$1.findKey(r,e);!i||t&&!matchHeaderValue(r,r[i],i,t)||(delete r[i],n=!0)}}return utils$1.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const i=t[r];e&&!matchHeaderValue(this,this[i],i,e,!0)||(delete this[i],n=!0)}return n}normalize(e){const t=this,r={};return utils$1.forEach(this,(n,i)=>{const o=utils$1.findKey(r,i);if(o)return t[o]=normalizeValue(n),void delete t[i];const s=e?formatHeader(i):String(i).trim();s!==i&&delete t[i],t[s]=normalizeValue(n),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return utils$1.forEach(this,(r,n)=>{null!=r&&!1!==r&&(t[n]=e&&utils$1.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[$internals]=this[$internals]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=normalizeHeader(e);t[n]||(buildAccessors(r,e),t[n]=!0)}return utils$1.isArray(e)?e.forEach(n):n(e),this}};function transformData(e,t){const r=this||defaults,n=t||r,i=AxiosHeaders$1.from(n.headers);let o=n.data;return utils$1.forEach(e,function(e){o=e.call(r,o,i.normalize(),t?t.status:void 0)}),i.normalize(),o}function isCancel$1(e){return!(!e||!e.__CANCEL__)}AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$1.reduceDescriptors(AxiosHeaders$1.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),utils$1.freezeMethods(AxiosHeaders$1);let CanceledError$1=class extends AxiosError$1{constructor(e,t,r){super(null==e?"canceled":e,AxiosError$1.ERR_CANCELED,t,r),this.name="CanceledError",this.__CANCEL__=!0}};function settle(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new AxiosError$1("Request failed with status code "+r.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}function parseProtocol(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function speedometer(e,t){e=e||10;const r=new Array(e),n=new Array(e);let i,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[s];i||(i=c),r[o]=a,n[o]=c;let u=s,d=0;for(;u!==o;)d+=r[u++],u%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i{i=o,r=null,n&&(clearTimeout(n),n=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=o?s(e,t):(r=e,n||(n=setTimeout(()=>{n=null,s(r)},o-a)))},()=>r&&s(r)]}const progressEventReducer=(e,t,r=3)=>{let n=0;const i=speedometer(50,250);return throttle(r=>{const o=r.loaded,s=r.lengthComputable?r.total:void 0,a=o-n,c=i(a);n=o;e({loaded:o,total:s,progress:s?o/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&o<=s?(s-o)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},progressEventDecorator=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},asyncDecorator=e=>(...t)=>utils$1.asap(()=>e(...t));var isURLSameOrigin=platform.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,platform.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(e,t,r,n,i,o,s){if("undefined"==typeof document)return;const a=[`${e}=${encodeURIComponent(t)}`];utils$1.isNumber(r)&&a.push(`expires=${new Date(r).toUTCString()}`),utils$1.isString(n)&&a.push(`path=${n}`),utils$1.isString(i)&&a.push(`domain=${i}`),!0===o&&a.push("secure"),utils$1.isString(s)&&a.push(`SameSite=${s}`),document.cookie=a.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function isAbsoluteURL(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function combineURLs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function buildFullPath(e,t,r){let n=!isAbsoluteURL(t);return e&&(n||0==r)?combineURLs(e,t):t}const headersToObject=e=>e instanceof AxiosHeaders$1?{...e}:e;function mergeConfig$1(e,t){t=t||{};const r={};function n(e,t,r,n){return utils$1.isPlainObject(e)&&utils$1.isPlainObject(t)?utils$1.merge.call({caseless:n},e,t):utils$1.isPlainObject(t)?utils$1.merge({},t):utils$1.isArray(t)?t.slice():t}function i(e,t,r,i){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e,0,i):n(e,t,0,i)}function o(e,t){if(!utils$1.isUndefined(t))return n(void 0,t)}function s(e,t){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,i,o){return o in t?n(r,i):o in e?n(void 0,r):void 0}const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(e,t,r)=>i(headersToObject(e),headersToObject(t),0,!0)};return utils$1.forEach(Object.keys({...e,...t}),function(n){const o=c[n]||i,s=o(e[n],t[n],n);utils$1.isUndefined(s)&&o!==a||(r[n]=s)}),r}var resolveConfig=e=>{const t=mergeConfig$1({},e);let{data:r,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:o,headers:s,auth:a}=t;if(t.headers=s=AxiosHeaders$1.from(s),t.url=buildURL(buildFullPath(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),utils$1.isFormData(r))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(utils$1.isFunction(r.getHeaders)){const e=r.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(([e,r])=>{t.includes(e.toLowerCase())&&s.set(e,r)})}if(platform.hasStandardBrowserEnv&&(n&&utils$1.isFunction(n)&&(n=n(t)),n||!1!==n&&isURLSameOrigin(t.url))){const e=i&&o&&cookies.read(o);e&&s.set(i,e)}return t};const isXHRAdapterSupported="undefined"!=typeof XMLHttpRequest;var xhrAdapter=isXHRAdapterSupported&&function(e){return new Promise(function(t,r){const n=resolveConfig(e);let i=n.data;const o=AxiosHeaders$1.from(n.headers).normalize();let s,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function g(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(s),n.signal&&n.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const n=AxiosHeaders$1.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());settle(function(e){t(e),g()},function(e){r(e),g()},{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(f)},m.onabort=function(){m&&(r(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,e,m)),m=null)},m.onerror=function(t){const n=t&&t.message?t.message:"Network Error",i=new AxiosError$1(n,AxiosError$1.ERR_NETWORK,e,m);i.event=t||null,r(i),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const i=n.transitional||transitionalDefaults;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new AxiosError$1(t,i.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,e,m)),m=null},void 0===i&&o.setContentType(null),"setRequestHeader"in m&&utils$1.forEach(o.toJSON(),function(e,t){m.setRequestHeader(t,e)}),utils$1.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),d&&"json"!==d&&(m.responseType=n.responseType),p&&([c,u]=progressEventReducer(p,!0),m.addEventListener("progress",c)),h&&m.upload&&([a,l]=progressEventReducer(h),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(s=t=>{m&&(r(!t||t.type?new CanceledError$1(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(s),n.signal&&(n.signal.aborted?s():n.signal.addEventListener("abort",s)));const y=parseProtocol(n.url);y&&-1===platform.protocols.indexOf(y)?r(new AxiosError$1("Unsupported protocol "+y+":",AxiosError$1.ERR_BAD_REQUEST,e)):m.send(i||null)})};const composeSignals=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const i=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;n.abort(t instanceof AxiosError$1?t:new CanceledError$1(t instanceof Error?t.message:t))}};let o=t&&setTimeout(()=>{o=null,i(new AxiosError$1(`timeout of ${t}ms exceeded`,AxiosError$1.ETIMEDOUT))},t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:a}=n;return a.unsubscribe=()=>utils$1.asap(s),a}},streamChunk=function*(e,t){let r=e.byteLength;if(r{const i=readBytes(e,t);let o,s=0,a=e=>{o||(o=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await i.next();if(t)return a(),void e.close();let o=n.byteLength;if(r){let e=s+=o;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},DEFAULT_CHUNK_SIZE=65536,{isFunction:isFunction}=utils$1,globalFetchAPI=(({Request:e,Response:t})=>({Request:e,Response:t}))(utils$1.global),{ReadableStream:ReadableStream$1,TextEncoder:TextEncoder$1}=utils$1.global,test=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},factory=e=>{e=utils$1.merge.call({skipUndefined:!0},globalFetchAPI,e);const{fetch:t,Request:r,Response:n}=e,i=t?isFunction(t):"function"==typeof fetch,o=isFunction(r),s=isFunction(n);if(!i)return!1;const a=i&&isFunction(ReadableStream$1),c=i&&("function"==typeof TextEncoder$1?(l=new TextEncoder$1,e=>l.encode(e)):async e=>new Uint8Array(await new r(e).arrayBuffer()));var l;const u=o&&a&&test(()=>{let e=!1;const t=new r(platform.origin,{body:new ReadableStream$1,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),d=s&&a&&test(()=>utils$1.isReadableStream(new n("").body)),h={stream:d&&(e=>e.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!h[e]&&(h[e]=(t,r)=>{let n=t&&t[e];if(n)return n.call(t);throw new AxiosError$1(`Response type '${e}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,r)})});const p=async(e,t)=>{const n=utils$1.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(utils$1.isBlob(e))return e.size;if(utils$1.isSpecCompliantForm(e)){const t=new r(platform.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return utils$1.isArrayBufferView(e)||utils$1.isArrayBuffer(e)?e.byteLength:(utils$1.isURLSearchParams(e)&&(e+=""),utils$1.isString(e)?(await c(e)).byteLength:void 0)})(t):n};return async e=>{let{url:i,method:s,data:a,signal:c,cancelToken:l,timeout:g,onDownloadProgress:m,onUploadProgress:f,responseType:y,headers:$,withCredentials:b="same-origin",fetchOptions:v}=resolveConfig(e),w=t||fetch;y=y?(y+"").toLowerCase():"text";let S=composeSignals([c,l&&l.toAbortSignal()],g),_=null;const E=S&&S.unsubscribe&&(()=>{S.unsubscribe()});let C;try{if(f&&u&&"get"!==s&&"head"!==s&&0!==(C=await p($,a))){let e,t=new r(i,{method:"POST",body:a,duplex:"half"});if(utils$1.isFormData(a)&&(e=t.headers.get("content-type"))&&$.setContentType(e),t.body){const[e,r]=progressEventDecorator(C,progressEventReducer(asyncDecorator(f)));a=trackStream(t.body,DEFAULT_CHUNK_SIZE,e,r)}}utils$1.isString(b)||(b=b?"include":"omit");const t=o&&"credentials"in r.prototype,c={...v,signal:S,method:s.toUpperCase(),headers:$.normalize().toJSON(),body:a,duplex:"half",credentials:t?b:void 0};_=o&&new r(i,c);let l=await(o?w(_,v):w(i,c));const g=d&&("stream"===y||"response"===y);if(d&&(m||g&&E)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=l[t]});const t=utils$1.toFiniteNumber(l.headers.get("content-length")),[r,i]=m&&progressEventDecorator(t,progressEventReducer(asyncDecorator(m),!0))||[];l=new n(trackStream(l.body,DEFAULT_CHUNK_SIZE,r,()=>{i&&i(),E&&E()}),e)}y=y||"text";let I=await h[utils$1.findKey(h,y)||"text"](l,e);return!g&&E&&E(),await new Promise((t,r)=>{settle(t,r,{data:I,headers:AxiosHeaders$1.from(l.headers),status:l.status,statusText:l.statusText,config:e,request:_})})}catch(t){if(E&&E(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,e,_),{cause:t.cause||t});throw AxiosError$1.from(t,t&&t.code,e,_)}}},seedCache=new Map,getFetch=e=>{let t=e&&e.env||{};const{fetch:r,Request:n,Response:i}=t,o=[n,i,r];let s,a,c=o.length,l=seedCache;for(;c--;)s=o[c],a=l.get(s),void 0===a&&l.set(s,a=c?new Map:factory(t)),l=a;return a};getFetch();const knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:{get:getFetch}};utils$1.forEach(knownAdapters,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const renderReason=e=>`- ${e}`,isResolvedHandle=e=>utils$1.isFunction(e)||null===e||!1===e;function getAdapter$1(e,t){e=utils$1.isArray(e)?e:[e];const{length:r}=e;let n,i;const o={};for(let s=0;s`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));let t=r?e.length>1?"since :\n"+e.map(renderReason).join("\n"):" "+renderReason(e[0]):"as no adapter specified";throw new AxiosError$1("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return i}var adapters={getAdapter:getAdapter$1,adapters:knownAdapters};function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError$1(null,e)}function dispatchRequest(e){throwIfCancellationRequested(e),e.headers=AxiosHeaders$1.from(e.headers),e.data=transformData.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return adapters.getAdapter(e.adapter||defaults.adapter,e)(e).then(function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,e.transformResponse,t),t.headers=AxiosHeaders$1.from(t.headers),t},function(t){return isCancel$1(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,e.transformResponse,t.response),t.response.headers=AxiosHeaders$1.from(t.response.headers))),Promise.reject(t)})}const VERSION$1="1.13.4",validators$1={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{validators$1[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const deprecatedWarnings={};function assertOptions(e,t,r){if("object"!=typeof e)throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let i=n.length;for(;i-- >0;){const o=n[i],s=t[o];if(s){const t=e[o],r=void 0===t||s(t,o,e);if(!0!==r)throw new AxiosError$1("option "+o+" must be "+r,AxiosError$1.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new AxiosError$1("Unknown option "+o,AxiosError$1.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,r){function n(e,t){return"[Axios v"+VERSION$1+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,i,o)=>{if(!1===e)throw new AxiosError$1(n(i," has been removed"+(t?" in "+t:"")),AxiosError$1.ERR_DEPRECATED);return t&&!deprecatedWarnings[i]&&(deprecatedWarnings[i]=!0,console.warn(n(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,i,o)}},validators$1.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var validator={assertOptions:assertOptions,validators:validators$1};const validators=validator.validators;let Axios$1=class{constructor(e){this.defaults=e||{},this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=mergeConfig$1(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:i}=t;void 0!==r&&validator.assertOptions(r,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),null!=n&&(utils$1.isFunction(n)?t.paramsSerializer={serialize:n}:validator.assertOptions(n,{encode:validators.function,serialize:validators.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),validator.assertOptions(t,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=i&&utils$1.merge(i.common,i[t.method]);i&&utils$1.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=AxiosHeaders$1.concat(o,i);const s=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))});const c=[];let l;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let u,d=0;if(!a){const e=[dispatchRequest.bind(this),void 0];for(e.unshift(...s),e.push(...c),u=e.length,l=Promise.resolve(t);d{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const n=new Promise(e=>{r.subscribe(e),t=e}).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e(function(e,n,i){r.reason||(r.reason=new CanceledError$1(e,n,i),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;const r=new e(function(e){t=e});return{token:r,cancel:t}}};function spread$1(e){return function(t){return e.apply(null,t)}}function isAxiosError$1(e){return utils$1.isObject(e)&&!0===e.isAxiosError}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};function createInstance(e){const t=new Axios$1(e),r=bind(Axios$1.prototype.request,t);return utils$1.extend(r,Axios$1.prototype,t,{allOwnKeys:!0}),utils$1.extend(r,t,null,{allOwnKeys:!0}),r.create=function(t){return createInstance(mergeConfig$1(e,t))},r}Object.entries(HttpStatusCode$1).forEach(([e,t])=>{HttpStatusCode$1[t]=e});const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$1,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function(e){return Promise.all(e)},axios.spread=spread$1,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=e=>formDataToJSON(utils$1.isHTMLForm(e)?new FormData(e):e),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios:Axios,AxiosError:AxiosError,CanceledError:CanceledError,isCancel:isCancel,CancelToken:CancelToken,VERSION:VERSION,all:all,Cancel:Cancel,isAxiosError:isAxiosError,spread:spread,toFormData:toFormData,AxiosHeaders:AxiosHeaders,HttpStatusCode:HttpStatusCode,formToJSON:formToJSON,getAdapter:getAdapter,mergeConfig:mergeConfig}=axios;class InvalidTokenError extends Error{}function b64DecodeUnicode(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function base64UrlDecode(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return b64DecodeUnicode(t)}catch(e){return atob(t)}}function jwtDecode(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${r+1}`);let i;try{i=base64UrlDecode(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${r+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${r+1} (${e.message})`)}}InvalidTokenError.prototype.name="InvalidTokenError";var browser="object"==typeof self?self.FormData:window.FormData,FormData$1=getDefaultExportFromCjs$2(browser);const NEVER=Object.freeze({status:"aborted"});function $constructor(e,t,r){function n(r,n){var i;Object.defineProperty(r,"_zod",{value:r._zod??{},enumerable:!1}),(i=r._zod).traits??(i.traits=new Set),r._zod.traits.add(e),t(r,n);for(const e in s.prototype)e in r||Object.defineProperty(r,e,{value:s.prototype[e].bind(r)});r._zod.constr=s,r._zod.def=n}const i=r?.Parent??Object;class o extends i{}function s(e){var t;const i=r?.Parent?new o:this;n(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}const $brand=Symbol("zod_brand");class $ZodAsyncError extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const globalConfig={};function config(e){return e&&Object.assign(globalConfig,e),globalConfig}function assertEqual(e){return e}function assertNotEqual(e){return e}function assertIs(e){}function assertNever(e){throw new Error}function assert(e){}function getEnumValues(e){const t=Object.values(e).filter(e=>"number"==typeof e),r=Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t);return r}function joinValues(e,t="|"){return e.map(e=>stringifyPrimitive(e)).join(t)}function jsonStringifyReplacer(e,t){return"bigint"==typeof t?t.toString():t}function cached(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function nullish$1(e){return null==e}function cleanRegex(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function floatSafeRemainder(e,t){const r=(e.toString().split(".")[1]||"").length,n=t.toString();let i=(n.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(n)){const e=n.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}const o=r>i?r:i;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}const EVALUATING=Symbol("evaluating");function defineLazy(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==EVALUATING)return void 0===n&&(n=EVALUATING,n=r()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function objectClone(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function assignProp(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs(...e){const t={};for(const r of e){const e=Object.getOwnPropertyDescriptors(r);Object.assign(t,e)}return Object.defineProperties({},t)}function cloneDef(e){return mergeDefs(e._zod.def)}function getElementAtPath(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function promiseAllObject(e){const t=Object.keys(e),r=t.map(t=>e[t]);return Promise.all(r).then(e=>{const r={};for(let n=0;n{};function isObject(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const allowsEval=cached(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function isPlainObject(e){if(!1===isObject(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!1!==isObject(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function shallowClone(e){return isPlainObject(e)?{...e}:e}function numKeys(e){let t=0;for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}const getParsedType=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":"undefined"!=typeof Map&&e instanceof Map?"map":"undefined"!=typeof Set&&e instanceof Set?"set":"undefined"!=typeof Date&&e instanceof Date?"date":"undefined"!=typeof File&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},propertyKeyTypes=new Set(["string","number","symbol"]),primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone(e,t,r){const n=new e._zod.constr(t??e._zod.def);return t&&!r?.parent||(n._zod.parent=e),n}function normalizeParams(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function createTransparentProxy(e){let t;return new Proxy({},{get:(r,n,i)=>(t??(t=e()),Reflect.get(t,n,i)),set:(r,n,i,o)=>(t??(t=e()),Reflect.set(t,n,i,o)),has:(r,n)=>(t??(t=e()),Reflect.has(t,n)),deleteProperty:(r,n)=>(t??(t=e()),Reflect.deleteProperty(t,n)),ownKeys:r=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(r,n)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)),defineProperty:(r,n,i)=>(t??(t=e()),Reflect.defineProperty(t,n,i))})}function stringifyPrimitive(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function optionalKeys(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}const NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function pick(e,t){const r=e._zod.def;return clone(e,mergeDefs(e._zod.def,{get shape(){const e={};for(const n in t){if(!(n in r.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(e[n]=r.shape[n])}return assignProp(this,"shape",e),e},checks:[]}))}function omit(e,t){const r=e._zod.def,n=mergeDefs(e._zod.def,{get shape(){const n={...e._zod.def.shape};for(const e in t){if(!(e in r.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return assignProp(this,"shape",n),n},checks:[]});return clone(e,n)}function extend(e,t){if(!isPlainObject(t))throw new Error("Invalid input to extend: expected a plain object");const r=mergeDefs(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return assignProp(this,"shape",r),r},checks:[]});return clone(e,r)}function merge(e,t){const r=mergeDefs(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return assignProp(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return clone(e,r)}function partial(e,t,r){const n=mergeDefs(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in n))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=e?new e({type:"optional",innerType:n[t]}):n[t])}else for(const t in n)i[t]=e?new e({type:"optional",innerType:n[t]}):n[t];return assignProp(this,"shape",i),i},checks:[]});return clone(t,n)}function required(e,t,r){const n=mergeDefs(t._zod.def,{get shape(){const n=t._zod.def.shape,i={...n};if(r)for(const t in r){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);r[t]&&(i[t]=new e({type:"nonoptional",innerType:n[t]}))}else for(const t in n)i[t]=new e({type:"nonoptional",innerType:n[t]});return assignProp(this,"shape",i),i},checks:[]});return clone(t,n)}function aborted(e,t=0){for(let r=t;r{var r;return(r=t).path??(r.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return"string"==typeof e?e:e?.message}function finalizeIssue(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const i=unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(r.customError?.(e))??unwrapMessage(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function getSizableOrigin(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function getLengthableOrigin(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function issue(...e){const[t,r,n]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:n}:{...t}}function cleanEnum(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}class Class{constructor(...e){}}var util=Object.freeze({__proto__:null,BIGINT_FORMAT_RANGES:BIGINT_FORMAT_RANGES,Class:Class,NUMBER_FORMAT_RANGES:NUMBER_FORMAT_RANGES,aborted:aborted,allowsEval:allowsEval,assert:assert,assertEqual:assertEqual,assertIs:assertIs,assertNever:assertNever,assertNotEqual:assertNotEqual,assignProp:assignProp,cached:cached,captureStackTrace:captureStackTrace,cleanEnum:cleanEnum,cleanRegex:cleanRegex,clone:clone,cloneDef:cloneDef,createTransparentProxy:createTransparentProxy,defineLazy:defineLazy,esc:esc,escapeRegex:escapeRegex,extend:extend,finalizeIssue:finalizeIssue,floatSafeRemainder:floatSafeRemainder,getElementAtPath:getElementAtPath,getEnumValues:getEnumValues,getLengthableOrigin:getLengthableOrigin,getParsedType:getParsedType,getSizableOrigin:getSizableOrigin,isObject:isObject,isPlainObject:isPlainObject,issue:issue,joinValues:joinValues,jsonStringifyReplacer:jsonStringifyReplacer,merge:merge,mergeDefs:mergeDefs,normalizeParams:normalizeParams,nullish:nullish$1,numKeys:numKeys,objectClone:objectClone,omit:omit,optionalKeys:optionalKeys,partial:partial,pick:pick,prefixIssues:prefixIssues,primitiveTypes:primitiveTypes,promiseAllObject:promiseAllObject,propertyKeyTypes:propertyKeyTypes,randomString:randomString,required:required,shallowClone:shallowClone,stringifyPrimitive:stringifyPrimitive,unwrapMessage:unwrapMessage});const initializer$1=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,jsonStringifyReplacer,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},$ZodError=$constructor("$ZodError",initializer$1),$ZodRealError=$constructor("$ZodError",initializer$1,{Parent:Error});function flattenError(e,t=e=>e.message){const r={},n=[];for(const i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function formatError(e,t){const r=t||function(e){return e.message},n={_errors:[]},i=e=>{for(const t of e.issues)if("invalid_union"===t.code&&t.errors.length)t.errors.map(e=>i({issues:e}));else if("invalid_key"===t.code)i({issues:t.issues});else if("invalid_element"===t.code)i({issues:t.issues});else if(0===t.path.length)n._errors.push(r(t));else{let e=n,i=0;for(;i{var o,s;for(const a of e.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map(e=>i({issues:e},a.path));else if("invalid_key"===a.code)i({issues:a.issues},a.path);else if("invalid_element"===a.code)i({issues:a.issues},a.path);else{const e=[...t,...a.path];if(0===e.length){n.errors.push(r(a));continue}let i=n,c=0;for(;c"object"==typeof e?e.key:e);for(const e of r)"number"==typeof e?t.push(`[${e}]`):"symbol"==typeof e?t.push(`[${JSON.stringify(String(e))}]`):/[^\w$]/.test(e)?t.push(`[${JSON.stringify(e)}]`):(t.length&&t.push("."),t.push(e));return t.join("")}function prettifyError(e){const t=[],r=[...e.issues].sort((e,t)=>(e.path??[]).length-(t.path??[]).length);for(const e of r)t.push(`✖ ${e.message}`),e.path?.length&&t.push(` → at ${toDotPath(e.path)}`);return t.join("\n")}const _parse=e=>(t,r,n,i)=>{const o=n?Object.assign(n,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new $ZodAsyncError;if(s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(t,i?.callee),t}return s.value},parse$1=_parse($ZodRealError),_parseAsync=e=>async(t,r,n,i)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>finalizeIssue(e,o,config())));throw captureStackTrace(t,i?.callee),t}return s.value},parseAsync$1=_parseAsync($ZodRealError),_safeParse=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new $ZodAsyncError;return o.issues.length?{success:!1,error:new(e??$ZodError)(o.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:o.value}},safeParse$1=_safeParse($ZodRealError),_safeParseAsync=e=>async(t,r,n)=>{const i=n?Object.assign(n,{async:!0}):{async:!0};let o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>finalizeIssue(e,i,config())))}:{success:!0,data:o.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),cuid$1=/^[cC][^\s-]{8,}$/,cuid2$1=/^[0-9a-z]+$/,ulid$1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid$1=/^[0-9a-vA-V]{20}$/,ksuid$1=/^[A-Za-z0-9]{27}$/,nanoid$2=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid$1=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid$1=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,uuid4=uuid$1(4),uuid6=uuid$1(6),uuid7=uuid$1(7),email$1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,_emoji$1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function emoji$1(){return new RegExp(_emoji$1,"u")}const ipv4$1=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6$1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,cidrv4$1=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6$1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64$1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url$1=/^[A-Za-z0-9_-]*$/,hostname$1=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,e164$1=/^\+(?:[0-9]){6,14}[0-9]$/,dateSource="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date$3=new RegExp(`^${dateSource}$`);function timeSource(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time$1(e){return new RegExp(`^${timeSource(e)}$`)}function datetime$1(e){const t=timeSource({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${dateSource}T(?:${n})$`)}const string$2=e=>new RegExp(`^${e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*"}$`),bigint$2=/^\d+n?$/,integer=/^\d+$/,number$2=/^-?\d+(?:\.\d+)?/i,boolean$2=/true|false/i,_null$2=/null/i,_undefined$2=/undefined/i,lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/;var regexes=Object.freeze({__proto__:null,base64:base64$1,base64url:base64url$1,bigint:bigint$2,boolean:boolean$2,browserEmail:browserEmail,cidrv4:cidrv4$1,cidrv6:cidrv6$1,cuid:cuid$1,cuid2:cuid2$1,date:date$3,datetime:datetime$1,domain:domain,duration:duration$1,e164:e164$1,email:email$1,emoji:emoji$1,extendedDuration:extendedDuration,guid:guid$1,hostname:hostname$1,html5Email:html5Email,idnEmail:idnEmail,integer:integer,ipv4:ipv4$1,ipv6:ipv6$1,ksuid:ksuid$1,lowercase:lowercase,nanoid:nanoid$2,null:_null$2,number:number$2,rfc5322Email:rfc5322Email,string:string$2,time:time$1,ulid:ulid$1,undefined:_undefined$2,unicodeEmail:unicodeEmail,uppercase:uppercase,uuid:uuid$1,uuid4:uuid4,uuid6:uuid6,uuid7:uuid7,xid:xid$1});const $ZodCheck=$constructor("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),numericOriginMap={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan=$constructor("$ZodCheckLessThan",(e,t)=>{$ZodCheck.init(e,t);const r=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?n.value<=t.value:n.value{$ZodCheck.init(e,t);const r=numericOriginMap[typeof t.value];e._zod.onattach.push(e=>{const r=e._zod.bag,n=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$ZodCheckMultipleOf=$constructor("$ZodCheckMultipleOf",(e,t)=>{$ZodCheck.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0===floatSafeRemainder(r.value,t.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckNumberFormat=$constructor("$ZodCheckNumberFormat",(e,t)=>{$ZodCheck.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,o]=NUMBER_FORMAT_RANGES[t.format];e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,n.minimum=i,n.maximum=o,r&&(n.pattern=integer)}),e._zod.check=s=>{const a=s.value;if(r){if(!Number.isInteger(a))return void s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}))}ao&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:e})}}),$ZodCheckBigIntFormat=$constructor("$ZodCheckBigIntFormat",(e,t)=>{$ZodCheck.init(e,t);const[r,n]=BIGINT_FORMAT_RANGES[t.format];e._zod.onattach.push(e=>{const i=e._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=i=>{const o=i.value;on&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:n,inst:e})}}),$ZodCheckMaxSize=$constructor("$ZodCheckMaxSize",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const n=r.value;n.size<=t.maximum||r.issues.push({origin:getSizableOrigin(n),code:"too_big",maximum:t.maximum,input:n,inst:e,continue:!t.abort})}}),$ZodCheckMinSize=$constructor("$ZodCheckMinSize",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;n.size>=t.minimum||r.issues.push({origin:getSizableOrigin(n),code:"too_small",minimum:t.minimum,input:n,inst:e,continue:!t.abort})}}),$ZodCheckSizeEquals=$constructor("$ZodCheckSizeEquals",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.size}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=r=>{const n=r.value,i=n.size;if(i===t.size)return;const o=i>t.size;r.issues.push({origin:getSizableOrigin(n),...o?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckMaxLength=$constructor("$ZodCheckMaxLength",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const n=r.value;if(n.length<=t.maximum)return;const i=getLengthableOrigin(n);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),$ZodCheckMinLength=$constructor("$ZodCheckMinLength",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const n=r.value;if(n.length>=t.minimum)return;const i=getLengthableOrigin(n);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),$ZodCheckLengthEquals=$constructor("$ZodCheckLengthEquals",(e,t)=>{var r;$ZodCheck.init(e,t),(r=e._zod.def).when??(r.when=e=>{const t=e.value;return!nullish$1(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{const n=r.value,i=n.length;if(i===t.length)return;const o=getLengthableOrigin(n),s=i>t.length;r.issues.push({origin:o,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckStringFormat=$constructor("$ZodCheckStringFormat",(e,t)=>{var r,n;$ZodCheck.init(e,t),e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),$ZodCheckRegex=$constructor("$ZodCheckRegex",(e,t)=>{$ZodCheckStringFormat.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),$ZodCheckLowerCase=$constructor("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=lowercase),$ZodCheckStringFormat.init(e,t)}),$ZodCheckUpperCase=$constructor("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=uppercase),$ZodCheckStringFormat.init(e,t)}),$ZodCheckIncludes=$constructor("$ZodCheckIncludes",(e,t)=>{$ZodCheck.init(e,t);const r=escapeRegex(t.includes),n=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckStartsWith=$constructor("$ZodCheckStartsWith",(e,t)=>{$ZodCheck.init(e,t);const r=new RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),$ZodCheckEndsWith=$constructor("$ZodCheckEndsWith",(e,t)=>{$ZodCheck.init(e,t);const r=new RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});function handleCheckPropertyResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues))}const $ZodCheckProperty=$constructor("$ZodCheckProperty",(e,t)=>{$ZodCheck.init(e,t),e._zod.check=e=>{const r=t.schema._zod.run({value:e.value[t.property],issues:[]},{});if(r instanceof Promise)return r.then(r=>handleCheckPropertyResult(r,e,t.property));handleCheckPropertyResult(r,e,t.property)}}),$ZodCheckMimeType=$constructor("$ZodCheckMimeType",(e,t)=>{$ZodCheck.init(e,t);const r=new Set(t.mime);e._zod.onattach.push(e=>{e._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),$ZodCheckOverwrite=$constructor("$ZodCheckOverwrite",(e,t)=>{$ZodCheck.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Doc{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length)),n=t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e);for(const e of n)this.content.push(e)}compile(){const e=Function,t=this?.args,r=[...(this?.content??[""]).map(e=>` ${e}`)];return new e(...t,r.join("\n"))}}const version={major:4,minor:0,patch:17},$ZodType=$constructor("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=version;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const t of n)for(const r of t._zod.onattach)r(e);if(0===n.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,r)=>{let n,i=aborted(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===r?.async)throw new $ZodAsyncError;if(n||s instanceof Promise)n=(n??Promise.resolve()).then(async()=>{await s;e.issues.length!==t&&(i||(i=aborted(e,t)))});else{if(e.issues.length===t)continue;i||(i=aborted(e,t))}}return n?n.then(()=>e):e};e._zod.run=(r,i)=>{const o=e._zod.parse(r,i);if(o instanceof Promise){if(!1===i.async)throw new $ZodAsyncError;return o.then(e=>t(e,n,i))}return t(o,n,i)}}e["~standard"]={validate:t=>{try{const r=safeParse$1(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return safeParseAsync$1(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),$ZodString=$constructor("$ZodString",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??string$2(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),$ZodStringFormat=$constructor("$ZodStringFormat",(e,t)=>{$ZodCheckStringFormat.init(e,t),$ZodString.init(e,t)}),$ZodGUID=$constructor("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=guid$1),$ZodStringFormat.init(e,t)}),$ZodUUID=$constructor("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=uuid$1(e))}else t.pattern??(t.pattern=uuid$1());$ZodStringFormat.init(e,t)}),$ZodEmail=$constructor("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=email$1),$ZodStringFormat.init(e,t)}),$ZodURL=$constructor("$ZodURL",(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=r=>{try{const n=r.value.trim(),i=new URL(n);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:hostname$1.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),void(t.normalize?r.value=i.href:r.value=n)}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),$ZodEmoji=$constructor("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=emoji$1()),$ZodStringFormat.init(e,t)}),$ZodNanoID=$constructor("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=nanoid$2),$ZodStringFormat.init(e,t)}),$ZodCUID=$constructor("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=cuid$1),$ZodStringFormat.init(e,t)}),$ZodCUID2=$constructor("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=cuid2$1),$ZodStringFormat.init(e,t)}),$ZodULID=$constructor("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ulid$1),$ZodStringFormat.init(e,t)}),$ZodXID=$constructor("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xid$1),$ZodStringFormat.init(e,t)}),$ZodKSUID=$constructor("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ksuid$1),$ZodStringFormat.init(e,t)}),$ZodISODateTime=$constructor("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=datetime$1(t)),$ZodStringFormat.init(e,t)}),$ZodISODate=$constructor("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=date$3),$ZodStringFormat.init(e,t)}),$ZodISOTime=$constructor("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=time$1(t)),$ZodStringFormat.init(e,t)}),$ZodISODuration=$constructor("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=duration$1),$ZodStringFormat.init(e,t)}),$ZodIPv4=$constructor("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ipv4$1),$ZodStringFormat.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv4"})}),$ZodIPv6=$constructor("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ipv6$1),$ZodStringFormat.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),$ZodCIDRv4=$constructor("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=cidrv4$1),$ZodStringFormat.init(e,t)}),$ZodCIDRv6=$constructor("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=cidrv6$1),$ZodStringFormat.init(e,t),e._zod.check=r=>{const[n,i]=r.value.split("/");try{if(!i)throw new Error;const e=Number(i);if(`${e}`!==i)throw new Error;if(e<0||e>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function isValidBase64(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const $ZodBase64=$constructor("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=base64$1),$ZodStringFormat.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{isValidBase64(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function isValidBase64URL(e){if(!base64url$1.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return isValidBase64(t.padEnd(4*Math.ceil(t.length/4),"="))}const $ZodBase64URL=$constructor("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=base64url$1),$ZodStringFormat.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{isValidBase64URL(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),$ZodE164=$constructor("$ZodE164",(e,t)=>{t.pattern??(t.pattern=e164$1),$ZodStringFormat.init(e,t)});function isValidJWT(e,t=null){try{const r=e.split(".");if(3!==r.length)return!1;const[n]=r;if(!n)return!1;const i=JSON.parse(atob(n));return(!("typ"in i)||"JWT"===i?.typ)&&(!!i.alg&&(!t||"alg"in i&&i.alg===t))}catch{return!1}}const $ZodJWT=$constructor("$ZodJWT",(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=r=>{isValidJWT(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),$ZodCustomStringFormat=$constructor("$ZodCustomStringFormat",(e,t)=>{$ZodStringFormat.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),$ZodNumber=$constructor("$ZodNumber",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=e._zod.bag.pattern??number$2,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}const i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),$ZodNumberFormat=$constructor("$ZodNumber",(e,t)=>{$ZodCheckNumberFormat.init(e,t),$ZodNumber.init(e,t)}),$ZodBoolean=$constructor("$ZodBoolean",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=boolean$2,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(e){}const i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),$ZodBigInt=$constructor("$ZodBigInt",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=bigint$2,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch(e){}return"bigint"==typeof r.value||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),$ZodBigIntFormat=$constructor("$ZodBigInt",(e,t)=>{$ZodCheckBigIntFormat.init(e,t),$ZodBigInt.init(e,t)}),$ZodSymbol=$constructor("$ZodSymbol",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>{const n=t.value;return"symbol"==typeof n||t.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:e}),t}}),$ZodUndefined=$constructor("$ZodUndefined",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_undefined$2,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(t,r)=>{const n=t.value;return void 0===n||t.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),t}}),$ZodNull=$constructor("$ZodNull",(e,t)=>{$ZodType.init(e,t),e._zod.pattern=_null$2,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{const n=t.value;return null===n||t.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),t}}),$ZodAny=$constructor("$ZodAny",(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e}),$ZodUnknown=$constructor("$ZodUnknown",(e,t)=>{$ZodType.init(e,t),e._zod.parse=e=>e}),$ZodNever=$constructor("$ZodNever",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),$ZodVoid=$constructor("$ZodVoid",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>{const n=t.value;return void 0===n||t.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),t}}),$ZodDate=$constructor("$ZodDate",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch(e){}const i=r.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),r}});function handleArrayResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),t.value[r]=e.value}const $ZodArray=$constructor("$ZodArray",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let e=0;ehandleArrayResult(t,r,e))):handleArrayResult(a,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function handlePropertyResult(e,t,r,n){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),void 0===e.value?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const $ZodObject=$constructor("$ZodObject",(e,t)=>{$ZodType.init(e,t);const r=cached(()=>{const e=Object.keys(t.shape);for(const r of e)if(!t.shape[r]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const r=optionalKeys(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}});defineLazy(e._zod,"propValues",()=>{const e=t.shape,r={};for(const t in e){const n=e[t]._zod;if(n.values){r[t]??(r[t]=new Set);for(const e of n.values)r[t].add(e)}}return r});let n;const i=isObject,o=!globalConfig.jitless,s=o&&allowsEval.value,a=t.catchall;let c;e._zod.parse=(l,u)=>{c??(c=r.value);const d=l.value;if(!i(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;const h=[];if(o&&s&&!1===u?.async&&!0!==u.jitless)n||(n=(e=>{const t=new Doc(["shape","payload","ctx"]),n=r.value,i=e=>{const t=esc(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let s=0;for(const e of n.keys)o[e]="key_"+s++;t.write("const newResult = {}");for(const e of n.keys){const r=o[e],n=esc(e);t.write(`const ${r} = ${i(e)};`),t.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${n}, ...iss.path] : [${n}]\n })));\n }\n \n if (${r}.value === undefined) {\n if (${n} in input) {\n newResult[${n}] = undefined;\n }\n } else {\n newResult[${n}] = ${r}.value;\n }\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,r)=>a(e,t,r)})(t.shape)),l=n(l,u);else{l.value={};const e=c.shape;for(const t of c.keys){const r=e[t]._zod.run({value:d[t],issues:[]},u);r instanceof Promise?h.push(r.then(e=>handlePropertyResult(e,l,t,d))):handlePropertyResult(r,l,t,d)}}if(!a)return h.length?Promise.all(h).then(()=>l):l;const p=[],g=c.keySet,m=a._zod,f=m.def.type;for(const e of Object.keys(d)){if(g.has(e))continue;if("never"===f){p.push(e);continue}const t=m.run({value:d[e],issues:[]},u);t instanceof Promise?h.push(t.then(t=>handlePropertyResult(t,l,e,d))):handlePropertyResult(t,l,e,d)}return p.length&&l.issues.push({code:"unrecognized_keys",keys:p,input:d,inst:e}),h.length?Promise.all(h).then(()=>l):l}});function handleUnionResults(e,t,r,n){for(const r of e)if(0===r.issues.length)return t.value=r.value,t;const i=e.filter(e=>!aborted(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,n,config())))}),t)}const $ZodUnion=$constructor("$ZodUnion",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),defineLazy(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),defineLazy(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazy(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>cleanRegex(e.source)).join("|")})$`)}});const r=1===t.options.length,n=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(r)return n(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>handleUnionResults(t,i,e,o)):handleUnionResults(a,i,e,o)}}),$ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(e,t)=>{$ZodUnion.init(e,t);const r=e._zod.parse;defineLazy(e._zod,"propValues",()=>{const e={};for(const r of t.options){const n=r._zod.propValues;if(!n||0===Object.keys(n).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[t,r]of Object.entries(n)){e[t]||(e[t]=new Set);for(const n of r)e[t].add(n)}}return e});const n=cached(()=>{const e=t.options,r=new Map;for(const n of e){const e=n._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const t of e){if(r.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,n)}}return r});e._zod.parse=(i,o)=>{const s=i.value;if(!isObject(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?r(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),i)}}),$ZodIntersection=$constructor("$ZodIntersection",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,r)=>{const n=e.value,i=t.left._zod.run({value:n,issues:[]},r),o=t.right._zod.run({value:n,issues:[]},r);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,r])=>handleIntersectionResults(e,t,r)):handleIntersectionResults(e,i,o)}});function mergeValues(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(isPlainObject(e)&&isPlainObject(t)){const r=Object.keys(t),n=Object.keys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of n){const n=mergeValues(e[r],t[r]);if(!n.valid)return{valid:!1,mergeErrorPath:[r,...n.mergeErrorPath]};i[r]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n{$ZodType.init(e,t);const r=t.items,n=r.length-[...r].reverse().findIndex(e=>"optional"!==e._zod.optin);e._zod.parse=(i,o)=>{const s=i.value;if(!Array.isArray(s))return i.issues.push({input:s,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=[];const a=[];if(!t.rest){const t=s.length>r.length,o=s.length=s.length&&c>=n)continue;const t=e._zod.run({value:s[c],issues:[]},o);t instanceof Promise?a.push(t.then(e=>handleTupleResult(e,i,c))):handleTupleResult(t,i,c)}if(t.rest){const e=s.slice(r.length);for(const r of e){c++;const e=t.rest._zod.run({value:r,issues:[]},o);e instanceof Promise?a.push(e.then(e=>handleTupleResult(e,i,c))):handleTupleResult(e,i,c)}}return a.length?Promise.all(a).then(()=>i):i}});function handleTupleResult(e,t,r){e.issues.length&&t.issues.push(...prefixIssues(r,e.issues)),t.value[r]=e.value}const $ZodRecord=$constructor("$ZodRecord",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!isPlainObject(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;const o=[];if(t.keyType._zod.values){const s=t.keyType._zod.values;r.value={};for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){const s=t.valueType._zod.run({value:i[e],issues:[]},n);s instanceof Promise?o.push(s.then(t=>{t.issues.length&&r.issues.push(...prefixIssues(e,t.issues)),r.value[e]=t.value})):(s.issues.length&&r.issues.push(...prefixIssues(e,s.issues)),r.value[e]=s.value)}let a;for(const e in i)s.has(e)||(a=a??[],a.push(e));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:a})}else{r.value={};for(const s of Reflect.ownKeys(i)){if("__proto__"===s)continue;const a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>finalizeIssue(e,n,config())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}const c=t.valueType._zod.run({value:i[s],issues:[]},n);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&r.issues.push(...prefixIssues(s,e.issues)),r.value[a.value]=e.value})):(c.issues.length&&r.issues.push(...prefixIssues(s,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),$ZodMap=$constructor("$ZodMap",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!(i instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),r;const o=[];r.value=new Map;for(const[s,a]of i){const c=t.keyType._zod.run({value:s,issues:[]},n),l=t.valueType._zod.run({value:a,issues:[]},n);c instanceof Promise||l instanceof Promise?o.push(Promise.all([c,l]).then(([t,o])=>{handleMapResult(t,o,r,s,i,e,n)})):handleMapResult(c,l,r,s,i,e,n)}return o.length?Promise.all(o).then(()=>r):r}});function handleMapResult(e,t,r,n,i,o,s){e.issues.length&&(propertyKeyTypes.has(typeof n)?r.issues.push(...prefixIssues(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map(e=>finalizeIssue(e,s,config()))})),t.issues.length&&(propertyKeyTypes.has(typeof n)?r.issues.push(...prefixIssues(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:n,issues:t.issues.map(e=>finalizeIssue(e,s,config()))})),r.value.set(e.value,t.value)}const $ZodSet=$constructor("$ZodSet",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!(i instanceof Set))return r.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),r;const o=[];r.value=new Set;for(const e of i){const i=t.valueType._zod.run({value:e,issues:[]},n);i instanceof Promise?o.push(i.then(e=>handleSetResult(e,r))):handleSetResult(i,r)}return o.length?Promise.all(o).then(()=>r):r}});function handleSetResult(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}const $ZodEnum=$constructor("$ZodEnum",(e,t)=>{$ZodType.init(e,t);const r=getEnumValues(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(e=>propertyKeyTypes.has(typeof e)).map(e=>"string"==typeof e?escapeRegex(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const o=t.value;return n.has(o)||t.issues.push({code:"invalid_value",values:r,input:o,inst:e}),t}}),$ZodLiteral=$constructor("$ZodLiteral",(e,t)=>{if($ZodType.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?escapeRegex(e):e?escapeRegex(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,n)=>{const i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),$ZodFile=$constructor("$ZodFile",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>{const n=t.value;return n instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:n,inst:e}),t}}),$ZodTransform=$constructor("$ZodTransform",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,r)=>{const n=t.transform(e.value,e);if(r.async){return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(e.value=t,e))}if(n instanceof Promise)throw new $ZodAsyncError;return e.value=n,e}});function handleOptionalResult(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const $ZodOptional=$constructor("$ZodOptional",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",e._zod.optout="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),defineLazy(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cleanRegex(e.source)})?$`):void 0}),e._zod.parse=(e,r)=>{if("optional"===t.innerType._zod.optin){const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>handleOptionalResult(t,e.value)):handleOptionalResult(n,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,r)}}),$ZodNullable=$constructor("$ZodNullable",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),defineLazy(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${cleanRegex(e.source)}|null)$`):void 0}),defineLazy(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,r)=>null===e.value?e:t.innerType._zod.run(e,r)}),$ZodDefault=$constructor("$ZodDefault",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{if(void 0===e.value)return e.value=t.defaultValue,e;const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(e=>handleDefaultResult(e,t)):handleDefaultResult(n,t)}});function handleDefaultResult(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const $ZodPrefault=$constructor("$ZodPrefault",(e,t)=>{$ZodType.init(e,t),e._zod.optin="optional",defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>(void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,r))}),$ZodNonOptional=$constructor("$ZodNonOptional",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(t=>handleNonOptionalResult(t,e)):handleNonOptionalResult(i,e)}});function handleNonOptionalResult(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const $ZodSuccess=$constructor("$ZodSuccess",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(t=>(e.value=0===t.issues.length,e)):(e.value=0===n.issues.length,e)}}),$ZodCatch=$constructor("$ZodCatch",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),defineLazy(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(n=>(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>finalizeIssue(e,r,config()))},input:e.value}),e.issues=[]),e)):(e.value=n.value,n.issues.length&&(e.value=t.catchValue({...e,error:{issues:n.issues.map(e=>finalizeIssue(e,r,config()))},input:e.value}),e.issues=[]),e)}}),$ZodNaN=$constructor("$ZodNaN",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(t,r)=>("number"==typeof t.value&&Number.isNaN(t.value)||t.issues.push({input:t.value,inst:e,expected:"nan",code:"invalid_type"}),t)}),$ZodPipe=$constructor("$ZodPipe",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"values",()=>t.in._zod.values),defineLazy(e._zod,"optin",()=>t.in._zod.optin),defineLazy(e._zod,"optout",()=>t.out._zod.optout),defineLazy(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,r)=>{const n=t.in._zod.run(e,r);return n instanceof Promise?n.then(e=>handlePipeResult(e,t,r)):handlePipeResult(n,t,r)}});function handlePipeResult(e,t,r){return e.issues.length?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const $ZodReadonly=$constructor("$ZodReadonly",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"propValues",()=>t.innerType._zod.propValues),defineLazy(e._zod,"values",()=>t.innerType._zod.values),defineLazy(e._zod,"optin",()=>t.innerType._zod.optin),defineLazy(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(e,r)=>{const n=t.innerType._zod.run(e,r);return n instanceof Promise?n.then(handleReadonlyResult):handleReadonlyResult(n)}});function handleReadonlyResult(e){return e.value=Object.freeze(e.value),e}const $ZodTemplateLiteral=$constructor("$ZodTemplateLiteral",(e,t)=>{$ZodType.init(e,t);const r=[];for(const e of t.parts)if("object"==typeof e&&null!==e){if(!e._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);const t=e._zod.pattern instanceof RegExp?e._zod.pattern.source:e._zod.pattern;if(!t)throw new Error(`Invalid template literal part: ${e._zod.traits}`);const n=t.startsWith("^")?1:0,i=t.endsWith("$")?t.length-1:t.length;r.push(t.slice(n,i))}else{if(null!==e&&!primitiveTypes.has(typeof e))throw new Error(`Invalid template literal part: ${e}`);r.push(escapeRegex(`${e}`))}e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(r,n)=>"string"!=typeof r.value?(r.issues.push({input:r.value,inst:e,expected:"template_literal",code:"invalid_type"}),r):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r)}),$ZodPromise=$constructor("$ZodPromise",(e,t)=>{$ZodType.init(e,t),e._zod.parse=(e,r)=>Promise.resolve(e.value).then(e=>t.innerType._zod.run({value:e,issues:[]},r))}),$ZodLazy=$constructor("$ZodLazy",(e,t)=>{$ZodType.init(e,t),defineLazy(e._zod,"innerType",()=>t.getter()),defineLazy(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),defineLazy(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),defineLazy(e._zod,"optin",()=>e._zod.innerType._zod.optin??void 0),defineLazy(e._zod,"optout",()=>e._zod.innerType._zod.optout??void 0),e._zod.parse=(t,r)=>e._zod.innerType._zod.run(t,r)}),$ZodCustom=$constructor("$ZodCustom",(e,t)=>{$ZodCheck.init(e,t),$ZodType.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(t=>handleRefineResult(t,r,n,e));handleRefineResult(i,r,n,e)}});function handleRefineResult(e,t,r,n){if(!e){const e={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(e.params=n._zod.def.params),t.issues.push(issue(e))}}const error$F=()=>{const e={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function t(t){return e[t]??null}const r={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return e=>{switch(e.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${e.expected}، ولكن تم إدخال ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(e.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?` أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${r} ${e.maximum.toString()} ${n.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${e.origin??"القيمة"} ${r} ${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${r} ${e.minimum.toString()} ${n.unit}`:`أصغر من اللازم: يفترض لـ ${e.origin} أن يكون ${r} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`نَص غير مقبول: يجب أن يبدأ بـ "${e.prefix}"`:"ends_with"===t.format?`نَص غير مقبول: يجب أن ينتهي بـ "${t.suffix}"`:"includes"===t.format?`نَص غير مقبول: يجب أن يتضمَّن "${t.includes}"`:"regex"===t.format?`نَص غير مقبول: يجب أن يطابق النمط ${t.pattern}`:`${r[t.format]??e.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${e.divisor}`;case"unrecognized_keys":return`معرف${e.keys.length>1?"ات":""} غريب${e.keys.length>1?"ة":""}: ${joinValues(e.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${e.origin}`;case"invalid_union":default:return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${e.origin}`}}};function ar(){return{localeError:error$F()}}const error$E=()=>{const e={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function t(t){return e[t]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${e.expected}, daxil olan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Yanlış dəyər: gözlənilən ${stringifyPrimitive(e.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${r}${e.maximum.toString()} ${n.unit??"element"}`:`Çox böyük: gözlənilən ${e.origin??"dəyər"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Çox kiçik: gözlənilən ${e.origin} ${r}${e.minimum.toString()} ${n.unit}`:`Çox kiçik: gözlənilən ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Yanlış mətn: "${t.prefix}" ilə başlamalıdır`:"ends_with"===t.format?`Yanlış mətn: "${t.suffix}" ilə bitməlidir`:"includes"===t.format?`Yanlış mətn: "${t.includes}" daxil olmalıdır`:"regex"===t.format?`Yanlış mətn: ${t.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${r[t.format]??e.format}`}case"not_multiple_of":return`Yanlış ədəd: ${e.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${e.keys.length>1?"lar":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} daxilində yanlış açar`;case"invalid_union":default:return"Yanlış dəyər";case"invalid_element":return`${e.origin} daxilində yanlış dəyər`}}};function az(){return{localeError:error$E()}}function getBelarusianPlural(e,t,r,n){const i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?n:1===o?t:o>=2&&o<=4?r:n}const error$D=()=>{const e={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function t(t){return e[t]??null}const r={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return e=>{switch(e.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${e.expected}, атрымана ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"лік";case"object":if(Array.isArray(e))return"масіў";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Няправільны ўвод: чакалася ${stringifyPrimitive(e.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);if(n){const t=getBelarusianPlural(Number(e.maximum),n.unit.one,n.unit.few,n.unit.many);return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна ${n.verb} ${r}${e.maximum.toString()} ${t}`}return`Занадта вялікі: чакалася, што ${e.origin??"значэнне"} павінна быць ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);if(n){const t=getBelarusianPlural(Number(e.minimum),n.unit.one,n.unit.few,n.unit.many);return`Занадта малы: чакалася, што ${e.origin} павінна ${n.verb} ${r}${e.minimum.toString()} ${t}`}return`Занадта малы: чакалася, што ${e.origin} павінна быць ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Няправільны радок: павінен пачынацца з "${t.prefix}"`:"ends_with"===t.format?`Няправільны радок: павінен заканчвацца на "${t.suffix}"`:"includes"===t.format?`Няправільны радок: павінен змяшчаць "${t.includes}"`:"regex"===t.format?`Няправільны радок: павінен адпавядаць шаблону ${t.pattern}`:`Няправільны ${r[t.format]??e.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${e.keys.length>1?"ключы":"ключ"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${e.origin}`;case"invalid_union":default:return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${e.origin}`}}};function be(){return{localeError:error$D()}}const error$C=()=>{const e={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(t){return e[t]??null}const r={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipus invàlid: s'esperava ${e.expected}, s'ha rebut ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Valor invàlid: s'esperava ${stringifyPrimitive(e.values[0])}`:`Opció invàlida: s'esperava una de ${joinValues(e.values," o ")}`;case"too_big":{const r=e.inclusive?"com a màxim":"menys de",n=t(e.origin);return n?`Massa gran: s'esperava que ${e.origin??"el valor"} contingués ${r} ${e.maximum.toString()} ${n.unit??"elements"}`:`Massa gran: s'esperava que ${e.origin??"el valor"} fos ${r} ${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?"com a mínim":"més de",n=t(e.origin);return n?`Massa petit: s'esperava que ${e.origin} contingués ${r} ${e.minimum.toString()} ${n.unit}`:`Massa petit: s'esperava que ${e.origin} fos ${r} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Format invàlid: ha de començar amb "${t.prefix}"`:"ends_with"===t.format?`Format invàlid: ha d'acabar amb "${t.suffix}"`:"includes"===t.format?`Format invàlid: ha d'incloure "${t.includes}"`:"regex"===t.format?`Format invàlid: ha de coincidir amb el patró ${t.pattern}`:`Format invàlid per a ${r[t.format]??e.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${e.divisor}`;case"unrecognized_keys":return`Clau${e.keys.length>1?"s":""} no reconeguda${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${e.origin}`;case"invalid_union":default:return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${e.origin}`}}};function ca(){return{localeError:error$C()}}const error$B=()=>{const e={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function t(t){return e[t]??null}const r={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return e=>{switch(e.code){case"invalid_type":return`Neplatný vstup: očekáváno ${e.expected}, obdrženo ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":if(Array.isArray(e))return"pole";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neplatný vstup: očekáváno ${stringifyPrimitive(e.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Hodnota je příliš velká: ${e.origin??"hodnota"} musí mít ${r}${e.maximum.toString()} ${n.unit??"prvků"}`:`Hodnota je příliš velká: ${e.origin??"hodnota"} musí být ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Hodnota je příliš malá: ${e.origin??"hodnota"} musí mít ${r}${e.minimum.toString()} ${n.unit??"prvků"}`:`Hodnota je příliš malá: ${e.origin??"hodnota"} musí být ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neplatný řetězec: musí začínat na "${t.prefix}"`:"ends_with"===t.format?`Neplatný řetězec: musí končit na "${t.suffix}"`:"includes"===t.format?`Neplatný řetězec: musí obsahovat "${t.includes}"`:"regex"===t.format?`Neplatný řetězec: musí odpovídat vzoru ${t.pattern}`:`Neplatný formát ${r[t.format]??e.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${e.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${e.origin}`;case"invalid_union":default:return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${e.origin}`}}};function cs(){return{localeError:error$B()}}const error$A=()=>{const e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},t={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function r(t){return e[t]??null}function n(e){return t[e]??e}const i={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldigt input: forventede ${n(e.expected)}, fik ${n((e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tal";case"object":return Array.isArray(e)?"liste":null===e?"null":Object.getPrototypeOf(e)!==Object.prototype&&e.constructor?e.constructor.name:"objekt"}return t})(e.input))}`;case"invalid_value":return 1===e.values.length?`Ugyldig værdi: forventede ${stringifyPrimitive(e.values[0])}`:`Ugyldigt valg: forventede en af følgende ${joinValues(e.values,"|")}`;case"too_big":{const t=e.inclusive?"<=":"<",i=r(e.origin),o=n(e.origin);return i?`For stor: forventede ${o??"value"} ${i.verb} ${t} ${e.maximum.toString()} ${i.unit??"elementer"}`:`For stor: forventede ${o??"value"} havde ${t} ${e.maximum.toString()}`}case"too_small":{const t=e.inclusive?">=":">",i=r(e.origin),o=n(e.origin);return i?`For lille: forventede ${o} ${i.verb} ${t} ${e.minimum.toString()} ${i.unit}`:`For lille: forventede ${o} havde ${t} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: skal starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: skal ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: skal indeholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: skal matche mønsteret ${t.pattern}`:`Ugyldig ${i[t.format]??e.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${e.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${e.origin}`;default:return"Ugyldigt input"}}};function da(){return{localeError:error$A()}}const error$z=()=>{const e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(t){return e[t]??null}const r={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return e=>{switch(e.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${e.expected}, erhalten ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"Zahl";case"object":if(Array.isArray(e))return"Array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ungültige Eingabe: erwartet ${stringifyPrimitive(e.values[0])}`:`Ungültige Option: erwartet eine von ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Zu groß: erwartet, dass ${e.origin??"Wert"} ${r}${e.maximum.toString()} ${n.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${e.origin??"Wert"} ${r}${e.maximum.toString()} ist`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Zu klein: erwartet, dass ${e.origin} ${r}${e.minimum.toString()} ${n.unit} hat`:`Zu klein: erwartet, dass ${e.origin} ${r}${e.minimum.toString()} ist`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ungültiger String: muss mit "${t.prefix}" beginnen`:"ends_with"===t.format?`Ungültiger String: muss mit "${t.suffix}" enden`:"includes"===t.format?`Ungültiger String: muss "${t.includes}" enthalten`:"regex"===t.format?`Ungültiger String: muss dem Muster ${t.pattern} entsprechen`:`Ungültig: ${r[t.format]??e.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${e.divisor} sein`;case"unrecognized_keys":return`${e.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${e.origin}`;case"invalid_union":default:return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${e.origin}`}}};function de(){return{localeError:error$z()}}const parsedType$3=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t},error$y=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(t){return e[t]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${e.expected}, received ${parsedType$3(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${stringifyPrimitive(e.values[0])}`:`Invalid option: expected one of ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Too big: expected ${e.origin??"value"} to have ${r}${e.maximum.toString()} ${n.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Too small: expected ${e.origin} to have ${r}${e.minimum.toString()} ${n.unit}`:`Too small: expected ${e.origin} to be ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":default:return"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`}}};function en(){return{localeError:error$y()}}const parsedType$2=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombro";case"object":if(Array.isArray(e))return"tabelo";if(null===e)return"senvalora";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t},error$x=()=>{const e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(t){return e[t]??null}const r={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return e=>{switch(e.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${e.expected}, riceviĝis ${parsedType$2(e.input)}`;case"invalid_value":return 1===e.values.length?`Nevalida enigo: atendiĝis ${stringifyPrimitive(e.values[0])}`:`Nevalida opcio: atendiĝis unu el ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${r}${e.maximum.toString()} ${n.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${e.origin??"valoro"} havu ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Tro malgranda: atendiĝis ke ${e.origin} havu ${r}${e.minimum.toString()} ${n.unit}`:`Tro malgranda: atendiĝis ke ${e.origin} estu ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nevalida karaktraro: devas komenciĝi per "${t.prefix}"`:"ends_with"===t.format?`Nevalida karaktraro: devas finiĝi per "${t.suffix}"`:"includes"===t.format?`Nevalida karaktraro: devas inkluzivi "${t.includes}"`:"regex"===t.format?`Nevalida karaktraro: devas kongrui kun la modelo ${t.pattern}`:`Nevalida ${r[t.format]??e.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${e.divisor}`;case"unrecognized_keys":return`Nekonata${e.keys.length>1?"j":""} ŝlosilo${e.keys.length>1?"j":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${e.origin}`;case"invalid_union":default:return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${e.origin}`}}};function eo(){return{localeError:error$x()}}const error$w=()=>{const e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(t){return e[t]??null}const r={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Entrada inválida: se esperaba ${e.expected}, recibido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"arreglo";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: se esperaba ${stringifyPrimitive(e.values[0])}`:`Opción inválida: se esperaba una de ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Demasiado grande: se esperaba que ${e.origin??"valor"} tuviera ${r}${e.maximum.toString()} ${n.unit??"elementos"}`:`Demasiado grande: se esperaba que ${e.origin??"valor"} fuera ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Demasiado pequeño: se esperaba que ${e.origin} tuviera ${r}${e.minimum.toString()} ${n.unit}`:`Demasiado pequeño: se esperaba que ${e.origin} fuera ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Cadena inválida: debe comenzar con "${t.prefix}"`:"ends_with"===t.format?`Cadena inválida: debe terminar en "${t.suffix}"`:"includes"===t.format?`Cadena inválida: debe incluir "${t.includes}"`:"regex"===t.format?`Cadena inválida: debe coincidir con el patrón ${t.pattern}`:`Inválido ${r[t.format]??e.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Llave${e.keys.length>1?"s":""} desconocida${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Llave inválida en ${e.origin}`;case"invalid_union":default:return"Entrada inválida";case"invalid_element":return`Valor inválido en ${e.origin}`}}};function es(){return{localeError:error$w()}}const error$v=()=>{const e={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function t(t){return e[t]??null}const r={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return e=>{switch(e.code){case"invalid_type":return`ورودی نامعتبر: می‌بایست ${e.expected} می‌بود، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"آرایه";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} دریافت شد`;case"invalid_value":return 1===e.values.length?`ورودی نامعتبر: می‌بایست ${stringifyPrimitive(e.values[0])} می‌بود`:`گزینه نامعتبر: می‌بایست یکی از ${joinValues(e.values,"|")} می‌بود`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`خیلی بزرگ: ${e.origin??"مقدار"} باید ${r}${e.maximum.toString()} ${n.unit??"عنصر"} باشد`:`خیلی بزرگ: ${e.origin??"مقدار"} باید ${r}${e.maximum.toString()} باشد`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`خیلی کوچک: ${e.origin} باید ${r}${e.minimum.toString()} ${n.unit} باشد`:`خیلی کوچک: ${e.origin} باید ${r}${e.minimum.toString()} باشد`}case"invalid_format":{const t=e;return"starts_with"===t.format?`رشته نامعتبر: باید با "${t.prefix}" شروع شود`:"ends_with"===t.format?`رشته نامعتبر: باید با "${t.suffix}" تمام شود`:"includes"===t.format?`رشته نامعتبر: باید شامل "${t.includes}" باشد`:"regex"===t.format?`رشته نامعتبر: باید با الگوی ${t.pattern} مطابقت داشته باشد`:`${r[t.format]??e.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${e.divisor} باشد`;case"unrecognized_keys":return`کلید${e.keys.length>1?"های":""} ناشناس: ${joinValues(e.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${e.origin}`;case"invalid_union":default:return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${e.origin}`}}};function fa(){return{localeError:error$v()}}const error$u=()=>{const e={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function t(t){return e[t]??null}const r={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return e=>{switch(e.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${e.expected}, oli ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Virheellinen syöte: täytyy olla ${stringifyPrimitive(e.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Liian suuri: ${n.subject} täytyy olla ${r}${e.maximum.toString()} ${n.unit}`.trim():`Liian suuri: arvon täytyy olla ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Liian pieni: ${n.subject} täytyy olla ${r}${e.minimum.toString()} ${n.unit}`.trim():`Liian pieni: arvon täytyy olla ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Virheellinen syöte: täytyy alkaa "${t.prefix}"`:"ends_with"===t.format?`Virheellinen syöte: täytyy loppua "${t.suffix}"`:"includes"===t.format?`Virheellinen syöte: täytyy sisältää "${t.includes}"`:"regex"===t.format?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${t.pattern}`:`Virheellinen ${r[t.format]??e.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${e.divisor} monikerta`;case"unrecognized_keys":return`${e.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function fi(){return{localeError:error$u()}}const error$t=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const r={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : ${e.expected} attendu, ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombre";case"object":if(Array.isArray(e))return"tableau";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} reçu`;case"invalid_value":return 1===e.values.length?`Entrée invalide : ${stringifyPrimitive(e.values[0])} attendu`:`Option invalide : une valeur parmi ${joinValues(e.values,"|")} attendue`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Trop grand : ${e.origin??"valeur"} doit ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"élément(s)"}`:`Trop grand : ${e.origin??"valeur"} doit être ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Trop petit : ${e.origin} doit ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Trop petit : ${e.origin} doit être ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au modèle ${t.pattern}`:`${r[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${joinValues(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};function fr(){return{localeError:error$t()}}const error$s=()=>{const e={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function t(t){return e[t]??null}const r={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return e=>{switch(e.code){case"invalid_type":return`Entrée invalide : attendu ${e.expected}, reçu ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrée invalide : attendu ${stringifyPrimitive(e.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"≤":"<",n=t(e.origin);return n?`Trop grand : attendu que ${e.origin??"la valeur"} ait ${r}${e.maximum.toString()} ${n.unit}`:`Trop grand : attendu que ${e.origin??"la valeur"} soit ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?"≥":">",n=t(e.origin);return n?`Trop petit : attendu que ${e.origin} ait ${r}${e.minimum.toString()} ${n.unit}`:`Trop petit : attendu que ${e.origin} soit ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chaîne invalide : doit commencer par "${t.prefix}"`:"ends_with"===t.format?`Chaîne invalide : doit se terminer par "${t.suffix}"`:"includes"===t.format?`Chaîne invalide : doit inclure "${t.includes}"`:"regex"===t.format?`Chaîne invalide : doit correspondre au motif ${t.pattern}`:`${r[t.format]??e.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${e.divisor}`;case"unrecognized_keys":return`Clé${e.keys.length>1?"s":""} non reconnue${e.keys.length>1?"s":""} : ${joinValues(e.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${e.origin}`;case"invalid_union":default:return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${e.origin}`}}};function frCA(){return{localeError:error$s()}}const error$r=()=>{const e={string:{unit:"אותיות",verb:"לכלול"},file:{unit:"בייטים",verb:"לכלול"},array:{unit:"פריטים",verb:"לכלול"},set:{unit:"פריטים",verb:"לכלול"}};function t(t){return e[t]??null}const r={regex:"קלט",email:"כתובת אימייל",url:"כתובת רשת",emoji:"אימוג'י",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"תאריך וזמן ISO",date:"תאריך ISO",time:"זמן ISO",duration:"משך זמן ISO",ipv4:"כתובת IPv4",ipv6:"כתובת IPv6",cidrv4:"טווח IPv4",cidrv6:"טווח IPv6",base64:"מחרוזת בבסיס 64",base64url:"מחרוזת בבסיס 64 לכתובות רשת",json_string:"מחרוזת JSON",e164:"מספר E.164",jwt:"JWT",template_literal:"קלט"};return e=>{switch(e.code){case"invalid_type":return`קלט לא תקין: צריך ${e.expected}, התקבל ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`קלט לא תקין: צריך ${stringifyPrimitive(e.values[0])}`:`קלט לא תקין: צריך אחת מהאפשרויות ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`גדול מדי: ${e.origin??"value"} צריך להיות ${r}${e.maximum.toString()} ${n.unit??"elements"}`:`גדול מדי: ${e.origin??"value"} צריך להיות ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`קטן מדי: ${e.origin} צריך להיות ${r}${e.minimum.toString()} ${n.unit}`:`קטן מדי: ${e.origin} צריך להיות ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`מחרוזת לא תקינה: חייבת להתחיל ב"${t.prefix}"`:"ends_with"===t.format?`מחרוזת לא תקינה: חייבת להסתיים ב "${t.suffix}"`:"includes"===t.format?`מחרוזת לא תקינה: חייבת לכלול "${t.includes}"`:"regex"===t.format?`מחרוזת לא תקינה: חייבת להתאים לתבנית ${t.pattern}`:`${r[t.format]??e.format} לא תקין`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${e.divisor}`;case"unrecognized_keys":return`מפתח${e.keys.length>1?"ות":""} לא מזוה${e.keys.length>1?"ים":"ה"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`מפתח לא תקין ב${e.origin}`;case"invalid_union":default:return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${e.origin}`}}};function he(){return{localeError:error$r()}}const error$q=()=>{const e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(t){return e[t]??null}const r={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return e=>{switch(e.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${e.expected}, a kapott érték ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"szám";case"object":if(Array.isArray(e))return"tömb";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Érvénytelen bemenet: a várt érték ${stringifyPrimitive(e.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Túl nagy: ${e.origin??"érték"} mérete túl nagy ${r}${e.maximum.toString()} ${n.unit??"elem"}`:`Túl nagy: a bemeneti érték ${e.origin??"érték"} túl nagy: ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Túl kicsi: a bemeneti érték ${e.origin} mérete túl kicsi ${r}${e.minimum.toString()} ${n.unit}`:`Túl kicsi: a bemeneti érték ${e.origin} túl kicsi ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Érvénytelen string: "${t.prefix}" értékkel kell kezdődnie`:"ends_with"===t.format?`Érvénytelen string: "${t.suffix}" értékkel kell végződnie`:"includes"===t.format?`Érvénytelen string: "${t.includes}" értéket kell tartalmaznia`:"regex"===t.format?`Érvénytelen string: ${t.pattern} mintának kell megfelelnie`:`Érvénytelen ${r[t.format]??e.format}`}case"not_multiple_of":return`Érvénytelen szám: ${e.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${e.origin}`;case"invalid_union":default:return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${e.origin}`}}};function hu(){return{localeError:error$q()}}const error$p=()=>{const e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(t){return e[t]??null}const r={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak valid: diharapkan ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak valid: diharapkan ${stringifyPrimitive(e.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Terlalu besar: diharapkan ${e.origin??"value"} memiliki ${r}${e.maximum.toString()} ${n.unit??"elemen"}`:`Terlalu besar: diharapkan ${e.origin??"value"} menjadi ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Terlalu kecil: diharapkan ${e.origin} memiliki ${r}${e.minimum.toString()} ${n.unit}`:`Terlalu kecil: diharapkan ${e.origin} menjadi ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak valid: harus dimulai dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak valid: harus berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak valid: harus menyertakan "${t.includes}"`:"regex"===t.format?`String tidak valid: harus sesuai pola ${t.pattern}`:`${r[t.format]??e.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${e.origin}`;case"invalid_union":default:return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${e.origin}`}}};function id(){return{localeError:error$p()}}const parsedType$1=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"númer";case"object":if(Array.isArray(e))return"fylki";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t},error$o=()=>{const e={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function t(t){return e[t]??null}const r={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return e=>{switch(e.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${parsedType$1(e.input)} þar sem á að vera ${e.expected}`;case"invalid_value":return 1===e.values.length?`Rangt gildi: gert ráð fyrir ${stringifyPrimitive(e.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} hafi ${r}${e.maximum.toString()} ${n.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${e.origin??"gildi"} sé ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Of lítið: gert er ráð fyrir að ${e.origin} hafi ${r}${e.minimum.toString()} ${n.unit}`:`Of lítið: gert er ráð fyrir að ${e.origin} sé ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ógildur strengur: verður að byrja á "${t.prefix}"`:"ends_with"===t.format?`Ógildur strengur: verður að enda á "${t.suffix}"`:"includes"===t.format?`Ógildur strengur: verður að innihalda "${t.includes}"`:"regex"===t.format?`Ógildur strengur: verður að fylgja mynstri ${t.pattern}`:`Rangt ${r[t.format]??e.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${e.divisor}`;case"unrecognized_keys":return`Óþekkt ${e.keys.length>1?"ir lyklar":"ur lykill"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${e.origin}`;case"invalid_union":default:return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${e.origin}`}}};function is(){return{localeError:error$o()}}const error$n=()=>{const e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(t){return e[t]??null}const r={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input non valido: atteso ${e.expected}, ricevuto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numero";case"object":if(Array.isArray(e))return"vettore";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input non valido: atteso ${stringifyPrimitive(e.values[0])}`:`Opzione non valida: atteso uno tra ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Troppo grande: ${e.origin??"valore"} deve avere ${r}${e.maximum.toString()} ${n.unit??"elementi"}`:`Troppo grande: ${e.origin??"valore"} deve essere ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Troppo piccolo: ${e.origin} deve avere ${r}${e.minimum.toString()} ${n.unit}`:`Troppo piccolo: ${e.origin} deve essere ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Stringa non valida: deve iniziare con "${t.prefix}"`:"ends_with"===t.format?`Stringa non valida: deve terminare con "${t.suffix}"`:"includes"===t.format?`Stringa non valida: deve includere "${t.includes}"`:"regex"===t.format?`Stringa non valida: deve corrispondere al pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${e.divisor}`;case"unrecognized_keys":return`Chiav${e.keys.length>1?"i":"e"} non riconosciut${e.keys.length>1?"e":"a"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${e.origin}`;case"invalid_union":default:return"Input non valido";case"invalid_element":return`Valore non valido in ${e.origin}`}}};function it(){return{localeError:error$n()}}const error$m=()=>{const e={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function t(t){return e[t]??null}const r={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return e=>{switch(e.code){case"invalid_type":return`無効な入力: ${e.expected}が期待されましたが、${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"数値";case"object":if(Array.isArray(e))return"配列";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}が入力されました`;case"invalid_value":return 1===e.values.length?`無効な入力: ${stringifyPrimitive(e.values[0])}が期待されました`:`無効な選択: ${joinValues(e.values,"、")}のいずれかである必要があります`;case"too_big":{const r=e.inclusive?"以下である":"より小さい",n=t(e.origin);return n?`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${n.unit??"要素"}${r}必要があります`:`大きすぎる値: ${e.origin??"値"}は${e.maximum.toString()}${r}必要があります`}case"too_small":{const r=e.inclusive?"以上である":"より大きい",n=t(e.origin);return n?`小さすぎる値: ${e.origin}は${e.minimum.toString()}${n.unit}${r}必要があります`:`小さすぎる値: ${e.origin}は${e.minimum.toString()}${r}必要があります`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無効な文字列: "${t.prefix}"で始まる必要があります`:"ends_with"===t.format?`無効な文字列: "${t.suffix}"で終わる必要があります`:"includes"===t.format?`無効な文字列: "${t.includes}"を含む必要があります`:"regex"===t.format?`無効な文字列: パターン${t.pattern}に一致する必要があります`:`無効な${r[t.format]??e.format}`}case"not_multiple_of":return`無効な数値: ${e.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${e.keys.length>1?"群":""}: ${joinValues(e.keys,"、")}`;case"invalid_key":return`${e.origin}内の無効なキー`;case"invalid_union":default:return"無効な入力";case"invalid_element":return`${e.origin}内の無効な値`}}};function ja(){return{localeError:error$m()}}const error$l=()=>{const e={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function t(t){return e[t]??null}const r={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return e=>{switch(e.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${e.expected} ប៉ុន្តែទទួលបាន ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":if(Array.isArray(e))return"អារេ (Array)";if(null===e)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(e.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${r} ${e.maximum.toString()} ${n.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${e.origin??"តម្លៃ"} ${r} ${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`តូចពេក៖ ត្រូវការ ${e.origin} ${r} ${e.minimum.toString()} ${n.unit}`:`តូចពេក៖ ត្រូវការ ${e.origin} ${r} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${t.prefix}"`:"ends_with"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${t.suffix}"`:"includes"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${t.includes}"`:"regex"===t.format?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${t.pattern}`:`មិនត្រឹមត្រូវ៖ ${r[t.format]??e.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${e.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${joinValues(e.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`;case"invalid_union":default:return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${e.origin}`}}};function kh(){return{localeError:error$l()}}const error$k=()=>{const e={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function t(t){return e[t]??null}const r={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return e=>{switch(e.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${e.expected}, 받은 타입은 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}입니다`;case"invalid_value":return 1===e.values.length?`잘못된 입력: 값은 ${stringifyPrimitive(e.values[0])} 이어야 합니다`:`잘못된 옵션: ${joinValues(e.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const r=e.inclusive?"이하":"미만",n="미만"===r?"이어야 합니다":"여야 합니다",i=t(e.origin),o=i?.unit??"요소";return i?`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()}${o} ${r}${n}`:`${e.origin??"값"}이 너무 큽니다: ${e.maximum.toString()} ${r}${n}`}case"too_small":{const r=e.inclusive?"이상":"초과",n="이상"===r?"이어야 합니다":"여야 합니다",i=t(e.origin),o=i?.unit??"요소";return i?`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()}${o} ${r}${n}`:`${e.origin??"값"}이 너무 작습니다: ${e.minimum.toString()} ${r}${n}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`잘못된 문자열: "${t.prefix}"(으)로 시작해야 합니다`:"ends_with"===t.format?`잘못된 문자열: "${t.suffix}"(으)로 끝나야 합니다`:"includes"===t.format?`잘못된 문자열: "${t.includes}"을(를) 포함해야 합니다`:"regex"===t.format?`잘못된 문자열: 정규식 ${t.pattern} 패턴과 일치해야 합니다`:`잘못된 ${r[t.format]??e.format}`}case"not_multiple_of":return`잘못된 숫자: ${e.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${joinValues(e.keys,", ")}`;case"invalid_key":return`잘못된 키: ${e.origin}`;case"invalid_union":default:return"잘못된 입력";case"invalid_element":return`잘못된 값: ${e.origin}`}}};function ko(){return{localeError:error$k()}}const error$j=()=>{const e={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function t(t){return e[t]??null}const r={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return e=>{switch(e.code){case"invalid_type":return`Грешен внес: се очекува ${e.expected}, примено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"број";case"object":if(Array.isArray(e))return"низа";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${stringifyPrimitive(e.values[0])}`:`Грешана опција: се очекува една ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Премногу голем: се очекува ${e.origin??"вредноста"} да има ${r}${e.maximum.toString()} ${n.unit??"елементи"}`:`Премногу голем: се очекува ${e.origin??"вредноста"} да биде ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Премногу мал: се очекува ${e.origin} да има ${r}${e.minimum.toString()} ${n.unit}`:`Премногу мал: се очекува ${e.origin} да биде ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неважечка низа: мора да започнува со "${t.prefix}"`:"ends_with"===t.format?`Неважечка низа: мора да завршува со "${t.suffix}"`:"includes"===t.format?`Неважечка низа: мора да вклучува "${t.includes}"`:"regex"===t.format?`Неважечка низа: мора да одгоара на патернот ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${e.origin}`;case"invalid_union":default:return"Грешен внес";case"invalid_element":return`Грешна вредност во ${e.origin}`}}};function mk(){return{localeError:error$j()}}const error$i=()=>{const e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(t){return e[t]??null}const r={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Input tidak sah: dijangka ${e.expected}, diterima ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nombor";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Input tidak sah: dijangka ${stringifyPrimitive(e.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Terlalu besar: dijangka ${e.origin??"nilai"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"elemen"}`:`Terlalu besar: dijangka ${e.origin??"nilai"} adalah ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Terlalu kecil: dijangka ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Terlalu kecil: dijangka ${e.origin} adalah ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`String tidak sah: mesti bermula dengan "${t.prefix}"`:"ends_with"===t.format?`String tidak sah: mesti berakhir dengan "${t.suffix}"`:"includes"===t.format?`String tidak sah: mesti mengandungi "${t.includes}"`:"regex"===t.format?`String tidak sah: mesti sepadan dengan corak ${t.pattern}`:`${r[t.format]??e.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${e.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${e.origin}`;case"invalid_union":default:return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${e.origin}`}}};function ms(){return{localeError:error$i()}}const error$h=()=>{const e={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function t(t){return e[t]??null}const r={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return e=>{switch(e.code){case"invalid_type":return`Ongeldige invoer: verwacht ${e.expected}, ontving ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"getal";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ongeldige invoer: verwacht ${stringifyPrimitive(e.values[0])}`:`Ongeldige optie: verwacht één van ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Te lang: verwacht dat ${e.origin??"waarde"} ${r}${e.maximum.toString()} ${n.unit??"elementen"} bevat`:`Te lang: verwacht dat ${e.origin??"waarde"} ${r}${e.maximum.toString()} is`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Te kort: verwacht dat ${e.origin} ${r}${e.minimum.toString()} ${n.unit} bevat`:`Te kort: verwacht dat ${e.origin} ${r}${e.minimum.toString()} is`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ongeldige tekst: moet met "${t.prefix}" beginnen`:"ends_with"===t.format?`Ongeldige tekst: moet op "${t.suffix}" eindigen`:"includes"===t.format?`Ongeldige tekst: moet "${t.includes}" bevatten`:"regex"===t.format?`Ongeldige tekst: moet overeenkomen met patroon ${t.pattern}`:`Ongeldig: ${r[t.format]??e.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${e.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${e.origin}`;case"invalid_union":default:return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${e.origin}`}}};function nl(){return{localeError:error$h()}}const error$g=()=>{const e={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function t(t){return e[t]??null}const r={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`Ugyldig input: forventet ${e.expected}, fikk ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"tall";case"object":if(Array.isArray(e))return"liste";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ugyldig verdi: forventet ${stringifyPrimitive(e.values[0])}`:`Ugyldig valg: forventet en av ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`For stor(t): forventet ${e.origin??"value"} til å ha ${r}${e.maximum.toString()} ${n.unit??"elementer"}`:`For stor(t): forventet ${e.origin??"value"} til å ha ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`For lite(n): forventet ${e.origin} til å ha ${r}${e.minimum.toString()} ${n.unit}`:`For lite(n): forventet ${e.origin} til å ha ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ugyldig streng: må starte med "${t.prefix}"`:"ends_with"===t.format?`Ugyldig streng: må ende med "${t.suffix}"`:"includes"===t.format?`Ugyldig streng: må inneholde "${t.includes}"`:"regex"===t.format?`Ugyldig streng: må matche mønsteret ${t.pattern}`:`Ugyldig ${r[t.format]??e.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${e.origin}`;case"invalid_union":default:return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${e.origin}`}}};function no(){return{localeError:error$g()}}const error$f=()=>{const e={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function t(t){return e[t]??null}const r={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return e=>{switch(e.code){case"invalid_type":return`Fâsit giren: umulan ${e.expected}, alınan ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"numara";case"object":if(Array.isArray(e))return"saf";if(null===e)return"gayb";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Fâsit giren: umulan ${stringifyPrimitive(e.values[0])}`:`Fâsit tercih: mûteberler ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Fazla büyük: ${e.origin??"value"}, ${r}${e.maximum.toString()} ${n.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${e.origin??"value"}, ${r}${e.maximum.toString()} olmalıydı.`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Fazla küçük: ${e.origin}, ${r}${e.minimum.toString()} ${n.unit} sahip olmalıydı.`:`Fazla küçük: ${e.origin}, ${r}${e.minimum.toString()} olmalıydı.`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Fâsit metin: "${t.prefix}" ile başlamalı.`:"ends_with"===t.format?`Fâsit metin: "${t.suffix}" ile bitmeli.`:"includes"===t.format?`Fâsit metin: "${t.includes}" ihtivâ etmeli.`:"regex"===t.format?`Fâsit metin: ${t.pattern} nakşına uymalı.`:`Fâsit ${r[t.format]??e.format}`}case"not_multiple_of":return`Fâsit sayı: ${e.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${e.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function ota(){return{localeError:error$f()}}const error$e=()=>{const e={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function t(t){return e[t]??null}const r={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return e=>{switch(e.code){case"invalid_type":return`ناسم ورودي: باید ${e.expected} وای, مګر ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"عدد";case"object":if(Array.isArray(e))return"ارې";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} ترلاسه شو`;case"invalid_value":return 1===e.values.length?`ناسم ورودي: باید ${stringifyPrimitive(e.values[0])} وای`:`ناسم انتخاب: باید یو له ${joinValues(e.values,"|")} څخه وای`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`ډیر لوی: ${e.origin??"ارزښت"} باید ${r}${e.maximum.toString()} ${n.unit??"عنصرونه"} ولري`:`ډیر لوی: ${e.origin??"ارزښت"} باید ${r}${e.maximum.toString()} وي`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`ډیر کوچنی: ${e.origin} باید ${r}${e.minimum.toString()} ${n.unit} ولري`:`ډیر کوچنی: ${e.origin} باید ${r}${e.minimum.toString()} وي`}case"invalid_format":{const t=e;return"starts_with"===t.format?`ناسم متن: باید د "${t.prefix}" سره پیل شي`:"ends_with"===t.format?`ناسم متن: باید د "${t.suffix}" سره پای ته ورسيږي`:"includes"===t.format?`ناسم متن: باید "${t.includes}" ولري`:"regex"===t.format?`ناسم متن: باید د ${t.pattern} سره مطابقت ولري`:`${r[t.format]??e.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${e.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${e.keys.length>1?"کلیډونه":"کلیډ"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${e.origin} کې`;case"invalid_union":default:return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${e.origin} کې`}}};function ps(){return{localeError:error$e()}}const error$d=()=>{const e={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function t(t){return e[t]??null}const r={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return e=>{switch(e.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${e.expected}, otrzymano ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"liczba";case"object":if(Array.isArray(e))return"tablica";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(e.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Za duża wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${r}${e.maximum.toString()} ${n.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Za mała wartość: oczekiwano, że ${e.origin??"wartość"} będzie mieć ${r}${e.minimum.toString()} ${n.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${e.origin??"wartość"} będzie wynosić ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${t.prefix}"`:"ends_with"===t.format?`Nieprawidłowy ciąg znaków: musi kończyć się na "${t.suffix}"`:"includes"===t.format?`Nieprawidłowy ciąg znaków: musi zawierać "${t.includes}"`:"regex"===t.format?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${t.pattern}`:`Nieprawidłow(y/a/e) ${r[t.format]??e.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${e.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${e.origin}`;case"invalid_union":default:return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${e.origin}`}}};function pl(){return{localeError:error$d()}}const error$c=()=>{const e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(t){return e[t]??null}const r={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return e=>{switch(e.code){case"invalid_type":return`Tipo inválido: esperado ${e.expected}, recebido ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"número";case"object":if(Array.isArray(e))return"array";if(null===e)return"nulo";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Entrada inválida: esperado ${stringifyPrimitive(e.values[0])}`:`Opção inválida: esperada uma das ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Muito grande: esperado que ${e.origin??"valor"} tivesse ${r}${e.maximum.toString()} ${n.unit??"elementos"}`:`Muito grande: esperado que ${e.origin??"valor"} fosse ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Muito pequeno: esperado que ${e.origin} tivesse ${r}${e.minimum.toString()} ${n.unit}`:`Muito pequeno: esperado que ${e.origin} fosse ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Texto inválido: deve começar com "${t.prefix}"`:"ends_with"===t.format?`Texto inválido: deve terminar com "${t.suffix}"`:"includes"===t.format?`Texto inválido: deve incluir "${t.includes}"`:"regex"===t.format?`Texto inválido: deve corresponder ao padrão ${t.pattern}`:`${r[t.format]??e.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${e.divisor}`;case"unrecognized_keys":return`Chave${e.keys.length>1?"s":""} desconhecida${e.keys.length>1?"s":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Chave inválida em ${e.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${e.origin}`;default:return"Campo inválido"}}};function pt(){return{localeError:error$c()}}function getRussianPlural(e,t,r,n){const i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?n:1===o?t:o>=2&&o<=4?r:n}const error$b=()=>{const e={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function t(t){return e[t]??null}const r={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return e=>{switch(e.code){case"invalid_type":return`Неверный ввод: ожидалось ${e.expected}, получено ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"массив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неверный ввод: ожидалось ${stringifyPrimitive(e.values[0])}`:`Неверный вариант: ожидалось одно из ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);if(n){const t=getRussianPlural(Number(e.maximum),n.unit.one,n.unit.few,n.unit.many);return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет иметь ${r}${e.maximum.toString()} ${t}`}return`Слишком большое значение: ожидалось, что ${e.origin??"значение"} будет ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);if(n){const t=getRussianPlural(Number(e.minimum),n.unit.one,n.unit.few,n.unit.many);return`Слишком маленькое значение: ожидалось, что ${e.origin} будет иметь ${r}${e.minimum.toString()} ${t}`}return`Слишком маленькое значение: ожидалось, что ${e.origin} будет ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неверная строка: должна начинаться с "${t.prefix}"`:"ends_with"===t.format?`Неверная строка: должна заканчиваться на "${t.suffix}"`:"includes"===t.format?`Неверная строка: должна содержать "${t.includes}"`:"regex"===t.format?`Неверная строка: должна соответствовать шаблону ${t.pattern}`:`Неверный ${r[t.format]??e.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${e.divisor}`;case"unrecognized_keys":return`Нераспознанн${e.keys.length>1?"ые":"ый"} ключ${e.keys.length>1?"и":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${e.origin}`;case"invalid_union":default:return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${e.origin}`}}};function ru(){return{localeError:error$b()}}const error$a=()=>{const e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(t){return e[t]??null}const r={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return e=>{switch(e.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${e.expected}, prejeto ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"število";case"object":if(Array.isArray(e))return"tabela";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Neveljaven vnos: pričakovano ${stringifyPrimitive(e.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} imelo ${r}${e.maximum.toString()} ${n.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${e.origin??"vrednost"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Premajhno: pričakovano, da bo ${e.origin} imelo ${r}${e.minimum.toString()} ${n.unit}`:`Premajhno: pričakovano, da bo ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Neveljaven niz: mora se začeti z "${t.prefix}"`:"ends_with"===t.format?`Neveljaven niz: mora se končati z "${t.suffix}"`:"includes"===t.format?`Neveljaven niz: mora vsebovati "${t.includes}"`:"regex"===t.format?`Neveljaven niz: mora ustrezati vzorcu ${t.pattern}`:`Neveljaven ${r[t.format]??e.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${e.divisor}`;case"unrecognized_keys":return`Neprepoznan${e.keys.length>1?"i ključi":" ključ"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${e.origin}`;case"invalid_union":default:return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${e.origin}`}}};function sl(){return{localeError:error$a()}}const error$9=()=>{const e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function t(t){return e[t]??null}const r={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return e=>{switch(e.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${e.expected}, fick ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"antal";case"object":if(Array.isArray(e))return"lista";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ogiltig inmatning: förväntat ${stringifyPrimitive(e.values[0])}`:`Ogiltigt val: förväntade en av ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`För stor(t): förväntade ${e.origin??"värdet"} att ha ${r}${e.maximum.toString()} ${n.unit??"element"}`:`För stor(t): förväntat ${e.origin??"värdet"} att ha ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`För lite(t): förväntade ${e.origin??"värdet"} att ha ${r}${e.minimum.toString()} ${n.unit}`:`För lite(t): förväntade ${e.origin??"värdet"} att ha ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ogiltig sträng: måste börja med "${t.prefix}"`:"ends_with"===t.format?`Ogiltig sträng: måste sluta med "${t.suffix}"`:"includes"===t.format?`Ogiltig sträng: måste innehålla "${t.includes}"`:"regex"===t.format?`Ogiltig sträng: måste matcha mönstret "${t.pattern}"`:`Ogiltig(t) ${r[t.format]??e.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${e.divisor}`;case"unrecognized_keys":return`${e.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${e.origin??"värdet"}`;case"invalid_union":default:return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${e.origin??"värdet"}`}}};function sv(){return{localeError:error$9()}}const error$8=()=>{const e={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function t(t){return e[t]??null}const r={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return e=>{switch(e.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${e.expected}, பெறப்பட்டது ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"எண் அல்லாதது":"எண்";case"object":if(Array.isArray(e))return"அணி";if(null===e)return"வெறுமை";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(e.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(e.values,"|")} இல் ஒன்று`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${r}${e.maximum.toString()} ${n.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${e.origin??"மதிப்பு"} ${r}${e.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${r}${e.minimum.toString()} ${n.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${e.origin} ${r}${e.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const t=e;return"starts_with"===t.format?`தவறான சரம்: "${t.prefix}" இல் தொடங்க வேண்டும்`:"ends_with"===t.format?`தவறான சரம்: "${t.suffix}" இல் முடிவடைய வேண்டும்`:"includes"===t.format?`தவறான சரம்: "${t.includes}" ஐ உள்ளடக்க வேண்டும்`:"regex"===t.format?`தவறான சரம்: ${t.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${r[t.format]??e.format}`}case"not_multiple_of":return`தவறான எண்: ${e.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${e.keys.length>1?"கள்":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} இல் தவறான விசை`;case"invalid_union":default:return"தவறான உள்ளீடு";case"invalid_element":return`${e.origin} இல் தவறான மதிப்பு`}}};function ta(){return{localeError:error$8()}}const error$7=()=>{const e={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function t(t){return e[t]??null}const r={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return e=>{switch(e.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${e.expected} แต่ได้รับ ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":if(Array.isArray(e))return"อาร์เรย์ (Array)";if(null===e)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(e.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"ไม่เกิน":"น้อยกว่า",n=t(e.origin);return n?`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${r} ${e.maximum.toString()} ${n.unit??"รายการ"}`:`เกินกำหนด: ${e.origin??"ค่า"} ควรมี${r} ${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?"อย่างน้อย":"มากกว่า",n=t(e.origin);return n?`น้อยกว่ากำหนด: ${e.origin} ควรมี${r} ${e.minimum.toString()} ${n.unit}`:`น้อยกว่ากำหนด: ${e.origin} ควรมี${r} ${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${t.prefix}"`:"ends_with"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${t.suffix}"`:"includes"===t.format?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${t.includes}" อยู่ในข้อความ`:"regex"===t.format?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${t.pattern}`:`รูปแบบไม่ถูกต้อง: ${r[t.format]??e.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${e.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${joinValues(e.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${e.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${e.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function th(){return{localeError:error$7()}}const parsedType=e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t},error$6=()=>{const e={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function t(t){return e[t]??null}const r={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return e=>{switch(e.code){case"invalid_type":return`Geçersiz değer: beklenen ${e.expected}, alınan ${parsedType(e.input)}`;case"invalid_value":return 1===e.values.length?`Geçersiz değer: beklenen ${stringifyPrimitive(e.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Çok büyük: beklenen ${e.origin??"değer"} ${r}${e.maximum.toString()} ${n.unit??"öğe"}`:`Çok büyük: beklenen ${e.origin??"değer"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Çok küçük: beklenen ${e.origin} ${r}${e.minimum.toString()} ${n.unit}`:`Çok küçük: beklenen ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Geçersiz metin: "${t.prefix}" ile başlamalı`:"ends_with"===t.format?`Geçersiz metin: "${t.suffix}" ile bitmeli`:"includes"===t.format?`Geçersiz metin: "${t.includes}" içermeli`:"regex"===t.format?`Geçersiz metin: ${t.pattern} desenine uymalı`:`Geçersiz ${r[t.format]??e.format}`}case"not_multiple_of":return`Geçersiz sayı: ${e.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${e.keys.length>1?"lar":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} içinde geçersiz anahtar`;case"invalid_union":default:return"Geçersiz değer";case"invalid_element":return`${e.origin} içinde geçersiz değer`}}};function tr(){return{localeError:error$6()}}const error$5=()=>{const e={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function t(t){return e[t]??null}const r={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return e=>{switch(e.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${e.expected}, отримано ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"число";case"object":if(Array.isArray(e))return"масив";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Неправильні вхідні дані: очікується ${stringifyPrimitive(e.values[0])}`:`Неправильна опція: очікується одне з ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Занадто велике: очікується, що ${e.origin??"значення"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"елементів"}`:`Занадто велике: очікується, що ${e.origin??"значення"} буде ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Занадто мале: очікується, що ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Занадто мале: очікується, що ${e.origin} буде ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Неправильний рядок: повинен починатися з "${t.prefix}"`:"ends_with"===t.format?`Неправильний рядок: повинен закінчуватися на "${t.suffix}"`:"includes"===t.format?`Неправильний рядок: повинен містити "${t.includes}"`:"regex"===t.format?`Неправильний рядок: повинен відповідати шаблону ${t.pattern}`:`Неправильний ${r[t.format]??e.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${e.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${e.keys.length>1?"і":""}: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${e.origin}`;case"invalid_union":default:return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${e.origin}`}}};function ua(){return{localeError:error$5()}}const error$4=()=>{const e={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function t(t){return e[t]??null}const r={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return e=>{switch(e.code){case"invalid_type":return`غلط ان پٹ: ${e.expected} متوقع تھا، ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"نمبر";case"object":if(Array.isArray(e))return"آرے";if(null===e)return"نل";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)} موصول ہوا`;case"invalid_value":return 1===e.values.length?`غلط ان پٹ: ${stringifyPrimitive(e.values[0])} متوقع تھا`:`غلط آپشن: ${joinValues(e.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`بہت بڑا: ${e.origin??"ویلیو"} کے ${r}${e.maximum.toString()} ${n.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${e.origin??"ویلیو"} کا ${r}${e.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`بہت چھوٹا: ${e.origin} کے ${r}${e.minimum.toString()} ${n.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${e.origin} کا ${r}${e.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const t=e;return"starts_with"===t.format?`غلط سٹرنگ: "${t.prefix}" سے شروع ہونا چاہیے`:"ends_with"===t.format?`غلط سٹرنگ: "${t.suffix}" پر ختم ہونا چاہیے`:"includes"===t.format?`غلط سٹرنگ: "${t.includes}" شامل ہونا چاہیے`:"regex"===t.format?`غلط سٹرنگ: پیٹرن ${t.pattern} سے میچ ہونا چاہیے`:`غلط ${r[t.format]??e.format}`}case"not_multiple_of":return`غلط نمبر: ${e.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${e.keys.length>1?"ز":""}: ${joinValues(e.keys,"، ")}`;case"invalid_key":return`${e.origin} میں غلط کی`;case"invalid_union":default:return"غلط ان پٹ";case"invalid_element":return`${e.origin} میں غلط ویلیو`}}};function ur(){return{localeError:error$4()}}const error$3=()=>{const e={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function t(t){return e[t]??null}const r={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return e=>{switch(e.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${e.expected}, nhận được ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"số";case"object":if(Array.isArray(e))return"mảng";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(e.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Quá lớn: mong đợi ${e.origin??"giá trị"} ${n.verb} ${r}${e.maximum.toString()} ${n.unit??"phần tử"}`:`Quá lớn: mong đợi ${e.origin??"giá trị"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Quá nhỏ: mong đợi ${e.origin} ${n.verb} ${r}${e.minimum.toString()} ${n.unit}`:`Quá nhỏ: mong đợi ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Chuỗi không hợp lệ: phải bắt đầu bằng "${t.prefix}"`:"ends_with"===t.format?`Chuỗi không hợp lệ: phải kết thúc bằng "${t.suffix}"`:"includes"===t.format?`Chuỗi không hợp lệ: phải bao gồm "${t.includes}"`:"regex"===t.format?`Chuỗi không hợp lệ: phải khớp với mẫu ${t.pattern}`:`${r[t.format]??e.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${e.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${e.origin}`;case"invalid_union":default:return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${e.origin}`}}};function vi(){return{localeError:error$3()}}const error$2=()=>{const e={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function t(t){return e[t]??null}const r={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return e=>{switch(e.code){case"invalid_type":return`无效输入:期望 ${e.expected},实际接收 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"非数字(NaN)":"数字";case"object":if(Array.isArray(e))return"数组";if(null===e)return"空值(null)";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`无效输入:期望 ${stringifyPrimitive(e.values[0])}`:`无效选项:期望以下之一 ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`数值过大:期望 ${e.origin??"值"} ${r}${e.maximum.toString()} ${n.unit??"个元素"}`:`数值过大:期望 ${e.origin??"值"} ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`数值过小:期望 ${e.origin} ${r}${e.minimum.toString()} ${n.unit}`:`数值过小:期望 ${e.origin} ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`无效字符串:必须以 "${t.prefix}" 开头`:"ends_with"===t.format?`无效字符串:必须以 "${t.suffix}" 结尾`:"includes"===t.format?`无效字符串:必须包含 "${t.includes}"`:"regex"===t.format?`无效字符串:必须满足正则表达式 ${t.pattern}`:`无效${r[t.format]??e.format}`}case"not_multiple_of":return`无效数字:必须是 ${e.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${joinValues(e.keys,", ")}`;case"invalid_key":return`${e.origin} 中的键(key)无效`;case"invalid_union":default:return"无效输入";case"invalid_element":return`${e.origin} 中包含无效值(value)`}}};function zhCN(){return{localeError:error$2()}}const error$1=()=>{const e={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function t(t){return e[t]??null}const r={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return e=>{switch(e.code){case"invalid_type":return`無效的輸入值:預期為 ${e.expected},但收到 ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":if(Array.isArray(e))return"array";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`無效的輸入值:預期為 ${stringifyPrimitive(e.values[0])}`:`無效的選項:預期為以下其中之一 ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`數值過大:預期 ${e.origin??"值"} 應為 ${r}${e.maximum.toString()} ${n.unit??"個元素"}`:`數值過大:預期 ${e.origin??"值"} 應為 ${r}${e.maximum.toString()}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`數值過小:預期 ${e.origin} 應為 ${r}${e.minimum.toString()} ${n.unit}`:`數值過小:預期 ${e.origin} 應為 ${r}${e.minimum.toString()}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`無效的字串:必須以 "${t.prefix}" 開頭`:"ends_with"===t.format?`無效的字串:必須以 "${t.suffix}" 結尾`:"includes"===t.format?`無效的字串:必須包含 "${t.includes}"`:"regex"===t.format?`無效的字串:必須符合格式 ${t.pattern}`:`無效的 ${r[t.format]??e.format}`}case"not_multiple_of":return`無效的數字:必須為 ${e.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${e.keys.length>1?"們":""}:${joinValues(e.keys,"、")}`;case"invalid_key":return`${e.origin} 中有無效的鍵值`;case"invalid_union":default:return"無效的輸入值";case"invalid_element":return`${e.origin} 中有無效的值`}}};function zhTW(){return{localeError:error$1()}}const error=()=>{const e={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function t(t){return e[t]??null}const r={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return e=>{switch(e.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${e.expected}, àmọ̀ a rí ${(e=>{const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"nọ́mbà";case"object":if(Array.isArray(e))return"akopọ";if(null===e)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}return t})(e.input)}`;case"invalid_value":return 1===e.values.length?`Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(e.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(e.values,"|")}`;case"too_big":{const r=e.inclusive?"<=":"<",n=t(e.origin);return n?`Tó pọ̀ jù: a ní láti jẹ́ pé ${e.origin??"iye"} ${n.verb} ${r}${e.maximum} ${n.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${r}${e.maximum}`}case"too_small":{const r=e.inclusive?">=":">",n=t(e.origin);return n?`Kéré ju: a ní láti jẹ́ pé ${e.origin} ${n.verb} ${r}${e.minimum} ${n.unit}`:`Kéré ju: a ní láti jẹ́ ${r}${e.minimum}`}case"invalid_format":{const t=e;return"starts_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${t.prefix}"`:"ends_with"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${t.suffix}"`:"includes"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${t.includes}"`:"regex"===t.format?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${t.pattern}`:`Aṣìṣe: ${r[t.format]??e.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${e.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${joinValues(e.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${e.origin}`;case"invalid_union":default:return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${e.origin}`}}};function yo(){return{localeError:error()}}var index$1=Object.freeze({__proto__:null,ar:ar,az:az,be:be,ca:ca,cs:cs,da:da,de:de,en:en,eo:eo,es:es,fa:fa,fi:fi,fr:fr,frCA:frCA,he:he,hu:hu,id:id,is:is,it:it,ja:ja,kh:kh,ko:ko,mk:mk,ms:ms,nl:nl,no:no,ota:ota,pl:pl,ps:ps,pt:pt,ru:ru,sl:sl,sv:sv,ta:ta,th:th,tr:tr,ua:ua,ur:ur,vi:vi,yo:yo,zhCN:zhCN,zhTW:zhTW});const $output=Symbol("ZodOutput"),$input=Symbol("ZodInput");class $ZodRegistry{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&"object"==typeof r&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function registry(){return new $ZodRegistry}const globalRegistry=registry();function _string(e,t){return new e({type:"string",...normalizeParams(t)})}function _coercedString(e,t){return new e({type:"string",coerce:!0,...normalizeParams(t)})}function _email(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(t)})}function _guid(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(t)})}function _uuid(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(t)})}function _uuidv4(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(t)})}function _uuidv6(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(t)})}function _uuidv7(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(t)})}function _url(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(t)})}function _emoji(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(t)})}function _nanoid(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(t)})}function _cuid(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(t)})}function _cuid2(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(t)})}function _ulid(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(t)})}function _xid(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(t)})}function _ksuid(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(t)})}function _ipv4(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(t)})}function _ipv6(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(t)})}function _cidrv4(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(t)})}function _cidrv6(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(t)})}function _base64(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(t)})}function _base64url(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(t)})}function _e164(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(t)})}function _jwt(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(t)})}const TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function _isoDateTime(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(t)})}function _isoDate(e,t){return new e({type:"string",format:"date",check:"string_format",...normalizeParams(t)})}function _isoTime(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(t)})}function _isoDuration(e,t){return new e({type:"string",format:"duration",check:"string_format",...normalizeParams(t)})}function _number(e,t){return new e({type:"number",checks:[],...normalizeParams(t)})}function _coercedNumber(e,t){return new e({type:"number",coerce:!0,checks:[],...normalizeParams(t)})}function _int(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(t)})}function _float32(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams(t)})}function _float64(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams(t)})}function _int32(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams(t)})}function _uint32(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams(t)})}function _boolean(e,t){return new e({type:"boolean",...normalizeParams(t)})}function _coercedBoolean(e,t){return new e({type:"boolean",coerce:!0,...normalizeParams(t)})}function _bigint(e,t){return new e({type:"bigint",...normalizeParams(t)})}function _coercedBigint(e,t){return new e({type:"bigint",coerce:!0,...normalizeParams(t)})}function _int64(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams(t)})}function _uint64(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams(t)})}function _symbol(e,t){return new e({type:"symbol",...normalizeParams(t)})}function _undefined$1(e,t){return new e({type:"undefined",...normalizeParams(t)})}function _null$1(e,t){return new e({type:"null",...normalizeParams(t)})}function _any(e){return new e({type:"any"})}function _unknown(e){return new e({type:"unknown"})}function _never(e,t){return new e({type:"never",...normalizeParams(t)})}function _void$1(e,t){return new e({type:"void",...normalizeParams(t)})}function _date(e,t){return new e({type:"date",...normalizeParams(t)})}function _coercedDate(e,t){return new e({type:"date",coerce:!0,...normalizeParams(t)})}function _nan(e,t){return new e({type:"nan",...normalizeParams(t)})}function _lt(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:!1})}function _lte(e,t){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(t),value:e,inclusive:!0})}function _gt(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:!1})}function _gte(e,t){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(t),value:e,inclusive:!0})}function _positive(e){return _gt(0,e)}function _negative(e){return _lt(0,e)}function _nonpositive(e){return _lte(0,e)}function _nonnegative(e){return _gte(0,e)}function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(t),value:e})}function _maxSize(e,t){return new $ZodCheckMaxSize({check:"max_size",...normalizeParams(t),maximum:e})}function _minSize(e,t){return new $ZodCheckMinSize({check:"min_size",...normalizeParams(t),minimum:e})}function _size(e,t){return new $ZodCheckSizeEquals({check:"size_equals",...normalizeParams(t),size:e})}function _maxLength(e,t){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(t),maximum:e})}function _minLength(e,t){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(t),minimum:e})}function _length(e,t){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(t),length:e})}function _regex(e,t){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(t),pattern:e})}function _lowercase(e){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(e)})}function _uppercase(e){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(e)})}function _includes(e,t){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(t),includes:e})}function _startsWith(e,t){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(t),prefix:e})}function _endsWith(e,t){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(t),suffix:e})}function _property(e,t,r){return new $ZodCheckProperty({check:"property",property:e,schema:t,...normalizeParams(r)})}function _mime(e,t){return new $ZodCheckMimeType({check:"mime_type",mime:e,...normalizeParams(t)})}function _overwrite(e){return new $ZodCheckOverwrite({check:"overwrite",tx:e})}function _normalize(e){return _overwrite(t=>t.normalize(e))}function _trim(){return _overwrite(e=>e.trim())}function _toLowerCase(){return _overwrite(e=>e.toLowerCase())}function _toUpperCase(){return _overwrite(e=>e.toUpperCase())}function _array(e,t,r){return new e({type:"array",element:t,...normalizeParams(r)})}function _union(e,t,r){return new e({type:"union",options:t,...normalizeParams(r)})}function _discriminatedUnion(e,t,r,n){return new e({type:"union",options:r,discriminator:t,...normalizeParams(n)})}function _intersection(e,t,r){return new e({type:"intersection",left:t,right:r})}function _tuple(e,t,r,n){const i=r instanceof $ZodType;return new e({type:"tuple",items:t,rest:i?r:null,...normalizeParams(i?n:r)})}function _record(e,t,r,n){return new e({type:"record",keyType:t,valueType:r,...normalizeParams(n)})}function _map(e,t,r,n){return new e({type:"map",keyType:t,valueType:r,...normalizeParams(n)})}function _set(e,t,r){return new e({type:"set",valueType:t,...normalizeParams(r)})}function _enum$1(e,t,r){const n=Array.isArray(t)?Object.fromEntries(t.map(e=>[e,e])):t;return new e({type:"enum",entries:n,...normalizeParams(r)})}function _nativeEnum(e,t,r){return new e({type:"enum",entries:t,...normalizeParams(r)})}function _literal(e,t,r){return new e({type:"literal",values:Array.isArray(t)?t:[t],...normalizeParams(r)})}function _file(e,t){return new e({type:"file",...normalizeParams(t)})}function _transform(e,t){return new e({type:"transform",transform:t})}function _optional(e,t){return new e({type:"optional",innerType:t})}function _nullable(e,t){return new e({type:"nullable",innerType:t})}function _default$1(e,t,r){return new e({type:"default",innerType:t,get defaultValue(){return"function"==typeof r?r():shallowClone(r)}})}function _nonoptional(e,t,r){return new e({type:"nonoptional",innerType:t,...normalizeParams(r)})}function _success(e,t){return new e({type:"success",innerType:t})}function _catch$1(e,t,r){return new e({type:"catch",innerType:t,catchValue:"function"==typeof r?r:()=>r})}function _pipe(e,t,r){return new e({type:"pipe",in:t,out:r})}function _readonly(e,t){return new e({type:"readonly",innerType:t})}function _templateLiteral(e,t,r){return new e({type:"template_literal",parts:t,...normalizeParams(r)})}function _lazy(e,t){return new e({type:"lazy",getter:t})}function _promise(e,t){return new e({type:"promise",innerType:t})}function _custom(e,t,r){const n=normalizeParams(r);n.abort??(n.abort=!0);return new e({type:"custom",check:"custom",fn:t,...n})}function _refine(e,t,r){return new e({type:"custom",check:"custom",fn:t,...normalizeParams(r)})}function _superRefine(e){const t=_check(r=>(r.addIssue=e=>{if("string"==typeof e)r.issues.push(issue(e,r.value,t._zod.def));else{const n=e;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=t),n.continue??(n.continue=!t._zod.def.abort),r.issues.push(issue(n))}},e(r.value,r)));return t}function _check(e,t){const r=new $ZodCheck({check:"custom",...normalizeParams(t)});return r._zod.check=e,r}function _stringbool(e,t){const r=normalizeParams(t);let n=r.truthy??["true","1","yes","on","y","enabled"],i=r.falsy??["false","0","no","off","n","disabled"];"sensitive"!==r.case&&(n=n.map(e=>"string"==typeof e?e.toLowerCase():e),i=i.map(e=>"string"==typeof e?e.toLowerCase():e));const o=new Set(n),s=new Set(i),a=e.Pipe??$ZodPipe,c=e.Boolean??$ZodBoolean,l=e.String??$ZodString,u=new(e.Transform??$ZodTransform)({type:"transform",transform:(e,t)=>{let n=e;return"sensitive"!==r.case&&(n=n.toLowerCase()),!!o.has(n)||!s.has(n)&&(t.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:t.value,inst:u,continue:!1}),{})},error:r.error}),d=new a({type:"pipe",in:new l({type:"string",error:r.error}),out:u,error:r.error});return new a({type:"pipe",in:d,out:new c({type:"boolean",error:r.error}),error:r.error})}function _stringFormat(e,t,r,n={}){const i=normalizeParams(n),o={...normalizeParams(n),check:"string_format",type:"string",format:t,fn:"function"==typeof r?r:e=>r.test(e),...i};r instanceof RegExp&&(o.pattern=r);return new e(o)}class $ZodFunction{constructor(e){this._def=e,this.def=e}implement(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=(...r)=>{const n=this._def.input?parse$1(this._def.input,r,void 0,{callee:t}):r;if(!Array.isArray(n))throw new Error("Invalid arguments schema: not an array or tuple schema.");const i=e(...n);return this._def.output?parse$1(this._def.output,i,void 0,{callee:t}):i};return t}implementAsync(e){if("function"!=typeof e)throw new Error("implement() must be called with a function");const t=async(...r)=>{const n=this._def.input?await parseAsync$1(this._def.input,r,void 0,{callee:t}):r;if(!Array.isArray(n))throw new Error("Invalid arguments schema: not an array or tuple schema.");const i=await e(...n);return this._def.output?parseAsync$1(this._def.output,i,void 0,{callee:t}):i};return t}input(...e){const t=this.constructor;return Array.isArray(e[0])?new t({type:"function",input:new $ZodTuple({type:"tuple",items:e[0],rest:e[1]}),output:this._def.output}):new t({type:"function",input:e[0],output:this._def.output})}output(e){return new(0,this.constructor)({type:"function",input:this._def.input,output:e})}}function _function(e){return new $ZodFunction({type:"function",input:Array.isArray(e?.input)?_tuple($ZodTuple,e?.input):e?.input??_array($ZodArray,_unknown($ZodUnknown)),output:e?.output??_unknown($ZodUnknown)})}class JSONSchemaGenerator{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??globalRegistry,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;const n=e._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o){o.count++;return t.schemaPath.includes(e)&&(o.cycle=t.path),o.schema}const s={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const r={...t,schemaPath:[...t.schemaPath,e],path:t.path},o=e._zod.parent;if(o)s.ref=o,this.process(o,r),this.seen.get(o).isParent=!0;else{const t=s.schema;switch(n.type){case"string":{const r=t;r.type="string";const{minimum:n,maximum:o,format:a,patterns:c,contentEncoding:l}=e._zod.bag;if("number"==typeof n&&(r.minLength=n),"number"==typeof o&&(r.maxLength=o),a&&(r.format=i[a]??a,""===r.format&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const e=[...c];1===e.length?r.pattern=e[0].source:e.length>1&&(s.schema.allOf=[...e.map(e=>({..."draft-7"===this.target||"draft-4"===this.target?{type:"string"}:{},pattern:e.source}))])}break}case"number":{const r=t,{minimum:n,maximum:i,format:o,multipleOf:s,exclusiveMaximum:a,exclusiveMinimum:c}=e._zod.bag;"string"==typeof o&&o.includes("int")?r.type="integer":r.type="number","number"==typeof c&&("draft-4"===this.target?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),"number"==typeof n&&(r.minimum=n,"number"==typeof c&&"draft-4"!==this.target&&(c>=n?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof a&&("draft-4"===this.target?(r.maximum=a,r.exclusiveMaximum=!0):r.exclusiveMaximum=a),"number"==typeof i&&(r.maximum=i,"number"==typeof a&&"draft-4"!==this.target&&(a<=i?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof s&&(r.multipleOf=s);break}case"boolean":t.type="boolean";break;case"bigint":if("throw"===this.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema");break;case"symbol":if("throw"===this.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema");break;case"null":t.type="null";break;case"any":case"unknown":break;case"undefined":if("throw"===this.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema");break;case"void":if("throw"===this.unrepresentable)throw new Error("Void cannot be represented in JSON Schema");break;case"never":t.not={};break;case"date":if("throw"===this.unrepresentable)throw new Error("Date cannot be represented in JSON Schema");break;case"array":{const i=t,{minimum:o,maximum:s}=e._zod.bag;"number"==typeof o&&(i.minItems=o),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=this.process(n.element,{...r,path:[...r.path,"items"]});break}case"object":{const e=t;e.type="object",e.properties={};const i=n.shape;for(const t in i)e.properties[t]=this.process(i[t],{...r,path:[...r.path,"properties",t]});const o=new Set(Object.keys(i)),s=new Set([...o].filter(e=>{const t=n.shape[e]._zod;return"input"===this.io?void 0===t.optin:void 0===t.optout}));s.size>0&&(e.required=Array.from(s)),"never"===n.catchall?._zod.def.type?e.additionalProperties=!1:n.catchall?n.catchall&&(e.additionalProperties=this.process(n.catchall,{...r,path:[...r.path,"additionalProperties"]})):"output"===this.io&&(e.additionalProperties=!1);break}case"union":t.anyOf=n.options.map((e,t)=>this.process(e,{...r,path:[...r.path,"anyOf",t]}));break;case"intersection":{const e=t,i=this.process(n.left,{...r,path:[...r.path,"allOf",0]}),o=this.process(n.right,{...r,path:[...r.path,"allOf",1]}),s=e=>"allOf"in e&&1===Object.keys(e).length,a=[...s(i)?i.allOf:[i],...s(o)?o.allOf:[o]];e.allOf=a;break}case"tuple":{const i=t;i.type="array";const o=n.items.map((e,t)=>this.process(e,{...r,path:[...r.path,"prefixItems",t]}));if("draft-2020-12"===this.target?i.prefixItems=o:i.items=o,n.rest){const e=this.process(n.rest,{...r,path:[...r.path,"items"]});"draft-2020-12"===this.target?i.items=e:i.additionalItems=e}n.rest&&(i.items=this.process(n.rest,{...r,path:[...r.path,"items"]}));const{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a);break}case"record":{const e=t;e.type="object","draft-4"!==this.target&&(e.propertyNames=this.process(n.keyType,{...r,path:[...r.path,"propertyNames"]})),e.additionalProperties=this.process(n.valueType,{...r,path:[...r.path,"additionalProperties"]});break}case"map":if("throw"===this.unrepresentable)throw new Error("Map cannot be represented in JSON Schema");break;case"set":if("throw"===this.unrepresentable)throw new Error("Set cannot be represented in JSON Schema");break;case"enum":{const e=t,r=getEnumValues(n.entries);r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),e.enum=r;break}case"literal":{const e=t,r=[];for(const e of n.values)if(void 0===e){if("throw"===this.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===this.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(e))}else r.push(e);if(0===r.length);else if(1===r.length){const t=r[0];e.type=null===t?"null":typeof t,"draft-4"===this.target?e.enum=[t]:e.const=t}else r.every(e=>"number"==typeof e)&&(e.type="number"),r.every(e=>"string"==typeof e)&&(e.type="string"),r.every(e=>"boolean"==typeof e)&&(e.type="string"),r.every(e=>null===e)&&(e.type="null"),e.enum=r;break}case"file":{const r=t,n={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:o,mime:s}=e._zod.bag;void 0!==i&&(n.minLength=i),void 0!==o&&(n.maxLength=o),s?1===s.length?(n.contentMediaType=s[0],Object.assign(r,n)):r.anyOf=s.map(e=>({...n,contentMediaType:e})):Object.assign(r,n);break}case"transform":if("throw"===this.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema");break;case"nullable":{const e=this.process(n.innerType,r);t.anyOf=[e,{type:"null"}];break}case"nonoptional":case"promise":case"optional":this.process(n.innerType,r),s.ref=n.innerType;break;case"success":t.type="boolean";break;case"default":this.process(n.innerType,r),s.ref=n.innerType,t.default=JSON.parse(JSON.stringify(n.defaultValue));break;case"prefault":this.process(n.innerType,r),s.ref=n.innerType,"input"===this.io&&(t._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break;case"catch":{let e;this.process(n.innerType,r),s.ref=n.innerType;try{e=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=e;break}case"nan":if("throw"===this.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema");break;case"template_literal":{const r=t,n=e._zod.pattern;if(!n)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=n.source;break}case"pipe":{const e="input"===this.io?"transform"===n.in._zod.def.type?n.out:n.in:n.out;this.process(e,r),s.ref=e;break}case"readonly":this.process(n.innerType,r),s.ref=n.innerType,t.readOnly=!0;break;case"lazy":{const t=e._zod.innerType;this.process(t,r),s.ref=t;break}case"custom":if("throw"===this.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")}}}const c=this.metadataRegistry.get(e);c&&Object.assign(s.schema,c),"input"===this.io&&isTransforming(e)&&(delete s.schema.examples,delete s.schema.default),"input"===this.io&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault;return this.seen.get(e).schema}emit(e,t){const r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=e=>{const t="draft-2020-12"===this.target?"$defs":"definitions";if(r.external){const n=r.external.registry.get(e[0])?.id,i=r.external.uri??(e=>e);if(n)return{ref:i(n)};const o=e[1].defId??e[1].schema.id??"schema"+this.counter++;return e[1].defId=o,{defId:o,ref:`${i("__shared")}#/${t}/${o}`}}if(e[1]===n)return{ref:"#"};const i=`#/${t}/`,o=e[1].schema.id??"__schema"+this.counter++;return{defId:o,ref:i+o}},o=e=>{if(e[1].schema.$ref)return;const t=e[1],{ref:r,defId:n}=i(e);t.def={...t.schema},n&&(t.defId=n);const o=t.schema;for(const e in o)delete o[e];o.$ref=r};if("throw"===r.cycles)for(const e of this.seen.entries()){const t=e[1];if(t.cycle)throw new Error(`Cycle detected: #/${t.cycle?.join("/")}/\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const t of this.seen.entries()){const n=t[1];if(e===t[0]){o(t);continue}if(r.external){const n=r.external.registry.get(t[0])?.id;if(e!==t[0]&&n){o(t);continue}}const i=this.metadataRegistry.get(t[0])?.id;i?o(t):(n.cycle||n.count>1&&"ref"===r.reused)&&o(t)}const s=(e,t)=>{const r=this.seen.get(e),n=r.def??r.schema,i={...n};if(null===r.ref)return;const o=r.ref;if(r.ref=null,o){s(o,t);const e=this.seen.get(o).schema;!e.$ref||"draft-7"!==t.target&&"draft-4"!==t.target?(Object.assign(n,e),Object.assign(n,i)):(n.allOf=n.allOf??[],n.allOf.push(e))}r.isParent||this.override({zodSchema:e,jsonSchema:n,path:r.path??[]})};for(const e of[...this.seen.entries()].reverse())s(e[0],{target:this.target});const a={};if("draft-2020-12"===this.target?a.$schema="https://json-schema.org/draft/2020-12/schema":"draft-7"===this.target?a.$schema="http://json-schema.org/draft-07/schema#":"draft-4"===this.target?a.$schema="http://json-schema.org/draft-04/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const t=r.external.registry.get(e)?.id;if(!t)throw new Error("Schema is missing an `id` property");a.$id=r.external.uri(t)}Object.assign(a,n.def);const c=r.external?.defs??{};for(const e of this.seen.entries()){const t=e[1];t.def&&t.defId&&(c[t.defId]=t.def)}r.external||Object.keys(c).length>0&&("draft-2020-12"===this.target?a.$defs=c:a.definitions=c);try{return JSON.parse(JSON.stringify(a))}catch(e){throw new Error("Error converting schema to JSON.")}}}function toJSONSchema(e,t){if(e instanceof $ZodRegistry){const r=new JSONSchemaGenerator(t),n={};for(const t of e._idmap.entries()){const[e,n]=t;r.process(n)}const i={},o={registry:e,uri:t?.uri,defs:n};for(const n of e._idmap.entries()){const[e,s]=n;i[e]=r.emit(s,{...t,external:o})}if(Object.keys(n).length>0){const e="draft-2020-12"===r.target?"$defs":"definitions";i.__shared={[e]:n}}return{schemas:i}}const r=new JSONSchemaGenerator(t);return r.process(e),r.emit(e,t)}function isTransforming(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;switch(n.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":case"custom":case"success":case"catch":return!1;case"array":return isTransforming(n.element,r);case"object":for(const e in n.shape)if(isTransforming(n.shape[e],r))return!0;return!1;case"union":for(const e of n.options)if(isTransforming(e,r))return!0;return!1;case"intersection":return isTransforming(n.left,r)||isTransforming(n.right,r);case"tuple":for(const e of n.items)if(isTransforming(e,r))return!0;return!(!n.rest||!isTransforming(n.rest,r));case"record":case"map":return isTransforming(n.keyType,r)||isTransforming(n.valueType,r);case"set":return isTransforming(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":case"default":case"prefault":return isTransforming(n.innerType,r);case"lazy":return isTransforming(n.getter(),r);case"transform":return!0;case"pipe":return isTransforming(n.in,r)||isTransforming(n.out,r)}throw new Error(`Unknown schema type: ${n.type}`)}var jsonSchema=Object.freeze({__proto__:null}),index=Object.freeze({__proto__:null,$ZodAny:$ZodAny,$ZodArray:$ZodArray,$ZodAsyncError:$ZodAsyncError,$ZodBase64:$ZodBase64,$ZodBase64URL:$ZodBase64URL,$ZodBigInt:$ZodBigInt,$ZodBigIntFormat:$ZodBigIntFormat,$ZodBoolean:$ZodBoolean,$ZodCIDRv4:$ZodCIDRv4,$ZodCIDRv6:$ZodCIDRv6,$ZodCUID:$ZodCUID,$ZodCUID2:$ZodCUID2,$ZodCatch:$ZodCatch,$ZodCheck:$ZodCheck,$ZodCheckBigIntFormat:$ZodCheckBigIntFormat,$ZodCheckEndsWith:$ZodCheckEndsWith,$ZodCheckGreaterThan:$ZodCheckGreaterThan,$ZodCheckIncludes:$ZodCheckIncludes,$ZodCheckLengthEquals:$ZodCheckLengthEquals,$ZodCheckLessThan:$ZodCheckLessThan,$ZodCheckLowerCase:$ZodCheckLowerCase,$ZodCheckMaxLength:$ZodCheckMaxLength,$ZodCheckMaxSize:$ZodCheckMaxSize,$ZodCheckMimeType:$ZodCheckMimeType,$ZodCheckMinLength:$ZodCheckMinLength,$ZodCheckMinSize:$ZodCheckMinSize,$ZodCheckMultipleOf:$ZodCheckMultipleOf,$ZodCheckNumberFormat:$ZodCheckNumberFormat,$ZodCheckOverwrite:$ZodCheckOverwrite,$ZodCheckProperty:$ZodCheckProperty,$ZodCheckRegex:$ZodCheckRegex,$ZodCheckSizeEquals:$ZodCheckSizeEquals,$ZodCheckStartsWith:$ZodCheckStartsWith,$ZodCheckStringFormat:$ZodCheckStringFormat,$ZodCheckUpperCase:$ZodCheckUpperCase,$ZodCustom:$ZodCustom,$ZodCustomStringFormat:$ZodCustomStringFormat,$ZodDate:$ZodDate,$ZodDefault:$ZodDefault,$ZodDiscriminatedUnion:$ZodDiscriminatedUnion,$ZodE164:$ZodE164,$ZodEmail:$ZodEmail,$ZodEmoji:$ZodEmoji,$ZodEnum:$ZodEnum,$ZodError:$ZodError,$ZodFile:$ZodFile,$ZodFunction:$ZodFunction,$ZodGUID:$ZodGUID,$ZodIPv4:$ZodIPv4,$ZodIPv6:$ZodIPv6,$ZodISODate:$ZodISODate,$ZodISODateTime:$ZodISODateTime,$ZodISODuration:$ZodISODuration,$ZodISOTime:$ZodISOTime,$ZodIntersection:$ZodIntersection,$ZodJWT:$ZodJWT,$ZodKSUID:$ZodKSUID,$ZodLazy:$ZodLazy,$ZodLiteral:$ZodLiteral,$ZodMap:$ZodMap,$ZodNaN:$ZodNaN,$ZodNanoID:$ZodNanoID,$ZodNever:$ZodNever,$ZodNonOptional:$ZodNonOptional,$ZodNull:$ZodNull,$ZodNullable:$ZodNullable,$ZodNumber:$ZodNumber,$ZodNumberFormat:$ZodNumberFormat,$ZodObject:$ZodObject,$ZodOptional:$ZodOptional,$ZodPipe:$ZodPipe,$ZodPrefault:$ZodPrefault,$ZodPromise:$ZodPromise,$ZodReadonly:$ZodReadonly,$ZodRealError:$ZodRealError,$ZodRecord:$ZodRecord,$ZodRegistry:$ZodRegistry,$ZodSet:$ZodSet,$ZodString:$ZodString,$ZodStringFormat:$ZodStringFormat,$ZodSuccess:$ZodSuccess,$ZodSymbol:$ZodSymbol,$ZodTemplateLiteral:$ZodTemplateLiteral,$ZodTransform:$ZodTransform,$ZodTuple:$ZodTuple,$ZodType:$ZodType,$ZodULID:$ZodULID,$ZodURL:$ZodURL,$ZodUUID:$ZodUUID,$ZodUndefined:$ZodUndefined,$ZodUnion:$ZodUnion,$ZodUnknown:$ZodUnknown,$ZodVoid:$ZodVoid,$ZodXID:$ZodXID,$brand:$brand,$constructor:$constructor,$input:$input,$output:$output,Doc:Doc,JSONSchema:jsonSchema,JSONSchemaGenerator:JSONSchemaGenerator,NEVER:NEVER,TimePrecision:TimePrecision,_any:_any,_array:_array,_base64:_base64,_base64url:_base64url,_bigint:_bigint,_boolean:_boolean,_catch:_catch$1,_check:_check,_cidrv4:_cidrv4,_cidrv6:_cidrv6,_coercedBigint:_coercedBigint,_coercedBoolean:_coercedBoolean,_coercedDate:_coercedDate,_coercedNumber:_coercedNumber,_coercedString:_coercedString,_cuid:_cuid,_cuid2:_cuid2,_custom:_custom,_date:_date,_default:_default$1,_discriminatedUnion:_discriminatedUnion,_e164:_e164,_email:_email,_emoji:_emoji,_endsWith:_endsWith,_enum:_enum$1,_file:_file,_float32:_float32,_float64:_float64,_gt:_gt,_gte:_gte,_guid:_guid,_includes:_includes,_int:_int,_int32:_int32,_int64:_int64,_intersection:_intersection,_ipv4:_ipv4,_ipv6:_ipv6,_isoDate:_isoDate,_isoDateTime:_isoDateTime,_isoDuration:_isoDuration,_isoTime:_isoTime,_jwt:_jwt,_ksuid:_ksuid,_lazy:_lazy,_length:_length,_literal:_literal,_lowercase:_lowercase,_lt:_lt,_lte:_lte,_map:_map,_max:_lte,_maxLength:_maxLength,_maxSize:_maxSize,_mime:_mime,_min:_gte,_minLength:_minLength,_minSize:_minSize,_multipleOf:_multipleOf,_nan:_nan,_nanoid:_nanoid,_nativeEnum:_nativeEnum,_negative:_negative,_never:_never,_nonnegative:_nonnegative,_nonoptional:_nonoptional,_nonpositive:_nonpositive,_normalize:_normalize,_null:_null$1,_nullable:_nullable,_number:_number,_optional:_optional,_overwrite:_overwrite,_parse:_parse,_parseAsync:_parseAsync,_pipe:_pipe,_positive:_positive,_promise:_promise,_property:_property,_readonly:_readonly,_record:_record,_refine:_refine,_regex:_regex,_safeParse:_safeParse,_safeParseAsync:_safeParseAsync,_set:_set,_size:_size,_startsWith:_startsWith,_string:_string,_stringFormat:_stringFormat,_stringbool:_stringbool,_success:_success,_superRefine:_superRefine,_symbol:_symbol,_templateLiteral:_templateLiteral,_toLowerCase:_toLowerCase,_toUpperCase:_toUpperCase,_transform:_transform,_trim:_trim,_tuple:_tuple,_uint32:_uint32,_uint64:_uint64,_ulid:_ulid,_undefined:_undefined$1,_union:_union,_unknown:_unknown,_uppercase:_uppercase,_url:_url,_uuid:_uuid,_uuidv4:_uuidv4,_uuidv6:_uuidv6,_uuidv7:_uuidv7,_void:_void$1,_xid:_xid,clone:clone,config:config,flattenError:flattenError,formatError:formatError,function:_function,globalConfig:globalConfig,globalRegistry:globalRegistry,isValidBase64:isValidBase64,isValidBase64URL:isValidBase64URL,isValidJWT:isValidJWT,locales:index$1,parse:parse$1,parseAsync:parseAsync$1,prettifyError:prettifyError,regexes:regexes,registry:registry,safeParse:safeParse$1,safeParseAsync:safeParseAsync$1,toDotPath:toDotPath,toJSONSchema:toJSONSchema,treeifyError:treeifyError,util:util,version:version});const ZodISODateTime=$constructor("ZodISODateTime",(e,t)=>{$ZodISODateTime.init(e,t),ZodStringFormat.init(e,t)});function datetime(e){return _isoDateTime(ZodISODateTime,e)}const ZodISODate=$constructor("ZodISODate",(e,t)=>{$ZodISODate.init(e,t),ZodStringFormat.init(e,t)});function date$2(e){return _isoDate(ZodISODate,e)}const ZodISOTime=$constructor("ZodISOTime",(e,t)=>{$ZodISOTime.init(e,t),ZodStringFormat.init(e,t)});function time(e){return _isoTime(ZodISOTime,e)}const ZodISODuration=$constructor("ZodISODuration",(e,t)=>{$ZodISODuration.init(e,t),ZodStringFormat.init(e,t)});function duration(e){return _isoDuration(ZodISODuration,e)}var iso=Object.freeze({__proto__:null,ZodISODate:ZodISODate,ZodISODateTime:ZodISODateTime,ZodISODuration:ZodISODuration,ZodISOTime:ZodISOTime,date:date$2,datetime:datetime,duration:duration,time:time});const initializer=(e,t)=>{$ZodError.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>formatError(e,t)},flatten:{value:t=>flattenError(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}},isEmpty:{get:()=>0===e.issues.length}})},ZodError=$constructor("ZodError",initializer),ZodRealError=$constructor("ZodError",initializer,{Parent:Error}),parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),ZodType=$constructor("ZodType",(e,t)=>($ZodType.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),e.clone=(t,r)=>clone(e,t,r),e.brand=()=>e,e.register=(t,r)=>(t.add(e,r),e),e.parse=(t,r)=>parse(e,t,r,{callee:e.parse}),e.safeParse=(t,r)=>safeParse(e,t,r),e.parseAsync=async(t,r)=>parseAsync(e,t,r,{callee:e.parseAsync}),e.safeParseAsync=async(t,r)=>safeParseAsync(e,t,r),e.spa=e.safeParseAsync,e.refine=(t,r)=>e.check(refine(t,r)),e.superRefine=t=>e.check(superRefine(t)),e.overwrite=t=>e.check(_overwrite(t)),e.optional=()=>optional(e),e.nullable=()=>nullable(e),e.nullish=()=>optional(nullable(e)),e.nonoptional=t=>nonoptional(e,t),e.array=()=>array(e),e.or=t=>union([e,t]),e.and=t=>intersection(e,t),e.transform=t=>pipe(e,transform(t)),e.default=t=>_default(e,t),e.prefault=t=>prefault(e,t),e.catch=t=>_catch(e,t),e.pipe=t=>pipe(e,t),e.readonly=()=>readonly(e),e.describe=t=>{const r=e.clone();return globalRegistry.add(r,{description:t}),r},Object.defineProperty(e,"description",{get:()=>globalRegistry.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return globalRegistry.get(e);const r=e.clone();return globalRegistry.add(r,t[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),_ZodString=$constructor("_ZodString",(e,t)=>{$ZodString.init(e,t),ZodType.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...t)=>e.check(_regex(...t)),e.includes=(...t)=>e.check(_includes(...t)),e.startsWith=(...t)=>e.check(_startsWith(...t)),e.endsWith=(...t)=>e.check(_endsWith(...t)),e.min=(...t)=>e.check(_minLength(...t)),e.max=(...t)=>e.check(_maxLength(...t)),e.length=(...t)=>e.check(_length(...t)),e.nonempty=(...t)=>e.check(_minLength(1,...t)),e.lowercase=t=>e.check(_lowercase(t)),e.uppercase=t=>e.check(_uppercase(t)),e.trim=()=>e.check(_trim()),e.normalize=(...t)=>e.check(_normalize(...t)),e.toLowerCase=()=>e.check(_toLowerCase()),e.toUpperCase=()=>e.check(_toUpperCase())}),ZodString=$constructor("ZodString",(e,t)=>{$ZodString.init(e,t),_ZodString.init(e,t),e.email=t=>e.check(_email(ZodEmail,t)),e.url=t=>e.check(_url(ZodURL,t)),e.jwt=t=>e.check(_jwt(ZodJWT,t)),e.emoji=t=>e.check(_emoji(ZodEmoji,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.uuid=t=>e.check(_uuid(ZodUUID,t)),e.uuidv4=t=>e.check(_uuidv4(ZodUUID,t)),e.uuidv6=t=>e.check(_uuidv6(ZodUUID,t)),e.uuidv7=t=>e.check(_uuidv7(ZodUUID,t)),e.nanoid=t=>e.check(_nanoid(ZodNanoID,t)),e.guid=t=>e.check(_guid(ZodGUID,t)),e.cuid=t=>e.check(_cuid(ZodCUID,t)),e.cuid2=t=>e.check(_cuid2(ZodCUID2,t)),e.ulid=t=>e.check(_ulid(ZodULID,t)),e.base64=t=>e.check(_base64(ZodBase64,t)),e.base64url=t=>e.check(_base64url(ZodBase64URL,t)),e.xid=t=>e.check(_xid(ZodXID,t)),e.ksuid=t=>e.check(_ksuid(ZodKSUID,t)),e.ipv4=t=>e.check(_ipv4(ZodIPv4,t)),e.ipv6=t=>e.check(_ipv6(ZodIPv6,t)),e.cidrv4=t=>e.check(_cidrv4(ZodCIDRv4,t)),e.cidrv6=t=>e.check(_cidrv6(ZodCIDRv6,t)),e.e164=t=>e.check(_e164(ZodE164,t)),e.datetime=t=>e.check(datetime(t)),e.date=t=>e.check(date$2(t)),e.time=t=>e.check(time(t)),e.duration=t=>e.check(duration(t))});function string$1(e){return _string(ZodString,e)}const ZodStringFormat=$constructor("ZodStringFormat",(e,t)=>{$ZodStringFormat.init(e,t),_ZodString.init(e,t)}),ZodEmail=$constructor("ZodEmail",(e,t)=>{$ZodEmail.init(e,t),ZodStringFormat.init(e,t)});function email(e){return _email(ZodEmail,e)}const ZodGUID=$constructor("ZodGUID",(e,t)=>{$ZodGUID.init(e,t),ZodStringFormat.init(e,t)});function guid(e){return _guid(ZodGUID,e)}const ZodUUID=$constructor("ZodUUID",(e,t)=>{$ZodUUID.init(e,t),ZodStringFormat.init(e,t)});function uuid(e){return _uuid(ZodUUID,e)}function uuidv4(e){return _uuidv4(ZodUUID,e)}function uuidv6(e){return _uuidv6(ZodUUID,e)}function uuidv7(e){return _uuidv7(ZodUUID,e)}const ZodURL=$constructor("ZodURL",(e,t)=>{$ZodURL.init(e,t),ZodStringFormat.init(e,t)});function url(e){return _url(ZodURL,e)}const ZodEmoji=$constructor("ZodEmoji",(e,t)=>{$ZodEmoji.init(e,t),ZodStringFormat.init(e,t)});function emoji(e){return _emoji(ZodEmoji,e)}const ZodNanoID=$constructor("ZodNanoID",(e,t)=>{$ZodNanoID.init(e,t),ZodStringFormat.init(e,t)});function nanoid$1(e){return _nanoid(ZodNanoID,e)}const ZodCUID=$constructor("ZodCUID",(e,t)=>{$ZodCUID.init(e,t),ZodStringFormat.init(e,t)});function cuid(e){return _cuid(ZodCUID,e)}const ZodCUID2=$constructor("ZodCUID2",(e,t)=>{$ZodCUID2.init(e,t),ZodStringFormat.init(e,t)});function cuid2(e){return _cuid2(ZodCUID2,e)}const ZodULID=$constructor("ZodULID",(e,t)=>{$ZodULID.init(e,t),ZodStringFormat.init(e,t)});function ulid(e){return _ulid(ZodULID,e)}const ZodXID=$constructor("ZodXID",(e,t)=>{$ZodXID.init(e,t),ZodStringFormat.init(e,t)});function xid(e){return _xid(ZodXID,e)}const ZodKSUID=$constructor("ZodKSUID",(e,t)=>{$ZodKSUID.init(e,t),ZodStringFormat.init(e,t)});function ksuid(e){return _ksuid(ZodKSUID,e)}const ZodIPv4=$constructor("ZodIPv4",(e,t)=>{$ZodIPv4.init(e,t),ZodStringFormat.init(e,t)});function ipv4(e){return _ipv4(ZodIPv4,e)}const ZodIPv6=$constructor("ZodIPv6",(e,t)=>{$ZodIPv6.init(e,t),ZodStringFormat.init(e,t)});function ipv6(e){return _ipv6(ZodIPv6,e)}const ZodCIDRv4=$constructor("ZodCIDRv4",(e,t)=>{$ZodCIDRv4.init(e,t),ZodStringFormat.init(e,t)});function cidrv4(e){return _cidrv4(ZodCIDRv4,e)}const ZodCIDRv6=$constructor("ZodCIDRv6",(e,t)=>{$ZodCIDRv6.init(e,t),ZodStringFormat.init(e,t)});function cidrv6(e){return _cidrv6(ZodCIDRv6,e)}const ZodBase64=$constructor("ZodBase64",(e,t)=>{$ZodBase64.init(e,t),ZodStringFormat.init(e,t)});function base64(e){return _base64(ZodBase64,e)}const ZodBase64URL=$constructor("ZodBase64URL",(e,t)=>{$ZodBase64URL.init(e,t),ZodStringFormat.init(e,t)});function base64url(e){return _base64url(ZodBase64URL,e)}const ZodE164=$constructor("ZodE164",(e,t)=>{$ZodE164.init(e,t),ZodStringFormat.init(e,t)});function e164(e){return _e164(ZodE164,e)}const ZodJWT=$constructor("ZodJWT",(e,t)=>{$ZodJWT.init(e,t),ZodStringFormat.init(e,t)});function jwt(e){return _jwt(ZodJWT,e)}const ZodCustomStringFormat=$constructor("ZodCustomStringFormat",(e,t)=>{$ZodCustomStringFormat.init(e,t),ZodStringFormat.init(e,t)});function stringFormat(e,t,r={}){return _stringFormat(ZodCustomStringFormat,e,t,r)}function hostname(e){return _stringFormat(ZodCustomStringFormat,"hostname",hostname$1,e)}const ZodNumber=$constructor("ZodNumber",(e,t)=>{$ZodNumber.init(e,t),ZodType.init(e,t),e.gt=(t,r)=>e.check(_gt(t,r)),e.gte=(t,r)=>e.check(_gte(t,r)),e.min=(t,r)=>e.check(_gte(t,r)),e.lt=(t,r)=>e.check(_lt(t,r)),e.lte=(t,r)=>e.check(_lte(t,r)),e.max=(t,r)=>e.check(_lte(t,r)),e.int=t=>e.check(int(t)),e.safe=t=>e.check(int(t)),e.positive=t=>e.check(_gt(0,t)),e.nonnegative=t=>e.check(_gte(0,t)),e.negative=t=>e.check(_lt(0,t)),e.nonpositive=t=>e.check(_lte(0,t)),e.multipleOf=(t,r)=>e.check(_multipleOf(t,r)),e.step=(t,r)=>e.check(_multipleOf(t,r)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function number$1(e){return _number(ZodNumber,e)}const ZodNumberFormat=$constructor("ZodNumberFormat",(e,t)=>{$ZodNumberFormat.init(e,t),ZodNumber.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}function float32(e){return _float32(ZodNumberFormat,e)}function float64(e){return _float64(ZodNumberFormat,e)}function int32(e){return _int32(ZodNumberFormat,e)}function uint32(e){return _uint32(ZodNumberFormat,e)}const ZodBoolean=$constructor("ZodBoolean",(e,t)=>{$ZodBoolean.init(e,t),ZodType.init(e,t)});function boolean$1(e){return _boolean(ZodBoolean,e)}const ZodBigInt=$constructor("ZodBigInt",(e,t)=>{$ZodBigInt.init(e,t),ZodType.init(e,t),e.gte=(t,r)=>e.check(_gte(t,r)),e.min=(t,r)=>e.check(_gte(t,r)),e.gt=(t,r)=>e.check(_gt(t,r)),e.gte=(t,r)=>e.check(_gte(t,r)),e.min=(t,r)=>e.check(_gte(t,r)),e.lt=(t,r)=>e.check(_lt(t,r)),e.lte=(t,r)=>e.check(_lte(t,r)),e.max=(t,r)=>e.check(_lte(t,r)),e.positive=t=>e.check(_gt(BigInt(0),t)),e.negative=t=>e.check(_lt(BigInt(0),t)),e.nonpositive=t=>e.check(_lte(BigInt(0),t)),e.nonnegative=t=>e.check(_gte(BigInt(0),t)),e.multipleOf=(t,r)=>e.check(_multipleOf(t,r));const r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function bigint$1(e){return _bigint(ZodBigInt,e)}const ZodBigIntFormat=$constructor("ZodBigIntFormat",(e,t)=>{$ZodBigIntFormat.init(e,t),ZodBigInt.init(e,t)});function int64(e){return _int64(ZodBigIntFormat,e)}function uint64(e){return _uint64(ZodBigIntFormat,e)}const ZodSymbol=$constructor("ZodSymbol",(e,t)=>{$ZodSymbol.init(e,t),ZodType.init(e,t)});function symbol(e){return _symbol(ZodSymbol,e)}const ZodUndefined=$constructor("ZodUndefined",(e,t)=>{$ZodUndefined.init(e,t),ZodType.init(e,t)});function _undefined(e){return _undefined$1(ZodUndefined,e)}const ZodNull=$constructor("ZodNull",(e,t)=>{$ZodNull.init(e,t),ZodType.init(e,t)});function _null(e){return _null$1(ZodNull,e)}const ZodAny=$constructor("ZodAny",(e,t)=>{$ZodAny.init(e,t),ZodType.init(e,t)});function any(){return _any(ZodAny)}const ZodUnknown=$constructor("ZodUnknown",(e,t)=>{$ZodUnknown.init(e,t),ZodType.init(e,t)});function unknown(){return _unknown(ZodUnknown)}const ZodNever=$constructor("ZodNever",(e,t)=>{$ZodNever.init(e,t),ZodType.init(e,t)});function never(e){return _never(ZodNever,e)}const ZodVoid=$constructor("ZodVoid",(e,t)=>{$ZodVoid.init(e,t),ZodType.init(e,t)});function _void(e){return _void$1(ZodVoid,e)}const ZodDate=$constructor("ZodDate",(e,t)=>{$ZodDate.init(e,t),ZodType.init(e,t),e.min=(t,r)=>e.check(_gte(t,r)),e.max=(t,r)=>e.check(_lte(t,r));const r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function date$1(e){return _date(ZodDate,e)}const ZodArray=$constructor("ZodArray",(e,t)=>{$ZodArray.init(e,t),ZodType.init(e,t),e.element=t.element,e.min=(t,r)=>e.check(_minLength(t,r)),e.nonempty=t=>e.check(_minLength(1,t)),e.max=(t,r)=>e.check(_maxLength(t,r)),e.length=(t,r)=>e.check(_length(t,r)),e.unwrap=()=>e.element});function array(e,t){return _array(ZodArray,e,t)}function keyof(e){const t=e._zod.def.shape;return _enum(Object.keys(t))}const ZodObject=$constructor("ZodObject",(e,t)=>{$ZodObject.init(e,t),ZodType.init(e,t),defineLazy(e,"shape",()=>t.shape),e.keyof=()=>_enum(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:unknown()}),e.loose=()=>e.clone({...e._zod.def,catchall:unknown()}),e.strict=()=>e.clone({...e._zod.def,catchall:never()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>extend(e,t),e.merge=t=>merge(e,t),e.pick=t=>pick(e,t),e.omit=t=>omit(e,t),e.partial=(...t)=>partial(ZodOptional,e,t[0]),e.required=(...t)=>required(ZodNonOptional,e,t[0])});function object(e,t){const r={type:"object",get shape(){return assignProp(this,"shape",e?objectClone(e):{}),this.shape},...normalizeParams(t)};return new ZodObject(r)}function strictObject(e,t){return new ZodObject({type:"object",get shape(){return assignProp(this,"shape",objectClone(e)),this.shape},catchall:never(),...normalizeParams(t)})}function looseObject(e,t){return new ZodObject({type:"object",get shape(){return assignProp(this,"shape",objectClone(e)),this.shape},catchall:unknown(),...normalizeParams(t)})}const ZodUnion=$constructor("ZodUnion",(e,t)=>{$ZodUnion.init(e,t),ZodType.init(e,t),e.options=t.options});function union(e,t){return new ZodUnion({type:"union",options:e,...normalizeParams(t)})}const ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(e,t)=>{ZodUnion.init(e,t),$ZodDiscriminatedUnion.init(e,t)});function discriminatedUnion(e,t,r){return new ZodDiscriminatedUnion({type:"union",options:t,discriminator:e,...normalizeParams(r)})}const ZodIntersection=$constructor("ZodIntersection",(e,t)=>{$ZodIntersection.init(e,t),ZodType.init(e,t)});function intersection(e,t){return new ZodIntersection({type:"intersection",left:e,right:t})}const ZodTuple=$constructor("ZodTuple",(e,t)=>{$ZodTuple.init(e,t),ZodType.init(e,t),e.rest=t=>e.clone({...e._zod.def,rest:t})});function tuple(e,t,r){const n=t instanceof $ZodType;return new ZodTuple({type:"tuple",items:e,rest:n?t:null,...normalizeParams(n?r:t)})}const ZodRecord=$constructor("ZodRecord",(e,t)=>{$ZodRecord.init(e,t),ZodType.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,r){return new ZodRecord({type:"record",keyType:e,valueType:t,...normalizeParams(r)})}function partialRecord(e,t,r){const n=clone(e);return n._zod.values=void 0,new ZodRecord({type:"record",keyType:n,valueType:t,...normalizeParams(r)})}const ZodMap=$constructor("ZodMap",(e,t)=>{$ZodMap.init(e,t),ZodType.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function map(e,t,r){return new ZodMap({type:"map",keyType:e,valueType:t,...normalizeParams(r)})}const ZodSet=$constructor("ZodSet",(e,t)=>{$ZodSet.init(e,t),ZodType.init(e,t),e.min=(...t)=>e.check(_minSize(...t)),e.nonempty=t=>e.check(_minSize(1,t)),e.max=(...t)=>e.check(_maxSize(...t)),e.size=(...t)=>e.check(_size(...t))});function set(e,t){return new ZodSet({type:"set",valueType:e,...normalizeParams(t)})}const ZodEnum=$constructor("ZodEnum",(e,t)=>{$ZodEnum.init(e,t),ZodType.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(e,n)=>{const i={};for(const n of e){if(!r.has(n))throw new Error(`Key ${n} not found in enum`);i[n]=t.entries[n]}return new ZodEnum({...t,checks:[],...normalizeParams(n),entries:i})},e.exclude=(e,n)=>{const i={...t.entries};for(const t of e){if(!r.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new ZodEnum({...t,checks:[],...normalizeParams(n),entries:i})}});function _enum(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ZodEnum({type:"enum",entries:r,...normalizeParams(t)})}function nativeEnum(e,t){return new ZodEnum({type:"enum",entries:e,...normalizeParams(t)})}const ZodLiteral=$constructor("ZodLiteral",(e,t)=>{$ZodLiteral.init(e,t),ZodType.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new ZodLiteral({type:"literal",values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ZodFile=$constructor("ZodFile",(e,t)=>{$ZodFile.init(e,t),ZodType.init(e,t),e.min=(t,r)=>e.check(_minSize(t,r)),e.max=(t,r)=>e.check(_maxSize(t,r)),e.mime=(t,r)=>e.check(_mime(Array.isArray(t)?t:[t],r))});function file(e){return _file(ZodFile,e)}const ZodTransform=$constructor("ZodTransform",(e,t)=>{$ZodTransform.init(e,t),ZodType.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=n=>{if("string"==typeof n)r.issues.push(issue(n,r.value,t));else{const t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),r.issues.push(issue(t))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then(e=>(r.value=e,r)):(r.value=i,r)}});function transform(e){return new ZodTransform({type:"transform",transform:e})}const ZodOptional=$constructor("ZodOptional",(e,t)=>{$ZodOptional.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new ZodOptional({type:"optional",innerType:e})}const ZodNullable=$constructor("ZodNullable",(e,t)=>{$ZodNullable.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ZodNullable({type:"nullable",innerType:e})}function nullish(e){return optional(nullable(e))}const ZodDefault=$constructor("ZodDefault",(e,t)=>{$ZodDefault.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new ZodDefault({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():shallowClone(t)}})}const ZodPrefault=$constructor("ZodPrefault",(e,t)=>{$ZodPrefault.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new ZodPrefault({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof t?t():shallowClone(t)}})}const ZodNonOptional=$constructor("ZodNonOptional",(e,t)=>{$ZodNonOptional.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ZodNonOptional({type:"nonoptional",innerType:e,...normalizeParams(t)})}const ZodSuccess=$constructor("ZodSuccess",(e,t)=>{$ZodSuccess.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function success(e){return new ZodSuccess({type:"success",innerType:e})}const ZodCatch=$constructor("ZodCatch",(e,t)=>{$ZodCatch.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new ZodCatch({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const ZodNaN=$constructor("ZodNaN",(e,t)=>{$ZodNaN.init(e,t),ZodType.init(e,t)});function nan(e){return _nan(ZodNaN,e)}const ZodPipe=$constructor("ZodPipe",(e,t)=>{$ZodPipe.init(e,t),ZodType.init(e,t),e.in=t.in,e.out=t.out});function pipe(e,t){return new ZodPipe({type:"pipe",in:e,out:t})}const ZodReadonly=$constructor("ZodReadonly",(e,t)=>{$ZodReadonly.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new ZodReadonly({type:"readonly",innerType:e})}const ZodTemplateLiteral=$constructor("ZodTemplateLiteral",(e,t)=>{$ZodTemplateLiteral.init(e,t),ZodType.init(e,t)});function templateLiteral(e,t){return new ZodTemplateLiteral({type:"template_literal",parts:e,...normalizeParams(t)})}const ZodLazy=$constructor("ZodLazy",(e,t)=>{$ZodLazy.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.getter()});function lazy(e){return new ZodLazy({type:"lazy",getter:e})}const ZodPromise=$constructor("ZodPromise",(e,t)=>{$ZodPromise.init(e,t),ZodType.init(e,t),e.unwrap=()=>e._zod.def.innerType});function promise(e){return new ZodPromise({type:"promise",innerType:e})}const ZodCustom=$constructor("ZodCustom",(e,t)=>{$ZodCustom.init(e,t),ZodType.init(e,t)});function check(e){const t=new $ZodCheck({check:"custom"});return t._zod.check=e,t}function custom(e,t){return _custom(ZodCustom,e??(()=>!0),t)}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e){return _superRefine(e)}function _instanceof(e,t={error:`Input not instance of ${e.name}`}){const r=new ZodCustom({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...normalizeParams(t)});return r._zod.bag.Class=e,r}const stringbool=(...e)=>_stringbool({Pipe:ZodPipe,Boolean:ZodBoolean,String:ZodString,Transform:ZodTransform},...e);function json(e){const t=lazy(()=>union([string$1(e),number$1(),boolean$1(),_null(),array(t),record(string$1(),t)]));return t}function preprocess(e,t){return pipe(transform(e),t)}const ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function setErrorMap(e){config({customError:e})}function getErrorMap(){return config().customError}var ZodFirstPartyTypeKind;function string(e){return _coercedString(ZodString,e)}function number(e){return _coercedNumber(ZodNumber,e)}function boolean(e){return _coercedBoolean(ZodBoolean,e)}function bigint(e){return _coercedBigint(ZodBigInt,e)}function date(e){return _coercedDate(ZodDate,e)}ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={});var coerce=Object.freeze({__proto__:null,bigint:bigint,boolean:boolean,date:date,number:number,string:string});config(en());var z=Object.freeze({__proto__:null,$brand:$brand,$input:$input,$output:$output,NEVER:NEVER,TimePrecision:TimePrecision,ZodAny:ZodAny,ZodArray:ZodArray,ZodBase64:ZodBase64,ZodBase64URL:ZodBase64URL,ZodBigInt:ZodBigInt,ZodBigIntFormat:ZodBigIntFormat,ZodBoolean:ZodBoolean,ZodCIDRv4:ZodCIDRv4,ZodCIDRv6:ZodCIDRv6,ZodCUID:ZodCUID,ZodCUID2:ZodCUID2,ZodCatch:ZodCatch,ZodCustom:ZodCustom,ZodCustomStringFormat:ZodCustomStringFormat,ZodDate:ZodDate,ZodDefault:ZodDefault,ZodDiscriminatedUnion:ZodDiscriminatedUnion,ZodE164:ZodE164,ZodEmail:ZodEmail,ZodEmoji:ZodEmoji,ZodEnum:ZodEnum,ZodError:ZodError,ZodFile:ZodFile,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind},ZodGUID:ZodGUID,ZodIPv4:ZodIPv4,ZodIPv6:ZodIPv6,ZodISODate:ZodISODate,ZodISODateTime:ZodISODateTime,ZodISODuration:ZodISODuration,ZodISOTime:ZodISOTime,ZodIntersection:ZodIntersection,ZodIssueCode:ZodIssueCode,ZodJWT:ZodJWT,ZodKSUID:ZodKSUID,ZodLazy:ZodLazy,ZodLiteral:ZodLiteral,ZodMap:ZodMap,ZodNaN:ZodNaN,ZodNanoID:ZodNanoID,ZodNever:ZodNever,ZodNonOptional:ZodNonOptional,ZodNull:ZodNull,ZodNullable:ZodNullable,ZodNumber:ZodNumber,ZodNumberFormat:ZodNumberFormat,ZodObject:ZodObject,ZodOptional:ZodOptional,ZodPipe:ZodPipe,ZodPrefault:ZodPrefault,ZodPromise:ZodPromise,ZodReadonly:ZodReadonly,ZodRealError:ZodRealError,ZodRecord:ZodRecord,ZodSet:ZodSet,ZodString:ZodString,ZodStringFormat:ZodStringFormat,ZodSuccess:ZodSuccess,ZodSymbol:ZodSymbol,ZodTemplateLiteral:ZodTemplateLiteral,ZodTransform:ZodTransform,ZodTuple:ZodTuple,ZodType:ZodType,ZodULID:ZodULID,ZodURL:ZodURL,ZodUUID:ZodUUID,ZodUndefined:ZodUndefined,ZodUnion:ZodUnion,ZodUnknown:ZodUnknown,ZodVoid:ZodVoid,ZodXID:ZodXID,_ZodString:_ZodString,_default:_default,any:any,array:array,base64:base64,base64url:base64url,bigint:bigint$1,boolean:boolean$1,catch:_catch,check:check,cidrv4:cidrv4,cidrv6:cidrv6,clone:clone,coerce:coerce,config:config,core:index,cuid:cuid,cuid2:cuid2,custom:custom,date:date$1,discriminatedUnion:discriminatedUnion,e164:e164,email:email,emoji:emoji,endsWith:_endsWith,enum:_enum,file:file,flattenError:flattenError,float32:float32,float64:float64,formatError:formatError,function:_function,getErrorMap:getErrorMap,globalRegistry:globalRegistry,gt:_gt,gte:_gte,guid:guid,hostname:hostname,includes:_includes,instanceof:_instanceof,int:int,int32:int32,int64:int64,intersection:intersection,ipv4:ipv4,ipv6:ipv6,iso:iso,json:json,jwt:jwt,keyof:keyof,ksuid:ksuid,lazy:lazy,length:_length,literal:literal,locales:index$1,looseObject:looseObject,lowercase:_lowercase,lt:_lt,lte:_lte,map:map,maxLength:_maxLength,maxSize:_maxSize,mime:_mime,minLength:_minLength,minSize:_minSize,multipleOf:_multipleOf,nan:nan,nanoid:nanoid$1,nativeEnum:nativeEnum,negative:_negative,never:never,nonnegative:_nonnegative,nonoptional:nonoptional,nonpositive:_nonpositive,normalize:_normalize,null:_null,nullable:nullable,nullish:nullish,number:number$1,object:object,optional:optional,overwrite:_overwrite,parse:parse,parseAsync:parseAsync,partialRecord:partialRecord,pipe:pipe,positive:_positive,prefault:prefault,preprocess:preprocess,prettifyError:prettifyError,promise:promise,property:_property,readonly:readonly,record:record,refine:refine,regex:_regex,regexes:regexes,registry:registry,safeParse:safeParse,safeParseAsync:safeParseAsync,set:set,setErrorMap:setErrorMap,size:_size,startsWith:_startsWith,strictObject:strictObject,string:string$1,stringFormat:stringFormat,stringbool:stringbool,success:success,superRefine:superRefine,symbol:symbol,templateLiteral:templateLiteral,toJSONSchema:toJSONSchema,toLowerCase:_toLowerCase,toUpperCase:_toUpperCase,transform:transform,treeifyError:treeifyError,trim:_trim,tuple:tuple,uint32:uint32,uint64:uint64,ulid:ulid,undefined:_undefined,union:union,unknown:unknown,uppercase:_uppercase,url:url,uuid:uuid,uuidv4:uuidv4,uuidv6:uuidv6,uuidv7:uuidv7,void:_void,xid:xid}),clientCapabilities=[{capability:"ADMIN_API_V2_APP_ADD",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_APP_ADD_OR_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_APP_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_ADD",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_ADD_OR_UPDATE",introducedInVersion:"1.5.0"},{capability:"ADMIN_API_V2_LAYOUT_UPDATE",introducedInVersion:"1.5.0"},{capability:"METRICS_ENDPOINTS_DB_CONNECTIVITY",introducedInVersion:"1.7.0"},{capability:"API_V2_SERVER_INFO_ENHANCED",introducedInVersion:"2.0.0"},{capability:"HTTP_TEST",introducedInVersion:"2.0.0"}],clientCapabilitiesByName=new Map;for(const e of clientCapabilities)clientCapabilitiesByName.set(e.capability,e);var BaseAPI=class{constructor(e){this.options=e,this.setOptions(e)}_responseSuccessCallback;_responseErrorCallback;_errorsInterceptorsId;_headersInterceptorId;_serverInfoWrapper={initialized:!1};axiosInstance;setOptions(e){if(!e.auth)throw new Error("please provide auth info");this.options=e,this._errorsInterceptorsId&&this.axiosInstance?.interceptors?.response?.eject(this._errorsInterceptorsId),this._headersInterceptorId&&this.axiosInstance?.interceptors?.request?.eject(this._headersInterceptorId);const t=this.getBaseHeaders(e);this.axiosInstance=axios.create({transformResponse:e.transformResponse,baseURL:e.baseUrl,headers:t,timeout:this.options.requestTimeout,withCredentials:e?.auth?.includeCredentials,validateStatus:this.defaultIsStatusCodeValid,maxContentLength:1/0,maxBodyLength:1/0}),this._errorsInterceptorsId=this.axiosInstance?.interceptors?.response?.use(e=>{try{this._responseSuccessCallback?.(e)}catch{}return e},e=>{try{this._responseErrorCallback?.(e)}catch{}return Promise.reject(e)}),this._headersInterceptorId=this.axiosInstance?.interceptors?.request?.use(async e=>{const t=this.getBaseHeaders(this.options);for(const[r,n]of Object.entries(t))e.headers.set(r,n);if(this.options.getHeaders){const t=await this.options.getHeaders({...e,method:e.method,url:e.url,body:e.data})??{};for(const[r,n]of Object.entries(t))e.headers.set(r,n)}return e},e=>Promise.reject(e))}async whoAmI(){return(await this.axiosInstance.get("/whoami")).data}onResponseSuccessCallback(e){this._responseSuccessCallback=e}onResponseErrorCallback(e){this._responseErrorCallback=e}async initialize(){try{const e=await this.axiosInstance.get("/v2/server/info");this.initializeServerInfo(e.data)}catch(e){if(404===(e?.response?.status??e?.status))return console.warn('Warning: The "GET /v2/server/info" endpoint returned a status code of 404. This means that the io.Manager server is version is < 1.5.0. Proceeding with an empty set of capabilities.'),void this.initializeServerInfo({version:"< 1.5.0",capabilities:[],licenseInfo:{licenseSupported:!1},base:void 0,machine:void 0,start:void 0});throw e}}get serverInfo(){return this._serverInfoWrapper.initialized||this.throwNotInitialized(),this._serverInfoWrapper}hasCapability(e){return this._serverInfoWrapper.initialized||this.throwNotInitialized(),this._serverInfoWrapper.capabilitiesByName.has(e)}async unloadClient(e,t){if(!e||!t)return;const r=new Headers({...this.getBaseHeaders(this.options),...await(this.options.getHeaders?.({method:"POST",url:`${this.options.baseUrl}/user/goodbye`}))}),n=new Request(`${this.options.baseUrl}/user/goodbye`,{method:"POST",headers:r,mode:"cors",cache:"default",keepalive:!0,body:JSON.stringify({session:e})});window.fetch(n)}getHeaders(e){return this.getBaseHeaders(e)}getBaseHeaders(e){const t={};if(e.auth?.username&&(t.user=e.auth.username),(e.auth?.basic?.username||e.auth?.basic?.password)&&(t.Authorization=`Basic ${this.toBase64(`${e.auth.basic.username}:${e.auth.basic.password}`)}`),e.auth?.token?.bearer&&(t.Authorization=`Bearer ${e.auth.token.bearer}`),e.headers)for(const r of Object.keys(e.headers))t[r]=e.headers[r];return t}initializeServerInfo(e){const t=new Map;for(const r of e.capabilities)t.set(r.capability,r);if("2.0.0"===e.version){const e={capability:"HTTP_TEST",introducedInVersion:"2.0.0"};t.set(e.capability,e)}Object.assign(this._serverInfoWrapper,{initialized:!0,capabilitiesByName:t,...e})}ensureCapability(e){if(this.options.disableCapabilityCheck)return;this._serverInfoWrapper.initialized||this.throwNotInitialized();if(!this._serverInfoWrapper.capabilitiesByName.get(e)){const t=clientCapabilitiesByName.get(e);if(!t)throw new Error(`Client capability "${e}" not found.`);throw new Error(`io.Manager server version "${this.serverInfo.version}" doesn't support capability "${e}" which was introduced in version "${t.introducedInVersion}".`)}}throwNotInitialized(){throw new Error("You need to call initialize() first, before calling this API.")}toBase64(e){return"undefined"!=typeof window?window.btoa(e):Buffer.from(e,"utf-8").toString("base64")}defaultIsStatusCodeValid(e){return e<400}};function customEncodeURIComponent(e){return decodeURIComponent(e)!==e?e:encodeURIComponent(e)}var PromiseWrapper=class{static delay(e){return new Promise(t=>setTimeout(t,e))}resolve=()=>{};reject=()=>{};promise;rejected=!1;resolved=!1;get ended(){return this.rejected||this.resolved}constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.resolved=!0,e(t)},this.reject=e=>{this.rejected=!0,t(e)}})}};function debugSanitizeValue(e){switch(typeof e){case"number":case"bigint":case"boolean":return e;case"string":return`Sanitized(type=string, length=${e.length})`;case"function":return`Sanitized(type=function, name=${e.name||"anonymous"})`;case"object":return null===e?"Sanitized(type=object, value=null)":e instanceof Date||e instanceof RegExp?e:`Sanitized(type=object, propertyCount=${Object.keys(e).length})`;default:return`Sanitized(type=${typeof e})`}}var RequestLogger=class{constructor(e,t,r,n){this.logger=e,this.logLevel=t,this.disableLogSanitization=r,this.logHTTPHeaders=n}shouldLogRequest(){return this.logger.isLevelEnabled(this.logLevel)}logRequest(e){if(!this.shouldLogRequest())return;const t=e();let r=`Calling endpoint "${t.endpointName}" (${t.operationName})`,n=!1;if(t.pathParameters&&Object.keys(t.pathParameters).length>0){const e=structuredClone(t.pathParameters);n&&(r+=" and"),r+=` with path parameters: ${JSON.stringify(e)}`,n=!0}if(t.queryParameters&&Object.keys(t.queryParameters).length>0){const e=structuredClone(t.queryParameters);n&&(r+=" and"),r+=` with query parameters: ${JSON.stringify(e)}`,n=!0}if(t.requestBody){const e=structuredClone(t.requestBody);if(!this.disableLogSanitization)for(const r of t.sanitizeRequestBodyProperties??[]){const t=e[r];t&&(e[r]=debugSanitizeValue(t))}n&&(r+=" and"),r+=` with request body: ${JSON.stringify(e)}`,n=!0}this.logger.log(this.logLevel,r)}logResponse(e){if(!this.shouldLogRequest())return;const t=e();let r=`Endpoint "${t.endpointName}" (${t.operationName}) returned status code of ${t.response.statusCode} and response body`;if("string"==typeof t.response.body)r+=" (string): ",r+=t.response.body;else if("boolean"==typeof t.response.body)r+=" (boolean): ",r+=t.response.body.toString();else if("number"==typeof t.response.body)r+=" (number): ",r+=t.response.body.toString();else if(void 0===t.response.body)r+=" is undefined";else if(null===t.response.body)r+=" is null";else if("object"==typeof t.response.body){const e=structuredClone(t.response.body);if(!this.disableLogSanitization)for(const r of t.sanitizeResponseBodyProperties??[]){const t=e[r];t&&(e[r]=debugSanitizeValue(t))}r+=" (object): ",r+=JSON.stringify(e)}else r+=" is something strange";this.logger.log(this.logLevel,r)}logRequestHeaders(e){if(!this.shouldLogRequest())return;if(!this.logHTTPHeaders)return;if(!this.disableLogSanitization)return;const t=e();this.logger.log(this.logLevel,`Using request headers: ${JSON.stringify(t)}`)}logResponseHeaders(e){if(!this.shouldLogRequest())return;if(!this.logHTTPHeaders)return;if(!this.disableLogSanitization)return;const t=e();this.logger.log(this.logLevel,`Received response headers: ${JSON.stringify(t)}`)}};function extendedOptional(e){return z.union([e,z.null(),z.undefined()]).optional()}function anyIsoDate(){return z.union([z.iso.datetime({offset:!0,local:!0}),z.iso.date()])}var zodHelpers={extendedOptional:extendedOptional,anyIsoDate:anyIsoDate};z.looseObject({name:z.string(),base:z.string(),version:z.string(),start:zodHelpers.anyIsoDate(),status:z.string()}),z.looseObject({id:z.string(),email:zodHelpers.extendedOptional(z.string()),groups:z.array(z.string()),apps:z.array(z.string())});var App2=z.looseObject({definition:z.looseObject({}),name:z.string(),disabled:z.boolean(),public:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),createdBy:z.string(),createdOn:zodHelpers.anyIsoDate(),lastModifiedBy:zodHelpers.extendedOptional(z.string()),lastModifiedOn:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())});z.looseObject({items:z.array(App2),total:z.number()}),z.looseObject({items:z.array(App2),total:z.number()});var AddOrUpdateAppRequest2=z.looseObject({definition:z.looseObject({}),name:z.string(),disabled:z.boolean(),public:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string()))});z.looseObject({apps:z.array(AddOrUpdateAppRequest2)}),z.looseObject({application:App2}),z.looseObject({definition:z.looseObject({}),name:z.string(),disabled:z.boolean(),public:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string()))}),z.looseObject({definition:z.looseObject({}),name:z.string(),disabled:z.boolean(),public:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string()))});var Layout2=z.looseObject({definition:z.string(),id:z.string(),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),public:z.boolean(),disabled:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),createdBy:z.string(),createdOn:zodHelpers.anyIsoDate(),lastModifiedBy:zodHelpers.extendedOptional(z.string()),lastModifiedOn:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),default:zodHelpers.extendedOptional(z.boolean())});z.looseObject({items:z.array(Layout2),total:z.number()}),z.looseObject({definition:z.string(),id:zodHelpers.extendedOptional(z.string()),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),public:z.boolean(),disabled:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),default:zodHelpers.extendedOptional(z.boolean())}),z.looseObject({layout:Layout2}),z.looseObject({definition:z.string(),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),public:z.boolean(),disabled:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),default:zodHelpers.extendedOptional(z.boolean())}),z.looseObject({definition:z.string(),id:zodHelpers.extendedOptional(z.string()),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),public:z.boolean(),disabled:z.boolean(),accessList:zodHelpers.extendedOptional(z.array(z.string())),default:zodHelpers.extendedOptional(z.boolean())});var Group=z.looseObject({name:z.string()});z.looseObject({items:z.array(Group),total:z.number()}),z.looseObject({canGetUserGroups:z.boolean(),canGetAllGroups:z.boolean(),canAddGroup:z.boolean(),canRemoveGroup:z.boolean(),canAddUserToGroup:z.boolean(),canRemoveUserFromGroup:z.boolean()}),z.looseObject({name:z.string()});var RefreshRequestLastDataInfoOthers=z.looseObject({groups:zodHelpers.extendedOptional(z.array(z.string()))}),RefreshRequestLastDataInfo=z.looseObject({checksum:zodHelpers.extendedOptional(z.string()),last:z.number(),other:zodHelpers.extendedOptional(RefreshRequestLastDataInfoOthers)}),RefreshRequestCategory=z.looseObject({include:z.boolean(),latestDataInfo:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),RefreshDataRequest=z.looseObject({applications:zodHelpers.extendedOptional(RefreshRequestCategory),layouts:zodHelpers.extendedOptional(RefreshRequestCategory),commands:zodHelpers.extendedOptional(RefreshRequestCategory),configs:zodHelpers.extendedOptional(RefreshRequestCategory)}),ApplicationRefreshResponseData=z.looseObject({data:zodHelpers.extendedOptional(z.array(z.looseObject({}))),hasChanges:z.boolean(),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),UserLayoutDefinition=z.looseObject({definition:z.string(),id:z.string(),type:z.string(),name:z.string(),owner:zodHelpers.extendedOptional(z.string()),default:zodHelpers.extendedOptional(z.boolean())}),LayoutRefreshResponseData=z.looseObject({hasChanges:z.boolean(),data:zodHelpers.extendedOptional(z.array(UserLayoutDefinition)),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),CommandStatus2=z.string().min(1),ResultType2=z.string().min(1),Command2=z.looseObject({status:CommandStatus2,resultType:zodHelpers.extendedOptional(ResultType2),traceContext:zodHelpers.extendedOptional(z.looseObject({})),id:z.string(),user:z.string(),session:z.string(),machine:z.string(),createdBy:z.string(),createdAt:z.number(),command:z.string(),commandParams:zodHelpers.extendedOptional(z.string()),resultData:zodHelpers.extendedOptional(z.looseObject({})),resultAt:zodHelpers.extendedOptional(z.number())}),CommandRefreshResponseData=z.looseObject({hasChanges:z.boolean(),data:zodHelpers.extendedOptional(z.array(Command2)),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),ConfigRefreshResponseData=z.looseObject({hasChanges:z.boolean(),data:zodHelpers.extendedOptional(z.array(z.looseObject({}))),info:zodHelpers.extendedOptional(RefreshRequestLastDataInfo)}),RefreshDataResponse=z.looseObject({applications:zodHelpers.extendedOptional(ApplicationRefreshResponseData),layouts:zodHelpers.extendedOptional(LayoutRefreshResponseData),commands:zodHelpers.extendedOptional(CommandRefreshResponseData),config:zodHelpers.extendedOptional(ConfigRefreshResponseData)});z.looseObject({session:z.string(),user:z.string(),email:zodHelpers.extendedOptional(z.string()),exp:z.number(),iat:z.number()}),z.looseObject({version:z.string()});var ConnectBrowserPlatformInfo=z.looseObject({version:z.string()});z.looseObject({platform:ConnectBrowserPlatformInfo});var ConnectBrowserInfo=z.looseObject({platform:ConnectBrowserPlatformInfo}),ConnectInfo=z.looseObject({version:z.string(),core:zodHelpers.extendedOptional(ConnectBrowserInfo),build:z.string(),region:z.string(),env:z.string()}),OSInfo=z.looseObject({name:zodHelpers.extendedOptional(z.string()),version:zodHelpers.extendedOptional(z.string()),arch:zodHelpers.extendedOptional(z.string())}),Bounds=z.looseObject({x:zodHelpers.extendedOptional(z.number()),y:zodHelpers.extendedOptional(z.number()),width:zodHelpers.extendedOptional(z.number()),height:zodHelpers.extendedOptional(z.number())}),Display=z.looseObject({bounds:zodHelpers.extendedOptional(Bounds),workingArea:zodHelpers.extendedOptional(Bounds),dpi:zodHelpers.extendedOptional(z.number()),isPrimary:zodHelpers.extendedOptional(z.boolean()),aspectRatio:zodHelpers.extendedOptional(z.string()),scaleFactor:zodHelpers.extendedOptional(z.number())}),MachineInfo=z.looseObject({user:z.string(),name:zodHelpers.extendedOptional(z.string()),os:zodHelpers.extendedOptional(OSInfo),displays:zodHelpers.extendedOptional(z.array(Display))}),HelloRequest=z.looseObject({glue:ConnectInfo,machine:zodHelpers.extendedOptional(MachineInfo),initialDataRequest:zodHelpers.extendedOptional(RefreshDataRequest),includeServerInfo:zodHelpers.extendedOptional(z.boolean())}),ServerCapability2=z.string().min(1),ServerCapabilityWithMetadata2=z.looseObject({capability:ServerCapability2,introducedInVersion:z.string()}),LicenseType2=z.string().min(1),LicenseOrganization=z.looseObject({displayName:z.string(),identifier:z.string()}),LicensePayload=z.looseObject({type:LicenseType2,licensee:z.string(),expiration:z.number(),organization:LicenseOrganization,email:z.string(),issuedBy:z.string()}),LicenseInfo2=z.looseObject({licensePayload:LicensePayload,isExpired:z.boolean(),licenseSupported:z.boolean()}),ServerInfoResponse2=z.looseObject({capabilities:z.array(ServerCapabilityWithMetadata2),version:z.string(),licenseInfo:zodHelpers.extendedOptional(LicenseInfo2),base:zodHelpers.extendedOptional(z.string()),start:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),machine:zodHelpers.extendedOptional(z.string())}),HelloResponse=z.looseObject({token:z.string(),data:RefreshDataResponse,serverInfo:zodHelpers.extendedOptional(ServerInfoResponse2),sessionNotPersisted:zodHelpers.extendedOptional(z.boolean())}),GoodbyeRequest=z.looseObject({session:z.string()}),RefreshTokenRequest=z.looseObject({token:z.string()}),RefreshTokenResponse=z.looseObject({token:z.string()}),SaveUserLayoutRequest=z.looseObject({definition:z.string(),id:zodHelpers.extendedOptional(z.string()),type:z.string(),name:z.string(),default:zodHelpers.extendedOptional(z.boolean())}),RenameLayoutRequest=z.looseObject({newName:z.string()}),SetDefaultLayoutRequest=z.looseObject({id:zodHelpers.extendedOptional(z.string())}),AddCommandResultRequest=z.looseObject({result:z.looseObject({})}),AddCommandFileResultRequest=z.looseObject({fileName:z.string(),contents:z.string()});z.looseObject({result:zodHelpers.extendedOptional(z.looseObject({}))});var AppPreferences=z.looseObject({data:z.looseObject({}),id:z.string(),app:z.string(),user:z.string(),lastUpdate:zodHelpers.anyIsoDate()}),AddOrUpdatePrefsRequest=z.looseObject({data:z.looseObject({}),merge:z.boolean(),id:zodHelpers.extendedOptional(z.string()),app:zodHelpers.extendedOptional(z.string()),user:zodHelpers.extendedOptional(z.string())});z.looseObject({attachment:z.string(),description:z.string()});var Feedback=z.looseObject({id:z.string(),date:zodHelpers.anyIsoDate(),user:z.string(),session:z.string(),description:z.string(),attachment:z.string(),reviewed:z.boolean(),comment:zodHelpers.extendedOptional(z.string())}),HttpTestRequest=z.looseObject({}),HttpTestResponse=z.looseObject({requestBody:z.looseObject({}),statusCode:z.number(),customHeader:zodHelpers.extendedOptional(z.string())}),LayoutIdentifier=z.looseObject({id:zodHelpers.extendedOptional(z.string()),name:zodHelpers.extendedOptional(z.string()),type:zodHelpers.extendedOptional(z.string())}),User2=z.looseObject({layouts:zodHelpers.extendedOptional(z.array(LayoutIdentifier)),id:z.string(),email:zodHelpers.extendedOptional(z.string()),password:zodHelpers.extendedOptional(z.string()),apps:z.array(z.string()),groups:z.array(z.string()),lastUpdated:zodHelpers.extendedOptional(z.number()),firstName:zodHelpers.extendedOptional(z.string()),lastName:zodHelpers.extendedOptional(z.string())});z.looseObject({items:z.array(User2),total:z.number()}),z.looseObject({items:z.array(User2),total:z.number()});var AddUserRequest=z.looseObject({layouts:zodHelpers.extendedOptional(z.array(LayoutIdentifier)),id:z.string(),email:zodHelpers.extendedOptional(z.string()),password:zodHelpers.extendedOptional(z.string()),apps:z.array(z.string()),groups:z.array(z.string()),lastUpdated:zodHelpers.extendedOptional(z.number()),firstName:zodHelpers.extendedOptional(z.string()),lastName:zodHelpers.extendedOptional(z.string())});z.looseObject({users:z.array(AddUserRequest)}),z.looseObject({user:User2}),z.looseObject({layouts:zodHelpers.extendedOptional(z.array(LayoutIdentifier)),apps:zodHelpers.extendedOptional(z.array(z.string()))});var UserAppStatusExplain2=z.string().min(1),UserAppStatus=z.looseObject({explain:UserAppStatusExplain2,app:App2,available:z.boolean(),explainMore:zodHelpers.extendedOptional(z.string())});z.looseObject({apps:z.array(UserAppStatus)}),z.looseObject({app:z.string()}),z.looseObject({layouts:z.array(Layout2)}),z.looseObject({id:LayoutIdentifier}),z.looseObject({user:z.string(),groups:z.array(z.string())}),z.looseObject({groups:z.array(z.string())});var Machine=z.looseObject({id:z.string(),user:z.string(),name:zodHelpers.extendedOptional(z.string()),os:zodHelpers.extendedOptional(OSInfo),displays:zodHelpers.extendedOptional(z.array(Display))});z.looseObject({items:z.array(Command2),total:z.number()}),z.looseObject({command:Command2}),z.looseObject({resultType:zodHelpers.extendedOptional(ResultType2),traceContext:zodHelpers.extendedOptional(z.looseObject({})),session:z.string(),command:z.string(),commandParams:zodHelpers.extendedOptional(z.string())}),z.looseObject({id:z.string()});var CommandType2=z.string().min(1);z.looseObject({type:CommandType2,paramsExample:zodHelpers.extendedOptional(z.string()),description:z.string()}),z.looseObject({version:z.string(),core:zodHelpers.extendedOptional(ConnectBrowserInfo),build:z.string(),region:z.string(),env:z.string()});var UserSession2=z.looseObject({id:z.string(),user:z.string(),start:zodHelpers.anyIsoDate(),end:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),glue:ConnectInfo,machine:z.string(),lastDataFetch:zodHelpers.extendedOptional(zodHelpers.anyIsoDate()),closed:zodHelpers.extendedOptional(z.boolean()),closeReason:zodHelpers.extendedOptional(z.string())});z.looseObject({items:z.array(UserSession2),total:z.number()});var CleanSessionsAction2=z.string().min(1);z.looseObject({action:CleanSessionsAction2,all:zodHelpers.extendedOptional(z.boolean()),lastFetchThresholdInMinutes:zodHelpers.extendedOptional(z.number()),createdBefore:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())}),z.looseObject({itemsCount:z.number()}),z.looseObject({items:z.array(Machine),total:z.number()});var ClientCrashInfo=z.looseObject({_companyName:z.string(),_productName:z.string(),_version:z.string(),build:z.string(),env:z.string(),guid:z.string(),machine:z.string(),osArch:z.string(),osPlatform:z.string(),osUser:z.string(),osVersion:z.string(),osarch:z.string(),pid:z.string(),plat:z.string(),platform:z.string(),process_type:z.string(),prod:z.string(),ptype:z.string(),region:z.string(),session:z.string(),user:z.string(),ver:z.string(),version:z.string(),filename:z.string(),isStoredCompressed:z.boolean()}),ClientCrash=z.looseObject({id:z.string(),date:zodHelpers.anyIsoDate(),user:zodHelpers.extendedOptional(z.string()),info:ClientCrashInfo,reviewed:z.boolean(),comment:zodHelpers.extendedOptional(z.string())});z.looseObject({items:z.array(ClientCrash),total:z.number()}),z.looseObject({upload_file_minidump:z.string(),_companyName:z.string(),_productName:z.string(),_version:z.string(),build:z.string(),env:z.string(),guid:z.string(),machine:z.string(),osArch:z.string(),osPlatform:z.string(),osUser:z.string(),osVersion:z.string(),osarch:z.string(),pid:z.string(),plat:z.string(),platform:z.string(),process_type:z.string(),prod:z.string(),ptype:z.string(),region:z.string(),session:z.string(),user:z.string(),ver:z.string(),version:z.string(),filename:z.string()}),z.looseObject({comment:zodHelpers.extendedOptional(z.string()),reviewed:z.boolean()}),z.looseObject({version:z.string(),started:z.string(),name:z.string(),machine:z.string()});var AppsDataSummary=z.looseObject({total:z.number()}),LayoutsDataSummary=z.looseObject({total:z.number(),common:z.number(),private:z.number()}),CrashesDataSummary=z.looseObject({total:z.number(),notReviewed:z.number()}),FeedbacksDataSummary=z.looseObject({total:z.number(),notReviewed:z.number()}),CommandsDataSummary=z.looseObject({total:z.number()}),UsersDataSummary=z.looseObject({total:z.number()}),SessionsDataSummary=z.looseObject({active:z.number()}),PrefsDataSummary=z.looseObject({total:z.number()});z.looseObject({apps:AppsDataSummary,layouts:LayoutsDataSummary,crashes:CrashesDataSummary,feedbacks:FeedbacksDataSummary,commands:CommandsDataSummary,users:UsersDataSummary,sessions:SessionsDataSummary,prefs:PrefsDataSummary}),z.looseObject({items:z.array(Feedback),total:z.number()}),z.looseObject({comment:zodHelpers.extendedOptional(z.string()),reviewed:z.boolean()}),z.looseObject({items:z.array(AppPreferences),total:z.number()});var AuditLogEntityType2=z.string().min(1),AuditLogOperation2=z.string().min(1),AuditLogRequest=z.looseObject({body:z.looseObject({}),action:z.string(),path:z.string(),params:z.string(),query:z.string()}),AuditLogResponse=z.looseObject({status:z.string(),body:z.looseObject({})}),AuditLog=z.looseObject({entityType:AuditLogEntityType2,operation:AuditLogOperation2,newValue:zodHelpers.extendedOptional(z.looseObject({})),oldValue:zodHelpers.extendedOptional(z.looseObject({})),id:z.string(),user:zodHelpers.extendedOptional(z.string()),parent:zodHelpers.extendedOptional(z.string()),date:zodHelpers.anyIsoDate(),session:zodHelpers.extendedOptional(z.string()),server:z.string(),entityId:zodHelpers.extendedOptional(z.string()),entityDisplayName:zodHelpers.extendedOptional(z.string()),operationComment:zodHelpers.extendedOptional(z.string()),request:zodHelpers.extendedOptional(AuditLogRequest),response:zodHelpers.extendedOptional(AuditLogResponse)});z.looseObject({items:z.array(AuditLog),total:z.number()}),z.looseObject({all:zodHelpers.extendedOptional(z.boolean()),createdBefore:zodHelpers.extendedOptional(zodHelpers.anyIsoDate())}),z.looseObject({version:z.string(),group:z.string(),user:z.string()});var ConfigEntry=z.looseObject({contents:z.looseObject({}),meta:zodHelpers.extendedOptional(z.looseObject({})),merge:zodHelpers.extendedOptional(z.boolean())});z.looseObject({"system.json":zodHelpers.extendedOptional(ConfigEntry),"themes.json":zodHelpers.extendedOptional(ConfigEntry),"stickywindows.json":zodHelpers.extendedOptional(ConfigEntry),"channels.json":zodHelpers.extendedOptional(ConfigEntry),"logger.json":zodHelpers.extendedOptional(ConfigEntry)});var ConnectSystemConfigIdentifier=z.looseObject({version:z.string(),group:z.string(),user:z.string()}),ConnectConfigs=z.looseObject({"system.json":zodHelpers.extendedOptional(ConfigEntry),"themes.json":zodHelpers.extendedOptional(ConfigEntry),"stickywindows.json":zodHelpers.extendedOptional(ConfigEntry),"channels.json":zodHelpers.extendedOptional(ConfigEntry),"logger.json":zodHelpers.extendedOptional(ConfigEntry)}),ConnectSystemConfigEntry=z.looseObject({identifier:ConnectSystemConfigIdentifier,configs:ConnectConfigs,weight:zodHelpers.extendedOptional(z.number())});z.looseObject({items:z.array(ConnectSystemConfigEntry),total:z.number()}),z.looseObject({identifiers:z.array(ConnectSystemConfigIdentifier),configs:ConnectConfigs}),z.looseObject({identifier:ConnectSystemConfigIdentifier,exact:z.boolean()}),z.looseObject({identifier:ConnectSystemConfigIdentifier,configs:ConnectConfigs,weight:zodHelpers.extendedOptional(z.number())});var ConnectConfigKey2=z.string().min(1);z.looseObject({config:ConnectConfigKey2,identifier:ConnectSystemConfigIdentifier}),z.looseObject({type:z.string().min(1),data:z.array(z.looseObject({}))}),z.looseObject({isValid:z.boolean(),errors:z.array(z.looseObject({}))});var TextFilterType2=z.string().min(1),TextFilterCondition=z.looseObject({filterType:z.string().min(1),type:TextFilterType2,filter:z.string(),in:zodHelpers.extendedOptional(z.array(z.string()))}),NumberFilterType2=z.string().min(1),NumberFilterCondition=z.looseObject({filterType:z.string().min(1),type:NumberFilterType2,filter:zodHelpers.extendedOptional(z.number()),filterTo:zodHelpers.extendedOptional(z.number())}),DateFilterType2=z.string().min(1),DateFilterCondition=z.looseObject({filterType:z.string().min(1),type:DateFilterType2,dateFrom:zodHelpers.extendedOptional(z.string()),dateTo:zodHelpers.extendedOptional(z.string())}),BooleanFilterType2=z.string().min(1),BooleanFilterCondition=z.looseObject({filterType:z.string().min(1),type:BooleanFilterType2,filter:z.boolean()}),LogicalConditionOperator2=z.string().min(1);z.looseObject({condition1:zodHelpers.extendedOptional(z.union([TextFilterCondition,NumberFilterCondition,DateFilterCondition,BooleanFilterCondition,z.looseObject({})])),condition2:zodHelpers.extendedOptional(z.union([TextFilterCondition,NumberFilterCondition,DateFilterCondition,BooleanFilterCondition,z.looseObject({})])),operator:zodHelpers.extendedOptional(LogicalConditionOperator2)});var SortOrderEnum2=z.string().min(1),SortOrder=z.looseObject({sort:SortOrderEnum2,colId:z.string()}),DataRequestOffset=z.looseObject({start:z.number(),count:z.number()});z.looseObject({filter:zodHelpers.extendedOptional(z.looseObject({})),ORFilters:zodHelpers.extendedOptional(z.array(z.looseObject({}))),groupKeys:zodHelpers.extendedOptional(z.array(z.string())),rowGroupCols:zodHelpers.extendedOptional(z.array(z.string())),sort:zodHelpers.extendedOptional(z.array(SortOrder)),offset:zodHelpers.extendedOptional(DataRequestOffset),excludeFields:zodHelpers.extendedOptional(z.array(z.string()))});var ZodSchemas={RefreshDataRequest:RefreshDataRequest,UserLayoutDefinition:UserLayoutDefinition,Command:Command2,RefreshDataResponse:RefreshDataResponse,HelloRequest:HelloRequest,HelloResponse:HelloResponse,GoodbyeRequest:GoodbyeRequest,RefreshTokenRequest:RefreshTokenRequest,RefreshTokenResponse:RefreshTokenResponse,SaveUserLayoutRequest:SaveUserLayoutRequest,RenameLayoutRequest:RenameLayoutRequest,SetDefaultLayoutRequest:SetDefaultLayoutRequest,AddCommandResultRequest:AddCommandResultRequest,AddCommandFileResultRequest:AddCommandFileResultRequest,AppPreferences:AppPreferences,AddOrUpdatePrefsRequest:AddOrUpdatePrefsRequest,Feedback:Feedback,HttpTestRequest:HttpTestRequest,HttpTestResponse:HttpTestResponse},RequestValidator=class{constructor(e){this.options=e}async validateRequestBody(e){if(this.options.disableRequestBodyValidation)return;const{requestBody:t,schema:r,operationName:n,endpointName:i}=e(),o=await r.safeParseAsync(t,{reportInput:!0});if(!o.success)throw new IOManagerRequestValidationError(`Request body schema validation failed for endpoint "${i}" (${n})`,{cause:o.error,schema:r})}async validateResponseBody(e){if(this.options.disableResponseBodyValidation)return;const{responseBody:t,schema:r,operationName:n,endpointName:i}=e(),o=await r.safeParseAsync(t,{reportInput:!0});if(!o.success)throw new IOManagerRequestValidationError(`Response body schema validation failed for endpoint "${i}" (${n})`,{cause:o.error,schema:r})}},IOManagerRequestValidationError=class extends Error{#c;constructor(e,t){super(e,t),this.name="IOManagerRequestValidationError",this.#c=t}getZodError(){return this.#c.cause}getSchema(){return this.#c.schema}},ClientAPI=class extends BaseAPI{sessionTokenString;sessionToken;requestLogger;requestValidator;constructor(e){super(e),this.setOptions(e)}setOptions(e){super.setOptions(e),this.sessionTokenString&&this.updateToken(this.sessionTokenString),e.logger&&(this.requestLogger=new RequestLogger(e.logger,e.requestLoggerLevel??"trace",e.disableLogSanitization??!1,e.logHTTPHeaders??!1)),this.requestValidator=new RequestValidator({disableLogSanitization:e.disableLogSanitization??!1,disableRequestBodyValidation:e.disableRequestBodyValidation??!1,disableResponseBodyValidation:e.disableResponseBodyValidation??!1})}unload(){this.sessionToken&&this.sessionTokenString&&this.unloadClient(this.sessionToken.session,this.sessionTokenString)}async refreshData(e,t){const r="POST",n="/user",i=`${r} ${n}`,o="refreshData";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.RefreshDataRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixRefreshDataResponse(s?.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.RefreshDataResponse,operationName:o,endpointName:i})),s.body}async getApps(e){const t="/user/apps",r=`GET ${t}`,n="getApps";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:z.array(z.looseObject({})),operationName:n,endpointName:r})),i.body}async getLayouts(e){const t="/user/layouts",r=`GET ${t}`,n="getLayouts";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),this.fixLayouts(i.body),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:z.array(ZodSchemas.UserLayoutDefinition),operationName:n,endpointName:r})),i.body}async saveLayout(e,t){const r="POST",n="/user/layouts",i=`${r} ${n}`,o="saveLayout";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.SaveUserLayoutRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixLayout(s.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.UserLayoutDefinition,operationName:o,endpointName:i})),s.body}async deleteUserLayout(e,t){const r="DELETE",n=`${r} /user/layouts/:id`,i="deleteUserLayout";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{id:e}}));const o=await this.sendRequest({method:r,url:`/user/layouts/${customEncodeURIComponent(e)}`,...t});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async deleteAllUserLayouts(e){const t="DELETE",r="/user/layouts/",n=`${t} ${r}`,i="deleteAllUserLayouts";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i}));const o=await this.sendRequest({method:t,url:r,...e});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o})),this.fixLayouts(o.body),await this.requestValidator.validateResponseBody(()=>({responseBody:o.body,schema:z.array(ZodSchemas.UserLayoutDefinition),operationName:i,endpointName:n})),o.body}async renameLayout(e,t,r){const n="POST",i=`${n} /user/layouts/:id/rename`,o="renameLayout",s={newName:t};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,pathParameters:{id:e},requestBody:s})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.RenameLayoutRequest,operationName:o,endpointName:i}));const a=await this.sendRequest({method:n,url:`/user/layouts/${customEncodeURIComponent(e)}/rename`,body:s,...r});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:a})),this.fixLayout(a.body),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:ZodSchemas.UserLayoutDefinition,operationName:o,endpointName:i})),a.body}async getDefaultLayout(e){const t="/user/layouts/default",r=`GET ${t}`,n="getDefaultLayout";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});if(this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),204!==i.statusCode)return await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:ZodSchemas.UserLayoutDefinition,operationName:n,endpointName:r})),this.fixLayout(i.body),i.body}async setDefaultLayout(e,t){const r="POST",n="/user/layouts/default",i=`${r} ${n}`,o="setDefaultLayout",s={id:e};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:s})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.SetDefaultLayoutRequest,operationName:o,endpointName:i}));const a=await this.sendRequest({method:r,url:n,body:s,...t});if(this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:a})),204!==a.statusCode)return this.fixLayout(a.body),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:zodHelpers.extendedOptional(ZodSchemas.UserLayoutDefinition),operationName:o,endpointName:i})),a.body}async openSession(e,t,r,n){const i="POST",o="/user/hello",s=`${i} ${o}`,a="openSession",c={machine:e,glue:t,...r??{}},l={"serverx-token":""};this.requestLogger?.logRequest(()=>({endpointName:s,operationName:a,requestBody:c,headers:l})),await this.requestValidator.validateRequestBody(()=>({requestBody:c,schema:ZodSchemas.HelloRequest,operationName:a,endpointName:s}));const u=await this.sendRequest({method:i,url:o,body:c,headers:l,...n});this.requestLogger?.logResponse(()=>({endpointName:s,operationName:a,response:u,sanitizeResponseBodyProperties:["token"]})),this.fixRefreshDataResponse(u?.body?.data),await this.requestValidator.validateResponseBody(()=>({responseBody:u.body,schema:ZodSchemas.HelloResponse,operationName:a,endpointName:s}));const d=this.updateToken(u.body.token);return u.body.serverInfo&&this.initializeServerInfo(u.body.serverInfo),{...u.body,token:d}}async closeSession(e,t){if(!(e=e??this.sessionToken.session))throw new Error("no active session");const r="POST",n="/user/goodbye",i=`${r} ${n}`,o="closeSession",s={session:e},a={"serverx-token":""};this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:s,headers:a})),await this.requestValidator.validateRequestBody(()=>({requestBody:s,schema:ZodSchemas.GoodbyeRequest,operationName:o,endpointName:i}));const c=await this.sendRequest({method:r,url:n,body:s,headers:a,...t});this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:c}))}async refreshToken(e){const t="POST",r="/user/refresh",n=`${t} ${r}`,i="refreshToken",o={token:this.sessionTokenString};this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,requestBody:o,sanitizeRequestBodyProperties:["token"]})),await this.requestValidator.validateRequestBody(()=>({requestBody:o,schema:ZodSchemas.RefreshTokenRequest,operationName:i,endpointName:n}));const s=await this.sendRequest({method:t,url:r,body:o,...e});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:s,sanitizeResponseBodyProperties:["token"]})),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.RefreshTokenResponse,operationName:i,endpointName:n})),this.updateToken(s.body.token)}async getCommands(e){const t="GET /user/commands/:session",r="getCommands";this.requestLogger?.logRequest(()=>({endpointName:t,operationName:r,pathParameters:{session:this.sessionToken.session}}));const n=await this.sendRequest({method:"GET",url:`/user/commands/${customEncodeURIComponent(this.sessionToken.session)}`,...e});return this.requestLogger?.logResponse(()=>({endpointName:t,operationName:r,response:n})),await this.requestValidator.validateResponseBody(()=>({responseBody:n.body,schema:z.array(ZodSchemas.Command),operationName:r,endpointName:t})),n.body}async setCommandResult(e,t,r){const n="POST",i=`${n} /user/commands/:commandId`,o="setCommandResult";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,pathParameters:{commandId:e},requestBody:t})),await this.requestValidator.validateRequestBody(()=>({requestBody:t,schema:ZodSchemas.AddCommandResultRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:n,url:`/user/commands/${customEncodeURIComponent(e)}`,body:t,...r});this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s}))}async setCommandFileResult(e,t,r,n){const i="POST",o=`${i} /user/commands/:commandId/file`,s="setCommandFileResult",a={fileName:t,contents:r};this.requestLogger?.logRequest(()=>({endpointName:o,operationName:s,pathParameters:{commandId:e},requestBody:a,sanitizeRequestBodyProperties:["contents"]})),await this.requestValidator.validateRequestBody(()=>({requestBody:a,schema:ZodSchemas.AddCommandFileResultRequest,operationName:s,endpointName:o}));const c=await this.sendRequest({method:i,url:`/user/commands/${customEncodeURIComponent(e)}/file`,body:a,...n});this.requestLogger?.logResponse(()=>({endpointName:o,operationName:s,response:c}))}async getPrefs(e,t,r){const n="GET /user/prefs/:app",i="getPrefs";let o=`/user/prefs/${customEncodeURIComponent(e)}`;const s=new URLSearchParams;t&&s.set("last",t.getTime().toString()),o+=`?${s.toString()}`,this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{app:e},queryParameters:Object.fromEntries(s.entries())}));const a=await this.sendRequest({method:"GET",url:o,validateStatusCode:e=>e<400||404===e,...r});return this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:a})),404===a.statusCode&&(a.body=void 0),await this.requestValidator.validateResponseBody(()=>({responseBody:a.body,schema:zodHelpers.extendedOptional(ZodSchemas.AppPreferences),operationName:i,endpointName:n})),a.body}async getAllPrefs(e){const t="/user/prefs/",r=`GET ${t}`,n="getAllPrefs";this.requestLogger?.logRequest(()=>({endpointName:r,operationName:n}));const i=await this.sendRequest({method:"GET",url:t,...e});return this.requestLogger?.logResponse(()=>({endpointName:r,operationName:n,response:i})),await this.requestValidator.validateResponseBody(()=>({responseBody:i.body,schema:ZodSchemas.AppPreferences.array(),operationName:n,endpointName:r})),i.body}async setPrefs(e,t){const r="POST",n="/user/prefs/",i=`${r} ${n}`,o="setPrefs";this.requestLogger?.logRequest(()=>({endpointName:i,operationName:o,requestBody:e})),await this.requestValidator.validateRequestBody(()=>({requestBody:e,schema:ZodSchemas.AddOrUpdatePrefsRequest,operationName:o,endpointName:i}));const s=await this.sendRequest({method:r,url:n,body:e,...t});return this.requestLogger?.logResponse(()=>({endpointName:i,operationName:o,response:s})),this.fixSetPrefsResponse(s?.body),await this.requestValidator.validateResponseBody(()=>({responseBody:s.body,schema:ZodSchemas.AppPreferences,operationName:o,endpointName:i})),s.body}async deletePrefs(e,t){const r="DELETE",n=`${r} /user/prefs/:app`,i="deletePrefs";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i,pathParameters:{app:e}}));const o=await this.sendRequest({method:r,url:`/user/prefs/${customEncodeURIComponent(e)}`,...t});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async deleteAllPrefs(e){const t="DELETE",r="/user/prefs/",n=`${t} ${r}`,i="deleteAllPrefs";this.requestLogger?.logRequest(()=>({endpointName:n,operationName:i}));const o=await this.sendRequest({method:t,url:r,...e});this.requestLogger?.logResponse(()=>({endpointName:n,operationName:i,response:o}))}async addFeedback(e,t,r){const n="POST",i="/user/feedbacks",o=`${n} ${i}`,s="addFeedback",a=new FormData$1;a.append("description",e),a.append("attachment",t),this.requestLogger?.logRequest(()=>({endpointName:o,operationName:s}));const c=await this.sendRequest({method:n,url:i,body:a,json:!1,...r});return this.requestLogger?.logResponse(()=>({endpointName:o,operationName:s,response:c})),await this.requestValidator.validateResponseBody(()=>({responseBody:c.body,schema:ZodSchemas.Feedback,operationName:s,endpointName:o})),c.body}async httpTest(e,t,r,n){this.ensureCapability("HTTP_TEST");const i="POST",o="/user/http-test",s=`${i} ${o}`,a="httpTest",c=new URLSearchParams;c.append("statusCode",e?.toString());const l=`${o}?${c.toString()}`,u={};r&&(u["X-Custom-IOManager-Header"]=r),this.requestLogger?.logRequest(()=>({endpointName:s,operationName:a,requestBody:t,queryParams:Object.fromEntries(c.entries()),headers:u})),await this.requestValidator.validateRequestBody(()=>({requestBody:t,schema:zodHelpers.extendedOptional(ZodSchemas.HttpTestRequest),operationName:a,endpointName:s}));const d=await this.sendRequest({method:i,url:l,body:t,headers:u,validateStatusCode:()=>!0,...n});return this.requestLogger?.logResponse(()=>({endpointName:s,operationName:a,response:d})),await this.requestValidator.validateResponseBody(()=>({responseBody:d.body,schema:ZodSchemas.HttpTestResponse,operationName:a,endpointName:s})),d}fixRefreshDataResponse(e){"string"==typeof e?.config?.info?.last&&(e.config.info.last=Number(e.config.info.last)),"string"==typeof e?.commands?.info?.last&&(e.commands.info.last=Number(e.commands.info.last)),"string"==typeof e?.applications?.info?.last&&(e.applications.info.last=Number(e.applications.info.last)),"string"==typeof e?.layouts?.info?.last&&(e.layouts.info.last=Number(e.layouts.info.last)),this.fixLayouts(e?.layouts?.data)}fixSetPrefsResponse(e){"string"==typeof e?.data&&(e.data=JSON.parse(e.data))}fixLayouts(e){if(Array.isArray(e))for(const t of e)this.fixLayout(t)}fixLayout(e){if(!e)return;let t;function r(){if(!t)try{t=JSON.parse(e.definition)}catch{}}"string"!=typeof e.name&&(r(),e.name="string"==typeof t?.name?t.name:""),"string"!=typeof e.type&&(r(),e.type="string"==typeof t?.type?t.type:"")}updateToken(e){return this.sessionToken=jwtDecode(e),this.sessionTokenString=e,this.options.headers=this.options.headers??{},this.options.headers["serverx-token"]=e,this.sessionToken}async sendRequest(e){return this.options.req?this.callCustomRequestImplementation(e):this.callAxiosRequestImplementation(e)}async callAxiosRequestImplementation(e){const t=await this.axiosInstance.request({method:e.method,url:e.url,headers:e.headers,timeout:e.timeout,data:e.body,validateStatus:e.validateStatusCode??this.defaultIsStatusCodeValid});return{body:t.data,statusCode:t.status,headers:t.headers}}async callCustomRequestImplementation(e){if(!this.options.req)throw new Error("this.options.req is falsy.");const t={...e,method:e.method?.toLowerCase(),baseUrl:e.baseUrl??this.options.baseUrl,url:this.resolveFullUrl(e.url,e.baseUrl??this.options.baseUrl),json:e.json??!0,timeout:e.timeout??this.options.requestTimeout},r={...this.getBaseHeaders(this.options)??{},...await(this.options.getHeaders?.(t)),...e.headers??{}};t.headers=r,this.interceptCustomRequest?.(t),this.requestLogger?.logRequestHeaders(()=>t.headers);const n=new PromiseWrapper;return this.options.req(t,(r,i)=>{if(r)if(this.interceptCustomResponseError){const e=this.interceptCustomResponseError?.(t,r,void 0);n.reject(e)}else n.reject(r);else{if(i?.body){const e=this.options?.transformResponse;i.body=e?.(i.body,i.headers)??i.body}this.requestLogger?.logResponseHeaders(()=>i?.headers);const r=e.validateStatusCode??this.defaultIsStatusCodeValid;if(i?.statusCode&&!r(i.statusCode)){const e=new CustomRequestError(`Request failed with status code ${i.statusCode}`),r=Math.floor(i.statusCode/100);if(4===r?e.code="ERR_BAD_REQUEST":5===r&&(e.code="ERR_BAD_RESPONSE"),this.interceptCustomResponseError){const r=this.interceptCustomResponseError?.(t,e,i);n.reject(r)}else n.reject(e)}else this.interceptCustomResponse?.(t,i),n.resolve(i)}}),n.promise}resolveFullUrl(e,t){let r=e;r.startsWith("/")&&(r=r.substring(1));let n=t;return n.endsWith("/")||(n+="/"),new URL(r,n).href}interceptCustomRequest;interceptCustomResponse;interceptCustomResponseError},CustomRequestError=class extends Error{code;status},SanitizedIOManagerApiError=class e extends Error{code;status;isSessionExpired;isCustomTimeoutError;validationErrors;request;responseBodyError;static fromAxiosError(t){const r=Number(t?.response?.status),n=t?.response?.data;let i;if(t?.message)i=t?.message;else if("errors"in t&&t?.errors&&Array.isArray(t?.errors)){const e=t?.errors?.map(e=>e?.message).filter(e=>e);e.length&&(i=e.join(", "))}const o=new e(i);if(o.name="SanitizedIOManagerApiError",o.stack=t?.stack,t instanceof IOManagerRequestValidationError){const e=t;o.validationErrors=e.getZodError().issues}Number.isFinite(r)&&(o.status=r),t?.code&&(o.code=t?.code),o.request={baseUrl:t?.config?.baseURL,url:t?.config?.url,method:t?.config?.method};const s=400===r&&"invalid-glue42-server-token"===n?.error?.message;return s&&(o.isSessionExpired=s),o.responseBodyError=n?.error,o}static fromCustomRequestError(t,r,n){const i=Number(r?.statusCode),o=r?.body,s=new e(n?.message);if(s.name="SanitizedIOManagerApiError",s.stack=n?.stack,n instanceof IOManagerRequestValidationError){const e=n;s.validationErrors=e.getZodError().issues}let a;Number.isFinite(i)&&(s.status=i),n?.code?s.code=n?.code:n?.message?.includes("net::ERR_CONNECTION_REFUSED")&&(s.code="ECONNREFUSED"),t.baseUrl&&t.url.startsWith(t.baseUrl)?(a=t.url.slice(t.baseUrl.length),a.startsWith("/")||(a=`/${a}`)):a=t.url,s.request={baseUrl:t.baseUrl,url:a,method:t.method};const c=400===i&&"invalid-glue42-server-token"===o?.error?.message;return c&&(s.isSessionExpired=c),s.responseBodyError=o?.error,n.isCustomTimeoutError&&(s.isCustomTimeoutError=n.isCustomTimeoutError),s}},CachedClientAPI=class extends ClientAPI{get connectionState(){return{isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching,disconnectionError:this._disconnectionError}}get token(){return this.sessionToken?this.sessionToken:this.options.enableCaching?this._cachedToken:void 0}_callbacks=CallbackRegistryFactory$2();_isConnected=!1;_refreshTokenIntervalId;_refreshDataIntervalId;_slowestRequests=[];_statParams;_lastApplicationsInfo;_lastLayoutsInfo;_lastCommandsInfo;_lastConfigsInfo;_lastApplicationsData;_lastLayoutsData;_lastConfigsData;_cachedToken;_disconnectionError;_sessionNotPersisted;_cachedClientRequestInterceptor;_cachedClientResponseInterceptor;get logger(){return this.options.logger}get cache(){if(!this.options.enableCaching)throw new Error("Accessing the cache is not allowed when caching is disabled.");return this.options.managerCache}constructor(e){super(e),this.setOptions(e)}setOptions(e){e.refresh??={},e.refresh.applications??=!0,e.refresh.layouts??=!0,e.refresh.commands??=!0,e.refresh.configs??=!1,super.setOptions(e);const t=e=>{const t={startTime:this.getNowMs(),startTimeDate:new Date,operation:`${e.method} ${e.url}`};e.__perf=t},r=e=>{const t=e.__perf;t.endTime=this.getNowMs(),t.duration=t.endTime-t.startTime,this._slowestRequests.push(t),this._slowestRequests.sort((e,t)=>t.duration-e.duration),this._slowestRequests.length>5&&this._slowestRequests.pop()};this._cachedClientRequestInterceptor&&this.axiosInstance.interceptors?.request?.eject(this._cachedClientRequestInterceptor),this._cachedClientRequestInterceptor=this.axiosInstance.interceptors.request.use(e=>(t(e),e),e=>e?.config?.method?Promise.reject(SanitizedIOManagerApiError.fromAxiosError(e)):Promise.reject(e)),this.interceptCustomRequest=e=>{t(e)},this._cachedClientResponseInterceptor&&this.axiosInstance.interceptors?.response?.eject(this._cachedClientResponseInterceptor),this._cachedClientResponseInterceptor=this.axiosInstance.interceptors.response.use(e=>(r(e.config),e),e=>(r(e.config),e?.config?.method?Promise.reject(SanitizedIOManagerApiError.fromAxiosError(e)):Promise.reject(e))),this.interceptCustomResponse=e=>{r(e)},this.interceptCustomResponseError=(e,t,n)=>(r(e),SanitizedIOManagerApiError.fromCustomRequestError(e,n,t))}async start(...e){this._statParams=e;const t=this._statParams[2]??={};let r;t.initialDataRequest??=this.createRefreshDataRequest(!0),t.includeServerInfo=!0,this.logger.info(`Initiating connection to ${this.options.baseUrl}`);let n=!1;try{let e;if(this.logger.info("Opening a session..."),this.options.enableCaching){const i=await this.cache.get("session");if(i&&(this._cachedToken=i.value),r=await this.readDataCache(t.initialDataRequest),n=Boolean(i&&r),n){const t=[...this._statParams];t[3]??={},t[3].timeout=this.options.openSessionRequestTimeout,e=await super.openSession(...t)}else e=await this.retryStart(...this._statParams)}else e=await this.retryStart(...this._statParams);return this.logger.info(`Session opened. Initial data received: ${this.getSnapshotSummary(e.data).join(", ")}`),this._sessionNotPersisted=e.sessionNotPersisted,e.sessionNotPersisted&&this.logger.warn("Session was opened in read-only mode and was not persisted on the server."),this.writeToFields(e.data),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",e.token),await this.cache.set("sessionNotPersisted",e.sessionNotPersisted),await this.writeDataCache(e.data)),this.notifyConnected(),this.startTokenTimer(),this.startDataTimer(),e}catch(e){if(this.notifyDisconnected(e),!this.options.enableCaching)throw this.logger.error("Failed to open a session.",e),e;if(!n)throw this.logger.error("Failed to open a session. Cache miss.",e),e;this.logger.warn("Failed to open a session. Proceeding from cache.",e);const t=await this.cache.get("sessionNotPersisted");return t?.value&&this.logger.warn("Cached session was opened in read-only mode and was not persisted on the server."),this.writeToFields(r),this.startTokenTimer(),this.startDataTimer(),{token:this._cachedToken,data:r}}}async stop(){this.stopTokenTimer(),this.stopDataTimer(),this.logger.info("Slowest requests:");for(const e of this._slowestRequests)this.logger.info(`${e.startTimeDate.toISOString()} - operation: ${e.operation}, duration (ms): ${e.duration}`);this.logger.info("Closing session."),await super.closeSession(void 0,{timeout:this.options.closeSessionRequestTimeout})}onConnectedStateChanged(e){return this._callbacks.add("onConnectedStateChanged",e)}async onAppsChanged(e){const t=this._callbacks.add("onAppsChanged",e);try{this._lastApplicationsData&&(this.logger.debug("Calling onAppsChanged",this._lastApplicationsData),this._callbacks.execute("onAppsChanged",this._lastApplicationsData))}catch(e){throw t(),e}return t}async onLayoutsChanged(e){const t=this._callbacks.add("onLayoutsChanged",e);try{this._lastLayoutsData&&(this.logger.debug("Calling onLayoutsChanged",this._lastLayoutsData),this._callbacks.execute("onLayoutsChanged",this._lastLayoutsData))}catch(e){throw t(),e}return t}async onCommandsReceived(e){return this._callbacks.add("onCommandsReceived",e)}async onConfigsChanged(e){const t=this._callbacks.add("onConfigsChanged",e);try{this._lastConfigsData&&(this.logger.debug("Calling onConfigsChanged",this._lastConfigsData),this._callbacks.execute("onConfigsChanged",this._lastConfigsData))}catch(e){throw t(),e}return t}openSession(...e){throw new Error("Calling `openSession` directly is not supported. Call `start` instead.")}closeSession(...e){throw new Error("Calling `closeSession` directly is not supported. Call `stop` instead.")}async refreshData(...e){this.logger.isTraceEnabled()?this.logger.trace(`Requesting data changes: ${JSON.stringify(e[0])}`):this.logger.info(`Requesting data changes: ${JSON.stringify(this.sanitizeGroups(e[0]))}`);let t=!1;try{const r=await this.handleAuth(async r=>(t=Boolean(r),r?r.data:await super.refreshData(...e)));if(this.notifyConnected(),r&&!t){const e=this.getSnapshotSummary(r);e.length?this.logger.info(`Data received: ${e.join(", ")}`):this.logger.info("No new data was received."),this.writeToFields(r),this.options.enableCaching&&await this.writeDataCache(r)}return r}catch(t){if(this.notifyDisconnected(t),!this.options.enableCaching)throw this.logger.debug("Refresh data request failed.",t),t;const r=await this.readDataCache(e[0]);if(!r)throw this.logger.debug("Refresh data request failed. Cache miss.",t),t;return this.logger.warn("Refresh data request failed. Returning data from cache.",t),r}}async refreshToken(...e){this.logger.info("Refreshing session token.");try{const t=await this.handleAuth(()=>super.refreshToken(...e));return this.notifyConnected(),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",t)),t}catch(e){throw this.notifyDisconnected(e),this.logger.debug("Refresh token request failed.",e),e}}async getPrefs(...e){const t=e[0];try{const r=await this.handleAuth(()=>super.getPrefs(...e));return this.notifyConnected(),this.options.enableCaching&&await this.updateAllPreferencesCache(t,r),r}catch(e){if(this.notifyDisconnected(e),!this.options.enableCaching)throw this.logger.debug("getPrefs request failed.",e),e;const r=await this.cache.get("prefs_data");if(!r)throw this.logger.debug("getPrefs request failed. Cache miss.",e),e;this.logger.debug("getPrefs request failed. Returning data from cache.",e);const n=r.value.find(e=>e.app===t);return n&&"string"==typeof n?.data&&(n.data=JSON.parse(n.data)),n}}getAllPrefs(...e){return this.handleRead("getAllPrefs","prefs_data",()=>super.getAllPrefs(...e))}getDefaultLayout(...e){return this.handleRead("getDefaultLayout","read_getDefaultLayout",()=>super.getDefaultLayout(...e))}whoAmI(...e){return this.handleRead("whoAmI","read_whoAmI",()=>super.whoAmI(...e))}async getLayouts(...e){const t=await this.handleRead("getLayouts","layouts_data",()=>super.getLayouts(...e));return this._lastLayoutsData=t,this._callbacks.execute("onLayoutsChanged",t),t}getLastLayouts(){return this._lastLayoutsData}getLastApps(){return this._lastApplicationsData}async getApps(...e){const t=await this.handleRead("getApps","applications_data",()=>super.getApps(...e));return this._lastApplicationsData=t,this._callbacks.execute("onAppsChanged",t),t}async getCommands(...e){const t=await this.handleAuth(()=>super.getCommands(...e));return this._callbacks.execute("onCommandsReceived",t),t}setPrefs(...e){return this.handleWrite("setPrefs","write_setPrefs",()=>super.setPrefs(...e))}setCommandResult(...e){return this.handleWrite("setCommandResult","write_setCommandResult",()=>super.setCommandResult(...e))}addFeedback(...e){return this.handleWrite("addFeedback","write_addFeedback",()=>super.addFeedback(...e))}setDefaultLayout(...e){return this.handleWrite("setDefaultLayout","write_setDefaultLayout",()=>super.setDefaultLayout(...e))}deleteAllPrefs(...e){return this.handleWrite("deleteAllPrefs","write_deleteAllPrefs",()=>super.deleteAllPrefs(...e))}deleteAllUserLayouts(...e){return this.handleWrite("deleteAllUserLayouts","write_deleteAllUserLayouts",()=>super.deleteAllUserLayouts(...e))}setCommandFileResult(...e){return this.handleWrite("setCommandFileResult","write_setCommandFileResult",()=>super.setCommandFileResult(...e))}saveLayout(...e){return this.handleWrite("saveLayout","write_saveLayout",()=>super.saveLayout(...e))}renameLayout(...e){return this.handleWrite("renameLayout","write_renameLayout",()=>super.renameLayout(...e))}deletePrefs(...e){return this.handleWrite("deletePrefs","write_deletePrefs",()=>super.deletePrefs(...e))}deleteUserLayout(...e){return this.handleWrite("deleteUserLayout","write_deleteUserLayout",()=>super.deleteUserLayout(...e))}notifyDisconnected(e){if(this._isConnected){this._isConnected=!1,this._disconnectionError=e,this.logger.warn("io.Manager connection state changed: disconnected.",e);const t={isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching,disconnectionError:e};this._callbacks.execute("onConnectedStateChanged",t)}}notifyConnected(){if(!this._isConnected){this._isConnected=!0,this._disconnectionError=void 0,this.logger.info("io.Manager connection state changed: connected.");const e={isConnected:this._isConnected,baseUrl:this.options.baseUrl,serverEnabled:!0,cacheEnabled:this.options.enableCaching};this._callbacks.execute("onConnectedStateChanged",e)}}async refreshTokenTimeout(){try{this.options.asyncSequelizer?await this.options.asyncSequelizer.enqueue(async()=>{await this.refreshToken()}):await this.refreshToken()}catch(e){this.logger.warn("Refresh token request failed.",e)}finally{this.startTokenTimer()}}async refreshDataTimeout(){const e=this.createRefreshDataRequest();try{this.options.asyncSequelizer?await this.options.asyncSequelizer.enqueue(async()=>{await this.refreshData(e)}):await this.refreshData(e)}catch(e){this.logger.warn("Refresh data request failed.",e)}finally{this.startDataTimer()}}createRefreshDataRequest(e){return{applications:{include:Boolean(this.options.refresh?.applications),latestDataInfo:e?void 0:this._lastApplicationsInfo},layouts:{include:Boolean(this.options.refresh?.layouts),latestDataInfo:e?void 0:this._lastLayoutsInfo},commands:{include:Boolean(this.options.refresh?.commands),latestDataInfo:e?void 0:this._lastCommandsInfo},configs:{include:Boolean(this.options.refresh?.configs),latestDataInfo:e?void 0:this._lastConfigsInfo}}}startTokenTimer(){this.logger.info(`Starting the session token refresh timer for ${this.options.tokenRefreshInterval}s`),this._refreshTokenIntervalId=setTimeout(this.refreshTokenTimeout.bind(this),1e3*this.options.tokenRefreshInterval)}startDataTimer(){this.logger.info(`Starting data refresh timer for ${this.options.fetchInterval}s`),this._refreshDataIntervalId=setTimeout(this.refreshDataTimeout.bind(this),1e3*this.options.fetchInterval)}async recreateSession(e){if(this.logger.debug("Opening a session..."),e&&!this._sessionNotPersisted)try{this.logger.debug("Closing old session."),await super.closeSession(e,{timeout:this.options.closeSessionRequestTimeout}),this.logger.debug("Old session closed.")}catch(e){this.logger.debug("Failed to close old session.",e)}const t=await super.openSession(...this._statParams);return this.logger.info(`Session opened. Initial data received: ${this.getSnapshotSummary(t.data).join(", ")}`),this._sessionNotPersisted=t.sessionNotPersisted,t.sessionNotPersisted&&this.logger.warn("Session was opened in read-only mode and was not persisted on the server."),this.writeToFields(t.data),this.options.enableCaching&&(this.logger.info("Writing session info to cache."),await this.cache.set("session",t.token),await this.cache.set("sessionNotPersisted",t.sessionNotPersisted),await this.writeDataCache(t.data)),t}stopTokenTimer(){this.logger.info("Stopping the session token refresh timer."),this._refreshTokenIntervalId&&clearTimeout(this._refreshTokenIntervalId)}stopDataTimer(){this.logger.info("Stopping the data refresh timer."),this._refreshDataIntervalId&&clearTimeout(this._refreshDataIntervalId)}writeToFields(e){e.applications?.hasChanges&&(this._lastApplicationsData=e.applications.data,this._lastApplicationsInfo=e.applications.info,this._callbacks.execute("onAppsChanged",e.applications.data)),e.layouts?.hasChanges&&(this._lastLayoutsData=e.layouts.data,this._lastLayoutsInfo=e.layouts.info,this._callbacks.execute("onLayoutsChanged",e.layouts.data)),e.config?.hasChanges&&(this._lastConfigsData=e.config.data,this._lastConfigsInfo=e.config.info,this._callbacks.execute("onConfigsChanged",e.config.data)),e.commands?.hasChanges&&(this._lastCommandsInfo=e.commands.info,this._callbacks.execute("onCommandsReceived",e.commands.data))}async writeDataCache(e){e.applications?.hasChanges&&(await this.cache.set("applications_data",e.applications.data),await this.cache.set("applications_info",e.applications.info)),e.layouts?.hasChanges&&(await this.cache.set("layouts_data",e.layouts.data),await this.cache.set("layouts_info",e.layouts.info)),e.config?.hasChanges&&(await this.cache.set("config_data",e.config.data),await this.cache.set("config_info",e.config.info)),e.commands?.hasChanges&&await this.cache.set("commands_info",e.commands.info)}async readDataCache(e){const t={};if(!0===e.applications?.include){const r=await this.cache.get("applications_info");if(!r)return void this.logger.debug('readDataCache: Could not find "applications_info" in cache.');if(this.lastDataInfoEquals(e.applications?.latestDataInfo,r.value))t.applications={hasChanges:!1};else{const e=await this.cache.get("applications_data");t.applications={hasChanges:!0,data:e?.value,info:r.value}}}if(!0===e.layouts?.include){const r=await this.cache.get("layouts_info");if(!r)return void this.logger.debug('readDataCache: Could not find "layouts_info" in cache.');if(this.lastDataInfoEquals(e.layouts?.latestDataInfo,r.value))t.layouts={hasChanges:!1};else{const e=await this.cache.get("layouts_data");t.layouts={hasChanges:!0,data:e?.value,info:r.value}}}if(!0===e.configs?.include){const r=await this.cache.get("config_info");if(!r)return void this.logger.debug('readDataCache: Could not find "config_info" in cache.');if(this.lastDataInfoEquals(e.configs?.latestDataInfo,r.value))t.config={hasChanges:!1};else{const e=await this.cache.get("config_data");t.config={hasChanges:!0,data:e?.value,info:r.value}}}return t}async updateAllPreferencesCache(e,t){const r=await this.cache.get("prefs_data");let n=r?.value||[];if(t){const r=n.findIndex(t=>t.app===e);-1!==r?n[r]=t:n.push(t)}else n=n.filter(t=>t.app!==e);await this.cache.set("prefs_data",n)}lastDataInfoEquals(e,t){return!(!e||!t)&&(e.checksum===t.checksum||Number(e.last)===Number(t.last))}async handleRead(e,t,r){this.logger.debug(`calling handleRead operationName=${e} cacheKey=${t}`);try{const e=await this.handleAuth(r);return this.notifyConnected(),this.options.enableCaching&&await this.cache.set(t,e),e}catch(r){if(this.notifyDisconnected(r),!this.options.enableCaching)throw this.logger.debug(`${e} request failed.`,r),r;const n=await this.cache.get(t);if(!n)throw this.logger.debug(`${e} request failed. Cache miss.`,r),r;if(this.logger.debug(`${e} request failed. Returning data from cache.`,r),"prefs_data"===t){const e=n.value;if(e)for(const t of e)"string"==typeof t.data&&(t.data=JSON.parse(t.data))}return n.value}}async handleWrite(e,t,r){this.logger.debug(`calling handleWrite operationName=${e} cacheKey=${t}`);try{const e=await this.handleAuth(r);return this.notifyConnected(),e}catch(t){const r=t;throw this.logger.debug(`${e} request failed.`,t),"ReadOnlyRequestViolationError"!==r.responseBodyError?.type&&this.notifyDisconnected(t),t}}async retryStart(...e){let t=0;for(;;)try{return t>0&&this.logger.info(`Opening a session [retry ${t} of ${this.options.startRetries}]`),await super.openSession(...e)}catch(e){if(t>=this.options.startRetries)throw e;this.logger.warn(`Failed to open a session. Retrying after ${this.options.startRetryInterval}s.`,e),t+=1,await new Promise(e=>setTimeout(e,1e3*this.options.startRetryInterval))}}getSnapshotSummary(e){const t=[];return e.applications?.hasChanges&&t.push(`applications (${e.applications.data?.length})`),e.layouts?.hasChanges&&t.push(`layouts (${e.layouts.data?.length})`),e.commands?.hasChanges&&t.push(`commands (${e.commands.data?.length})`),e.config?.hasChanges&&t.push(`remote configs (${e.config.data?.length})`),t}async handleAuth(e){let t;if(!this.sessionToken||!this.sessionTokenString||this._sessionNotPersisted){let e;if(this.sessionToken||this.logger.info("Session is not open (started from cache). Opening a session..."),this._sessionNotPersisted&&this.logger.info("Session is not persisted on the server (server was in read-only mode when it created it). Opening a new session..."),this.options.enableCaching){const t=await this.cache.get("session");e=t?.value?.session}try{t=await this.recreateSession(e)}catch(e){throw this.logger.warn("Failed to open a session.",e),e}}try{return await e(t)}catch(r){if(r?.isSessionExpired){try{this.logger.warn("Session expired. Opening a new session...",r),t=await this.recreateSession(this.sessionToken?.session)}catch(e){throw this.logger.warn("Failed to re-open the session.",e),r}return await e(t)}throw r}}getNowMs(){return this.options.getNowMs?this.options.getNowMs():Number(new Date)}sanitizeGroups(e){if(null==e)return e;if("object"!=typeof e)return e;const t=structuredClone(e);function r(e){return e?Array.isArray(e)?`__REMOVED(length=${e.length})`:"__REMOVED(NON_ARRAY_TRUTHY_VALUE)":"__REMOVED(falsy)"}return function e(t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))for(const r of t)e(r);else for(const n in t)t.hasOwnProperty(n)&&("groups"===n?t[n]=r(t[n]):e(t[n]))}(t),t}};const managerOperationDecoder=oneOf$1(constant$2("operationCheck")),DEFAULT_RESPONSE_TIMEOUT_MS=1e4,PREFS_CACHE_KEY="prefs_data",LAYOUTS_CACHE_KEY="layouts_data",DEFAULT_LAYOUT_CACHE_KEY="read_getDefaultLayout",PREFS_CHANGED_EVENT_KEY="onPrefsChanged",APPS_ADDED_EVENT_KEY="onAppsAdded",APPS_DELETED_EVENT_KEY="onAppsDeleted",APPS_CHANGED_EVENT_KEY="onAppsChanged",LAYOUTS_CHANGED_EVENT_KEY="onLayoutsChanged",LAYOUTS_ADDED_EVENT_KEY="onLayoutsAdded",LAYOUTS_REMOVED_EVENT_KEY="onLayoutsRemoved",LAYOUTS_RENAMED_EVENT_KEY="onLayoutsRenamed",CONNECTED_STATE_CHANGED_EVENT_KEY="onConnectedStateChanged",defaultDataRefreshIntervalMS=6e4,defaultTokenRefreshIntervalMS=36e5;class ManagerController{identity;sequelizer;buildClient;buildCache;started=!1;name="io.Manager Client";globalConfig;config;unloadCallback;callbacks=CallbackRegistryFactory$2();lastApps=[];lastLayouts=[];lastLayoutIdsByKey=new Map;client;managerCache;get managerConnectionState(){const e={serverEnabled:!1,isConnected:!1};return this.config?this.client.connectionState:e}operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n){this.identity=e,this.sequelizer=t,this.buildClient=r,this.buildCache=n,this.unloadCallback=this.handleUnload.bind(this),window.addEventListener("pagehide",this.unloadCallback)}get logger(){return logger.get("manager.controller")}get isStarted(){return this.started}get isCritical(){return this.config?.critical??!0}ready(){return Promise.resolve()}handlePlatformShutdown(){this.started=!1,window.removeEventListener("pagehide",this.unloadCallback),this.handleUnload(),this.managerCache?.dispose()}async configurePostStart(){if(!this.config)return;const e=this.globalConfig?.user?.id||"__no_user__";this.managerCache=this.buildCache(this.config,e),await this.managerCache.initialize();const t={baseUrl:this.config.url,auth:this.config.auth,headers:this.config.headers,getHeaders:this.config.getHeaders,fetchInterval:(this.config.fetchIntervalMS||defaultDataRefreshIntervalMS)/1e3,tokenRefreshInterval:(this.config.tokenRefreshIntervalMS||defaultTokenRefreshIntervalMS)/1e3,startRetries:0,startRetryInterval:1e4,refresh:{applications:Boolean(this.config.features?.applicationsStore??!0),layouts:Boolean(this.config.features?.layoutsStore??!0),commands:!1,configs:!1},requestTimeout:this.config.requests?.timeout??this.config.responseTimeoutMS??DEFAULT_RESPONSE_TIMEOUT_MS,openSessionRequestTimeout:this.config.requests?.openSessionTimeout??DEFAULT_RESPONSE_TIMEOUT_MS,closeSessionRequestTimeout:this.config.requests?.closeSessionTimeout??DEFAULT_RESPONSE_TIMEOUT_MS,enableCaching:!0,managerCache:this.managerCache,asyncSequelizer:this.sequelizer,logger:this.createManagerLogger()};this.client=this.buildClient(t),this.logger?.trace("The client API is ready.");const r=await this.identity.getMachineInfo(e),n=this.identity.getGlueInfo();this.logger?.trace(`Opening a session for machine: ${JSON.stringify(r)} and glue: ${JSON.stringify(n)}`),this.client.onConnectedStateChanged(this.handleOnConnectedStateChanged.bind(this)),await this.client.onAppsChanged(this.handleOnAppsChanged.bind(this)),await this.client.onLayoutsChanged(this.handleOnLayoutsChanged.bind(this)),await this.client.start(r,n),this.config.features?.preferencesStore&&await this.client.getAllPrefs(),this.started=!0,this.logger?.info(`Module ${this.name} started`)}async start(e){e.manager&&(this.globalConfig=e,this.config=e.manager,this.logger?.info("Starting the Manager controller."))}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this manager control message, because the controller has not been started");const t=e.data,r=e.commandId,n=managerOperationDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This manager request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Manager request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Manager request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}onConnectedStateChanged(e){return this.callbacks.add(CONNECTED_STATE_CHANGED_EVENT_KEY,e)}async saveLayouts(e,t,r){return this.sequelizer.enqueue(async()=>{let n;if(r&&this.logger?.trace(`[${r}] handling "saveLayouts" request | mode=${t}`),n="replace"===t?await this.client.deleteAllUserLayouts():await this.getAllCachedLayouts(),e.length){const t=new Map;for(const e of n)t.set(this.getLayoutKey(e),e);for(const r of e){const e={type:r.type,name:r.name,definition:JSON.stringify(r)},n=await this.client.saveLayout(e);t.set(this.getLayoutKey(r),n)}n=Array.from(t.values()),await this.managerCache.set(LAYOUTS_CACHE_KEY,n)}this.handleOnLayoutsChanged(n),r&&this.logger?.trace(`[${r}] request completed, layouts saved`)})}async renameLayout(e,t,r,n){return this.sequelizer.enqueue(async()=>{n&&this.logger?.trace(`[${n}] handling "renameLayout" request | oldName=${e}, newName=${t}, type=${r}`);const i=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:r}));if(!i)throw new Error(`Layout with name="${e}" and type="${r}" not found.`);const o=await this.client.renameLayout(i,t),s={id:o.id,name:o.name,type:o.type,definition:o.definition};let a=await this.getAllCachedLayouts();a=a.filter(e=>e.id!==i),a.push(s),await this.managerCache.set(LAYOUTS_CACHE_KEY,a),this.setLastLayouts(a,this.parseLayouts(a));const c=this.parseLayouts([s]).map(t=>({...t,prevName:e}));this.callbacks.execute(LAYOUTS_RENAMED_EVENT_KEY,c),n&&this.logger?.trace(`[${n}] request completed, layout renamed`)})}async deleteLayout(e,t,r){return this.sequelizer.enqueue(async()=>{r&&this.logger?.trace(`[${r}] handling "deleteLayout" request | layoutName=${e}, type=${t}`);const n=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:t}));if(!n)throw new Error(`Layout with name="${e}" and type="${t}" not found.`);await this.client.deleteUserLayout(n);let i=await this.getAllCachedLayouts();i=i.filter(e=>e.id!==n),await this.managerCache.set(LAYOUTS_CACHE_KEY,i),this.handleOnLayoutsChanged(i),r&&this.logger?.trace(`[${r}] request completed, layout deleted`)})}async getAllLayouts(e,t){t&&this.logger?.trace(`[${t}] handling "getAllLayouts" request | type=${e}`);const r=this.lastLayouts.filter(t=>t.type===e);return t&&this.logger?.trace(`[${t}] request completed, layouts retrieved`),r}async getLayout(e,t,r){r&&this.logger?.trace(`[${r}] handling "getLayout" request | layoutName=${e}, type=${t}`);const n=this.lastLayouts.find(r=>r.name===e&&r.type===t);return r&&this.logger?.trace(`[${r}] request completed, layout retrieved`),n}onLayoutsChanged(e){return this.callbacks.add(LAYOUTS_CHANGED_EVENT_KEY,e)}onLayoutsAdded(e){return this.callbacks.add(LAYOUTS_ADDED_EVENT_KEY,e)}onLayoutsRemoved(e){return this.callbacks.add(LAYOUTS_REMOVED_EVENT_KEY,e)}onLayoutsRenamed(e){return this.callbacks.add(LAYOUTS_RENAMED_EVENT_KEY,e)}async clearDefaultLayout(e){return this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "clearDefaultLayout" request`);const t=await this.client.setDefaultLayout();await this.managerCache.set(DEFAULT_LAYOUT_CACHE_KEY,t),e&&this.logger?.trace(`[${e}] request completed, default layout cleared`)})}async getDefaultLayout(e){return this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "getDefaultLayout" request`);const t=await this.client.getDefaultLayout();if(!t)return;const r="string"==typeof t.definition?JSON.parse(t.definition):t.definition,n=glueLayoutDecoder.run(r);if(!n.ok)throw n.error;return e&&this.logger?.trace(`[${e}] request completed, default layout retrieved`),r})}async setDefaultLayout(e,t){return this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "setDefaultLayout" request`);const r=this.lastLayoutIdsByKey.get(this.getLayoutKey({name:e,type:"Global"}));if(!r)throw new Error(`Layout with name="${e}" and type="Global" not found.`);const n=await this.client.setDefaultLayout(r);await this.managerCache.set(DEFAULT_LAYOUT_CACHE_KEY,n),t&&this.logger?.trace(`[${t}] request completed, default layout set`)})}getAllApps(){return this.lastApps}onAppsAdded(e){return this.callbacks.add(APPS_ADDED_EVENT_KEY,e)}onAppsDeleted(e){return this.callbacks.add(APPS_DELETED_EVENT_KEY,e)}onAppsChanged(e){return this.callbacks.add(APPS_CHANGED_EVENT_KEY,e)}async getPrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "getPrefs" request for app=${e}`);const r=await this.getAllCachedPrefs();let n;try{n=await this.client.getPrefs(e)}catch(e){if(!(e instanceof SanitizedIOManagerApiError&&404===e.status))throw e;n=void 0}if(n){const e=r.find(e=>e.app===n?.app);if(e&&!objEqualFast(e.data,n.data)){const e={app:n.app,prefs:this.transformPrefs(n)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,e)}}const i=n?this.transformPrefs(n):void 0;return t&&this.logger?.trace(`[${t}] request completed, prefs retrieved`),i}):ioError.raiseError("Cannot get preferences, because the feature is not enabled")}async getAllPrefs(e){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "getAllPrefs" request`);const t=await this.getAllCachedPrefs(),r=await this.client.getAllPrefs();this.notifyPrefs(t,r);const n=r.map(this.transformPrefs);return e&&this.logger?.trace(`[${e}] request completed, all prefs retrieved`),n}):ioError.raiseError("Cannot get all preferences, because the feature is not enabled")}async savePrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "savePrefs" request`);const r=await this.client.setPrefs({app:e.app,data:e.data,merge:!e.overwrite});await this.mergeInPreferenceCache([r]);const n={app:r.app,prefs:this.transformPrefs(r)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,n),t&&this.logger?.trace(`[${t}] request completed, preferences saved`)}):ioError.raiseError("Cannot save preferences, because the feature is not enabled")}async clearPrefs(e,t){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{t&&this.logger?.trace(`[${t}] handling "clearPrefs" request`);const r=await Promise.all(e.map(e=>this.client.setPrefs({app:e,data:{},merge:!1})));await this.mergeInPreferenceCache(r);for(const e of r){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}t&&this.logger?.trace(`[${t}] request completed, preferences cleared`)}):ioError.raiseError("Cannot clear preferences, because the feature is not enabled")}async clearAllPrefs(e){return this.config?.features?.preferencesStore?this.sequelizer.enqueue(async()=>{e&&this.logger?.trace(`[${e}] handling "clearAllPrefs" request`);let t=await this.client.getAllPrefs();t=await Promise.all(t.map(e=>this.client.setPrefs({app:e.app,data:{},merge:!1}))),await this.managerCache.set(PREFS_CACHE_KEY,t);for(const e of t){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}e&&this.logger?.trace(`[${e}] request completed, all preferences cleared`)}):ioError.raiseError("Cannot clear all preferences, because the feature is not enabled")}clearCache(){return this.managerCache?.clear()}onPrefsChanged(e){return this.config?.features?.preferencesStore?this.callbacks.add(PREFS_CHANGED_EVENT_KEY,e):ioError.raiseError("Cannot subscribe to prefs changes, because the feature is not enabled")}handleOnLayoutsChanged(e){const t=this.parseLayouts(e);this.notifyLayouts(this.lastLayouts,t),this.setLastLayouts(e,t)}setLastLayouts(e,t){this.lastLayouts=t,this.lastLayoutIdsByKey.clear();for(const t of e)this.lastLayoutIdsByKey.set(this.getLayoutKey(t),t.id)}getLayoutKey(e){return e.name+" | "+e.type}notifyLayouts(e,t){const r=[],n=[],i=[],o=new Set(t.map(e=>e.name)),s=new Map;for(const t of e)o.has(t.name)||n.push(t),s.set(this.getLayoutKey(t),t);for(const e of t){const t=s.get(this.getLayoutKey(e));t?objEqualFast(e,t)||i.push(e):r.push(e)}r.length&&this.callbacks.execute(LAYOUTS_ADDED_EVENT_KEY,r),n.length&&this.callbacks.execute(LAYOUTS_REMOVED_EVENT_KEY,n),i.length&&this.callbacks.execute(LAYOUTS_CHANGED_EVENT_KEY,i)}parseLayouts(e){const t=e.map(e=>"string"==typeof e.definition?JSON.parse(e.definition):e.definition);return this.sanitizeLayouts(t).valid}sanitizeLayouts(e){return e.reduce((e,t)=>{const r=glueLayoutDecoder.run(t);return r.ok?e.valid.push(t):this.logger?.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]})}sanitizeApps(e){return e.reduce((e,t)=>{const r=allApplicationDefinitionsDecoder.run(t);return r.ok?e.valid.push(t):this.logger?.warn(`An app with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},{valid:[]})}notifyPrefs(e,t){const r=[],n=new Map;for(const t of e)n.set(t.app,t);for(const e of t){const t=n.get(e.app);t&&!objEqualFast(e.data,t.data)&&r.push(e)}for(const e of r){const t={app:e.app,prefs:this.transformPrefs(e)};this.callbacks.execute(PREFS_CHANGED_EVENT_KEY,t)}}async mergeInPreferenceCache(e){const t=await this.getAllCachedPrefs();for(const r of e){const e=t.findIndex(e=>e.app===r.app);-1!==e?t[e]=r:t.push(r)}await this.managerCache.set(PREFS_CACHE_KEY,t)}async getAllCachedPrefs(){const e=(await this.managerCache.get(PREFS_CACHE_KEY))?.value??[];for(const t of e)"string"==typeof t?.data&&(t.data=JSON.parse(t.data));return e}async getAllCachedLayouts(){return(await this.managerCache.get(LAYOUTS_CACHE_KEY))?.value??[]}handleOnConnectedStateChanged(e){const t=e=>e?{message:e.message,name:e.name,code:e.code,status:e.status,request:e.request,isSessionExpired:e.isSessionExpired}:e;this.callbacks.execute(CONNECTED_STATE_CHANGED_EVENT_KEY,(e=>{const{disconnectionError:r,...n}=e;return{...n,disconnectionError:t(r)}})(e))}handleOnAppsChanged(e){let t=e;t=this.sanitizeApps(t)?.valid,this.notifyApps(this.lastApps,t),this.lastApps=t}notifyApps(e,t){const r=[],n=[],i=[],o=new Set(t.map(e=>e.name)),s=new Map;for(const t of e)o.has(t.name)||n.push(t),s.set(t.name,t);for(const e of t){const t=s.get(e.name);t?objEqualFast(e,t)||i.push(e):r.push(e)}r.length&&this.callbacks.execute(APPS_ADDED_EVENT_KEY,r),n.length&&this.callbacks.execute(APPS_DELETED_EVENT_KEY,n),i.length&&this.callbacks.execute(APPS_CHANGED_EVENT_KEY,i)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}handleUnload(){this.client&&this.client.unload()}transformPrefs({app:e,data:t,lastUpdate:r}){return{app:e,data:t,lastUpdate:r}}createManagerLogger(){const e=logger.get("io-manager-connection"),t=e=>{if(e instanceof SanitizedIOManagerApiError)return JSON.stringify(e,null,2);if(e instanceof IOManagerRequestValidationError)return`${e.toString()} ${e.getZodError().toString()}`;if(e instanceof Error)return extractErrorMsg$1(e);try{return JSON.stringify(e)}catch{return"[Unable to serialize]"}},r=(e,r)=>r.length?`${e} ${r.map(t).join(" ").trim()}`:e;return{trace(t,...n){e?.canPublish("trace")&&e?.trace(r(t,n))},debug(t,...n){e?.canPublish("debug")&&e?.debug(r(t,n))},info(t,...n){e?.canPublish("info")&&e?.info(r(t,n))},warn(t,...n){e?.canPublish("warn")&&e?.warn(r(t,n))},error(t,...n){e?.canPublish("error")&&e?.error(r(t,n))},isTraceEnabled:()=>Boolean(e?.canPublish("trace")),isDebugEnabled:()=>Boolean(e?.canPublish("debug")),isInfoEnabled:()=>Boolean(e?.canPublish("info")),isWarnEnabled:()=>Boolean(e?.canPublish("warn")),isErrorEnabled:()=>Boolean(e?.canPublish("error")),isLevelEnabled:t=>Boolean(e?.canPublish(t)),log:(t,n,...i)=>{e?.canPublish(t)&&e?.log(r(n,i),t)}}}}class Identity{uaParser;glueController;pluginsController;workspacesFrameUrl;constructor(e,t,r,n){this.uaParser=e,this.glueController=t,this.pluginsController=r,this.workspacesFrameUrl=n}get logger(){return logger.get("manager.identity")}async getMachineInfo(e){const t=this.uaParser.getResult();return{user:e,name:"",os:{name:t.os.name||"",version:t.os.version||"",arch:t.cpu.architecture||""},browser:{name:t.browser.name,version:t.browser.version,engine:t.engine.name},mobileDevice:"mobile"===t.device?.type?{vendor:t.device.vendor,model:t.device.model}:void 0,displays:await this.getDisplays()}}getGlueInfo(){return{version:"",build:"",region:"",env:"",core:{web:{version:this.glueController.clientGlue.version},platform:{version:this.glueController.platformVersion,plugins:this.pluginsController.registeredPlugins},plus:{version:version$1}},workspaces:this.glueController.isWorkspacesEnabled?{version:this.glueController.clientGlue.workspaces?.version,frameUrl:this.workspacesFrameUrl}:void 0}}async getDisplays(){try{const{state:e}=await getWindowManagementPermissionStatus(this.logger);if("granted"!==e)return[]}catch(e){return this.logger?.warn(extractErrorMsg$1(e)),[]}return(await window.getScreenDetails()).screens.map(e=>({bounds:{x:e.left,y:e.top,width:e.width,height:e.height},workingArea:{x:e.availLeft,y:e.availTop,width:e.availWidth,height:e.availHeight},dpi:e.devicePixelRatio,isPrimary:e.isPrimary}))}}const prefsOperationTypesDecoder=oneOf$1(constant$2("operationCheck"),constant$2("clear"),constant$2("clearAll"),constant$2("get"),constant$2("getAll"),constant$2("set"),constant$2("update"),constant$2("prefsHello"),constant$2("registerSubscriber")),appPreferencesDecoder=object$3({app:nonEmptyStringDecoder$2,data:object$3(),lastUpdate:optional$3(nonEmptyStringDecoder$2)}),basePrefsConfigDecoder=object$3({app:nonEmptyStringDecoder$2}),subscriberRegisterConfigDecoder=object$3({interopId:nonEmptyStringDecoder$2,appName:optional$3(nonEmptyStringDecoder$2)}),getPrefsResultDecoder=object$3({prefs:appPreferencesDecoder}),getAllPrefsResultDecoder=object$3({all:array$3(appPreferencesDecoder)}),changePrefsDataDecoder=object$3({app:nonEmptyStringDecoder$2,data:object$3()}),prefsHelloSuccessDecoder=object$3({platform:object$3({app:nonEmptyStringDecoder$2}),validNonExistentApps:optional$3(array$3(nonEmptyStringDecoder$2))});class PrefsController{glueController;localStore;managerStore;restStore;operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},clear:{name:"clear",execute:this.clear.bind(this),dataDecoder:basePrefsConfigDecoder},clearAll:{name:"clearAll",execute:this.clearAll.bind(this)},get:{name:"get",execute:this.get.bind(this),dataDecoder:basePrefsConfigDecoder,resultDecoder:getPrefsResultDecoder},getAll:{name:"getAll",execute:this.getAll.bind(this),resultDecoder:getAllPrefsResultDecoder},set:{name:"set",execute:this.set.bind(this),dataDecoder:changePrefsDataDecoder},update:{name:"update",execute:this.update.bind(this),dataDecoder:changePrefsDataDecoder},prefsHello:{name:"prefsHello",execute:this.prefsHello.bind(this),resultDecoder:prefsHelloSuccessDecoder},registerSubscriber:{name:"registerSubscriber",dataDecoder:subscriberRegisterConfigDecoder,execute:this.registerSubscriber.bind(this)}};started=!1;unsubFuncs=[];_platformAppName=`Platform-${window.location.origin}`;config;store;constructor(e,t,r,n){this.glueController=e,this.localStore=t,this.managerStore=r,this.restStore=n}get logger(){return logger.get("prefs.controller")}get systemValidNonExistentApps(){return[systemPrefsAppName]}get validNonExistentApps(){return this.systemValidNonExistentApps.concat(this.config?.validNonExistentApps??[])}handlePlatformShutdown(){this.started=!1,this.unsubFuncs.forEach(e=>e()),this.unsubFuncs=[],this.store.stop()}get platformAppName(){return this._platformAppName}get storeType(){return this.store.type}async start(e){this.logger?.trace("initializing prefs"),this.started=!0,this.config=e.applicationPreferences,this.store=this.getStore(e),this.setupStoreListeners(),await this.store.start(e),this.logger?.trace("initialization is completed")}ready(){return Promise.resolve()}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this prefs control message, because the controller has not been started");const t=e.data,r=e.commandId,n=prefsOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This prefs request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Prefs request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Prefs request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async registerSubscriber({interopId:e,appName:t},r){this.trace(`[${r}] handling registerSubscriber command with interopId: ${e}`,r);const n=t?this.glueController.clientGlue.appManager.applications().find(e=>e.name===t):void 0;if(t&&!n)return ioError.raiseError(`Cannot register subscriber with appName "${t}", because the application is not valid.`);this.store.processNewSubscriber(t),this.trace(`[${r}] registerSubscriber command was executed successfully`,r)}async get({app:e},t){this.trace(`[${t}] handling get command with app: ${e}`,t);const r={app:e,data:{}};return{prefs:await this.store.getPrefs(e,t)||r}}async update({app:e,data:t},r){this.trace(`[${r}] handling update command with app: ${e} and data: ${JSON.stringify(t)}`,r);const n=this.validateApp(e);await this.store.savePrefs({app:n,data:t,overwrite:!1},r),this.trace(`[${r}] update command was executed successfully`,r)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}async clear({app:e},t){this.trace(`[${t}] handling clear command with app: ${e}`,t);const r=this.validateApp(e);await this.store.clearPrefs([r],t),this.trace(`[${t}] clear command was executed successfully`,t)}async clearAll(e,t){this.trace(`[${t}] handling clearAll command`,t),await this.store.clearAllPrefs(t),this.trace(`[${t}] clearAll command was executed successfully`,t)}async getAll(e,t){this.trace(`[${t}] handling getAll command`,t);const r=await this.store.getAllPrefs(t);return this.trace(`[${t}] getAll command was executed successfully`,t),{all:r}}async set({app:e,data:t},r){this.trace(`[${r}] handling set command with app: ${e} and data: ${JSON.stringify(t)}`,r);const n=this.validateApp(e);await this.store.savePrefs({app:n,data:t,overwrite:!0},r),this.trace(`[${r}] set command was executed successfully`,r)}async prefsHello(){return{platform:{app:this._platformAppName},validNonExistentApps:this.validNonExistentApps}}validateApp(e){const t=this.glueController.getAllApplicationNames();return e===this._platformAppName||t.includes(e)||this.validNonExistentApps.includes(e)?e:ioError.raiseError(`The provided app name "${e}" is not valid.`)}trace(e,t){t&&this.logger?.trace(e)}setupStoreListeners(){const e=this.store.onPrefsChanged(e=>{this.emitStreamData("prefsChanged",{prefs:e.prefs})});this.unsubFuncs.push(e)}emitStreamData(e,t){this.logger?.trace(`sending notification of event: ${e} with data: ${JSON.stringify(t)}`),this.glueController.pushSystemMessage("prefs",e,t)}getStore(e){const t=e.applicationPreferences?.store?.type,r=!(!e?.manager?.url||!e?.manager?.features?.preferencesStore),n=!!e?.applicationPreferences?.store?.rest?.url;return!t&&r?this.managerStore:t||r?"local"===t?this.localStore:"rest"===t&&n?this.restStore:"rest"!==t||n?"manager"===t&&r?this.managerStore:"manager"!==t||r?ioError.raiseError("Cannot set prefs store."):ioError.raiseError("The prefs store is configured to be managed, but the manager is not configured."):ioError.raiseError("The prefs store is configured to be rest, but the rest url is not configured."):this.localStore}}class IdbBasedIOManagerCache{kvStoreName="data";dbVersion=1;dbNamePrefix="IOManagerCache";logger=logger.get("io-manager-cache");config;dbName;database;data={};constructor(e,t){if(!("indexedDB"in window))throw new Error("Cannot initialize the local storage, because IndexedDB is not supported");this.config=e,this.dbName=`${this.dbNamePrefix}-${t}-${e.url}`}async get(e){const t=this.data[e];return t?(this.logger?.trace(`Read cache data for key: ${e}`),t):void this.logger?.trace(`Read cache data for key: ${e} - key not found.`)}async set(e,t){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Write cache data for key: ${e}`);const r=this.data[e];r?r.value=t:this.data[e]={value:t},await this.database.put(this.kvStoreName,{value:t,key:e})}async remove(e){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Remove cache data for key: ${e}`),delete this.data[e],await this.database.delete(this.kvStoreName,e)}async initialize(){if(this.database=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)}),this.config.cache?.clearOld)if("databases"in indexedDB){const e=(await indexedDB.databases()).filter(e=>e.name?.startsWith(this.dbNamePrefix)&&e.name!==this.dbName);for(const t of e)if(t.name)try{this.logger?.info(`Deleting cache db "${t.name}"`),await deleteDB(t.name)}catch(e){this.logger?.warn(`Failed to delete db "${t.name}". Error: ${extractErrorMsg$1(e)}`)}}else this.logger?.warn("Could not delete extraneous cache databases. This engine does not support indexedDB.databases.");await this.readFromDB()}async dispose(){this.logger?.trace(`Closing idb connection: "${this.dbName}"`),this.database?.close(),delete this.database}async clear(){await this.dispose(),this.logger?.trace(`Deleting idb database: "${this.dbName}"`),await deleteDB(this.dbName),await this.initialize()}setUpDB(e){e.objectStoreNames.contains(this.kvStoreName)||e.createObjectStore(this.kvStoreName,{keyPath:"key"})}async readFromDB(){if(!this.database)throw new Error("Database not initialized.");this.logger?.trace(`Reading from db: "${this.dbName}"`);const e=await this.database.getAll(this.kvStoreName),t={};for(const r of e)t[r.key]=r;this.data=t}}class SessionStorageBasedIOManagerCache{storageKeyPrefix="IOManagerCache";storageKey;logger=logger.get("io-manager-cache");config;data={};constructor(e,t){if(!("sessionStorage"in window))throw new Error("Cannot initialize the local storage, because sessionStorage is not supported");this.config=e,this.storageKey=`${this.storageKeyPrefix}-${t}-${e.url}`}async get(e){const t=this.data[e];return t?(this.logger?.trace(`Read cache data for key: ${e}`),t):void this.logger?.trace(`Read cache data for key: ${e} - key not found.`)}async set(e,t){this.logger?.trace(`Write cache data for key: ${e}`);const r=this.data[e];r?r.value=t:this.data[e]={value:t},this.writeToSessionStorage()}async remove(e){this.logger?.trace(`Remove cache data for key: ${e}`),delete this.data[e],this.writeToSessionStorage()}async initialize(){if(this.config.cache?.clearOld){const e=Object.keys(sessionStorage).filter(e=>e.startsWith(this.storageKeyPrefix)&&e!==this.storageKey);for(const t of e)try{this.logger?.info(`Deleting cache item "${t}"`),sessionStorage.removeItem(t)}catch(e){this.logger?.warn(`Failed to delete cache with key "${t}". Error: ${extractErrorMsg$1(e)}`)}}await this.readFromSessionStorage()}async dispose(){}async clear(){this.logger?.trace(`Deleting sessionStorage item with key "${this.storageKey}"`),sessionStorage.removeItem(this.storageKey),await this.initialize(),this.writeToSessionStorage()}async readFromSessionStorage(){let e;this.logger?.trace(`Reading sessionStorage item with key "${this.storageKey}"`);try{e=sessionStorage.getItem(this.storageKey)}catch(e){return this.logger?.warn(`Failed to read sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`),void(this.data={})}if(!e)return this.logger?.warn(`sessionStorage item with key "${this.storageKey}" does not exist.`),void(this.data={});try{this.data=JSON.parse(e)}catch(e){this.logger?.warn(`Failed to parse json from sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`),this.data={}}}writeToSessionStorage(){let e;this.logger?.trace(`Writing cache to sessionStorage item with key "${this.storageKey}"`);try{e=JSON.stringify(this.data)}catch(e){return void this.logger?.warn(`Failed to serialize io-manager cache. ${extractErrorMsg$1(e)}`)}try{sessionStorage.setItem(this.storageKey,e)}catch(e){this.logger?.warn(`Failed to write to sessionStorage item with key "${this.storageKey}". ${extractErrorMsg$1(e)}`)}}}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let nanoid=(e=21)=>{let t="",r=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=urlAlphabet[63&r[e]];return t};const otelOperationTypesDecoder=oneOf$1(constant$2("operationCheck"));class OtelController{telemetry;getNewMetricsDependencyBuilder;glueController;getPlatformController;systemController;applicationsController;layoutsController;workspacesController;serviceId=nanoid();serviceName="io.Connect Browser";config;platformController;started=!1;operations={operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)}};constructor(e,t,r,n,i,o,s,a){this.telemetry=e,this.getNewMetricsDependencyBuilder=t,this.glueController=r,this.getPlatformController=n,this.systemController=i,this.applicationsController=o,this.layoutsController=s,this.workspacesController=a}get logger(){return logger.get("otel.controller")}get glue(){return this.glueController.clientGlue}get metricsDependencyContainer(){const e=this.getNewMetricsDependencyBuilder();e.withInstanceStartedHandler(this.instanceStartedHandler.bind(this)).withInstanceStoppedHandler(this.instanceStoppedHandler.bind(this)).withInstanceReadyHandler(this.instanceReadyHandler.bind(this)).withInstanceFocusedHandler(this.instanceFocusedHandler.bind(this)).withInstanceErrorHandler(this.instanceErrorHandler.bind(this)).withLayoutRestoredHandler(this.layoutRestoredHandler.bind(this)).withWorkspaceRestoredHandler(this.workspaceRestoredHandler.bind(this)).withWorkspaceStoppedHandler(this.workspaceStoppedHandler.bind(this)).withPlatformStartedHandler(this.platformStartedHandler.bind(this)).withPlatformErrorHandler(this.platformErrorHandler.bind(this));return e.build()}get metricsSettings(){if(!this.config.otel?.metrics)return{enabled:!1};const{additionalResourceAttributes:e,getAdditionalAttributes:t,headers:r,metrics:n,publishInterval:i=3e4,url:o}=this.config.otel.metrics,s=t?.();this.warnIfPlatformVersionAttributeIsProvided(s),this.warnIfPlatformVersionAttributeIsProvided(e);const a=n?.map(e=>({...e,enabled:e.enabled??!0,name:e.name??e.type,description:e.description??"no description"}));return{additionalResourceAttributes:e,additionalAttributes:s,enabled:!0,headers:r,metrics:a,platformMetricsEnabled:!0,publishInterval:i,url:o}}get settings(){const e=this.config.otel?.getAdditionalAttributes?.(),t=this.config.otel?.additionalResourceAttributes;return this.warnIfPlatformVersionAttributeIsProvided(e),this.warnIfPlatformVersionAttributeIsProvided(t),{additionalAttributes:e,additionalResourceAttributes:t,enabled:!!this.config.otel?.metrics,headers:this.config.otel?.headers,metrics:this.metricsSettings,platformVersion:this.glueController.platformVersion,serviceId:this.serviceId,serviceName:this.serviceName,serviceVersion:this.glueController.platformVersion,userId:this.config.user?.id}}warnIfPlatformVersionAttributeIsProvided(e){e&&"platformVersion"in e&&this.logger?.warn("The provided additional attributes override the default platform version settings.")}async start(e){this.config=e,this.shouldStartController()&&(this.platformController=this.getPlatformController(),this.logger?.trace("Starting the Otel controller."))}async configurePostStart(){if(this.shouldStartController())try{await this.telemetry.start(this.settings,this.metricsDependencyContainer),this.started=!0}catch(e){const t=extractErrorMsg$1(e);this.logger?.error(`Failed to start Otel Controller. Reason: ${t}`)}}ready(){return Promise.resolve()}async handlePlatformShutdown(){if(this.started)try{await this.telemetry.stop(),this.started=!1,this.resetMetricHandlerSubscriptionCounters()}catch(e){const t=extractErrorMsg$1(e);this.logger?.error(`Failed to stop Otel Controller. Reason: ${t}`)}}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this otel control message, because the controller has not been started");const t=e.data,r=e.commandId,n=otelOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This otel request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`Otel request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`Otel request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}shouldStartController(){return!!this.config.otel?.metrics?.url}incrementMetricHandlerSubscriptionCounter(e){window.testingOtel&&++window.testingOtel.metricHandlers[e].numberOfSubscriptions}resetMetricHandlerSubscriptionCounters(){window.testingOtel&&Object.values(window.testingOtel.metricHandlers).forEach(e=>{e.numberOfSubscriptions=0})}instanceStartedHandler(e){this.incrementMetricHandlerSubscriptionCounter("instanceStarted");const t=t=>{const r={application:t.application.name};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceStarted.callback(r);e(r)},r=this.glue.appManager.onInstanceStarted(t);return this.glue.appManager.instances().forEach(t),r}instanceStoppedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceStopped"),this.glue.appManager.onInstanceStopped(t=>{const r={application:t.application.name};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceStopped.callback(r);e(r)})}instanceReadyHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceReady"),this.applicationsController.onInstanceStarted(({api:t="unknown",applicationName:r,startup:n})=>{const i={api:t,application:r,startTime:n.start,endTime:n.end};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceReady.callback(i);e(i)})}instanceFocusedHandler(e){this.incrementMetricHandlerSubscriptionCounter("instanceFocused");const t=this.glue.windows.onWindowGotFocus(t=>{const r=this.glue.appManager.instances().find(e=>e.id===t.id),n={application:r?.application?.name??t.name,focused:!0};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceFocused.callback(n);e(n)}),r=this.glue.windows.onWindowLostFocus(t=>{const r=this.glue.appManager.instances().find(e=>e.id===t.id),n={application:r?.application?.name??t.name,focused:!1};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceFocused.callback(n);e(n)});return()=>{t(),r()}}instanceErrorHandler(e){return this.incrementMetricHandlerSubscriptionCounter("instanceError"),this.systemController.onClientError(({callerId:t})=>{const r={application:this.glueController.getAppNameByInstanceId(t??"")??"unknown"};if(window.testingOtel)return window.testingOtel.metricHandlers.instanceError.callback(r);e(r)})}layoutRestoredHandler(e){return this.incrementMetricHandlerSubscriptionCounter("layoutRestored"),this.layoutsController.onLayoutRestored(({layoutName:t,startTime:r,endTime:n})=>{const i={layout:t,startTime:r,endTime:n};if(window.testingOtel)return window.testingOtel.metricHandlers.layoutRestored.callback(i);e(i)})}workspaceRestoredHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceRestored"),this.workspacesController.onWorkspaceRestored(({layoutName:t,startTime:r,endTime:n})=>{const i={layout:t,startTime:r,endTime:n};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceRestored.callback(i);e(i)})}workspaceStoppedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("workspaceStopped"),this.workspacesController.onWorkspaceClosed(({layoutName:t})=>{const r={layout:t};if(window.testingOtel)return window.testingOtel.metricHandlers.workspaceStopped.callback(r);e(r)})}platformStartedHandler(e){return this.incrementMetricHandlerSubscriptionCounter("platformStarted"),this.platformController.onPlatformStarted(({platformVersion:t,startup:r})=>{const n={startTime:r.start,endTime:r.end,api:t};if(window.testingOtel)return window.testingOtel.metricHandlers.platformStarted.callback(n);e(n)})}platformErrorHandler(e){return this.incrementMetricHandlerSubscriptionCounter("platformError"),this.systemController.onPlatformError(()=>{const t={};if(window.testingOtel)return window.testingOtel.metricHandlers.platformError.callback(t);e(t)})}}class Telemetry{getNewContainerBuilder;buildLogger;container=null;constructor(e,t){this.getNewContainerBuilder=e,this.buildLogger=t}get logger(){return logger.get("otel.telemetry")}async start(e,t){if(this.container)return ioError.raiseError("An Otel container has already been started");this.logger?.trace(`Starting an Otel container with settings: ${JSON.stringify(e)}`);const r=this.buildContainer(e,t);await r.start(),this.container=r,this.logger?.trace("The Otel container has been started successfully")}async stop(){this.container&&(await this.container.stop(),this.container=null,this.logger?.trace("The Otel container has been stopped successfully"))}buildContainer(e,t){const r=this.getNewContainerBuilder();if(this.logger&&r.withLogger(this.buildLogger(this.logger)),r.withSettings(e),e.metrics?.enabled){r.withMetrics().withDependencyContainer(t)}return r.build()}}class LoggerAdapter{logger;logLevelMap={error:30,warn:50,info:60,debug:70,trace:80};constructor(e){this.logger=e}get level(){const e=this.logger.consoleLevel();return this.logLevelMap[e]??60}error(e,...t){const r=this.tryStringify(e,t);this.logger.error(r)}warn(e,...t){const r=this.tryStringify(e,t);this.logger.warn(r)}info(e,...t){const r=this.tryStringify(e,t);this.logger.info(r)}debug(e,...t){const r=this.tryStringify(e,t);this.logger.debug(r)}verbose(e,...t){const r=this.tryStringify(e,t);this.logger.trace(r)}tryStringify(e,t){try{return JSON.stringify(t.length?{message:e,args:t}:{message:e})}catch(t){return e}}}const defaultWidgetConfig={channels:{selector:{enable:!0,type:"default"},displayMode:"all"},position:"bottom-center",displayInWorkspace:!1,restoreLastKnownPosition:!0};class UIController{sessionStorage;glueController;started=!1;config;operations={getResources:{name:"getResources",dataDecoder:getResourcesDataDecoder,resultDecoder:getResourcesResultDecoder,execute:this.handleGetResources.bind(this)},operationCheck:{name:"operationCheck",dataDecoder:operationCheckConfigDecoder,resultDecoder:operationCheckResultDecoder,execute:this.handleOperationCheck.bind(this)},requestAlert:{name:"requestAlert",dataDecoder:uiAlertRequestMessageDecoder,execute:this.handleAlertRequest.bind(this)},requestDialog:{name:"requestDialog",dataDecoder:uiDialogRequestMessageDecoder,resultDecoder:uiDialogClientResponseDecoder,execute:this.handleDialogRequest.bind(this)},alertInteropAction:{name:"alertInteropAction",dataDecoder:alertInteropActionDataDecoder,execute:this.handleAlertInteropAction.bind(this)},getModalsStatus:{name:"getModalsStatus",resultDecoder:modalsStatusResponseDecoder,execute:this.handleGetModalsStatus.bind(this)}};clientOperations={showAlert:{name:"showAlert",execute:noop$1},showDialog:{name:"showDialog",execute:noop$1},operationCheck:{name:"operationCheck",execute:noop$1},showResolver:{name:"showResolver",execute:noop$1}};constructor(e,t){this.sessionStorage=e,this.glueController=t}async start(e){this.started=!0,this.config=e}ready(){return Promise.resolve()}async openResolver({config:e,initialCaller:t,methodResponseTimeoutMs:r,commandId:n}){this.logger?.trace(`[${n}] Handling open resolver request with config: ${JSON.stringify(e)}`);const i=this.getIntentResolverTargetInstance(t.instanceId,n);return(await this.glueController.callInstance("ui",this.clientOperations.showResolver,{config:e},{instance:i},{methodResponseTimeoutMs:r})).result}async handleControl(e){if(!this.started)return ioError.raiseError("Cannot handle this UI control message, because the controller has not been started");const t=e.data,r=e.commandId,n=uiOperationTypesDecoder.run(e.operation);if(!n.ok)return ioError.raiseError(`This UI request cannot be completed, because the operation name did not pass validation: ${JSON.stringify(n.error)}`);const i=n.result,o=this.operations[i].dataDecoder?.run(t);if(o&&!o.ok)return ioError.raiseError(`UI request for ${i} rejected, because the provided arguments did not pass the validation: ${JSON.stringify(o.error)}`);this.logger?.debug(`[${r}] ${i} command is valid with data: ${JSON.stringify(t)}`);const s=await this.operations[i].execute(t,r),a=this.operations[i].resultDecoder?.run(s);return a&&!a.ok?ioError.raiseError(`UI request for ${i} could not be completed, because the operation result did not pass the validation: ${JSON.stringify(a.error)}`):(this.logger?.trace(`[${r}] ${i} command was executed successfully`),s)}async handleOperationCheck(e){return{isSupported:Object.keys(this.operations).some(t=>t.toLowerCase()===e.operation.toLowerCase())}}get logger(){return logger.get("ui.controller")}async handleGetResources({origin:e}){return{resources:{widget:this.getWidgetResources(e),modals:this.getModalsResources(e),intentResolver:this.getIntentResolverResources(e)}}}async handleGetModalsStatus(e,t){this.logger?.trace(`[${t}] Handling get status request`);const r={status:{platformConfigured:!!this.config.modals}};return this.logger?.trace(`[${t}] Get status request was handled successfully with response: ${JSON.stringify(r)}`),r}async handleAlertRequest(e,t){if(this.logger?.trace(`[${t}] Handling alert request with config: ${JSON.stringify(e)}`),!this.config.modals)return ioError.raiseError(`[${t}] Cannot handle alert request, because modals are not configured in the platform`);const r=this.getModalsTargetInstance(e.target.instance,t,e.target.container);this.logger?.trace(`[${t}] Target instance for the alert request is: ${r}`);const{isSupported:n}=await this.glueController.checkClientOperationSupport("ui",this.clientOperations.showAlert,{instance:r});if(!n)return ioError.raiseError(`[${t}] Cannot handle alert request, because the target instance does not support the operation`);this.logger?.trace(`[${t}] Calling the showAlert operation with the provided config`),await this.glueController.callInstance("ui",this.clientOperations.showAlert,e,{instance:r}),this.logger?.trace(`[${t}] Alert request was handled successfully`)}async handleDialogRequest(e,t){if(this.logger?.trace(`[${t}] Handling dialog request with config: ${JSON.stringify(e)}`),!this.config.modals)return ioError.raiseError(`[${t}] Cannot handle dialog request, because modals are not configured in the platform`);const r=this.getModalsTargetInstance(e.target.instance,t,e.target.container);this.logger?.trace(`[${t}] Target instance for the dialog request is: ${r}`);const{isSupported:n}=await this.glueController.checkClientOperationSupport("ui",this.clientOperations.showDialog,{instance:r});if(!n)return ioError.raiseError(`[${t}] Cannot handle dialog request, because the target instance does not support the operation`);this.logger?.trace(`[${t}] Calling the showDialog operation with the provided config`);const{timer:i}=e.config,o={methodResponseTimeoutMs:i?.duration?getSafeTimeoutDelay(i.duration+DEFAULT_METHOD_RESPONSE_TIMEOUT_MS$1):MAX_SET_TIMEOUT_DELAY},s=await this.glueController.callInstance("ui",this.clientOperations.showDialog,e,{instance:r},o);return this.logger?.trace(`[${t}] Dialog request was handled successfully.`),s}getWidgetResources(e){if(!this.config?.widget)return;return checkIsOriginBlocked(e,this.config.widget.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,config:this.config?.widget?.defaultConfig||defaultWidgetConfig,sources:this.config.widget.sources}}getModalsResources(e){if(!this.config?.modals)return;return checkIsOriginBlocked(e,this.config.modals.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,sources:this.config.modals.sources}}getIntentResolverResources(e){if(!this.config?.intentResolver)return;return checkIsOriginBlocked(e,this.config.intentResolver.blockList)?{blockedOrigin:!0}:{blockedOrigin:!1,sources:this.config.intentResolver.sources}}getModalsTargetInstance(e,t,r){const n=r?this.retrieveWindowContainerInstanceId(e,r):e;return this.glueController.getLocalServers().some(e=>e.instance===n)?n:ioError.raiseError(`[${t}] Cannot handle modals request, because the target instance does not exist - ${n}`)}retrieveWindowContainerInstanceId(e,t){if("Global"===t)return ioError.raiseError(`Cannot retrieve the instance id for the client with id: ${e}, because the container type - "Global" is not supported`);const r=this.sessionStorage.getWorkspaceClientById(e);return r?r.frameId:e}async handleAlertInteropAction(e,t){this.logger?.trace(`[${t}] Handling alert interop action with config: ${JSON.stringify(e)}`);const{method:r,arguments:n,target:i}=e.interopAction.settings,o=i?this.getInteropInstanceTarget(i,t):void 0;this.logger?.trace(`[${t}] Instance target for the alert interop action is: ${JSON.stringify(o)}`),await this.glueController.invokeMethod(r,n,o)}getInteropInstanceTarget(e,t){if("best"===e||"all"===e)return e;const r=this.glueController.getLocalServers().find(t=>t.instance===e);return r||ioError.raiseError(`[${t}] No interop instance was found for the provided target ${e}.`)}getIntentResolverTargetInstance(e,t){const r=this.sessionStorage.getWorkspaceClientById(e);this.logger?.trace(`[${t}] Initial caller id '${e}' ${r?"is":"isn't"} a workspace client.`);const n=r?r.frameId:e;return this.logger?.trace(`[${t}] Target instance id for the intent resolver is: ${n}`),n}}class LocalPrefsStore{idbController;registry=CallbackRegistryFactory$2();type="local";constructor(e){this.idbController=e}async start(){}stop(){}async getPrefs(e){return await this.idbController.getPrefs(e)}async savePrefs(e){const t=e.overwrite?"setPrefs":"updatePrefs",r=await this.idbController[t]({app:e.app,data:e.data,lastUpdate:getLastUpdateTimestamp()});this.registry.execute("prefsChanged",{app:e.app,prefs:r})}async clearPrefs(e){await Promise.all(e.map(async e=>{const t=await this.idbController.setPrefs({app:e,data:{},lastUpdate:getLastUpdateTimestamp()});this.registry.execute("prefsChanged",{app:e,prefs:t})}))}async clearAllPrefs(){(await this.idbController.clearAllPrefs(getLastUpdateTimestamp())).forEach(e=>{this.registry.execute("prefsChanged",{app:e.app,prefs:e})})}async getAllPrefs(){return await this.idbController.getAllPrefs()}onPrefsChanged(e){return this.registry.add("prefsChanged",e)}processNewSubscriber(){}}class ManagerPrefsStore{managerController;type="manager";constructor(e){this.managerController=e}async start(){}stop(){}async getPrefs(e,t){return await this.managerController.getPrefs(e,t)}async savePrefs(e,t){await this.managerController.savePrefs(e,t)}async clearPrefs(e,t){await this.managerController.clearPrefs(e,t)}async clearAllPrefs(e){await this.managerController.clearAllPrefs(e)}async getAllPrefs(e){return await this.managerController.getAllPrefs(e)}onPrefsChanged(e){return this.managerController.onPrefsChanged(e)}processNewSubscriber(){}}const defaultRestHeaders={"Content-Type":"application/json",Accept:"application/json"},defaultRestRequestTimeoutMS=3e4;class RestPrefsStore{sequelizer;scheduler;cache;sessionController;type="rest";registry=CallbackRegistryFactory$2();cacheConfig;url;requestTimeout;pollingInterval;userCustomHeaders={};getUserRequestInit=()=>({});fetched={};get logger(){return logger.get("applications.prefs.rest.store")}constructor(e,t,r,n){this.sequelizer=e,this.scheduler=t,this.cache=r,this.sessionController=n}async start(e){const t=e.applicationPreferences?.store?.rest;if(!t)return ioError.raiseError("Cannot setup prefs rest store, because of missing config");if(!t.pollingInterval&&t.cache?.enabled)return ioError.raiseError("Cannot setup prefs rest store, because polling interval is not set while cache is enabled");if(t.pollingInterval&&t.pollingInterval<5e3)return ioError.raiseError("Cannot setup prefs rest store, because polling interval is set to less than 5000ms");this.url=this.getBaseUrl(t.url),this.requestTimeout=t.requestTimeout??defaultRestRequestTimeoutMS,this.userCustomHeaders=t.customHeaders??{},this.getUserRequestInit=t.getRequestInit??(()=>({})),this.pollingInterval=t.pollingInterval??0,this.cacheConfig=t.cache??{},await this.cache.start(t);const r=this.sessionController.getAllPrefsRestSchedulerCache().map(e=>e.app);this.sessionController.clearAllPrefsRestSchedulerCache(),r.forEach(e=>this.addSchedulerEntry(e))}stop(){this.cache.stop()}async getPrefs(e,t){return this.sequelizer.enqueue(async()=>{const r=this.cacheConfig.enabled,n=r&&this.fetched[e]?await this.cache.getPrefs(e):void 0;let i;try{i=n??await this.getPrefsFromServer(e,t)}catch(t){const n=r&&await this.cache.getPrefs(e);return n?(this.logger?.warn(`Failed to fetch prefs for app ${e} from server, using cached prefs: ${t}`),n):ioError.raiseError(`Failed to fetch prefs for app ${e} from server and no cached prefs available: ${t}`)}return await this.comparePrefs(i),this.addSchedulerEntry(e),await this.cache.setPrefs(i),i})}async savePrefs(e,t){return this.sequelizer.enqueue(async()=>{const r=await this.getPrefsFromServer(e.app),n=e.overwrite?{}:r.data,i=e.overwrite?{app:e.app,data:e.data}:{app:e.app,data:{...n,...e.data}},o=this.getRequest("/","POST",i),s=await fetchTimeout(o,this.requestTimeout);if(!s.ok)return ioError.raiseError(`[${t}] The POST rest for prefs for app ${e.app} returned invalid status: ${s.status}`);const a=await this.getPrefsFromServer(e.app);await this.comparePrefs(a,r),this.addSchedulerEntry(e.app),await this.cache.setPrefs(a)})}async clearPrefs(e,t){return this.sequelizer.enqueue(async()=>{await Promise.all(e.map(async e=>{await this.clearPrefsFromServer(e,t),await this.comparePrefs({app:e,data:{}}),await this.cache.clearPrefs(e)}))})}async clearAllPrefs(e){return this.sequelizer.enqueue(async()=>{const t=(await this.getAllPrefsFromServer(e)).filter(e=>Object.keys(e.data).length);for(const r of t)try{await this.clearPrefsFromServer(r.app,e),await this.comparePrefs({app:r.app,data:{}})}catch(e){this.logger?.warn(`Failed to clear prefs for app ${r.app}: ${e}`)}await this.cache.clearAllPrefs()})}async getAllPrefs(e){return this.sequelizer.enqueue(async()=>{const t=await this.getAllPrefsFromServer(e),r=await this.cache.getAllPrefs();for(const e of r){const r=t.find(t=>t.app===e.app);r&&(await this.comparePrefs(r,e),await this.cache.setPrefs(r))}return t})}onPrefsChanged(e){return this.registry.add("prefsChanged",e)}processNewSubscriber(e){e?(this.logger?.info(`Processing new subscriber for appName: ${e}`),this.addSchedulerEntry(e)):this.logger?.trace("No appName provided, skipping new subscriber processing.")}async getAllPrefsFromServer(e){const t=this.getRequest("/all","GET"),r=await fetchTimeout(t,this.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The GET all rest for all prefs returned invalid status: ${r.status}`);const n=await r.json(),i=array$3(appPreferencesDecoder).run(n);return i.ok?i.result:ioError.raiseError(`[${e}] The GET all rest for all prefs returned invalid data: ${i.error}`)}async getPrefsFromServer(e,t){const r=new URLSearchParams({app:e}).toString(),n=this.getRequest(`/?${r}`,"GET"),i=await fetchTimeout(n,this.requestTimeout);if(!i.ok)return ioError.raiseError(`[${t}] The GET rest for prefs for app ${e} returned invalid status: ${i.status}`);const o=await i.json(),s=appPreferencesDecoder.run(o);return s.ok?(this.fetched[o.app]=!0,s.result):ioError.raiseError(`[${t}] The GET rest for prefs for app ${e} returned invalid data: ${s.error}`)}async clearPrefsFromServer(e,t){const r={app:e,data:{}},n=this.getRequest("/","POST",r),i=await fetchTimeout(n,this.requestTimeout);if(!i.ok)return ioError.raiseError(`[${t}] The POST rest for prefs for app ${e} returned invalid status: ${i.status}`)}async comparePrefs(e,t){const r=t??await this.cache.getPrefs(e.app);r&&JSON.stringify(r.data)===JSON.stringify(e.data)||this.registry.execute("prefsChanged",{app:e.app,prefs:e})}getRequest(e,t,r){const n=new Headers;for(const e in defaultRestHeaders)n.append(e,defaultRestHeaders[e]);for(const e in this.userCustomHeaders)n.append(e,this.userCustomHeaders[e]);const i={method:t,headers:n,mode:"cors",cache:"default",body:r?JSON.stringify(r):void 0},o=`${this.url}${e}`,s=this.getUserRequestInit({url:o,requestInit:i});return new Request(o,{...i,...s})}getBaseUrl(e){return e.endsWith("/")?e.slice(0,-1):e}addSchedulerEntry(e){if(!this.pollingInterval)return void this.logger?.info(`Polling interval is not set, skipping scheduler entry addition for app: ${e}`);const t=new URLSearchParams({app:e}).toString(),r=`prefs:get:${e}`,n={key:r,getRequest:()=>this.getRequest(`/?${t}`,"GET"),timeout:this.requestTimeout,refreshIntervalMS:this.pollingInterval,onData:this.processSchedulerGetPrefsUpdate.bind(this),onError:t=>this.logger?.error(`Error during get prefs for ${e} request:`,t)};this.scheduler.checkEntryExists(r)||(this.sessionController.savePrefsRestSchedulerCache({app:e}),this.scheduler.register(n))}processSchedulerGetPrefsUpdate(e){return this.sequelizer.enqueue(async()=>{this.fetched[e.app]=!0;const t=appPreferencesDecoder.run(e);if(!t.ok)return this.logger?.warn(`The GET rest for prefs as part of polling for app ${e.app} returned invalid data: ${t.error}`);await this.comparePrefs(t.result),await this.cache.setPrefs(t.result)})}}class LocalLayoutsStore{idbController;sessionStore;localStore;registry=CallbackRegistryFactory$2();mode="idb";get logger(){return logger.get("layouts.local.store")}constructor(e,t,r){this.idbController=e,this.sessionStore=t,this.localStore=r}async start(e){if(this.mode=e.layouts.mode,!e.layouts.local.length)return;const t=e.layouts.local.filter(e=>"Global"===e.type),r=e.layouts.local.filter(e=>"Workspace"===e.type);await Promise.all([this.localMergeImport(t,"Global"),this.localMergeImport(r,"Workspace")])}stop(){"idb"===this.mode&&(this.idbController.clearLayouts("Global").catch(e=>this.logger?.warn(extractErrorMsg$1(e))),this.idbController.clearLayouts("Workspace").catch(e=>this.logger?.warn(extractErrorMsg$1(e))))}async saveLayouts(e,t,r,n){const i="merge"===r?this.localMergeImport.bind(this):this.localReplaceImport.bind(this);this.logger?.trace(`[${n}] importing the layouts in local ${r} mode`),await Promise.all([i(t,"Global"),i(e,"Workspace")]),this.logger?.trace(`[${n}] mass import completed, responding to caller`)}async deleteLayout(e,t){await this.localDelete(e.name,e.type),this.registry.execute("layouts-removed",[e]),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed`)}async renameLayout(e,t,r){let n;try{n=await this.localRename(e,t)}catch(t){const n=extractErrorMsg$1(t);return this.logger?.trace(`[${r}] Layout named ${e.name} has not been renamed. Reason: ${n}.`),{status:n}}return this.registry.execute("layouts-renamed",[{...n,prevName:e.name}]),this.logger?.trace(`[${r}] Layout named ${e.name} has been renamed to ${t}.`),{status:"Success"}}async getDefaultLayout(e){const t=this.localStore.getDefaultGlobalLayoutName(),r=await this.getAll("Global");return this.logger?.trace(this.createGetDefaultGlobalLogMessage(e,t)),r.find(e=>e.name===t)}async setDefaultLayout(e,t){this.localStore.saveDefaultGlobalLayout(e),this.logger?.trace(`[${t}] request completed for global layout with name ${e}, responding to the caller`)}async clearDefaultLayout(e){this.localStore.clearDefaultGlobalLayout(),this.logger?.trace(`[${e}] request completed, responding to the caller`)}async getAllLayouts(e){return"idb"===this.mode?await this.idbController.getAllLayouts(e):this.sessionStore.getLayoutSnapshot(e).layouts}onLayoutsAdded(e){return this.registry.add("layouts-added",e)}onLayoutsChanged(e){return this.registry.add("layouts-changed",e)}onLayoutsRemoved(e){return this.registry.add("layouts-removed",e)}onLayoutsRenamed(e){return this.registry.add("layouts-renamed",e)}async localMergeImport(e,t){const r=await this.getAll(t),n=[],i=[];for(const t of e){const e=r.findIndex(e=>e.name===t.name);e>-1&&!objEqual(t,r[e])?(this.logger?.trace(`change detected at layout ${t.name}`),i.push(t),r[e]=t):e<0&&(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),n.push(t),r.push(t))}await this.localCleanSave(r,t),await this.announceEvents({added:n,changed:i})}async localReplaceImport(e,t){const r=await this.getAll(t),n=[],i=[],o=[];for(const t of e){const e=r.findIndex(e=>e.name===t.name);e<0?(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),n.push(t)):(objEqual(t,r[e])||(this.logger?.trace(`change detected at layout ${t.name}`),i.push(t)),r.splice(e,1))}r.forEach(e=>{this.logger?.trace(`layout ${e.name} missing, removing and announcing`),o.push(e)}),await this.localCleanSave(e,t),await this.announceEvents({added:n,changed:i,removed:o})}async localCleanSave(e,t){if("session"!==this.mode){await this.idbController.clearLayouts(t);for(const t of e)await this.idbController.storeLayout(t)}else this.sessionStore.saveLayoutSnapshot({layouts:e},t)}async localDelete(e,t){if("idb"===this.mode)return void await this.idbController.deleteLayout(e,t);const r=this.sessionStore.getLayoutSnapshot(t).layouts,n=r.findIndex(t=>t.name===e);n>-1&&r.splice(n,1),this.sessionStore.saveLayoutSnapshot({layouts:r},t)}async localRename(e,t){const r={...e,name:t};if("idb"===this.mode)return this.idbController.renameLayout(r,e.name);const n=this.sessionStore.getLayoutSnapshot(e.type).layouts,i=n.findIndex(({name:t})=>t===e.name),o=-1===i?n.length:i;return n.splice(o,1,r),this.sessionStore.saveLayoutSnapshot({layouts:n},e.type),r}async getAll(e){const t="Workspace"===e?"Workspace":"Global";return"idb"===this.mode?await this.idbController.getAllLayouts(t):this.sessionStore.getLayoutSnapshot(t).layouts}async announceEvents(e){const t=[];e.added?.length&&t.push(this.throttleEvents(e.added,"layouts-added")),e.changed?.length&&t.push(this.throttleEvents(e.changed,"layouts-changed")),e.removed?.length&&t.push(this.throttleEvents(e.removed,"layouts-removed")),e.renamed?.length&&t.push(this.throttleEvents(e.renamed,"layouts-renamed")),await Promise.all(t),await this.waitEventFlush()}async throttleEvents(e,t){let r=0;for(const n of e)++r,r%10==0&&await this.waitEventFlush(),this.registry.execute(t,[n])}createGetDefaultGlobalLogMessage(e,t){return t?`[${e}] request completed, responding to the caller with layout with name ${t}`:`[${e}] request completed, no default global layout found, responding to the caller`}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}}class ManagerLayoutsStore{manager;get logger(){return logger.get("layouts.manager.store")}constructor(e){this.manager=e}async start(){}stop(){}async saveLayouts(e,t,r,n){this.logger?.trace(`[${n}] importing the layouts to manager`),await this.manager.saveLayouts([...e,...t],r,n),this.logger?.trace(`[${n}] mass import to manager completed, responding to caller`)}async deleteLayout(e,t){await this.manager.deleteLayout(e.name,e.type,t),this.logger?.trace(`[${t}] layout with name "${e.name}" and type: "${e.type}" has been removed from manager`)}async renameLayout(e,t,r){return await this.manager.renameLayout(e.name,t,e.type,r),this.logger?.trace(`[${r}] Layout named ${e.name} has been renamed to ${t} in manager.`),{status:"Success"}}async getDefaultLayout(e){this.logger?.trace(`[${e}] getting default global layout from manager`);const t=await this.manager.getDefaultLayout(e);return this.logger?.trace(this.createGetDefaultGlobalLogMessage(e,t?.name)),t}async setDefaultLayout(e,t){this.logger?.trace(`[${t}] setting default global layout in manager`),await this.manager.setDefaultLayout(e,t),this.logger?.trace(`[${t}] request completed for global layout with name ${e}, responding to the caller`)}async clearDefaultLayout(e){this.logger?.trace(`[${e}] clearing default global layout in manager`),await this.manager.clearDefaultLayout(e),this.logger?.trace(`[${e}] request completed, responding to the caller`)}async getAllLayouts(e,t){return await this.manager.getAllLayouts(e,t)}onLayoutsAdded(e){return this.manager.onLayoutsAdded(e)}onLayoutsChanged(e){return this.manager.onLayoutsChanged(e)}onLayoutsRemoved(e){return this.manager.onLayoutsRemoved(e)}onLayoutsRenamed(e){return this.manager.onLayoutsRenamed(e)}createGetDefaultGlobalLogMessage(e,t){return t?`[${e}] request completed, responding to the caller with layout with name ${t}`:`[${e}] request completed, no default global layout found, responding to the caller`}}class RestLayoutsStore{sequelizer;scheduler;cache;registry=CallbackRegistryFactory$2();cacheConfig;config;get logger(){return logger.get("layouts.rest.store")}constructor(e,t,r){this.sequelizer=e,this.scheduler=t,this.cache=r}async start(e){const t=e.layouts?.rest;if(!t)return ioError.raiseError("Cannot setup layouts rest store, because of missing config");this.config=this.prepareConfig(t),this.logger?.info(`Starting layouts rest store with config: ${JSON.stringify({...this.config,customHeaders:"omitted"})}`),this.cacheConfig=t.cache??{},await this.cache.start(t),this.logger?.trace("Finished starting layouts rest store"),await this.dataWarmUp(),this.logger?.trace("Finished data warm up"),this.configureScheduler(),this.logger?.info("Layouts rest store started")}stop(){this.cache.stop()}async getAllLayouts(e,t){return this.sequelizer.enqueue(()=>this.getAllLayoutsNoSeq(e,t))}async saveLayouts(e,t,r,n){return this.sequelizer.enqueue(async()=>{const i=[...e,...t];"replace"===r&&await this.deleteAllLayoutsFromServer(n);const o=1===i.length;for(const e of i)try{await this.saveLayoutToServer(e,n)}catch(t){if(!o){this.logger?.warn(`Failed to save layout ${e.name} type:${e.type} with error: ${t}, continuing with the rest`);continue}return ioError.raiseError(`Failed to save layout ${e.name} type:${e.type} with error: ${t}`)}const s=await this.getAllLayoutsFromServer(n);await this.processNewLayoutsSnapshot(s)})}async deleteLayout(e,t){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] Deleting layout ${e.name} type:${e.type}`);const r=this.getRequest("/layouts","DELETE",{name:e.name,type:e.type}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`Failed to remove layout ${e.name} and type: ${e.type}: ${n.statusText}`);this.logger?.trace(`[${t}] Removed layout ${e.name} type:${e.type}`),await this.cache.deleteLayout(e),await this.announceEvents({removed:[e]})})}async renameLayout(e,t,r){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${r}] Renaming layout ${e.name} type:${e.type} to ${t}`);const n=this.getRequest("/layouts","PUT",{layout:e,newName:t}),i=await fetchTimeout(n,this.config.requestTimeout);return i.ok?(await this.cache.updateLayout({...e,name:t}),this.registry.execute("layouts-renamed",[{...e,name:t,prevName:e.name}]),{status:"Success"}):{status:`Failed to rename layout ${e.name} type:${e.type}: ${i.statusText}`}})}async getDefaultLayout(e){return this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${e}] Getting default layout`);const t=this.getRequest("/layouts/default","GET"),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for get default layout returned invalid status: ${r.status}`);let n;try{n=await r.json()}catch(t){return void this.logger?.trace(`[${e}] No default layout found`)}if(!n?.name)return void this.logger?.trace(`[${e}] No default layout found`);const i=n.name;return(await this.getAllLayoutsNoSeq("Global",e)).find(e=>e.name===i)})}async setDefaultLayout(e,t){this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${t}] Setting default layout to ${e}`);const r=this.getRequest("/layouts/default","POST",{name:e}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`[${t}] The rest for set default layout returned invalid status: ${n.status}`);this.logger?.trace(`[${t}] Set default layout to ${e}`)})}async clearDefaultLayout(e){this.sequelizer.enqueue(async()=>{this.logger?.trace(`[${e}] Clearing default layout`);const t=this.getRequest("/layouts/default","POST",{}),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for clear default layout returned invalid status: ${r.status}`);this.logger?.trace(`[${e}] Default layout cleared`)})}onLayoutsAdded(e){return this.registry.add("layouts-added",e)}onLayoutsChanged(e){return this.registry.add("layouts-changed",e)}onLayoutsRemoved(e){return this.registry.add("layouts-removed",e)}onLayoutsRenamed(e){return this.registry.add("layouts-renamed",e)}async getAllLayoutsNoSeq(e,t){const r=this.cacheConfig.enabled?await this.cache.getAllLayouts("all"):void 0;if(r?.length)return r.filter(t=>t.type===e);const n=await this.getAllLayoutsFromServer(t);return(await this.processNewLayoutsSnapshot(n)).filter(t=>t.type===e)}async getAllLayoutsFromServer(e){this.logger?.trace(`[${e}] Fetching all layouts from server`);const t=this.getRequest("/layouts","GET"),r=await fetchTimeout(t,this.config.requestTimeout);if(!r.ok)return ioError.raiseError(`[${e}] The rest for get all layouts returned invalid status: ${r.status}`);const n=await r.json();if(!n?.layouts)return ioError.raiseError(`[${e}] The rest for get all layouts returned invalid response`);return this.sanitizeLayouts(n.layouts)}async deleteAllLayoutsFromServer(e){const t=(await this.getAllLayoutsFromServer(e)).map(e=>this.getLayoutId(e.name,e.type)),r=this.getRequest("/layouts","DELETE",{ids:t}),n=await fetchTimeout(r,this.config.requestTimeout);if(!n.ok)return ioError.raiseError(`[${e}] Failed to remove all layouts: ${n.statusText}`);this.logger?.trace(`[${e}] Removed all layouts`)}async saveLayoutToServer(e,t){const r=this.getRequest("/layouts","POST",{layout:e}),n=await fetchTimeout(r,this.config.requestTimeout),i=`[${t}] Failed to save layout ${e.name} type:${e.type}: ${n.statusText}`;if(!n.ok)throw new Error(i);this.logger?.trace(`[${t}] Saved layout ${e.name} type:${e.type}`)}getBaseUrl(e){return e.endsWith("/")?e.slice(0,-1):e}getRequest(e,t,r){const n=new Headers;for(const e in defaultRestHeaders$1)n.append(e,defaultRestHeaders$1[e]);for(const e in this.config.customHeaders)n.append(e,this.config.customHeaders[e]);const i={method:t,headers:n,mode:"cors",cache:"default",body:r?JSON.stringify(r):void 0},o=`${this.config.url}${e}`,s=this.config.getRequestInit?.({url:o,requestInit:i});return new Request(o,{...i,...s})}getLayoutId(e,t){return`${e.toLowerCase()} (${t})`}sanitizeLayouts(e){return e.reduce((e,t)=>{const r=glueLayoutDecoder.run(t);return r.ok&&e.push(t),r.ok||this.logger?.warn(`A layout with name: ${t.name} was not imported, because of error: ${JSON.stringify(r.error)}`),e},[])}async executeLayoutsChangeDetection(e,t){if(!e.length)return;const r=[],n=[],i=[],o=await this.cache.getAllLayouts(t);for(const t of e){const e=o.findIndex(e=>e.name===t.name);e<0?(this.logger?.trace(`new layout: ${t.name} detected, adding and announcing`),r.push(t)):(objEqual(t,o[e])||(this.logger?.trace(`change detected at layout ${t.name}`),n.push(t)),o.splice(e,1))}o.forEach(e=>{this.logger?.trace(`layout ${e.name} missing, removing and announcing`),i.push(e)}),await this.announceEvents({added:r,changed:n,removed:i})}async announceEvents(e){const t=[];e.added?.length&&t.push(this.throttleEvents(e.added,"layouts-added")),e.changed?.length&&t.push(this.throttleEvents(e.changed,"layouts-changed")),e.removed?.length&&t.push(this.throttleEvents(e.removed,"layouts-removed")),e.renamed?.length&&t.push(this.throttleEvents(e.renamed,"layouts-renamed")),await Promise.all(t),await this.waitEventFlush()}async throttleEvents(e,t){let r=0;for(const n of e)++r,r%10==0&&await this.waitEventFlush(),this.registry.execute(t,[n])}waitEventFlush(){return new Promise(e=>setTimeout(e,10))}processSchedulerGetAllLayoutsUpdate(e){return this.sequelizer.enqueue(async()=>{this.logger?.trace("Processing scheduler get all layouts update"),await this.processNewLayoutsSnapshot(e.layouts),this.logger?.trace("Finished processing scheduler get all layouts update")})}async processNewLayoutsSnapshot(e){const t=this.sanitizeLayouts(e),r=t.filter(e=>"Workspace"===e.type),n=t.filter(e=>"Global"===e.type);return await this.executeLayoutsChangeDetection(r,"Workspace"),await this.executeLayoutsChangeDetection(n,"Global"),await this.cache.saveLayouts(t,"replace"),t}configureScheduler(){if(!this.config.pollingInterval)return void this.logger?.info("Polling interval is not set, skipping scheduler setup");const e="layouts:get:all";if(this.scheduler.checkEntryExists(e))return;const t={key:e,getRequest:()=>this.getRequest("/layouts","GET"),timeout:this.config.requestTimeout,refreshIntervalMS:this.config.pollingInterval,onData:this.processSchedulerGetAllLayoutsUpdate.bind(this),onError:e=>this.logger?.error("Error during get all layouts from scheduler",e)};this.scheduler.register(t)}async dataWarmUp(){const e=this.getAllLayoutsFromServer("start-up");if(this.config.waitInitialResponse)try{const t=await e;await this.cache.saveLayouts(t,"replace")}catch(e){return this.handleDataWarmUpFail(e)}else e.then(e=>this.cache.saveLayouts(e,"replace")).catch(e=>{const t=extractErrorMsg$1(e);this.logger?.warn(`Layouts store initial data warm up failed: ${t}`)})}prepareConfig(e){const t={...e,url:this.getBaseUrl(e.url),requestTimeout:e.requestTimeout??defaultRestRequestTimeoutMS$1,customHeaders:e.customHeaders??{},getRequestInit:e.getRequestInit??(()=>({})),waitInitialResponse:e.waitInitialResponse??!0};return t.pollingInterval&&t.pollingInterval<5e3?ioError.raiseError("Polling interval must be at least 5000ms"):t.cache?.enabled&&!t.pollingInterval?ioError.raiseError("Polling interval is required when cache is enabled"):t}async handleDataWarmUpFail(e){const t=await this.cache.getAllLayouts("all"),r=extractErrorMsg$1(e);if(!this.cacheConfig.enabled||!t.length)return ioError.raiseError(`Layouts store initial data warm up failed: ${r}`);this.logger?.warn(`Layouts store initial data warm up failed, but cache is not empty, continuing with cached data. Response error: ${r}`)}}class RestScheduler{localStorageController;entries=new Map;currentAbortControllers=new Map;_handleConnectionChange;isAppOnline=navigator.onLine;isActive=!1;schedulerLockName;constructor(e){this.localStorageController=e}start(e){if(this.isActive)return;this.entries.size?(this.schedulerLockName=`io-connect-rest-scheduler-lock-${e?.id||"public"}`,this.isActive=!0,this.setupOnlineTracker(),this.tick()):this.logger?.info("No entries registered in the RestScheduler, skipping start.")}stop(){this.isActive=!1,this.currentAbortControllers.forEach(e=>e.abort()),this.currentAbortControllers.clear(),this.entries.clear(),this.localStorageController.clearRestSchedulerEntries(),window.removeEventListener("offline",this._handleConnectionChange),window.removeEventListener("online",this._handleConnectionChange)}checkEntryExists(e){return this.entries.has(e)}register(e){if(this.checkEntryExists(e.key))return ioError.raiseError(`Request with key "${e.key}" is already registered.`);this.entries.set(e.key,e);this.localStorageController.getRestSchedulerEntry(e.key)||this.setInitialLocalStorageEntry(e)}async tick(){if(this.isActive){if(await this.waitInterval(),!this.isAppOnline)return this.isActive=!1,void this.logger?.warn("App is offline, ticking stopped.");await navigator.locks.request(this.schedulerLockName,{ifAvailable:!0},async e=>{if(e)try{await this.executeTick()}catch(e){this.logger?.error("Error during rest scheduler tick:",e)}else this.logger?.trace("The scheduler lock is already held by another process, skipping this tick.")}),this.tick()}}async executeTick(){const e=Date.now(),t=this.localStorageController.getAllRestSchedulerEntries(),r=Array.from(this.entries).reduce((r,[n,i])=>{const o=t[n];return o||(this.setInitialLocalStorageEntry(i),r.push(n)),o&&e>=o.nextRefreshAt&&r.push(n),r},[]);if(!r.length)return;const n=this.splitKeysBasedOnConcurrency(r);for(const e of n)try{const t=Promise.all(e.map(async e=>{await this.refreshKey(e)}));await t}catch(e){const t="string"==typeof e?e:JSON.stringify(e.message);this.logger?.warn(t)}}async refreshKey(e){const t=this.entries.get(e);if(!t)return ioError.raiseError(`No request registered with key "${e}".`);if(t.continuationCheck&&!t.continuationCheck())return this.logger?.trace(`Cancelling request for key "${e}" as continuation check failed.`),this.entries.delete(e),void this.localStorageController.deleteRestSchedulerEntry(e);const r=t.getRequest(),n=new AbortController;let i,o;this.currentAbortControllers.set(e,n);try{i=await fetchTimeout(r,t.timeout,n),o=Date.now()}catch(t){return this.setEntryFailure(e,Date.now())}if(!i.ok)return this.setEntryFailure(e,o,i.status);let s=null;try{s=await i.json()}catch(e){}finally{this.setEntrySuccess(e,s,o)}}setupOnlineTracker(){this._handleConnectionChange=this.handleConnectionChange.bind(this),window.addEventListener("offline",this._handleConnectionChange),window.addEventListener("online",this._handleConnectionChange)}setEntryFailure(e,t,r){this.currentAbortControllers.delete(e);const n=this.localStorageController.getRestSchedulerEntry(e),i=this.entries.get(e);if(!i)return ioError.raiseError(`No entry found for key "${e}" in local storage.`);const o=Math.ceil(250*Math.random())+t+Math.min(i.refreshIntervalMS*Math.pow(2,n?.errorCount??0),36e5),s=n?{...n,nextRefreshAt:o,errorCount:n.errorCount+1}:{key:i.key,nextRefreshAt:o,lastRefreshedAt:0,errorCount:1};this.localStorageController.saveRestSchedulerEntry(s);const a=`Request failed with status ${r||"timeout"} for key "${e}" and url "${i.getRequest().url}".`;return i.onError?.(a),ioError.raiseError(a)}setEntrySuccess(e,t,r){this.currentAbortControllers.delete(e);const n=this.localStorageController.getRestSchedulerEntry(e),i=this.entries.get(e);if(!i)return ioError.raiseError(`No entry found for key "${e}" in local storage.`);const o=r+i.refreshIntervalMS+Math.ceil(250*Math.random()),s=n?{...n,errorCount:0,lastRefreshedAt:r,nextRefreshAt:o}:{key:i.key,nextRefreshAt:o,lastRefreshedAt:r,errorCount:0};this.localStorageController.saveRestSchedulerEntry(s);try{i.onData(t)}catch(e){this.logger?.warn(`[${i.key}] Error occurred while processing data: ${e}`)}}setInitialLocalStorageEntry(e){const t={key:e.key,nextRefreshAt:Date.now()+e.refreshIntervalMS+Math.ceil(250*Math.random()),lastRefreshedAt:0,errorCount:0};this.localStorageController.saveRestSchedulerEntry(t)}splitKeysBasedOnConcurrency(e){const t=[],r=e.length;for(let n=0;nsetTimeout(t,e??globalTickIntervalMSForScheduler))}get logger(){return logger.get("system.rest.scheduler")}}class PrefsRestCache{idbCacheController;allKnownPrefs=[];cacheConfig={};constructor(e){this.idbCacheController=e}async start(e){this.allKnownPrefs=[],this.cacheConfig=e.cache??{}}async stop(){this.allKnownPrefs=[]}async getPrefs(e){return this.cacheConfig.enabled?(await this.idbCacheController.getPrefs(e))?.prefs:this.allKnownPrefs.find(t=>t.app===e)}async getAllPrefs(){if(!this.cacheConfig.enabled)return this.allKnownPrefs;return(await this.idbCacheController.getAllPrefs()).map(e=>e.prefs)}async setPrefs(e){this.allKnownPrefs=this.allKnownPrefs.filter(t=>t.app!==e.app),this.allKnownPrefs.push(e),this.cacheConfig.enabled&&await this.idbCacheController.setPrefs(e,Date.now())}async clearPrefs(e){this.allKnownPrefs=this.allKnownPrefs.filter(t=>t.app!==e),this.cacheConfig.enabled&&await this.idbCacheController.deleteManyPrefs([e])}async clearAllPrefs(){this.allKnownPrefs=[],this.cacheConfig.enabled&&await this.idbCacheController.clearPrefs()}}class IdbCacheController{_database;dbName;dbVersion=1;globalLayoutsObjectStoreName="globalLayouts";prefsObjectStoreName="prefs";workspaceLayoutsObjectStoreName="workspaceLayouts";appsDefObjectStoreName="applicationDefinitions";constructor(){this.dbName=defaultCacheDBName,"indexedDB"in window||ioError.raiseError("Cannot initialize the local storage, because IndexedDB is not supported")}get database(){return this._database?this._database:ioError.raiseError("There is no open database")}async start(e){this.dbName=`${defaultCacheDBName}-${e?.id??"public"}`;const t=await openDB(this.dbName,this.dbVersion,{upgrade:this.setUpDB.bind(this)});this._database=t}stop(){this._database&&(this.database.close(),delete this._database,this.dbName=defaultCacheDBName)}async clear(){this._database&&(await this.database.clear(this.globalLayoutsObjectStoreName),await this.database.clear(this.workspaceLayoutsObjectStoreName),await this.database.clear(this.prefsObjectStoreName),await this.database.clear(this.appsDefObjectStoreName))}async deleteOtherDBs(){const e=(await indexedDB.databases()).filter(e=>e.name&&e.name!==this.dbName&&e.name.startsWith(defaultCacheDBName)).map(e=>new Promise((t,r)=>{if(!e.name)return t();const n=indexedDB.deleteDatabase(e.name);n.onerror=t=>{console.error("Error deleting database:",t),r(new Error(`Error deleting database: ${e.name}`))},n.onsuccess=()=>{t()}}));await Promise.all(e)}async getAllLayouts(e){if("all"===e){return[...(await this.database.getAll(this.globalLayoutsObjectStoreName)).map(e=>e.layout),...(await this.database.getAll(this.workspaceLayoutsObjectStoreName)).map(e=>e.layout)]}return(await this.database.getAll(this.getLayoutsObjectStoreName(e))).map(e=>e.layout)}deleteLayout(e,t){const r=this.getLayoutsObjectStoreName(t);return this.database.delete(r,e)}storeLayout(e,t){const r=this.getLayoutsObjectStoreName(e.type);return this.database.put(r,{layout:e,lastUpdated:t},e.name)}clearLayouts(e){const t=this.getLayoutsObjectStoreName(e);return this.database.clear(t)}async getPrefs(e){return this.database.get(this.prefsObjectStoreName,e)}getAllPrefs(){return this.database.getAll(this.prefsObjectStoreName)}async setPrefs(e,t){await this.database.put(this.prefsObjectStoreName,{prefs:e,lastUpdated:t},e.app)}async deleteManyPrefs(e){for(const t of e)await this.database.delete(this.prefsObjectStoreName,t)}async clearPrefs(){await this.database.clear(this.prefsObjectStoreName)}async getAllApps(){return(await this.database.getAll(this.appsDefObjectStoreName)).map(e=>e.definition)}async setApps(e,t){const r=this.database.transaction(this.appsDefObjectStoreName,"readwrite");await Promise.all([r.store.clear(),...e.map(e=>r.store.put({definition:e,lastUpdated:t},e.name)),r.done])}setUpDB(e){e.objectStoreNames.contains(this.workspaceLayoutsObjectStoreName)||e.createObjectStore(this.workspaceLayoutsObjectStoreName),e.objectStoreNames.contains(this.globalLayoutsObjectStoreName)||e.createObjectStore(this.globalLayoutsObjectStoreName),e.objectStoreNames.contains(this.prefsObjectStoreName)||e.createObjectStore(this.prefsObjectStoreName),e.objectStoreNames.contains(this.appsDefObjectStoreName)||e.createObjectStore(this.appsDefObjectStoreName)}getLayoutsObjectStoreName(e){return"Global"!==e&&"Workspace"!==e?ioError.raiseError(`Invalid layout type: ${e}`):"Global"===e?this.globalLayoutsObjectStoreName:this.workspaceLayoutsObjectStoreName}}class LayoutsRestCache{idbCacheController;allKnownLayouts=[];cacheConfig={};constructor(e){this.idbCacheController=e}async start(e){this.allKnownLayouts=[],this.cacheConfig=e.cache??{}}async stop(){this.allKnownLayouts=[]}async getAllLayouts(e){return this.cacheConfig.enabled?await this.idbCacheController.getAllLayouts(e):this.allKnownLayouts.filter(t=>"all"===e||t.type===e)}saveLayouts(e,t){return"replace"===t?this.replaceLayouts(e):this.mergeLayouts(e)}async deleteLayout(e){this.allKnownLayouts=this.allKnownLayouts.filter(t=>t.name!==e.name&&t.type!==e.type),this.cacheConfig.enabled&&await this.idbCacheController.deleteLayout(e.name,e.type)}async updateLayout(e){this.allKnownLayouts=this.allKnownLayouts.filter(t=>t.name!==e.name&&t.type!==e.type),this.allKnownLayouts.push(e),this.cacheConfig.enabled&&await this.idbCacheController.storeLayout(e,Date.now())}async replaceLayouts(e){if(this.allKnownLayouts=e,this.cacheConfig.enabled){await this.idbCacheController.clearLayouts("Global"),await this.idbCacheController.clearLayouts("Workspace");for(const t of e)await this.idbCacheController.storeLayout(t,Date.now())}}async mergeLayouts(e){for(const t of e)await this.updateLayout(t)}}class AppsRestCache{idbCacheController;sessionController;cacheConfig={};constructor(e,t){this.idbCacheController=e,this.sessionController=t}async start(e){this.cacheConfig=e?.cache??{}}async getAllRemoteApps(){return this.cacheConfig.enabled?this.idbCacheController.getAllApps():this.sessionController.getAllApps("remote")}async getAllMemoryApps(){return this.sessionController.getAllApps("inmemory")}async saveMemoryApps(e){this.sessionController.overwriteApps(e,"inmemory")}async saveRemoteApps(e){return this.cacheConfig.enabled?this.idbCacheController.setApps(e,Date.now()):this.sessionController.overwriteApps(e,"remote")}async removeMemoryApp(e){return this.sessionController.removeApp(e,"inmemory")}}class IoC{config;_gatewayInstance;_platformInstance;_mainController;_glueController;_portsBridge;_windowsController;_applicationsController;_appDirectory;_remoteWatcher;_layoutsController;_workspacesController;_hibernationWatcher;_intentsController;_legacyResolverController;_channelsController;_notificationsController;_extensionController;_sessionController;_localStorageController;_stateChecker;_framesController;_systemController;_idbController;_serviceWorkerController;_preferredConnectionController;_transactionsController;_interceptionController;_pluginsController;_domainsController;_licenseController;_layoutsBuilder;_layoutsRestorer;_layoutsValidator;_layoutsResetter;_searchController;_appsSearchRepo;_layoutsSearchRepo;_workspacesSearchRepo;_themesController;_managerController;_managerIdentity;_prefsController;_otelController;_otelTelemetry;_uiController;_localPrefsStore;_managerPrefsStore;_restPrefsStore;_localLayoutsStore;_managerLayoutsStore;_restLayoutsStore;_restScheduler;_prefsRestCache;_layoutsRestCache;_appsRestCache;_idbCacheController;constructor(e){this.config=e}get gateway(){return this._gatewayInstance||(this._gatewayInstance=new Gateway),this._gatewayInstance}get platform(){return this._platformInstance||(this._platformInstance=new Platform(this.controller,this.sessionController,this.localStorageController,this.config)),this._platformInstance}get domainsController(){return this._domainsController||(this._domainsController=new DomainsController(this.systemController,this.windowsController,this.applicationsController,this.layoutsController,this.workspacesController,this.intentsController,this.channelsController,this.notificationsController,this.extensionController,this.searchController,this.themesController,this.managerController,this.prefsController,this.otelController,this.uiController)),this._domainsController}get controller(){return this._mainController||(this._mainController=new PlatformController(this.domainsController,this.glueController,this.portsBridge,this.stateController,this.serviceWorkerController,this.preferredConnectionController,this.interceptionController,this.pluginsController,this.sessionController,this.licenseController,this.localStorageController,this.idbController,this.idbCacheController,this.restScheduler)),this._mainController}get glueController(){return this._glueController||(this._glueController=new GlueController(this.portsBridge,this.sessionController)),this._glueController}get restScheduler(){return this._restScheduler||(this._restScheduler=new RestScheduler(this.localStorageController)),this._restScheduler}get idbCacheController(){return this._idbCacheController||(this._idbCacheController=new IdbCacheController),this._idbCacheController}get prefsRestCache(){return this._prefsRestCache||(this._prefsRestCache=new PrefsRestCache(this.idbCacheController)),this._prefsRestCache}get layoutsRestCache(){return this._layoutsRestCache||(this._layoutsRestCache=new LayoutsRestCache(this.idbCacheController)),this._layoutsRestCache}get appsRestCache(){return this._appsRestCache||(this._appsRestCache=new AppsRestCache(this.idbCacheController,this.sessionController)),this._appsRestCache}get systemController(){return this._systemController||(this._systemController=new SystemController(this.sessionController,this.workspacesController,this.glueController,this.pluginsController)),this._systemController}get searchController(){return this._searchController||(this._searchController=new SearchController(this.glueController,this.appsSearchRepo,this.layoutsSearchRepo,this.workspacesSearchRepo)),this._searchController}get uiController(){return this._uiController||(this._uiController=new UIController(this.sessionController,this.glueController)),this._uiController}get themesController(){return this._themesController||(this._themesController=new ThemesController(this.glueController,this.localStorageController)),this._themesController}get sessionController(){return this._sessionController||(this._sessionController=new SessionStorageController),this._sessionController}get localStorageController(){return this._localStorageController||(this._localStorageController=new LocalStoreController),this._localStorageController}get stateController(){return this._stateChecker||(this._stateChecker=new WindowsStateController(this.sessionController)),this._stateChecker}get windowsController(){return this._windowsController||(this._windowsController=new WindowsController(this.glueController,this.sessionController,this.stateController,this)),this._windowsController}get applicationsController(){return this._applicationsController||(this._applicationsController=new ApplicationsController(this.glueController,this.sessionController,this.stateController,this.appDirectory,this.managerController,this)),this._applicationsController}get appDirectory(){return this._appDirectory||(this._appDirectory=new AppDirectory(this.remoteWatcher,this.managerController,this.appsRestCache)),this._appDirectory}get remoteWatcher(){return this._remoteWatcher||(this._remoteWatcher=new RemoteWatcher(this.restScheduler)),this._remoteWatcher}get licenseController(){return this._licenseController||(this._licenseController=new LicenseController),this._licenseController}get localLayoutsStore(){return this._localLayoutsStore||(this._localLayoutsStore=new LocalLayoutsStore(this.idbController,this.sessionController,this.localStorageController)),this._localLayoutsStore}get managerLayoutsStore(){return this._managerLayoutsStore||(this._managerLayoutsStore=new ManagerLayoutsStore(this.managerController)),this._managerLayoutsStore}get restLayoutsStore(){return this._restLayoutsStore||(this._restLayoutsStore=new RestLayoutsStore(this.createSequelizer(),this.restScheduler,this.layoutsRestCache)),this._restLayoutsStore}get layoutsController(){return this._layoutsController||(this._layoutsController=new LayoutsController(this.glueController,this.layoutsBuilder,this.layoutsRestorer,this.localLayoutsStore,this.managerLayoutsStore,this.restLayoutsStore,this.sessionController)),this._layoutsController}get workspacesController(){return this._workspacesController||(this._workspacesController=new WorkspacesController(this.framesController,this.glueController,this.stateController,this.hibernationWatcher,this.createSequelizer(),this.sessionController,this)),this._workspacesController}get hibernationWatcher(){return this._hibernationWatcher||(this._hibernationWatcher=new WorkspaceHibernationWatcher(this.sessionController,this.createSequelizer())),this._hibernationWatcher}get intentsController(){return this._intentsController||(this._intentsController=new IntentsController(this.glueController,this.legacyResolverController,this.appDirectory,this.windowsController,this.prefsController,this.uiController)),this._intentsController}get legacyResolverController(){return this._legacyResolverController||(this._legacyResolverController=new LegacyResolverController(this.glueController,this.workspacesController,this.windowsController,this.prefsController)),this._legacyResolverController}get channelsController(){return this._channelsController||(this._channelsController=new ChannelsController(this.glueController,this.sessionController,this.workspacesController)),this._channelsController}get extensionController(){return this._extensionController||(this._extensionController=new ExtensionController(this.sessionController)),this._extensionController}get layoutsBuilder(){return this._layoutsBuilder||(this._layoutsBuilder=new Builder(this.glueController,this.sessionController,this.windowsController,this.workspacesController)),this._layoutsBuilder}get layoutsRestorer(){return this._layoutsRestorer||(this._layoutsRestorer=new Restorer(this.glueController,this.layoutsValidator,this.layoutsResetter,this.workspacesController,this.sessionController)),this._layoutsRestorer}get layoutsValidator(){return this._layoutsValidator||(this._layoutsValidator=new LayoutValidator(this.glueController,this.workspacesController)),this._layoutsValidator}get layoutsResetter(){return this._layoutsResetter||(this._layoutsResetter=new Resetter(this.glueController,this.workspacesController)),this._layoutsResetter}get notificationsController(){return this._notificationsController||(this._notificationsController=new NotificationsController(this.glueController,this.serviceWorkerController,this.sessionController,this.localStorageController,this.prefsController)),this._notificationsController}get framesController(){return this._framesController||(this._framesController=new FramesController(this.sessionController,this.glueController,this)),this._framesController}get idbController(){return this._idbController||(this._idbController=new IDBController),this._idbController}get portsBridge(){return this._portsBridge||(this._portsBridge=new PortsBridge(this.gateway,this.sessionController,this.stateController,this)),this._portsBridge}get serviceWorkerController(){return this._serviceWorkerController||(this._serviceWorkerController=new ServiceWorkerController(this.idbController)),this._serviceWorkerController}get transactionsController(){return this._transactionsController||(this._transactionsController=new TransactionsController),this._transactionsController}get interceptionController(){return this._interceptionController||(this._interceptionController=new InterceptionController),this._interceptionController}get pluginsController(){return this._pluginsController||(this._pluginsController=new PluginsController(this.interceptionController,this.glueController)),this._pluginsController}get appsSearchRepo(){return this._appsSearchRepo||(this._appsSearchRepo=new ApplicationsRepository(this.glueController)),this._appsSearchRepo}get managerController(){return this._managerController||(this._managerController=new ManagerController(this.managerIdentity,this.createSequelizer(),this.buildClient.bind(this),this.buildCache.bind(this))),this._managerController}get managerIdentity(){return this._managerIdentity||(this._managerIdentity=new Identity(new uaParserExports.UAParser,this.glueController,this.pluginsController,this.config?.workspaces?.src)),this._managerIdentity}get layoutsSearchRepo(){return this._layoutsSearchRepo||(this._layoutsSearchRepo=new LayoutsRepository(this.glueController)),this._layoutsSearchRepo}get workspacesSearchRepo(){return this._workspacesSearchRepo||(this._workspacesSearchRepo=new WorkspacesRepository(this.glueController)),this._workspacesSearchRepo}get preferredConnectionController(){return this._preferredConnectionController||(this._preferredConnectionController=new PreferredConnectionController(this.glueController,this.portsBridge,this.createSequelizer())),this._preferredConnectionController}get localPrefsStore(){return this._localPrefsStore||(this._localPrefsStore=new LocalPrefsStore(this.idbController)),this._localPrefsStore}get managerPrefsStore(){return this._managerPrefsStore||(this._managerPrefsStore=new ManagerPrefsStore(this.managerController)),this._managerPrefsStore}get restPrefsStore(){return this._restPrefsStore||(this._restPrefsStore=new RestPrefsStore(this.createSequelizer(),this.restScheduler,this.prefsRestCache,this.sessionController)),this._restPrefsStore}get prefsController(){return this._prefsController||(this._prefsController=new PrefsController(this.glueController,this.localPrefsStore,this.managerPrefsStore,this.restPrefsStore)),this._prefsController}get otelController(){return this._otelController||(this._otelController=new OtelController(this.otelTelemetry,this.getNewMetricsDependencyBuilder.bind(this),this.glueController,this.getPlatformController.bind(this),this.systemController,this.applicationsController,this.layoutsController,this.workspacesController)),this._otelController}createMessageChannel(){return new MessageChannel}createSequelizer(e){return new AsyncSequelizer(e)}buildClient(e){return new CachedClientAPI(e)}buildCache(e,t){return e.cache?.enabled??1?new IdbBasedIOManagerCache(e,t):new SessionStorageBasedIOManagerCache(e,t)}getPlatformController(){return this.controller}getNewMetricsDependencyBuilder(){return new dist.MetricsDependencyBuilder}getNewOtelContainerBuilder(){return new dist.Builder}buildOtelLogger(e){return new LoggerAdapter(e)}get otelTelemetry(){return this._otelTelemetry||(this._otelTelemetry=new Telemetry(this.getNewOtelContainerBuilder.bind(this),this.buildOtelLogger.bind(this))),this._otelTelemetry}}let platformCache;const checkSingleton=()=>{const e=window.glue42core||window.iobrowser;if(e?.platformStarted)throw new Error("The Glue42 Core Platform has already been started for this application.")},initPlatformAPi=async e=>{const t=new IoC(e);await t.platform.ready();return{io:t.platform.getClientGlue(),platform:t?.platform.getPlatformApi()}},ioConnectBrowserPlatformFactory=async e=>{if(window.glue42gd||window.iodesktop)return fallbackToEnterprise(e);const t=!e?.connection?.alwaysPlatform&&await checkIsOpenerIOConnect(e?.connection),r=checkIfPlacedInWorkspace();if(e?.clientOnly||t||r){return{io:e?.browserFactory?await(e?.browserFactory(e?.browser)):await iOConnectBrowserFactory(e?.browser)}}try{checkSingleton()}catch(e){return void 0===platformCache?Promise.reject(new Error(e)):platformCache}const n=initPlatformAPi(e);return e?.browser?.memoizeAPI&&(platformCache=n),n};"undefined"!=typeof window&&(window.IOBrowserPlatform=ioConnectBrowserPlatformFactory);const legacyGlobal=window.glue42gd||window.glue42core,ioGlobal=window.iodesktop||window.iobrowser;return legacyGlobal||ioGlobal||(window.iobrowser={webStarted:!1}),ioConnectBrowserPlatformFactory}); -//# sourceMappingURL=browser.platform.umd.js.map diff --git a/javascript/start/clients/lib/workspaces.umd.js b/javascript/start/clients/lib/workspaces.umd.js deleted file mode 100644 index 8d833a0..0000000 --- a/javascript/start/clients/lib/workspaces.umd.js +++ /dev/null @@ -1,5618 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.workspaces = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder.oneOf; - /** See `Decoder.union` */ - Decoder.union; - /** See `Decoder.intersection` */ - var intersection = Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - Decoder.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder.lazy; - - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number"); - const positiveNumberDecoder = number().where((num) => num > 0, "Expected a positive number"); - const windowDragModeDecoder = oneOf(constant("keepInside"), constant("autoEject")); - const isWindowInSwimlaneResultDecoder = object({ - inWorkspace: boolean() - }); - const frameVisibilityResultDecoder = object({ - isVisible: boolean() - }); - const iconDecoder = object({ - base64Image: nonEmptyStringDecoder - }); - const setIconArgumentsDecoder = object({ - icon: iconDecoder, - frameId: nonEmptyStringDecoder - }); - const allParentDecoder = oneOf(constant("workspace"), constant("row"), constant("column"), constant("group")); - const subParentDecoder = oneOf(constant("row"), constant("column"), constant("group")); - const frameStateDecoder = oneOf(constant("maximized"), constant("minimized"), constant("normal")); - const loadingAnimationTypeDecoder = oneOf(constant("workspace")); - const checkThrowCallback = (callback, allowUndefined) => { - const argumentType = typeof callback; - if (allowUndefined && argumentType !== "function" && argumentType !== "undefined") { - throw new Error(`Provided argument must be either undefined or of type function, provided: ${argumentType}`); - } - if (!allowUndefined && argumentType !== "function") { - throw new Error(`Provided argument must be of type function, provided: ${argumentType}`); - } - }; - const workspaceBuilderCreateConfigDecoder = optional(object({ - saveLayout: optional(boolean()) - })); - const deleteLayoutConfigDecoder = object({ - name: nonEmptyStringDecoder - }); - const windowDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const groupDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropHeader: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()) - }); - const rowDefinitionConfigDecoder = object({ - minHeight: optional(number()), - maxHeight: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const columnDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const swimlaneWindowDefinitionDecoder = object({ - type: optional(constant("window")), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const strictSwimlaneWindowDefinitionDecoder = object({ - type: constant("window"), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const parentDefinitionDecoder = optional(object({ - type: optional(subParentDecoder), - children: optional(lazy(() => array(oneOf(swimlaneWindowDefinitionDecoder, parentDefinitionDecoder)))), - config: optional(anyJson()) - })); - const strictColumnDefinitionDecoder = object({ - type: constant("column"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(columnDefinitionConfigDecoder) - }); - const strictRowDefinitionDecoder = object({ - type: constant("row"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(rowDefinitionConfigDecoder) - }); - const strictGroupDefinitionDecoder = object({ - type: constant("group"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(groupDefinitionConfigDecoder) - }); - const strictParentDefinitionDecoder = oneOf(strictGroupDefinitionDecoder, strictColumnDefinitionDecoder, strictRowDefinitionDecoder); - oneOf(string().where((s) => s.toLowerCase() === "maximized", "Expected a case insensitive variation of 'maximized'"), string().where((s) => s.toLowerCase() === "normal", "Expected a case insensitive variation of 'normal'")); - const newFrameConfigDecoder = object({ - bounds: optional(object({ - left: optional(number()), - top: optional(number()), - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - })), - isVisible: optional(boolean()), - frameId: optional(nonEmptyStringDecoder) - }); - const loadingStrategyDecoder = oneOf(constant("direct"), constant("delayed"), constant("lazy")); - const restoreWorkspaceConfigDecoder = optional(object({ - app: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - loadingStrategy: optional(loadingStrategyDecoder), - title: optional(nonEmptyStringDecoder), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - frameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - lockdown: optional(boolean()), - activateFrame: optional(boolean()), - newFrame: optional(oneOf(newFrameConfigDecoder, boolean())), - noTabHeader: optional(boolean()), - inMemoryLayout: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - allowSystemHibernation: optional(boolean()) - })); - const openWorkspaceConfigDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const workspaceDefinitionDecoder = object({ - children: optional(array(oneOf(swimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder))), - context: optional(anyJson()), - config: optional(object({ - title: optional(nonEmptyStringDecoder), - position: optional(nonNegativeNumberDecoder), - isFocused: optional(boolean()), - noTabHeader: optional(boolean()), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - loadingStrategy: optional(loadingStrategyDecoder), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showCloseButton: optional(boolean()), - allowSplitters: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - windowDragMode: optional(windowDragModeDecoder) - })), - frame: optional(object({ - activate: optional(boolean()), - reuseFrameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - newFrame: optional(oneOf(boolean(), newFrameConfigDecoder)) - })) - }); - const workspaceSelectorDecoder = object({ - workspaceId: nonEmptyStringDecoder - }); - const restoreWorkspaceDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const emptyFrameDefinitionDecoder = optional(object({ - applicationName: optional(string()), - frameConfig: optional(newFrameConfigDecoder), - context: optional(object()), - layoutComponentId: optional(nonEmptyStringDecoder) - })); - const frameInitConfigDecoder = object({ - workspaces: array(oneOf(optional(workspaceDefinitionDecoder), optional(restoreWorkspaceDefinitionDecoder))) - }); - const frameInitProtocolConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaces: array(oneOf(workspaceDefinitionDecoder, restoreWorkspaceDefinitionDecoder)) - }); - const builderConfigDecoder = object({ - type: allParentDecoder, - definition: optional(oneOf(workspaceDefinitionDecoder, parentDefinitionDecoder)) - }); - const workspaceCreateConfigDecoder = intersection(workspaceDefinitionDecoder, object({ - saveConfig: optional(object({ - saveLayout: optional(boolean()) - })) - })); - const getFrameSummaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const frameInitializationContextDecoder = object({ - context: optional(object()) - }); - const frameSummaryDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - object({ - type: subParentDecoder, - id: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number() - }); - const eventTypeDecoder = oneOf(constant("frame"), constant("workspace"), constant("container"), constant("window")); - const streamRequestArgumentsDecoder = object({ - type: eventTypeDecoder, - branch: nonEmptyStringDecoder - }); - const workspaceEventActionDecoder = oneOf(constant("opened"), constant("closing"), constant("closed"), constant("focus"), constant("added"), constant("loaded"), constant("removed"), constant("childrenUpdate"), constant("containerChange"), constant("maximized"), constant("restored"), constant("minimized"), constant("normal"), constant("selected"), constant("lock-configuration-changed"), constant("hibernated"), constant("resumed")); - const workspaceConfigResultDecoder = object({ - frameId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder, - positionIndex: nonNegativeNumberDecoder, - name: nonEmptyStringDecoder, - layoutName: optional(nonEmptyStringDecoder), - isHibernated: optional(boolean()), - isSelected: optional(boolean()), - allowDrop: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - widthInPx: optional(number()), - heightInPx: optional(number()), - isPinned: optional(boolean()), - windowDragMode: optional(windowDragModeDecoder), - loadingStrategy: optional(loadingStrategyDecoder) - }); - const baseChildSnapshotConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number(), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()) - }); - const parentSnapshotConfigDecoder = anyJson(); - const swimlaneWindowSnapshotConfigDecoder = intersection(baseChildSnapshotConfigDecoder, object({ - windowId: optional(nonEmptyStringDecoder), - isMaximized: optional(boolean()), - isFocused: boolean(), - isSelected: optional(boolean()), - title: optional(string()), - appName: optional(nonEmptyStringDecoder), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - widthInPx: optional(number()), - heightInPx: optional(number()), - context: optional(anyJson()) - })); - const customWorkspaceSubParentSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: parentSnapshotConfigDecoder, - children: optional(lazy(() => array(customWorkspaceChildSnapshotDecoder))), - type: oneOf(constant("row"), constant("column"), constant("group")) - }); - const customWorkspaceWindowSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: swimlaneWindowSnapshotConfigDecoder, - type: constant("window") - }); - const customWorkspaceChildSnapshotDecoder = oneOf(customWorkspaceWindowSnapshotDecoder, customWorkspaceSubParentSnapshotDecoder); - const childSnapshotResultDecoder = customWorkspaceChildSnapshotDecoder; - const workspaceSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder, - children: array(childSnapshotResultDecoder), - frameSummary: frameSummaryDecoder, - context: optional(anyJson()) - }); - const windowLayoutItemDecoder = object({ - type: constant("window"), - config: object({ - appName: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - url: optional(nonEmptyStringDecoder), - title: optional(string()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - isMaximized: optional(boolean()) - }) - }); - const groupLayoutItemDecoder = object({ - type: constant("group"), - config: anyJson(), - children: array(oneOf(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object({ - type: constant("column"), - config: anyJson(), - children: array(oneOf(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object({ - type: constant("row"), - config: anyJson(), - children: array(oneOf(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutDecoder = object({ - name: nonEmptyStringDecoder, - type: constant("Workspace"), - metadata: optional(anyJson()), - components: array(object({ - type: constant("Workspace"), - application: optional(string()), - state: object({ - config: anyJson(), - context: anyJson(), - children: array(oneOf(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }) - })) - }); - const workspacesImportLayoutDecoder = object({ - layout: workspaceLayoutDecoder, - mode: oneOf(constant("replace"), constant("merge")) - }); - const workspacesImportLayoutsDecoder = object({ - layouts: array(workspaceLayoutDecoder), - mode: oneOf(constant("replace"), constant("merge")) - }); - const exportedLayoutsResultDecoder = object({ - layouts: array(workspaceLayoutDecoder) - }); - const frameSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - const frameSummariesResultDecoder = object({ - summaries: array(frameSummaryResultDecoder) - }); - const workspaceSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder - }); - const workspaceSummariesResultDecoder = object({ - summaries: array(workspaceSummaryResultDecoder) - }); - const frameSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: anyJson(), - workspaces: array(workspaceSnapshotResultDecoder) - }); - const layoutSummaryDecoder = object({ - name: nonEmptyStringDecoder, - applicationName: optional(string()) - }); - const layoutSummariesDecoder = object({ - summaries: array(layoutSummaryDecoder) - }); - const simpleWindowOperationSuccessResultDecoder = object({ - windowId: nonEmptyStringDecoder - }); - const voidResultDecoder = anyJson(); - const frameStateResultDecoder = object({ - state: frameStateDecoder - }); - const frameBoundsDecoder = object({ - top: number(), - left: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const frameBoundsResultDecoder = object({ - bounds: frameBoundsDecoder - }); - const getWorkspaceIconResultDecoder = object({ - icon: optional(nonEmptyStringDecoder) - }); - const getPlatformFrameIdResultDecoder = object({ - id: optional(nonEmptyStringDecoder) - }); - const operationCheckResultDecoder = object({ - isSupported: boolean() - }); - const resizeConfigDecoder = object({ - width: optional(positiveNumberDecoder), - height: optional(positiveNumberDecoder), - relative: optional(boolean()) - }); - const moveConfigDecoder = object({ - top: optional(number()), - left: optional(number()), - relative: optional(boolean()) - }); - const simpleItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const closeOptionsDecoder = object({ - allowPrevent: optional(boolean()), - showDialog: optional(boolean()), - }); - const closeItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - closeOptions: optional(closeOptionsDecoder) - }); - const frameSnapshotConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - excludeIds: optional(boolean()) - }); - const frameStateConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - requestedState: frameStateDecoder - }); - const setItemTitleConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder - }); - const moveWindowConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - containerId: nonEmptyStringDecoder - }); - const resizeItemConfigDecoder = intersection(simpleItemConfigDecoder, resizeConfigDecoder); - const setMaximizationBoundaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - enabled: boolean() - }); - const moveFrameConfigDecoder = intersection(simpleItemConfigDecoder, moveConfigDecoder); - object({ - id: nonEmptyStringDecoder, - type: subParentDecoder - }); - const addWindowConfigDecoder = object({ - definition: swimlaneWindowDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addContainerConfigDecoder = object({ - definition: strictParentDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addItemResultDecoder = object({ - itemId: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder) - }); - const pingResultDecoder = object({ - live: boolean() - }); - const bundleWorkspaceConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - workspaceId: nonEmptyStringDecoder - }); - const bundleItemConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - itemId: nonEmptyStringDecoder - }); - const containerSummaryResultDecoder = object({ - itemId: nonEmptyStringDecoder, - config: parentSnapshotConfigDecoder - }); - const frameStreamDataDecoder = object({ - frameSummary: frameSummaryDecoder, - frameBounds: optional(frameBoundsDecoder) - }); - const workspaceStreamDataDecoder = object({ - workspaceSummary: workspaceSummaryResultDecoder, - frameSummary: frameSummaryDecoder, - workspaceSnapshot: optional(workspaceSnapshotResultDecoder), - frameBounds: optional(frameBoundsDecoder) - }); - const containerStreamDataDecoder = object({ - containerSummary: containerSummaryResultDecoder - }); - const windowStreamDataDecoder = object({ - windowSummary: object({ - itemId: nonEmptyStringDecoder, - parentId: nonEmptyStringDecoder, - config: swimlaneWindowSnapshotConfigDecoder - }) - }); - const workspaceLayoutSaveConfigDecoder = object({ - name: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - saveContext: optional(boolean()), - allowMultiple: optional(boolean()), - metadata: optional(object()) - }); - const workspaceLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - }); - const lockWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - config: optional(workspaceLockConfigDecoder) - }); - const windowLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const elementResizeConfigDecoder = object({ - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - }); - const lockWindowDecoder = object({ - windowPlacementId: nonEmptyStringDecoder, - config: optional(windowLockConfigDecoder) - }); - const rowLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const columnLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const groupLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - allowDropHeader: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()), - }); - const lockRowDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("row"), - config: optional(rowLockConfigDecoder) - }); - const lockColumnDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("column"), - config: optional(columnLockConfigDecoder) - }); - const lockGroupDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("group"), - config: optional(groupLockConfigDecoder) - }); - const lockContainerDecoder = oneOf(lockRowDecoder, lockColumnDecoder, lockGroupDecoder); - const pinWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const setWorkspaceIconDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const workspacePinOptionsDecoder = optional(object({ - icon: optional(nonEmptyStringDecoder) - })); - const frameShowConfigDecoder = optional(object({ - activate: optional(boolean()) - })); - const shortcutConfigDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const shortcutClickedDataDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const frameClosingDataDecoder = object({ - frameId: nonEmptyStringDecoder, - }); - const setMaximizationBoundaryAPIConfigDecoder = object({ - enabled: boolean() - }); - const loadingAnimationConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - type: loadingAnimationTypeDecoder - }); - const operationCheckConfigDecoder = object({ - operation: nonEmptyStringDecoder - }); - const setWindowDragModeDecoder = object({ - itemId: nonEmptyStringDecoder, - dragMode: windowDragModeDecoder - }); - const setLoadingStrategyDecoder = object({ - itemId: nonEmptyStringDecoder, - strategy: loadingStrategyDecoder - }); - const frameClosingResultDecoder = object({ - prevent: boolean() - }); - const sizeDecoder = object({ - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const boundsDecoder = object({ - left: number(), - top: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const popupTargetLocationDecoder = oneOf(constant("none"), constant("left"), constant("right"), constant("top"), constant("bottom")); - const popupConfigDecoder = object({ - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const ShowPopupConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const changeFrameVisibilityConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - activate: optional(boolean()), - isVisible: boolean() - }); - const frameDialogOptionsDecoder = object({ - mode: optional(oneOf(constant("Global"), constant("WindowContainer"))), - type: string(), - size: optional(sizeDecoder), - message: nonEmptyStringDecoder, - messageTitle: optional(nonEmptyStringDecoder), - movable: optional(boolean()), - transparent: optional(boolean()), - title: nonEmptyStringDecoder, - context: optional(anyJson()), - affirmativeButtonName: optional(nonEmptyStringDecoder), - showAffirmativeButton: optional(boolean()), - cancelButtonName: optional(nonEmptyStringDecoder), - showCancelButton: optional(boolean()), - negativeButtonName: optional(nonEmptyStringDecoder), - showNegativeButton: optional(boolean()), - defaultAction: optional(oneOf(constant("affirmative"), constant("negative"), constant("cancel"))), - timerDuration: optional(positiveNumberDecoder), - showTimer: optional(boolean()), - inputMaxLength: optional(positiveNumberDecoder), - inputPattern: optional(nonEmptyStringDecoder), - inputPatternErrorMessage: optional(nonEmptyStringDecoder), - inputPlaceholder: optional(string()), - blur: optional(boolean()) - }); - const showFrameDialogConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - options: frameDialogOptionsDecoder - }); - - const webPlatformMethodName = "T42.Web.Platform.Control"; - const webPlatformWspStreamName = "T42.Web.Platform.WSP.Stream"; - const OUTGOING_METHODS = { - control: { name: "T42.Workspaces.Control", isStream: false }, - frameStream: { name: "T42.Workspaces.Stream.Frame", isStream: true }, - workspaceStream: { name: "T42.Workspaces.Stream.Workspace", isStream: true }, - containerStream: { name: "T42.Workspaces.Stream.Container", isStream: true }, - windowStream: { name: "T42.Workspaces.Stream.Window", isStream: true } - }; - const INCOMING_METHODS = { - control: { name: "T42.Workspaces.Client.Control", isStream: false }, - }; - const STREAMS = { - frame: { name: "T42.Workspaces.Stream.Frame", payloadDecoder: frameStreamDataDecoder }, - workspace: { name: "T42.Workspaces.Stream.Workspace", payloadDecoder: workspaceStreamDataDecoder }, - container: { name: "T42.Workspaces.Stream.Container", payloadDecoder: containerStreamDataDecoder }, - window: { name: "T42.Workspaces.Stream.Window", payloadDecoder: windowStreamDataDecoder } - }; - const CLIENT_OPERATIONS = { - shortcutClicked: { name: "shortcutClicked", argsDecoder: shortcutClickedDataDecoder, resultDecoder: voidResultDecoder }, - frameClosing: { name: "frameClosing", argsDecoder: frameClosingDataDecoder, resultDecoder: frameClosingResultDecoder }, - }; - const OPERATIONS = { - ping: { name: "ping", resultDecoder: pingResultDecoder }, - isWindowInWorkspace: { name: "isWindowInWorkspace", argsDecoder: simpleItemConfigDecoder, resultDecoder: isWindowInSwimlaneResultDecoder }, - createWorkspace: { name: "createWorkspace", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: workspaceCreateConfigDecoder }, - createFrame: { name: "createFrame", resultDecoder: frameSummaryResultDecoder, argsDecoder: emptyFrameDefinitionDecoder }, - initFrame: { name: "initFrame", resultDecoder: voidResultDecoder, argsDecoder: frameInitProtocolConfigDecoder }, - getAllFramesSummaries: { name: "getAllFramesSummaries", resultDecoder: frameSummariesResultDecoder }, - getFrameSummary: { name: "getFrameSummary", resultDecoder: frameSummaryDecoder, argsDecoder: getFrameSummaryConfigDecoder }, - getAllWorkspacesSummaries: { name: "getAllWorkspacesSummaries", resultDecoder: workspaceSummariesResultDecoder }, - getWorkspaceSnapshot: { name: "getWorkspaceSnapshot", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: simpleItemConfigDecoder }, - getAllLayoutsSummaries: { name: "getAllLayoutsSummaries", resultDecoder: layoutSummariesDecoder }, - openWorkspace: { name: "openWorkspace", argsDecoder: openWorkspaceConfigDecoder, resultDecoder: workspaceSnapshotResultDecoder }, - deleteLayout: { name: "deleteLayout", resultDecoder: voidResultDecoder, argsDecoder: deleteLayoutConfigDecoder }, - saveLayout: { name: "saveLayout", resultDecoder: workspaceLayoutDecoder, argsDecoder: workspaceLayoutSaveConfigDecoder }, - importLayout: { name: "importLayout", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutDecoder }, - importLayouts: { name: "importLayouts", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutsDecoder }, - exportAllLayouts: { name: "exportAllLayouts", resultDecoder: exportedLayoutsResultDecoder }, - restoreItem: { name: "restoreItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - maximizeItem: { name: "maximizeItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - focusItem: { name: "focusItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeItem: { name: "closeItem", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeWorkspace: { name: "closeWorkspace", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - resizeItem: { name: "resizeItem", argsDecoder: resizeItemConfigDecoder, resultDecoder: voidResultDecoder }, - setMaximizationBoundary: { name: "setMaximizationBoundary", argsDecoder: setMaximizationBoundaryConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameState: { name: "changeFrameState", argsDecoder: frameStateConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameState: { name: "getFrameState", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameStateResultDecoder }, - getFrameBounds: { name: "getFrameBounds", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameBoundsResultDecoder }, - moveFrame: { name: "moveFrame", argsDecoder: moveFrameConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameSnapshot: { name: "getFrameSnapshot", argsDecoder: frameSnapshotConfigDecoder, resultDecoder: frameSnapshotResultDecoder }, - forceLoadWindow: { name: "forceLoadWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - ejectWindow: { name: "ejectWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - setItemTitle: { name: "setItemTitle", argsDecoder: setItemTitleConfigDecoder, resultDecoder: voidResultDecoder }, - moveWindowTo: { name: "moveWindowTo", argsDecoder: moveWindowConfigDecoder, resultDecoder: voidResultDecoder }, - addWindow: { name: "addWindow", argsDecoder: addWindowConfigDecoder, resultDecoder: addItemResultDecoder }, - addContainer: { name: "addContainer", argsDecoder: addContainerConfigDecoder, resultDecoder: addItemResultDecoder }, - bundleWorkspace: { name: "bundleWorkspace", argsDecoder: bundleWorkspaceConfigDecoder, resultDecoder: voidResultDecoder }, - bundleItem: { name: "bundleItem", argsDecoder: bundleItemConfigDecoder, resultDecoder: voidResultDecoder }, - hibernateWorkspace: { name: "hibernateWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - resumeWorkspace: { name: "resumeWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - lockWorkspace: { name: "lockWorkspace", argsDecoder: lockWorkspaceDecoder, resultDecoder: voidResultDecoder }, - lockWindow: { name: "lockWindow", argsDecoder: lockWindowDecoder, resultDecoder: voidResultDecoder }, - lockContainer: { name: "lockContainer", argsDecoder: lockContainerDecoder, resultDecoder: voidResultDecoder }, - pinWorkspace: { name: "pinWorkspace", argsDecoder: pinWorkspaceDecoder, resultDecoder: voidResultDecoder }, - unpinWorkspace: { name: "unpinWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - getWorkspaceIcon: { name: "getWorkspaceIcon", argsDecoder: workspaceSelectorDecoder, resultDecoder: getWorkspaceIconResultDecoder }, - setWorkspaceIcon: { name: "setWorkspaceIcon", argsDecoder: setWorkspaceIconDecoder, resultDecoder: voidResultDecoder }, - registerShortcut: { name: "registerShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - unregisterShortcut: { name: "unregisterShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - showLoadingAnimation: { name: "showLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - hideLoadingAnimation: { name: "hideLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - getPlatformFrameId: { name: "getPlatformFrameId", resultDecoder: getPlatformFrameIdResultDecoder }, - operationCheck: { name: "operationCheck", argsDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - setWindowDragMode: { name: "setWindowDragMode", argsDecoder: setWindowDragModeDecoder, resultDecoder: voidResultDecoder }, - setLoadingStrategy: { name: "setLoadingStrategy", argsDecoder: setLoadingStrategyDecoder, resultDecoder: voidResultDecoder }, - getTaskbarIcon: { name: "getTaskbarIcon", resultDecoder: iconDecoder }, - setTaskbarIcon: { name: "setTaskbarIcon", argsDecoder: setIconArgumentsDecoder, resultDecoder: voidResultDecoder }, - subscribeToFrameClosing: { name: "subscribeToFrameClosing", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - showPopup: { name: "showPopup", argsDecoder: ShowPopupConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameVisibility: { name: "changeFrameVisibility", argsDecoder: changeFrameVisibilityConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameVisibility: { name: "getFrameVisibility", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameVisibilityResultDecoder }, - showFrameDialog: { name: "showFrameDialog", argsDecoder: showFrameDialogConfigDecoder, resultDecoder: anyJson() } - }; - - class PromiseWrapper { - resolve; - reject; - promise; - constructor() { - this.promise = new Promise((res, rej) => { - this.resolve = res; - this.reject = rej; - }); - } - } - - class Bridge { - transport; - registry; - activeSubscriptions = []; - pendingSubScriptions = []; - constructor(transport, registry) { - this.transport = transport; - this.registry = registry; - } - async createCoreEventSubscription() { - await this.transport.coreSubscriptionReady(this.handleCoreEvent.bind(this)); - } - handleCoreSubscription(config) { - const registryKey = `${config.eventType}-${config.action}`; - const scope = config.scope; - const scopeId = config.scopeId; - return this.registry.add(registryKey, (args) => { - const scopeConfig = { - type: scope, - id: scopeId - }; - const receivedIds = { - frame: args.frameSummary?.id || args.windowSummary?.config.frameId, - workspace: args.workspaceSummary?.id || args.windowSummary?.config.workspaceId, - container: args.containerSummary?.itemId, - window: args.windowSummary?.itemId - }; - const shouldInvokeCallback = this.checkScopeMatch(scopeConfig, receivedIds); - if (!shouldInvokeCallback) { - return; - } - config.callback(args); - }); - } - async send(operationName, operationArgs, invocationOptions) { - const operationDefinition = Object.values(OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - try { - const operationResult = await this.transport.transmitControl(operationDefinition.name, operationArgs, invocationOptions); - operationDefinition.resultDecoder.runWithException(operationResult); - return operationResult; - } - catch (error) { - if (error.kind) { - throw new Error(`Unexpected internal incoming validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - throw new Error(error.message); - } - } - async subscribe(config) { - const pendingSub = this.getPendingSubscription(config); - if (pendingSub) { - await pendingSub.promise; - } - let activeSub = this.getActiveSubscription(config); - const registryKey = this.getRegistryKey(config); - if (!activeSub) { - const pendingPromise = new PromiseWrapper(); - const pendingSubscription = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - promise: pendingPromise.promise - }; - this.pendingSubScriptions.push(pendingSubscription); - try { - const stream = STREAMS[config.eventType]; - const gdSub = await this.transport.subscribe(stream.name, this.getBranchKey(config), config.eventType); - gdSub.onData((streamData) => { - const data = streamData.data; - const requestedArgumentsResult = streamRequestArgumentsDecoder.run(streamData.requestArguments); - const actionResult = workspaceEventActionDecoder.run(data.action); - if (!requestedArgumentsResult.ok || !actionResult.ok) { - return; - } - const streamType = requestedArgumentsResult.result.type; - const branch = requestedArgumentsResult.result.branch; - const keyToExecute = `${streamType}-${branch}-${actionResult.result}`; - const validatedPayload = STREAMS[streamType].payloadDecoder.run(data.payload); - if (!validatedPayload.ok) { - return; - } - this.registry.execute(keyToExecute, validatedPayload.result); - }); - activeSub = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - callbacksCount: 0, - gdSub - }; - this.activeSubscriptions.push(activeSub); - pendingPromise.resolve(); - } - catch (error) { - pendingPromise.reject(error); - throw error; - } - finally { - this.removePendingSubscription(pendingSubscription); - } - } - const unsubscribe = this.registry.add(registryKey, config.callback); - ++activeSub.callbacksCount; - return () => { - unsubscribe(); - --activeSub.callbacksCount; - if (activeSub.callbacksCount === 0) { - activeSub.gdSub.close(); - this.activeSubscriptions.splice(this.activeSubscriptions.indexOf(activeSub), 1); - } - }; - } - onOperation(callback) { - const wrappedCallback = (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - callback(payload, caller); - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - onOperationWithResponse(callback) { - const wrappedCallback = async (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - const result = await callback(payload, caller); - if (operationDefinition.resultDecoder) { - try { - operationDefinition.resultDecoder.runWithException(result); - } - catch (error) { - throw new Error(`Unexpected internal outgoing result validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - return result; - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - checkScopeMatch(scope, receivedIds) { - if (scope.type === "global") { - return true; - } - if (scope.type === "frame" && scope.id === receivedIds.frame) { - return true; - } - if (scope.type === "workspace" && scope.id === receivedIds.workspace) { - return true; - } - if (scope.type === "container" && scope.id === receivedIds.container) { - return true; - } - if (scope.type === "window" && scope.id === receivedIds.window) { - return true; - } - return false; - } - handleCoreEvent(args) { - const data = args.data; - try { - const verifiedAction = workspaceEventActionDecoder.runWithException(data.action); - const verifiedType = eventTypeDecoder.runWithException(data.type); - const verifiedPayload = STREAMS[verifiedType].payloadDecoder.runWithException(data.payload); - const registryKey = `${verifiedType}-${verifiedAction}`; - this.registry.execute(registryKey, verifiedPayload); - } - catch (error) { - console.warn(`Cannot handle event with data ${JSON.stringify(data)}, because of validation error: ${error.message}`); - } - } - getBranchKey(config) { - return config.scope === "global" ? config.scope : `${config.scope}_${config.scopeId}`; - } - getRegistryKey(config) { - return `${config.eventType}-${this.getBranchKey(config)}-${config.action}`; - } - getActiveSubscription(config) { - return this.activeSubscriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - getPendingSubscription(config) { - return this.pendingSubScriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - removePendingSubscription(pendingSubscription) { - const index = this.pendingSubScriptions.indexOf(pendingSubscription); - if (index >= 0) { - this.pendingSubScriptions.splice(index, 1); - } - } - } - - const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage; - reject(message); - }, timeoutMilliseconds); - promise() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - - const isDesktop = () => { - return typeof window === "undefined" ? - true : - window.glue42gd || window.iodesktop; - }; - const browserGlobal = () => { - return typeof window === "undefined" ? null : - window.glue42core || window.iobrowser; - }; - - class InteropTransport { - agm; - registry; - defaultTransportTimeout = 120000; - coreEventMethodInitiated = false; - corePlatformSubPromise; - constructor(agm, registry) { - this.agm = agm; - this.registry = registry; - } - async initiate(actualWindowId) { - if (isDesktop()) { - await Promise.all(Object.values(OUTGOING_METHODS).map((method) => { - return this.verifyMethodLive(method.name); - })); - await Promise.all(Object.keys(INCOMING_METHODS).map((method) => { - return this.registerMethod(method); - })); - return; - } - const systemId = browserGlobal().communicationId; - await Promise.all([ - this.verifyMethodLive(webPlatformMethodName, systemId), - this.verifyMethodLive(webPlatformWspStreamName, systemId) - ]); - await this.transmitControl("frameHello", { windowId: actualWindowId }); - } - coreSubscriptionReady(eventCallback) { - if (!this.coreEventMethodInitiated) { - this.subscribePlatform(eventCallback); - } - return this.corePlatformSubPromise; - } - subscribePlatform(eventCallback) { - this.coreEventMethodInitiated = true; - const systemId = browserGlobal().communicationId; - this.corePlatformSubPromise = this.agm.subscribe(webPlatformWspStreamName, systemId ? { target: { instance: systemId } } : undefined); - this.corePlatformSubPromise - .then((sub) => { - sub.onData((data) => eventCallback(data.data)); - }); - } - async subscribe(streamName, streamBranch, streamType) { - const subscriptionArgs = { - branch: streamBranch, - type: streamType - }; - let subscription; - try { - subscription = await this.agm.subscribe(streamName, { arguments: subscriptionArgs }); - } - catch (error) { - const message = `Internal subscription error! Error details: stream - ${streamName}, branch: ${streamBranch}. Internal message: ${error.message}`; - throw new Error(message); - } - return subscription; - } - async transmitControl(operation, operationArguments, invocationOptions) { - const invocationArguments = isDesktop() ? { operation, operationArguments } : { operation, domain: "workspaces", data: operationArguments }; - const methodName = isDesktop() ? OUTGOING_METHODS.control.name : webPlatformMethodName; - const platformTarget = isDesktop() ? undefined : browserGlobal().communicationId; - let invocationResult; - const baseErrorMessage = `Internal Workspaces Communication Error. Attempted operation: ${JSON.stringify(invocationArguments)}. `; - try { - invocationResult = await this.agm.invoke(methodName, invocationArguments, platformTarget ? { instance: platformTarget } : "best", { methodResponseTimeoutMs: invocationOptions?.timeout ?? this.defaultTransportTimeout }); - if (!invocationResult) { - throw new Error("Received unsupported result from GD - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from GD - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - onInternalMethodInvoked(key, callback) { - return this.registry.add(key, callback); - } - verifyMethodLive(name, systemId) { - return promisePlus(() => { - return new Promise((resolve) => { - const hasMethod = this.agm.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = systemId ? - method.getServers().some((server) => server.instance === systemId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - resolve(); - return; - } - const unSub = this.agm.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = systemId ? - server.instance === systemId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }); - }, 15000, "Timeout waiting for the Workspaces communication channels"); - } - registerMethod(key) { - const method = INCOMING_METHODS[key]; - return this.agm.register(method.name, (args, caller) => { - return Promise.all(this.registry.execute(key, args, caller)); - }); - } - } - - const privateData$4 = new WeakMap(); - class ParentBuilder { - constructor(definition, base) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$4.set(this, { base, children, definition }); - } - get type() { - return privateData$4.get(this).definition.type; - } - addColumn(definition) { - const base = privateData$4.get(this).base; - return base.add("column", privateData$4.get(this).children, definition); - } - addRow(definition) { - const base = privateData$4.get(this).base; - return base.add("row", privateData$4.get(this).children, definition); - } - addGroup(definition) { - const base = privateData$4.get(this).base; - return base.add("group", privateData$4.get(this).children, definition); - } - addWindow(definition) { - const base = privateData$4.get(this).base; - base.addWindow(privateData$4.get(this).children, definition); - return this; - } - serialize() { - const definition = privateData$4.get(this).definition; - definition.children = privateData$4.get(this).base.serializeChildren(privateData$4.get(this).children); - return definition; - } - } - - class BaseBuilder { - getBuilder; - constructor(getBuilder) { - this.getBuilder = getBuilder; - } - wrapChildren(children) { - return children.map((child) => { - if (child.type === "window") { - return child; - } - return this.getBuilder({ type: child.type, definition: child }); - }); - } - add(type, children, definition) { - const validatedDefinition = parentDefinitionDecoder.runWithException(definition); - const childBuilder = this.getBuilder({ type, definition: validatedDefinition }); - children.push(childBuilder); - return childBuilder; - } - addWindow(children, definition) { - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - validatedDefinition.type = "window"; - children.push(validatedDefinition); - } - serializeChildren(children) { - return children.map((child) => { - if (child instanceof ParentBuilder) { - return child.serialize(); - } - else { - return child; - } - }); - } - } - - const privateData$3 = new WeakMap(); - class WorkspaceBuilder { - constructor(definition, base, controller) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$3.set(this, { base, children, definition, controller }); - } - addColumn(definition) { - const children = privateData$3.get(this).children; - const areAllColumns = children.every((child) => child instanceof ParentBuilder && child.type === "column"); - if (!areAllColumns) { - throw new Error("Cannot add a column to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("column", children, definition); - } - addRow(definition) { - const children = privateData$3.get(this).children; - const areAllRows = children.every((child) => child instanceof ParentBuilder && child.type === "row"); - if (!areAllRows) { - throw new Error("Cannot add a row to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("row", children, definition); - } - addGroup(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a group to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - return base.add("group", children, definition); - } - addWindow(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a window to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - base.addWindow(children, definition); - return this; - } - getChildAt(index) { - nonNegativeNumberDecoder.runWithException(index); - const data = privateData$3.get(this).children; - return data[index]; - } - async create(config) { - const saveConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - const definition = privateData$3.get(this).definition; - definition.children = privateData$3.get(this).base.serializeChildren(privateData$3.get(this).children); - const controller = privateData$3.get(this).controller; - return controller.createWorkspace(definition, saveConfig); - } - } - - const privateData$2 = new WeakMap(); - const getBase$2 = (model) => { - return privateData$2.get(model).base; - }; - class Row { - constructor(base) { - privateData$2.set(this, { base }); - } - get type() { - return "row"; - } - get id() { - return getBase$2(this).getId(this); - } - get frameId() { - return getBase$2(this).getFrameId(this); - } - get workspaceId() { - return getBase$2(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$2(this).getPositionIndex(this); - } - get children() { - return getBase$2(this).getAllChildren(this); - } - get parent() { - return getBase$2(this).getMyParent(this); - } - get frame() { - return getBase$2(this).getMyFrame(this); - } - get workspace() { - return getBase$2(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$2(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$2(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$2(this).getMinWidth(this); - } - get minHeight() { - return getBase$2(this).getMinHeight(this); - } - get maxWidth() { - return getBase$2(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$2(this).getMaxHeight(this); - } - get width() { - return getBase$2(this).getWidthInPx(this); - } - get height() { - return getBase$2(this).getHeightInPx(this); - } - get isPinned() { - return getBase$2(this).getIsPinned(this); - } - get isMaximized() { - return getBase$2(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$2(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$2(this).addWindow(this, definition, "row"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "group", "row", definition); - } - async addColumn(definition) { - if (definition?.type && definition.type !== "column") { - throw new Error(`Expected a column definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "column", "row", definition); - } - async addRow() { - throw new Error("Adding rows as row children is not supported"); - } - removeChild(predicate) { - return getBase$2(this).removeChild(this, predicate); - } - maximize() { - return getBase$2(this).maximize(this); - } - restore() { - return getBase$2(this).restore(this); - } - close() { - return getBase$2(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : rowLockConfigDecoder.runWithException(lockConfigResult); - return getBase$2(this).lockContainer(this, verifiedConfig); - } - async setHeight(height) { - nonNegativeNumberDecoder.runWithException(height); - return getBase$2(this).setHeight(this, height); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$2(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$2(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData$1 = new WeakMap(); - const getBase$1 = (model) => { - return privateData$1.get(model).base; - }; - class Column { - constructor(base) { - privateData$1.set(this, { base }); - } - get type() { - return "column"; - } - get id() { - return getBase$1(this).getId(this); - } - get frameId() { - return getBase$1(this).getFrameId(this); - } - get workspaceId() { - return getBase$1(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$1(this).getPositionIndex(this); - } - get children() { - return getBase$1(this).getAllChildren(this); - } - get parent() { - return getBase$1(this).getMyParent(this); - } - get frame() { - return getBase$1(this).getMyFrame(this); - } - get workspace() { - return getBase$1(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$1(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$1(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$1(this).getMinWidth(this); - } - get minHeight() { - return getBase$1(this).getMinHeight(this); - } - get maxWidth() { - return getBase$1(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$1(this).getMaxHeight(this); - } - get width() { - return getBase$1(this).getWidthInPx(this); - } - get height() { - return getBase$1(this).getHeightInPx(this); - } - get isPinned() { - return getBase$1(this).getIsPinned(this); - } - get isMaximized() { - return getBase$1(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$1(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$1(this).addWindow(this, definition, "column"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "group", "column", definition); - } - async addColumn() { - throw new Error("Adding columns as column children is not supported"); - } - async addRow(definition) { - if (definition?.type && definition.type !== "row") { - throw new Error(`Expected a row definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "row", "column", definition); - } - removeChild(predicate) { - return getBase$1(this).removeChild(this, predicate); - } - maximize() { - return getBase$1(this).maximize(this); - } - restore() { - return getBase$1(this).restore(this); - } - close() { - return getBase$1(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : columnLockConfigDecoder.runWithException(lockConfigResult); - return getBase$1(this).lockContainer(this, verifiedConfig); - } - async setWidth(width) { - nonNegativeNumberDecoder.runWithException(width); - return getBase$1(this).setWidth(this, width); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$1(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$1(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData = new WeakMap(); - const getBase = (model) => { - return privateData.get(model).base; - }; - class Group { - constructor(base) { - privateData.set(this, { base }); - } - get type() { - return "group"; - } - get id() { - return getBase(this).getId(this); - } - get frameId() { - return getBase(this).getFrameId(this); - } - get workspaceId() { - return getBase(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase(this).getPositionIndex(this); - } - get children() { - return getBase(this).getAllChildren(this); - } - get parent() { - return getBase(this).getMyParent(this); - } - get frame() { - return getBase(this).getMyFrame(this); - } - get workspace() { - return getBase(this).getMyWorkspace(this); - } - get allowExtract() { - return getBase(this).getAllowExtract(this); - } - get allowReorder() { - return getBase(this).getAllowReorder(this); - } - get allowDropLeft() { - return getBase(this).getAllowDropLeft(this); - } - get allowDropRight() { - return getBase(this).getAllowDropRight(this); - } - get allowDropTop() { - return getBase(this).getAllowDropTop(this); - } - get allowDropBottom() { - return getBase(this).getAllowDropBottom(this); - } - get allowDropHeader() { - return getBase(this).getAllowDropHeader(this); - } - get allowDrop() { - return getBase(this).getAllowDrop(this); - } - get showMaximizeButton() { - return getBase(this).getShowMaximizeButton(this); - } - get showEjectButton() { - return getBase(this).getShowEjectButton(this); - } - get showAddWindowButton() { - return getBase(this).getShowAddWindowButton(this); - } - get minWidth() { - return getBase(this).getMinWidth(this); - } - get minHeight() { - return getBase(this).getMinHeight(this); - } - get maxWidth() { - return getBase(this).getMaxWidth(this); - } - get maxHeight() { - return getBase(this).getMaxHeight(this); - } - get width() { - return getBase(this).getWidthInPx(this); - } - get height() { - return getBase(this).getHeightInPx(this); - } - get isMaximized() { - return getBase(this).getIsMaximized(this); - } - addWindow(definition) { - return getBase(this).addWindow(this, definition, "group"); - } - async addGroup() { - throw new Error("Adding groups as group child is not supported"); - } - async addColumn() { - throw new Error("Adding columns as group child is not supported"); - } - async addRow() { - throw new Error("Adding rows as group child is not supported"); - } - removeChild(predicate) { - return getBase(this).removeChild(this, predicate); - } - maximize() { - return getBase(this).maximize(this); - } - restore() { - return getBase(this).restore(this); - } - close() { - return getBase(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropRight: this.allowDropRight, - allowDropTop: this.allowDropTop, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : groupLockConfigDecoder.runWithException(lockConfigResult); - return getBase(this).lockContainer(this, verifiedConfig); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - return getBase(this).setSize(this, config.width, config.height); - } - async bundleToRow() { - await getBase(this).bundleTo(this, "row"); - await this.workspace.refreshReference(); - } - async bundleToColumn() { - await getBase(this).bundleTo(this, "column"); - await this.workspace.refreshReference(); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase(this).processLocalSubscription(this, config); - return unsubscribe; - } - } - - const DEFAULT_WINDOW_DRAG_MODE = "keepInside"; - const ONE_DAY_MS = 86_400_000; - - const data$3 = new WeakMap(); - const getData$3 = (model) => { - return data$3.get(model).manager.getWorkspaceData(model); - }; - const getDataManager = (model) => { - return data$3.get(model).manager; - }; - class Workspace { - constructor(dataManager) { - data$3.set(this, { manager: dataManager }); - } - get id() { - return getData$3(this).id; - } - get frameId() { - return getData$3(this).config.frameId; - } - get positionIndex() { - return getData$3(this).config.positionIndex; - } - get title() { - return getData$3(this).config.title; - } - get layoutName() { - return getData$3(this).config.layoutName; - } - get isHibernated() { - return getData$3(this).config.isHibernated; - } - get isSelected() { - return getData$3(this).config.isSelected; - } - get children() { - return getData$3(this).children; - } - get frame() { - return getData$3(this).frame; - } - get allowSplitters() { - return getData$3(this).config.allowSplitters; - } - get allowSystemHibernation() { - return getData$3(this).config.allowSystemHibernation; - } - get allowDrop() { - return getData$3(this).config.allowDrop; - } - get allowDropLeft() { - return getData$3(this).config.allowDropLeft; - } - get allowDropTop() { - return getData$3(this).config.allowDropTop; - } - get allowDropRight() { - return getData$3(this).config.allowDropRight; - } - get allowDropBottom() { - return getData$3(this).config.allowDropBottom; - } - get allowExtract() { - return getData$3(this).config.allowExtract; - } - get allowWindowReorder() { - return getData$3(this).config.allowWindowReorder; - } - get showCloseButton() { - return getData$3(this).config.showCloseButton; - } - get showSaveButton() { - return getData$3(this).config.showSaveButton; - } - get allowWorkspaceTabReorder() { - return getData$3(this).config.allowWorkspaceTabReorder; - } - get allowWorkspaceTabExtract() { - return getData$3(this).config.allowWorkspaceTabExtract; - } - get minWidth() { - return getData$3(this).config.minWidth; - } - get minHeight() { - return getData$3(this).config.minHeight; - } - get maxWidth() { - return getData$3(this).config.maxWidth; - } - get maxHeight() { - return getData$3(this).config.maxHeight; - } - get width() { - return getData$3(this).config.widthInPx; - } - get height() { - return getData$3(this).config.heightInPx; - } - get showWindowCloseButtons() { - return getData$3(this).config.showWindowCloseButtons; - } - get showEjectButtons() { - return getData$3(this).config.showEjectButtons; - } - get showAddWindowButtons() { - return getData$3(this).config.showAddWindowButtons; - } - get isPinned() { - return getData$3(this).config.isPinned; - } - get windowDragMode() { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - return DEFAULT_WINDOW_DRAG_MODE; - } - return getData$3(this).config.windowDragMode; - } - get loadingStrategy() { - if (!isDesktop()) { - console.warn("The workspace.loadingStrategy property is not supported in IO Connect Browser"); - } - return getData$3(this).config.loadingStrategy; - } - async setLoadingStrategy(strategy) { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - const controller = getData$3(this).controller; - await controller.setLoadingStrategy(this.id, strategy); - await this.refreshReference(); - } - async removeChild(predicate) { - checkThrowCallback(predicate); - const child = this.children.find(predicate); - if (!child) { - return; - } - await child.close(); - await this.refreshReference(); - } - async remove(predicate) { - checkThrowCallback(predicate); - const controller = getData$3(this).controller; - const child = controller.iterateFindChild(this.children, predicate); - await child.close(); - await this.refreshReference(); - } - async focus() { - await getData$3(this).controller.focusItem(this.id); - await this.refreshReference(); - } - async close() { - const controller = getData$3(this).controller; - await controller.closeWorkspace(this.id, this.frameId); - } - snapshot() { - return getData$3(this).controller.getSnapshot(this.id, "workspace"); - } - async saveLayout(name, config) { - nonEmptyStringDecoder.runWithException(name); - await getData$3(this).controller.saveLayout({ name, workspaceId: this.id, saveContext: config?.saveContext, metadata: config?.metadata, allowMultiple: config?.allowMultiple }); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const controller = getData$3(this).controller; - await controller.setItemTitle(this.id, title); - await this.refreshReference(); - } - getContext() { - const controller = getData$3(this).controller; - return controller.getWorkspaceContext(this.id); - } - setContext(data) { - const controller = getData$3(this).controller; - return controller.setWorkspaceContext(this.id, data); - } - updateContext(data) { - const controller = getData$3(this).controller; - return controller.updateWorkspaceContext(this.id, data); - } - onContextUpdated(callback) { - const controller = getData$3(this).controller; - return controller.subscribeWorkspaceContextUpdated(this.id, callback); - } - async refreshReference() { - const newSnapshot = (await getData$3(this).controller.getSnapshot(this.id, "workspace")); - const currentChildrenFlat = getData$3(this).controller.flatChildren(getData$3(this).children); - const newChildren = getData$3(this).controller.refreshChildren({ - existingChildren: currentChildrenFlat, - workspace: this, - parent: this, - children: newSnapshot.children - }); - const currentFrame = this.frame; - let actualFrame; - if (currentFrame.id === newSnapshot.config.frameId) { - getDataManager(this).remapFrame(currentFrame, newSnapshot.frameSummary); - actualFrame = currentFrame; - } - else { - const frameCreateConfig = { - summary: newSnapshot.frameSummary - }; - const newFrame = getData$3(this).ioc.getModel("frame", frameCreateConfig); - actualFrame = newFrame; - } - getDataManager(this).remapWorkspace(this, { - config: newSnapshot.config, - children: newChildren, - frame: actualFrame - }); - } - async getIcon() { - const controller = getData$3(this).controller; - return controller.getWorkspaceIcon(this.id); - } - async setIcon(icon) { - const controller = getData$3(this).controller; - return controller.setWorkspaceIcon(this.id, icon); - } - getBox(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type !== "window" && predicate(child)); - } - getAllBoxes(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allParents = controller.iterateFilterChildren(children, (child) => child.type !== "window"); - if (!predicate) { - return allParents; - } - return allParents.filter(predicate); - } - getRow(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "row" && predicate(parent)); - } - getAllRows(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "row" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "row"); - } - getColumn(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "column" && predicate(parent)); - } - getAllColumns(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "column" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "column"); - } - getGroup(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "group" && predicate(parent)); - } - getAllGroups(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "group" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "group"); - } - getWindow(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type === "window" && predicate(child)); - } - getAllWindows(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allWindows = controller.iterateFilterChildren(children, (child) => child.type === "window"); - if (!predicate) { - return allWindows; - } - return allWindows.filter(predicate); - } - addRow(definition) { - return getData$3(this).base.addParent(this, "row", "workspace", definition); - } - addColumn(definition) { - return getData$3(this).base.addParent(this, "column", "workspace", definition); - } - addGroup(definition) { - return getData$3(this).base.addParent(this, "group", "workspace", definition); - } - addWindow(definition) { - return getData$3(this).base.addWindow(this, definition, "workspace"); - } - async bundleToRow() { - await getData$3(this).controller.bundleWorkspaceTo("row", this.id); - await this.refreshReference(); - } - async bundleToColumn() { - await getData$3(this).controller.bundleWorkspaceTo("column", this.id); - await this.refreshReference(); - } - async hibernate() { - await getData$3(this).controller.hibernateWorkspace(this.id); - await this.refreshReference(); - } - async resume() { - await getData$3(this).controller.resumeWorkspace(this.id); - await this.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowWindowReorder: this.allowWindowReorder, - allowSplitters: this.allowSplitters, - showCloseButton: this.showCloseButton, - showSaveButton: this.showSaveButton, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - showAddWindowButtons: this.showAddWindowButtons, - showEjectButtons: this.showEjectButtons, - showWindowCloseButtons: this.showWindowCloseButtons - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : workspaceLockConfigDecoder.runWithException(lockConfigResult); - await getData$3(this).controller.lockWorkspace(this.id, verifiedConfig); - await this.refreshReference(); - } - async pin(options) { - workspacePinOptionsDecoder.runWithException(options); - await getData$3(this).controller.pinWorkspace(this.id, options?.icon); - await this.refreshReference(); - } - async unpin() { - await getData$3(this).controller.unpinWorkspace(this.id); - await this.refreshReference(); - } - async showLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.showWorkspaceLoadingAnimation(this.id); - } - async hideLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.hideWorkspaceLoadingAnimation(this.id); - } - async setWindowDragMode(mode) { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - throw new Error("Not supported in IO Connect Browser"); - } - windowDragModeDecoder.runWithException(mode); - await getData$3(this).controller.setWindowDragMode(this.id, mode); - await this.refreshReference(); - } - async onClosed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - action: "closed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onHibernated(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "hibernated", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onResumed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "resumed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "added", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - action: "removed", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const foundWindow = this.getWindow((win) => { - return win.id && win.id === payload.windowSummary.config.windowId; - }); - callback(foundWindow); - }; - const config = { - action: "loaded", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowMaximized(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "maximized", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRestored(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "restored", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowSelected(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "selected", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowSplitters: this.allowSplitters, - allowWindowReorder: this.allowWindowReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - showAddWindowButtons: this.showAddWindowButtons, - showCloseButton: this.showCloseButton, - showEjectButtons: this.showEjectButtons, - showSaveButton: this.showSaveButton, - showWindowCloseButtons: this.showWindowCloseButtons - }); - }; - const config = { - action: "lock-configuration-changed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$2 = new WeakMap(); - const getData$2 = (model) => { - return data$2.get(model).manager.getWindowData(model); - }; - class Window { - constructor(dataManager) { - data$2.set(this, { manager: dataManager }); - } - get id() { - return getData$2(this).config.windowId; - } - get elementId() { - return getData$2(this).id; - } - get type() { - return "window"; - } - get frameId() { - return getData$2(this).frame.id; - } - get workspaceId() { - return getData$2(this).workspace.id; - } - get positionIndex() { - return getData$2(this).config.positionIndex; - } - get isMaximized() { - return getData$2(this).config.isMaximized; - } - get isLoaded() { - return getData$2(this).controller.checkIsWindowLoaded(this.id); - } - get isSelected() { - return getData$2(this).config.isSelected; - } - get focused() { - return this.getGdWindow().isFocused; - } - get title() { - return getData$2(this).config.title; - } - get allowExtract() { - return getData$2(this).config.allowExtract; - } - get allowReorder() { - return getData$2(this).config.allowReorder; - } - get showCloseButton() { - return getData$2(this).config.showCloseButton; - } - get width() { - return getData$2(this).config.widthInPx; - } - get height() { - return getData$2(this).config.heightInPx; - } - get minWidth() { - return getData$2(this).config.minWidth; - } - get minHeight() { - return getData$2(this).config.minHeight; - } - get maxWidth() { - return getData$2(this).config.maxWidth; - } - get maxHeight() { - return getData$2(this).config.maxHeight; - } - get workspace() { - return getData$2(this).workspace; - } - get frame() { - return getData$2(this).frame; - } - get parent() { - return getData$2(this).parent; - } - get appName() { - return getData$2(this).config.appName; - } - async forceLoad() { - if (this.isLoaded) { - return; - } - const controller = getData$2(this).controller; - const itemId = getData$2(this).id; - const windowId = await controller.forceLoadWindow(itemId); - getData$2(this).config.windowId = windowId; - await this.workspace.refreshReference(); - } - async focus() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.focusItem(id); - await this.workspace.refreshReference(); - } - async close() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.closeItem(id); - await getData$2(this) - .parent - .removeChild((child) => child.id === id); - await this.workspace.refreshReference(); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const itemId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.setItemTitle(itemId, title); - await this.workspace.refreshReference(); - } - async maximize() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.maximizeItem(id); - await this.workspace.refreshReference(); - } - async restore() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.restoreItem(id); - await this.workspace.refreshReference(); - } - async eject() { - if (!this.isLoaded) { - throw new Error("Cannot eject this window, because it is not loaded yet"); - } - const itemId = getData$2(this).id; - const windowId = getData$2(this).config.windowId; - const newWindowId = await getData$2(this).controller.ejectWindow(itemId, windowId); - getData$2(this).config.windowId = newWindowId; - await this.workspace.refreshReference(); - return this.getGdWindow(); - } - getGdWindow() { - if (!this.isLoaded) { - throw new Error("Cannot fetch this GD window, because the window is not yet loaded"); - } - const myId = getData$2(this).config.windowId; - const controller = getData$2(this).controller; - return controller.getGDWindow(myId); - } - async moveTo(parent) { - if (!(parent instanceof Row || parent instanceof Column || parent instanceof Group)) { - throw new Error("Cannot add to the provided parent, because the provided parent is not an instance of Row, Column or Group"); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - const foundParent = await controller.getParent((p) => p.id === parent.id); - if (!foundParent) { - throw new Error("Cannot move the window to the selected parent, because this parent does not exist."); - } - await controller.moveWindowTo(myId, parent.id); - await this.workspace.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : windowLockConfigDecoder.runWithException(lockConfigResult); - const windowPlacementId = getData$2(this).id; - await getData$2(this).controller.lockWindow(windowPlacementId, verifiedConfig); - await this.workspace.refreshReference(); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.resizeItem(myId, { - height: verifiedConfig.height, - width: verifiedConfig.width, - relative: false - }); - await this.workspace.refreshReference(); - } - async onRemoved(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback(); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$1 = new WeakMap(); - const getData$1 = (model) => { - return data$1.get(model).manager.getFrameData(model); - }; - class Frame { - constructor(dataManager) { - data$1.set(this, { manager: dataManager }); - } - async registerShortcut(shortcut, callback) { - nonEmptyStringDecoder.runWithException(shortcut); - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const unsubscribe = await getData$1(this).controller.registerShortcut(shortcut, myId, callback); - return unsubscribe; - } - get id() { - return getData$1(this).summary.id; - } - get isInitialized() { - return getData$1(this).summary.isInitialized; - } - getBounds() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameBounds(myId); - } - async resize(config) { - const validatedConfig = resizeConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.resizeItem(myId, validatedConfig); - } - async move(config) { - const validatedConfig = moveConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.moveFrame(myId, validatedConfig); - } - focus() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.focusItem(myId); - } - async state() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameState(myId); - } - setIcon(icon) { - if (!isDesktop()) { - throw new Error("frame.setIcon() is not supported in IO Connect Browser"); - } - iconDecoder.runWithException(icon); - const frameId = this.id; - return getData$1(this).controller.setTaskbarIcon(icon, frameId); - } - getIcon() { - if (!isDesktop()) { - throw new Error("frame.getIcon() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getTaskbarIcon(frameId); - } - isVisible() { - if (!isDesktop()) { - throw new Error("frame.isVisible() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getFrameVisibility(frameId); - } - async minimize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "minimized"); - } - async maximize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "maximized"); - } - async restore() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "normal"); - } - close(options) { - const validatedOptions = optional(closeOptionsDecoder).runWithException(options); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.closeFrame(myId, validatedOptions); - } - snapshot() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getSnapshot(myId, "frame"); - } - async workspaces() { - const controller = getData$1(this).controller; - return controller.getWorkspacesByFrameId(this.id); - } - async getConstraints() { - const controller = getData$1(this).controller; - const myId = getData$1(this).summary.id; - return controller.getFrameConstraints(myId); - } - async restoreWorkspace(name, options) { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return getData$1(this).controller.restoreWorkspace(name, validatedOptions); - } - createWorkspace(definition, config) { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - return getData$1(this).controller.createWorkspace(validatedDefinition, validatedConfig); - } - async init(config) { - frameInitConfigDecoder.runWithException(config); - if (getData$1(this).summary.isInitialized) { - throw new Error("The frame has already been initialized"); - } - return getData$1(this).controller.initFrame(this.id, config); - } - async showPopup(config) { - if (!isDesktop()) { - throw new Error("Popup operations are not supported in IO Connect Browser"); - } - const validatedConfig = popupConfigDecoder.runWithException(config); - const controller = getData$1(this).controller; - await controller.showPopup(validatedConfig, this.id); - return controller.getGDWindow(validatedConfig.windowId); - } - async show(config) { - if (!isDesktop()) { - throw new Error("The show operation is not supported in IO Connect Browser"); - } - const validatedConfig = frameShowConfigDecoder.runWithException(config); - return getData$1(this).controller.showFrame(this.id, validatedConfig); - } - async hide() { - if (!isDesktop()) { - throw new Error("The hide operation is not supported in IO Connect Browser"); - } - return getData$1(this).controller.hideFrame(this.id); - } - async showDialog(options) { - if (!isDesktop()) { - throw new Error("The showModal operation is not supported in IO Connect Browser"); - } - frameDialogOptionsDecoder.runWithException(options); - return getData$1(this).controller.showFrameDialog(this.id, options); - } - async onClosing(callback) { - if (!isDesktop()) { - throw new Error("Frame closing operations are not supported in io.Connect Browser"); - } - checkThrowCallback(callback); - const wrappedCallback = async () => { - let shouldPrevent = false; - const preventClose = () => shouldPrevent = true; - await callback({ prevent: preventClose }); - return { prevent: shouldPrevent }; - }; - const unsubscribe = await getData$1(this).controller.registerFrameOnClosing(this.id, wrappedCallback); - return unsubscribe; - } - async onClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMaximized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "maximized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMinimized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "minimized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onNormal(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "normal", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceOpened(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "opened", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceSelected(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.getWorkspaceById(payload.workspaceSummary.id); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "selected", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "added", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => { - return parent.id === payload.windowSummary.parentId; - }); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "loaded", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onInitializationRequested(callback) { - checkThrowCallback(callback); - if (!this.isInitialized) { - callback(getData$1(this).summary.initializationContext); - } - return () => { }; - } - async onFocusChanged(callback) { - checkThrowCallback(callback); - const myData = getData$1(this); - const { id } = myData.summary; - const wrappedCallback = (args) => { - callback({ isFocused: args.frameSummary.isFocused }); - }; - const config = { - callback: wrappedCallback, - action: "focus", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await myData.controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - class PrivateDataManager { - parentsData = new WeakMap(); - workspacesData = new WeakMap(); - windowsData = new WeakMap(); - framesData = new WeakMap(); - deleteData(model) { - if (model instanceof Window) { - this.windowsData.delete(model); - } - if (model instanceof Workspace) { - this.workspacesData.delete(model); - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - this.parentsData.delete(model); - } - if (model instanceof Frame) { - this.framesData.delete(model); - } - } - setWindowData(model, data) { - this.windowsData.set(model, data); - } - setWorkspaceData(model, data) { - this.workspacesData.set(model, data); - } - setParentData(model, data) { - this.parentsData.set(model, data); - } - setFrameData(model, data) { - this.framesData.set(model, data); - } - getWindowData(model) { - return this.windowsData.get(model); - } - getWorkspaceData(model) { - return this.workspacesData.get(model); - } - getParentData(model) { - return this.parentsData.get(model); - } - getFrameData(model) { - return this.framesData.get(model); - } - remapChild(model, newData) { - if (model instanceof Window) { - const data = this.windowsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - const data = this.parentsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - remapFrame(model, newData) { - const data = this.framesData.get(model); - data.summary = newData; - } - remapWorkspace(model, newData) { - const data = this.workspacesData.get(model); - data.frame = newData.frame || data.frame; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - - const data = new WeakMap(); - const getData = (base, model) => { - const manager = data.get(base).manager; - if (model instanceof Workspace) { - return manager.getWorkspaceData(model); - } - return data.get(base).manager.getParentData(model); - }; - class Base { - frameId; - workspaceId; - positionIndex; - constructor(dataManager) { - data.set(this, { manager: dataManager }); - } - getId(model) { - return getData(this, model).id; - } - getPositionIndex(model) { - return getData(this, model).config.positionIndex; - } - getWorkspaceId(model) { - const privateData = getData(this, model); - return privateData.config.workspaceId || privateData.workspace.id; - } - getFrameId(model) { - return getData(this, model).frame.id; - } - getAllChildren(model, predicate) { - checkThrowCallback(predicate, true); - const children = getData(this, model).children; - if (typeof predicate === "undefined") { - return children; - } - return children.filter(predicate); - } - getMyParent(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).parent; - } - getMyFrame(model) { - return getData(this, model).frame; - } - getMyWorkspace(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).workspace; - } - async addWindow(model, definition, parentType) { - if (!definition.appName && !definition.windowId) { - throw new Error("The window definition should contain either an appName or a windowId"); - } - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - const controller = getData(this, model).controller; - const operationResult = await controller.add("window", getData(this, model).id, parentType, validatedDefinition); - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getWindow(w => w.elementId === operationResult.itemId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getWindow(w => w.elementId === operationResult.itemId); - } - async addParent(model, typeToAdd, parentType, definition) { - const parentDefinition = this.transformDefinition(typeToAdd, definition); - const controller = getData(this, model).controller; - const newParentId = (await controller.add("container", getData(this, model).id, parentType, parentDefinition)).itemId; - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getBox((parent) => parent.id === newParentId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getBox((parent) => parent.id === newParentId); - } - async removeChild(model, predicate) { - checkThrowCallback(predicate); - const child = this.getAllChildren(model).find(predicate); - if (!child) { - return; - } - await child.close(); - if (model instanceof Workspace) { - await model.refreshReference(); - return; - } - await this.getMyWorkspace(model).refreshReference(); - } - async maximize(model) { - const { controller, id } = getData(this, model); - await controller.maximizeItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async restore(model) { - const { controller, id } = getData(this, model); - await controller.restoreItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async close(model) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.closeItem(modelData.id); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async lockContainer(model, config) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.lockContainer(modelData.id, model.type, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - getAllowDrop(model) { - return getData(this, model).config.allowDrop; - } - getAllowDropLeft(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropLeft is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropLeft; - } - getAllowDropRight(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropRight is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropRight; - } - getAllowDropTop(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropTop is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropTop; - } - getAllowDropBottom(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropBottom is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropBottom; - } - getAllowDropHeader(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropHeader is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropHeader; - } - getAllowSplitters(model) { - const privateData = getData(this, model); - if (privateData.type === "group") { - throw new Error(`Cannot get allow splitters from private data ${privateData.type}`); - } - return privateData.config.allowSplitters; - } - getAllowExtract(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowExtract; - } - getAllowReorder(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowReorder; - } - getShowMaximizeButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show maximize button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showMaximizeButton; - } - getShowEjectButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show eject button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showEjectButton; - } - getShowAddWindowButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get add window button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showAddWindowButton; - } - getMinWidth(model) { - const privateData = getData(this, model); - return privateData.config.minWidth; - } - getMaxWidth(model) { - const privateData = getData(this, model); - return privateData.config.maxWidth; - } - getMinHeight(model) { - const privateData = getData(this, model); - return privateData.config.minHeight; - } - getMaxHeight(model) { - const privateData = getData(this, model); - return privateData.config.maxHeight; - } - getWidthInPx(model) { - const privateData = getData(this, model); - return privateData.config.widthInPx; - } - getHeightInPx(model) { - const privateData = getData(this, model); - return privateData.config.heightInPx; - } - getIsPinned(model) { - const privateData = getData(this, model); - return privateData.config.isPinned; - } - getIsMaximized(model) { - const privateData = getData(this, model); - return privateData.config.isMaximized; - } - getMaximizationBoundary(model) { - const privateData = getData(this, model); - return privateData.config.maximizationBoundary; - } - async setHeight(model, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setWidth(model, width) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setSize(model, width, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width, - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setMaximizationBoundary(model, config) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.setMaximizationBoundary(id, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async bundleTo(model, type) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.bundleItemTo(type, id); - } - async processLocalSubscription(model, subscriptionConfig) { - return getData(this, model).controller.processLocalSubscription(subscriptionConfig, this.getId(model)); - } - transformDefinition(type, definition) { - let parentDefinition; - if (typeof definition === "undefined") { - parentDefinition = { type, children: [] }; - } - else if (definition instanceof ParentBuilder) { - parentDefinition = definition.serialize(); - } - else { - if (typeof definition.type === "undefined") { - definition.type = type; - } - parentDefinition = strictParentDefinitionDecoder.runWithException(definition); - parentDefinition.children = parentDefinition.children || []; - } - return parentDefinition; - } - } - - class BaseController { - ioc; - windows; - contexts; - layouts; - constructor(ioc, windows, contexts, layouts) { - this.ioc = ioc; - this.windows = windows; - this.contexts = contexts; - this.layouts = layouts; - } - get bridge() { - return this.ioc.bridge; - } - get privateDataManager() { - return this.ioc.privateDataManager; - } - checkIsWindowLoaded(windowId) { - return (!!windowId) && this.windows.list().some((win) => win.id === windowId); - } - async createWorkspace(createConfig) { - const snapshot = await this.bridge.send(OPERATIONS.createWorkspace.name, createConfig); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async createEmptyFrame(definition) { - const frameSummary = await this.bridge.send(OPERATIONS.createFrame.name, definition); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - async initFrame(frameId, config) { - await this.bridge.send(OPERATIONS.initFrame.name, { frameId, ...config }); - } - async restoreWorkspace(name, options) { - const snapshot = await this.bridge.send(OPERATIONS.openWorkspace.name, { name, restoreOptions: options }); - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: snapshot.config.frameId }); - const frameConfig = { - summary: frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async add(type, parentId, parentType, definition) { - let operationName; - const operationArgs = { definition, parentId, parentType }; - if (type === "window") { - operationName = OPERATIONS.addWindow.name; - } - else if (type === "container") { - operationName = OPERATIONS.addContainer.name; - } - else { - throw new Error(`Unrecognized add type: ${type}`); - } - return await this.bridge.send(operationName, operationArgs); - } - async getFrame(windowId) { - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: windowId }); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - getFrames(allFrameSummaries, predicate) { - return allFrameSummaries.reduce((frames, frameSummary) => { - const frameConfig = { - summary: frameSummary - }; - const frameToCheck = this.ioc.getModel("frame", frameConfig); - if (!predicate || predicate(frameToCheck)) { - frames.push(frameToCheck); - } - return frames; - }, []); - } - getAllWorkspaceSummaries(...bridgeResults) { - const allSummaries = bridgeResults.reduce((summaries, summaryResult) => { - summaries.push(...summaryResult.summaries); - return summaries; - }, []); - return allSummaries.map((summary) => { - return Object.assign({}, { id: summary.id, width: summary.config.widthInPx, height: summary.config.heightInPx }, summary.config); - }); - } - handleOnSaved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - const addedUnSub = this.layouts.onAdded(wrappedCallback); - const changedUnSub = this.layouts.onChanged(wrappedCallback); - return () => { - addedUnSub(); - changedUnSub(); - }; - } - handleOnRemoved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - return this.layouts.onRemoved(wrappedCallback); - } - async importLayouts(layouts, mode) { - await this.layouts.import(layouts, mode); - } - async transformStreamPayloadToWorkspace(payload) { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const snapshot = payload.workspaceSnapshot || (await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId: payload.workspaceSummary.id })); - const workspaceConfig = { frame, snapshot }; - const workspace = this.ioc.getModel("workspace", workspaceConfig); - return workspace; - } - async fetchWorkspace(itemId) { - const snapshot = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async bundleWorkspaceTo(type, workspaceId) { - await this.bridge.send(OPERATIONS.bundleWorkspace.name, { type, workspaceId }); - } - async bundleItemTo(type, itemId) { - const isSupported = await this.isOperationSupported(OPERATIONS.bundleItem.name); - if (!isSupported) { - throw new Error(`Operation ${OPERATIONS.bundleItem.name} is not supported. Ensure that you are running the latest version of all packages`); - } - await this.bridge.send(OPERATIONS.bundleItem.name, { type, itemId }); - } - async getTaskbarIcon(frameId) { - return await this.bridge.send(OPERATIONS.getTaskbarIcon.name, { frameId }); - } - async setTaskbarIcon(icon, frameId) { - await this.bridge.send(OPERATIONS.setTaskbarIcon.name, { icon, frameId }); - } - getWorkspaceContext(workspaceId) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.get(contextName); - } - setWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.set(contextName, data); - } - updateWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.update(contextName, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.subscribe(contextName, callback); - } - async restoreItem(itemId) { - await this.bridge.send(OPERATIONS.restoreItem.name, { itemId }); - } - async maximizeItem(itemId) { - await this.bridge.send(OPERATIONS.maximizeItem.name, { itemId }); - } - async focusItem(itemId) { - await this.bridge.send(OPERATIONS.focusItem.name, { itemId }); - } - async closeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.closeWorkspace.name, { itemId: workspaceId }); - } - async closeItem(itemId) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId }); - } - async closeFrame(itemId, closeOptions) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId, closeOptions }); - } - async resizeItem(itemId, config) { - await this.bridge.send(OPERATIONS.resizeItem.name, Object.assign({}, { itemId }, config)); - } - async setMaximizationBoundary(itemId, config) { - await this.bridge.send(OPERATIONS.setMaximizationBoundary.name, Object.assign({}, { itemId }, config)); - } - async showWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.showLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.hideLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async setWindowDragMode(workspaceId, dragMode) { - await this.bridge.send(OPERATIONS.setWindowDragMode.name, { itemId: workspaceId, dragMode }); - } - async moveFrame(itemId, config) { - await this.bridge.send(OPERATIONS.moveFrame.name, Object.assign({}, { itemId }, config)); - } - getGDWindow(itemId) { - return this.windows.list().find((gdWindow) => gdWindow.id === itemId); - } - async forceLoadWindow(itemId) { - const controlResult = await this.bridge.send(OPERATIONS.forceLoadWindow.name, { itemId }); - return controlResult.windowId; - } - async ejectWindow(itemId, windowId) { - return await this.bridge.send(OPERATIONS.ejectWindow.name, { itemId, windowId }); - } - async moveWindowTo(itemId, newParentId) { - await this.bridge.send(OPERATIONS.moveWindowTo.name, { itemId, containerId: newParentId }); - } - async getSnapshot(itemId, type) { - let result; - if (type === "workspace") { - result = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - } - else if (type === "frame") { - result = await this.bridge.send(OPERATIONS.getFrameSnapshot.name, { itemId }); - } - return result; - } - async setItemTitle(itemId, title) { - await this.bridge.send(OPERATIONS.setItemTitle.name, { itemId, title }); - } - refreshChildren(config) { - const { parent, children, existingChildren, workspace } = config; - if (parent instanceof Window || parent.type === "window") { - return; - } - const newChildren = children.map((newChildSnapshot) => { - let childToAdd = existingChildren.find((child) => { - return child.type === "window" ? child.elementId === newChildSnapshot.id : child.id === newChildSnapshot.id; - }); - if (childToAdd) { - this.privateDataManager.remapChild(childToAdd, { - parent: parent, - children: [], - config: newChildSnapshot.config - }); - } - else { - let createConfig; - if (newChildSnapshot.type === "window") { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - }; - } - else { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - children: [] - }; - } - childToAdd = this.ioc.getModel(newChildSnapshot.type, createConfig); - } - if (newChildSnapshot.type !== "window") { - this.refreshChildren({ - workspace, existingChildren, - children: newChildSnapshot.children, - parent: childToAdd - }); - } - return childToAdd; - }); - if (parent instanceof Workspace) { - return newChildren; - } - else { - this.privateDataManager.remapChild(parent, { children: newChildren }); - return newChildren; - } - } - iterateFindChild(children, predicate) { - let foundChild = children.find((child) => predicate(child)); - if (foundChild) { - return foundChild; - } - children.some((child) => { - if (child instanceof Window) { - return false; - } - foundChild = this.iterateFindChild(child.children, predicate); - if (foundChild) { - return true; - } - }); - return foundChild; - } - iterateFilterChildren(children, predicate) { - const foundChildren = children.filter((child) => predicate(child)); - const grandChildren = children.reduce((innerFound, child) => { - if (child instanceof Window) { - return innerFound; - } - innerFound.push(...this.iterateFilterChildren(child.children, predicate)); - return innerFound; - }, []); - foundChildren.push(...grandChildren); - return foundChildren; - } - notifyWindowAdded(windowId) { - return new Promise((resolve) => { - const alreadyPresent = this.windows.list().some((win) => win.id === windowId); - if (alreadyPresent) { - return resolve(); - } - const unsubscribe = this.windows.onWindowAdded((win) => { - if (win.id !== windowId) { - return; - } - if (unsubscribe) { - unsubscribe(); - } - resolve(); - }); - }); - } - async hibernateWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.hibernateWorkspace.name, { workspaceId }); - } - async resumeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.resumeWorkspace.name, { workspaceId }); - } - async lockWorkspace(workspaceId, config) { - await this.bridge.send(OPERATIONS.lockWorkspace.name, { workspaceId, config }); - } - async lockWindow(windowPlacementId, config) { - await this.bridge.send(OPERATIONS.lockWindow.name, { windowPlacementId, config }); - } - async lockContainer(itemId, type, config) { - await this.bridge.send(OPERATIONS.lockContainer.name, { itemId, type, config }); - } - async pinWorkspace(workspaceId, icon) { - await this.bridge.send(OPERATIONS.pinWorkspace.name, { workspaceId, icon }); - } - async unpinWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.unpinWorkspace.name, { workspaceId }); - } - async getWorkspaceIcon(workspaceId) { - const result = await this.bridge.send(OPERATIONS.getWorkspaceIcon.name, { workspaceId }); - return result.icon; - } - setWorkspaceIcon(workspaceId, icon) { - return this.bridge.send(OPERATIONS.setWorkspaceIcon.name, { workspaceId, icon }); - } - async getPlatformFrameId() { - try { - const result = await this.bridge.send(OPERATIONS.getPlatformFrameId.name, {}); - return result; - } - catch (error) { - return {}; - } - } - async setLoadingStrategy(workspaceId, strategy) { - await this.isOperationSupported(OPERATIONS.setLoadingStrategy.name); - return this.bridge.send(OPERATIONS.setLoadingStrategy.name, { itemId: workspaceId, strategy }); - } - async showFrame(frameId, config) { - const payload = { frameId, isVisible: true, ...config }; - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, payload); - } - async hideFrame(frameId) { - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, { frameId, isVisible: false }); - } - async getFrameVisibility(frameId) { - const result = await this.bridge.send(OPERATIONS.getFrameVisibility.name, { itemId: frameId }); - return result.isVisible; - } - async showFrameDialog(frameId, options) { - const result = await this.bridge.send(OPERATIONS.showFrameDialog.name, { frameId, options }, { timeout: ONE_DAY_MS }); - return result; - } - async isOperationSupported(operation) { - if (isDesktop()) { - return { isSupported: true }; - } - return await this.bridge.send(OPERATIONS.operationCheck.name, { operation }); - } - async showPopup(config, frameId) { - return this.bridge.send(OPERATIONS.showPopup.name, { ...config, frameId }); - } - } - - class MainController { - bridge; - base; - shortcutsController; - closingController; - constructor(bridge, base, shortcutsController, closingController) { - this.bridge = bridge; - this.base = base; - this.shortcutsController = shortcutsController; - this.closingController = closingController; - } - setTaskbarIcon(icon, frameId) { - return this.base.setTaskbarIcon(icon, frameId); - } - getTaskbarIcon(frameId) { - return this.base.getTaskbarIcon(frameId); - } - checkIsWindowLoaded(windowId) { - return this.base.checkIsWindowLoaded(windowId); - } - async checkIsInSwimlane(windowId) { - const controlResult = await this.bridge.send(OPERATIONS.isWindowInWorkspace.name, { itemId: windowId }); - return controlResult.inWorkspace; - } - async createWorkspace(definition, saveConfig) { - const createConfig = Object.assign({}, definition, { saveConfig }); - return await this.base.createWorkspace(createConfig); - } - async createEmptyFrame(definition) { - return await this.base.createEmptyFrame(definition); - } - async initFrame(frameId, config) { - return this.base.initFrame(frameId, config); - } - async restoreWorkspace(name, options) { - const allLayouts = await this.getLayoutSummaries(); - const layoutExists = allLayouts.some((summary) => summary.name === name); - if (!layoutExists) { - throw new Error(`This layout: ${name} cannot be restored, because it doesn't exist.`); - } - if (options?.frameId) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - const foundMatchingFrame = allFrameSummaries.summaries.some((summary) => summary.id === options.frameId); - if (!foundMatchingFrame) { - throw new Error(`Cannot reuse the frame with id: ${options.frameId}, because there is no frame with that ID found`); - } - } - return await this.base.restoreWorkspace(name, options); - } - async add(type, parentId, parentType, definition) { - return await this.base.add(type, parentId, parentType, definition); - } - processLocalSubscription(config, levelId) { - return isDesktop() ? - this.handleEnterpriseLocalSubscription(config, levelId) : - this.handleCoreLocalSubscription(config, levelId); - } - processGlobalSubscription(callback, eventType, action) { - return isDesktop() ? - this.handleEnterpriseGlobalSubscription(callback, eventType, action) : - this.handleCoreGlobalSubscription(callback, eventType, action); - } - async getFrame(selector) { - if (selector.windowId) { - return await this.base.getFrame(selector.windowId); - } - if (selector.predicate) { - return (await this.getFrames(selector.predicate))[0]; - } - throw new Error(`The provided selector is not valid: ${JSON.stringify(selector)}`); - } - async getFrames(predicate) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - return this.base.getFrames(allFrameSummaries.summaries, predicate); - } - getWorkspaceById(workspaceId) { - return this.base.fetchWorkspace(workspaceId); - } - async getWorkspaceByWindowId(itemId) { - if (!isDesktop()) { - return (await this.getWorkspaces((wsp) => !!wsp.getWindow((w) => w.id === itemId)))[0]; - } - return this.base.fetchWorkspace(itemId); - } - transformStreamPayloadToWorkspace(payload) { - return this.base.transformStreamPayloadToWorkspace(payload); - } - async getWorkspace(predicate) { - let foundWorkspace; - await this.iterateWorkspaces((wsp, end) => { - if (predicate(wsp)) { - foundWorkspace = wsp; - end(); - } - }); - return foundWorkspace; - } - async getWorkspaces(predicate) { - const matchingWorkspaces = []; - await this.iterateWorkspaces((wsp) => { - if (!predicate || predicate(wsp)) { - matchingWorkspaces.push(wsp); - } - }); - return matchingWorkspaces; - } - async getWorkspacesByFrameId(frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - const workspacesForFrame = await Promise.all(summariesForFrame.map((summary) => { - return this.base.fetchWorkspace(summary.id); - })); - return workspacesForFrame; - } - async isLastWorkspaceInFrame(workspaceId, frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - return summariesForFrame.length === 1 && summariesForFrame[0].id === workspaceId; - } - async getAllWorkspaceSummaries() { - const allSummariesResult = await this.bridge.send(OPERATIONS.getAllWorkspacesSummaries.name, {}); - return this.base.getAllWorkspaceSummaries(allSummariesResult); - } - async getWindow(predicate) { - let resultWindow; - await this.iterateWorkspaces((wsp, end) => { - const foundWindow = wsp.getWindow(predicate); - if (foundWindow) { - resultWindow = foundWindow; - end(); - } - }); - return resultWindow; - } - async getParent(predicate) { - let resultParent; - await this.iterateWorkspaces((wsp, end) => { - const foundParent = wsp.getBox(predicate); - if (foundParent) { - resultParent = foundParent; - end(); - } - }); - return resultParent; - } - async getLayoutSummaries() { - const allLayouts = await this.bridge.send(OPERATIONS.getAllLayoutsSummaries.name); - return allLayouts.summaries; - } - async deleteLayout(name) { - await this.bridge.send(OPERATIONS.deleteLayout.name, { name }); - } - async exportLayout(predicate) { - const allLayoutsResult = await this.bridge.send(OPERATIONS.exportAllLayouts.name); - return allLayoutsResult.layouts.reduce((matchingLayouts, layout) => { - if (!predicate || predicate(layout)) { - matchingLayouts.push(layout); - } - return matchingLayouts; - }, []); - } - async saveLayout(config) { - return await this.bridge.send(OPERATIONS.saveLayout.name, config); - } - async importLayouts(layouts, mode) { - if (isDesktop()) { - try { - await this.bridge.send(OPERATIONS.importLayouts.name, { layouts, mode }); - } - catch (error) { - await Promise.all(layouts.map((layout) => this.bridge.send(OPERATIONS.importLayout.name, { layout, mode }))); - } - return; - } - await this.base.importLayouts(layouts, mode); - } - handleOnSaved(callback) { - return this.base.handleOnSaved(callback); - } - handleOnRemoved(callback) { - return this.base.handleOnRemoved(callback); - } - async bundleWorkspaceTo(type, workspaceId) { - return await this.base.bundleWorkspaceTo(type, workspaceId); - } - async bundleItemTo(type, id) { - return await this.base.bundleItemTo(type, id); - } - getWorkspaceContext(workspaceId) { - return this.base.getWorkspaceContext(workspaceId); - } - setWorkspaceContext(workspaceId, data) { - return this.base.setWorkspaceContext(workspaceId, data); - } - updateWorkspaceContext(workspaceId, data) { - return this.base.updateWorkspaceContext(workspaceId, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - return this.base.subscribeWorkspaceContextUpdated(workspaceId, callback); - } - async restoreItem(itemId) { - return await this.base.restoreItem(itemId); - } - async maximizeItem(itemId) { - return await this.base.maximizeItem(itemId); - } - async focusItem(itemId) { - return await this.base.focusItem(itemId); - } - async changeFrameState(frameId, state) { - await this.bridge.send(OPERATIONS.changeFrameState.name, { frameId, requestedState: state }); - } - async getFrameBounds(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameBounds.name, { itemId: frameId }); - return frameResult.bounds; - } - async getFrameState(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameState.name, { itemId: frameId }); - return frameResult.state; - } - async closeWorkspace(workspaceId, frameId) { - if (isDesktop()) { - return await this.closeItem(workspaceId); - } - let closeWorkspaceCommandExists = false; - try { - const { isSupported } = await this.base.isOperationSupported(OPERATIONS.closeWorkspace.name); - closeWorkspaceCommandExists = isSupported; - } - catch (error) { - closeWorkspaceCommandExists = false; - } - if (closeWorkspaceCommandExists) { - return await this.base.closeWorkspace(workspaceId); - } - return await this.legacyCloseWorkspace(workspaceId, frameId); - } - async closeItem(itemId) { - return await this.base.closeItem(itemId); - } - async closeFrame(itemId, closeOptions) { - return await this.base.closeFrame(itemId, closeOptions); - } - async resizeItem(itemId, config) { - return await this.base.resizeItem(itemId, config); - } - async setMaximizationBoundary(itemId, config) { - return await this.base.setMaximizationBoundary(itemId, config); - } - async showWorkspaceLoadingAnimation(workspaceId) { - return await this.base.showWorkspaceLoadingAnimation(workspaceId); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - return await this.base.hideWorkspaceLoadingAnimation(workspaceId); - } - async setWindowDragMode(workspaceId, dragMode) { - return await this.base.setWindowDragMode(workspaceId, dragMode); - } - async moveFrame(itemId, config) { - return await this.base.moveFrame(itemId, config); - } - getGDWindow(itemId) { - return this.base.getGDWindow(itemId); - } - async forceLoadWindow(itemId) { - const windowId = await this.base.forceLoadWindow(itemId); - await this.base.notifyWindowAdded(windowId); - return windowId; - } - async ejectWindow(itemId, windowId) { - const id = (await this.base.ejectWindow(itemId, windowId)).windowId; - await this.base.notifyWindowAdded(id); - return id; - } - async moveWindowTo(itemId, newParentId) { - return await this.base.moveWindowTo(itemId, newParentId); - } - async getSnapshot(itemId, type) { - return await this.base.getSnapshot(itemId, type); - } - async setItemTitle(itemId, title) { - return await this.base.setItemTitle(itemId, title); - } - flatChildren(children) { - return children.reduce((soFar, child) => { - soFar.push(child); - if (child.type !== "window") { - soFar.push(...this.flatChildren(child.children)); - } - return soFar; - }, []); - } - refreshChildren(config) { - return this.base.refreshChildren(config); - } - iterateFindChild(children, predicate) { - return this.base.iterateFindChild(children, predicate); - } - iterateFilterChildren(children, predicate) { - return this.base.iterateFilterChildren(children, predicate); - } - hibernateWorkspace(workspaceId) { - return this.base.hibernateWorkspace(workspaceId); - } - resumeWorkspace(workspaceId) { - return this.base.resumeWorkspace(workspaceId); - } - lockWorkspace(workspaceId, config) { - return this.base.lockWorkspace(workspaceId, config); - } - lockWindow(windowPlacementId, config) { - return this.base.lockWindow(windowPlacementId, config); - } - lockContainer(itemId, type, config) { - return this.base.lockContainer(itemId, type, config); - } - pinWorkspace(workspaceId, icon) { - return this.base.pinWorkspace(workspaceId, icon); - } - unpinWorkspace(workspaceId) { - return this.base.unpinWorkspace(workspaceId); - } - getWorkspaceIcon(workspaceId) { - return this.base.getWorkspaceIcon(workspaceId); - } - setWorkspaceIcon(workspaceId, icon) { - return this.base.setWorkspaceIcon(workspaceId, icon); - } - async getFrameConstraints(frameId) { - const frameSnapshot = await this.getSnapshot(frameId, "frame"); - return { - minWidth: frameSnapshot.config.minWidth, - maxWidth: frameSnapshot.config.maxWidth, - minHeight: frameSnapshot.config.minHeight, - maxHeight: frameSnapshot.config.maxHeight, - }; - } - registerShortcut(shortcut, frameId, callback) { - return this.shortcutsController.registerShortcut(shortcut, frameId, callback); - } - getPlatformFrameId() { - return this.base.getPlatformFrameId(); - } - setLoadingStrategy(workspaceId, strategy) { - return this.base.setLoadingStrategy(workspaceId, strategy); - } - registerFrameOnClosing(frameId, callback) { - return this.closingController.registerFrameOnClosing(frameId, callback); - } - showPopup(config, frameId) { - return this.base.showPopup(config, frameId); - } - async showFrame(frameId, config) { - return this.base.showFrame(frameId, config); - } - async hideFrame(frameId) { - return this.base.hideFrame(frameId); - } - async getFrameVisibility(frameId) { - return this.base.getFrameVisibility(frameId); - } - async showFrameDialog(frameId, options) { - return this.base.showFrameDialog(frameId, options); - } - async handleCoreLocalSubscription(config, levelId) { - await this.bridge.createCoreEventSubscription(); - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseLocalSubscription(config, levelId) { - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async handleCoreGlobalSubscription(callback, eventType, action) { - await this.bridge.createCoreEventSubscription(); - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseGlobalSubscription(callback, eventType, action) { - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async iterateWorkspaces(callback) { - let ended = false; - const end = () => { ended = true; }; - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - for (const summary of workspaceSummaries) { - if (ended) { - return; - } - const wsp = await this.base.fetchWorkspace(summary.id); - callback(wsp, end); - } - } - async legacyCloseWorkspace(workspaceId, frameId) { - const isLastWorkspaceInFrame = await this.isLastWorkspaceInFrame(workspaceId, frameId); - const platformFrameId = (await this.getPlatformFrameId()).id; - const shouldCloseFrame = isLastWorkspaceInFrame && - platformFrameId !== frameId; - if (shouldCloseFrame) { - return await this.closeFrame(frameId, {}); - } - await this.closeItem(workspaceId); - } - } - - class ShortcutsController { - bridge; - _shortcuts = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.bridge.onOperation((payload) => { - if (payload.operation === CLIENT_OPERATIONS.shortcutClicked.name) { - const data = payload.data; - this._shortcuts.execute(`${data.frameId}-${data.shortcut}`); - } - }); - } - async registerShortcut(shortcut, frameId, callback) { - await this.bridge.send(OPERATIONS.registerShortcut.name, { shortcut, frameId }); - const un = this._shortcuts.add(`${frameId}-${shortcut}`, callback); - return () => { - un(); - this.bridge.send(OPERATIONS.unregisterShortcut.name, { shortcut, frameId }); - }; - } - } - - class ClosingController { - bridge; - registry = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.subscribeToFrameClosing(); - } - async registerFrameOnClosing(frameId, callback) { - await this.bridge.send(OPERATIONS.subscribeToFrameClosing.name, { itemId: frameId }); - return this.registry.add(frameId, callback); - } - subscribeToFrameClosing() { - this.bridge.onOperationWithResponse(async (payload) => { - if (payload.operation !== CLIENT_OPERATIONS.frameClosing.name) { - return; - } - const data = payload.data; - const frameClosingResult = await Promise.all(this.registry.execute(data.frameId)); - return this.aggregateFrameClosingResult(frameClosingResult); - }); - } - aggregateFrameClosingResult(results) { - return { - prevent: results.some((result) => result?.prevent) - }; - } - } - - class IoC { - agm; - windows; - layouts; - contexts; - _controllerInstance; - _bridgeInstance; - _transportInstance; - _privateDataManagerInstance; - _parentBaseInstance; - _baseController; - _shortcutsController; - _closingController; - constructor(agm, windows, layouts, contexts) { - this.agm = agm; - this.windows = windows; - this.layouts = layouts; - this.contexts = contexts; - } - get baseController() { - if (!this._baseController) { - this._baseController = new BaseController(this, this.windows, this.contexts, this.layouts); - } - return this._baseController; - } - get controller() { - if (!this._controllerInstance) { - this._controllerInstance = new MainController(this.bridge, this.baseController, this.shortcutsController, this.closingController); - } - return this._controllerInstance; - } - get shortcutsController() { - if (!this._shortcutsController) { - this._shortcutsController = new ShortcutsController(this.bridge); - } - return this._shortcutsController; - } - get closingController() { - if (!this._closingController) { - this._closingController = new ClosingController(this.bridge); - } - return this._closingController; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new Bridge(this.transport, CallbackFactory()); - } - return this._bridgeInstance; - } - get transport() { - if (!this._transportInstance) { - this._transportInstance = new InteropTransport(this.agm, CallbackFactory()); - } - return this._transportInstance; - } - get privateDataManager() { - if (!this._privateDataManagerInstance) { - this._privateDataManagerInstance = new PrivateDataManager(); - } - return this._privateDataManagerInstance; - } - get parentBase() { - if (!this._parentBaseInstance) { - this._parentBaseInstance = new Base(this.privateDataManager); - } - return this._parentBaseInstance; - } - async initiate(actualWindowId) { - await this.transport.initiate(actualWindowId); - } - getModel(type, createConfig) { - switch (type) { - case "frame": { - const newFrame = new Frame(this.privateDataManager); - const { summary } = createConfig; - const frameData = { summary, controller: this.controller }; - this.privateDataManager.setFrameData(newFrame, frameData); - return newFrame; - } - case "window": { - const { id, parent, frame, workspace, config } = createConfig; - const windowPrivateData = { - type: "window", - controller: this.controller, - config, id, parent, frame, workspace - }; - const newWindow = new Window(this.privateDataManager); - this.privateDataManager.setWindowData(newWindow, windowPrivateData); - return newWindow; - } - case "row": - case "column": - case "group": { - const { id, children, parent, frame, workspace, config } = createConfig; - const newParent = type === "column" ? new Column(this.parentBase) : - type === "row" ? new Row(this.parentBase) : new Group(this.parentBase); - const builtChildren = this.buildChildren(children, frame, workspace, newParent); - const parentPrivateData = { - id, parent, frame, workspace, - config, - type, - controller: this.controller, - children: builtChildren, - }; - this.privateDataManager.setParentData(newParent, parentPrivateData); - return newParent; - } - case "workspace": { - const { snapshot, frame } = createConfig; - const newWorkspace = new Workspace(this.privateDataManager); - const children = this.buildChildren(snapshot.children, frame, newWorkspace, newWorkspace); - const workspacePrivateData = { - id: snapshot.id, - type: "workspace", - config: snapshot.config, - base: this.parentBase, - controller: this.controller, - children, frame, ioc: this - }; - this.privateDataManager.setWorkspaceData(newWorkspace, workspacePrivateData); - return newWorkspace; - } - default: throw new Error(`Unrecognized type: ${type}`); - } - } - getBuilder(config) { - config.definition = config.definition || {}; - if (!Array.isArray(config.definition.children)) { - config.definition.children = []; - } - const baseBuilder = new BaseBuilder(this.getBuilder.bind(this)); - switch (config.type) { - case "workspace": { - return new WorkspaceBuilder(config.definition, baseBuilder, this.controller); - } - case "row": - case "column": - case "group": { - config.definition.type = config.type; - return new ParentBuilder(config.definition, baseBuilder); - } - default: throw new Error(`Unexpected Builder creation error, provided config: ${JSON.stringify(config)}`); - } - } - buildChildren(children, frame, workspace, parent) { - return children.map((child) => { - switch (child.type) { - case "window": return this.getModel("window", { - id: child.id, - config: child.config, - frame, workspace, parent - }); - case "column": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "row": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "group": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - default: throw new Error(`Unsupported child type: ${child.type}`); - } - }); - } - } - - var version = "4.2.3"; - - const composeAPI = (glue, ioc) => { - const controller = ioc.controller; - const inWorkspace = () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - return controller.checkIsInSwimlane(myId); - }; - const getBuilder = (config) => { - const validatedConfig = builderConfigDecoder.runWithException(config); - return ioc.getBuilder(validatedConfig); - }; - const getMyFrame = async () => { - const windowId = glue.windows.my().id; - if (!windowId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(windowId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your frame, because this window is not in a workspace"); - } - return controller.getFrame({ windowId }); - }; - const getFrame = async (predicate) => { - checkThrowCallback(predicate); - return controller.getFrame({ predicate }); - }; - const getAllFrames = async (predicate) => { - checkThrowCallback(predicate, true); - return controller.getFrames(predicate); - }; - const getAllWorkspacesSummaries = () => { - return controller.getAllWorkspaceSummaries(); - }; - const getMyWorkspace = async () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my workspace, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(myId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your workspace, because this window is not in a workspace"); - } - return await controller.getWorkspaceByWindowId(myId); - }; - const getWorkspace = async (predicate) => { - checkThrowCallback(predicate); - return (await controller.getWorkspaces(predicate))[0]; - }; - const getWorkspaceById = async (workspaceId) => { - nonEmptyStringDecoder.runWithException(workspaceId); - return controller.getWorkspaceById(workspaceId); - }; - const getAllWorkspaces = (predicate) => { - checkThrowCallback(predicate, true); - return controller.getWorkspaces(predicate); - }; - const getWindow = async (predicate) => { - checkThrowCallback(predicate); - return controller.getWindow(predicate); - }; - const getParent = async (predicate) => { - checkThrowCallback(predicate); - return controller.getParent(predicate); - }; - const restoreWorkspace = async (name, options) => { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return controller.restoreWorkspace(name, validatedOptions); - }; - const createWorkspace = async (definition, saveConfig) => { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(saveConfig); - return controller.createWorkspace(validatedDefinition, validatedConfig); - }; - const createEmptyFrame = async (definition) => { - const validatedDefinition = emptyFrameDefinitionDecoder.runWithException(definition); - return controller.createEmptyFrame(validatedDefinition ?? {}); - }; - const layouts = { - getSummaries: () => { - return controller.getLayoutSummaries(); - }, - delete: async (name) => { - nonEmptyStringDecoder.runWithException(name); - return controller.deleteLayout(name); - }, - export: async (predicate) => { - checkThrowCallback(predicate, true); - return controller.exportLayout(predicate); - }, - import: async (layouts, mode = "replace") => { - if (!Array.isArray(layouts)) { - throw new Error(`The provided layouts argument is not an array: ${JSON.stringify(layouts)}`); - } - layouts.forEach((layout) => workspaceLayoutDecoder.runWithException(layout)); - return controller.importLayouts(layouts, mode); - }, - save: async (config) => { - const verifiedConfig = workspaceLayoutSaveConfigDecoder.runWithException(config); - return controller.saveLayout(verifiedConfig); - }, - onSaved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnSaved(callback); - }, - onRemoved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnRemoved(callback); - } - }; - const onFrameOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - callback(frame); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "opened"); - return unsubscribe; - }; - const onFrameClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "closed"); - return unsubscribe; - }; - const onWorkspaceOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "opened"); - return unsubscribe; - }; - const onWorkspaceClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "closed"); - return unsubscribe; - }; - const onWorkspaceHibernated = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "hibernated"); - return unsubscribe; - }; - const onWorkspaceResumed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "resumed"); - return unsubscribe; - }; - const onWindowAdded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "added"); - return unsubscribe; - }; - const onWindowLoaded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const foundWindow = workspace.getWindow((win) => win.id && win.id === payload.windowSummary.config.windowId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "loaded"); - return unsubscribe; - }; - const onWindowRemoved = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "removed"); - return unsubscribe; - }; - const onWindowMaximized = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "maximized"); - return unsubscribe; - }; - const onWindowRestored = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "restored"); - return unsubscribe; - }; - const onWindowSelected = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "selected"); - return unsubscribe; - }; - const waitForFrame = async (id) => { - nonEmptyStringDecoder.runWithException(id); - return new Promise((res, rej) => { - let unsub = () => { - }; - onFrameOpened((f) => { - if (f.id === id) { - res(f); - unsub(); - } - }).then((u) => { - unsub = u; - return getAllFrames(); - }).then((frames) => { - const myFrame = frames.find((f) => f.id === id); - if (myFrame) { - res(myFrame); - unsub(); - } - }).catch(rej); - }); - }; - return { - inWorkspace, - getBuilder, - getMyFrame, - getFrame, - getAllFrames, - getAllWorkspacesSummaries, - getMyWorkspace, - getWorkspace, - getWorkspaceById, - getAllWorkspaces, - getWindow, - getBox: getParent, - restoreWorkspace, - createWorkspace, - createEmptyFrame, - waitForFrame, - layouts, - onFrameOpened, - onFrameClosed, - onWorkspaceOpened, - onWorkspaceClosed, - onWorkspaceHibernated, - onWorkspaceResumed, - onWindowAdded, - onWindowLoaded, - onWindowRemoved, - onWindowMaximized, - onWindowRestored, - onWindowSelected, - version - }; - }; - - const factoryFunction = async (io) => { - const ioc = new IoC(io.agm, io.windows, io.layouts, io.contexts); - const actualWindowId = io.interop.instance.windowId; - await ioc.initiate(actualWindowId); - io.workspaces = composeAPI(io, ioc); - }; - if (typeof window !== "undefined") { - window.IOWorkspaces = factoryFunction; - } - - return factoryFunction; - -})); -//# sourceMappingURL=workspaces.umd.js.map diff --git a/javascript/start/clients/package-lock.json b/javascript/start/clients/package-lock.json new file mode 100644 index 0000000..0fd5599 --- /dev/null +++ b/javascript/start/clients/package-lock.json @@ -0,0 +1,1291 @@ +{ + "name": "clients", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "clients", + "version": "1.0.0", + "dependencies": { + "@interopio/browser-platform": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@interopio/browser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser/-/browser-4.2.4.tgz", + "integrity": "sha512-BPgkwH6N8HyGf7st99ZJwQ7arijz9j1bGu7pUAXBrtbv6cu4zH5GR7JKPGANZmFl0uefNPQyAQ4hc7C/i1i++A==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0", + "@interopio/search-api": "^3.2.1", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.2" + } + }, + "node_modules/@interopio/browser-platform": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser-platform/-/browser-platform-4.2.4.tgz", + "integrity": "sha512-Xo3zwB2thiPkMTPsfPMHbLtfxvhhip3UX/CHFK2H1ymyF3+PcETn+TZdz1a+awJOICAvDbW6n9EHPCBj/fQVzQ==", + "license": "Commercial", + "dependencies": { + "@interopio/browser": "^4.2.4", + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0" + } + }, + "node_modules/@interopio/core": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@interopio/core/-/core-6.8.1.tgz", + "integrity": "sha512-WFWIV8JilNuAcxXaB+81IjL9j82sU73ABMUUEOWpvWoyqxhPlneOS+rSYViFX5gdk5pLH3fM6T/MmRGn3UFLwQ==", + "license": "MIT", + "dependencies": { + "callback-registry": "^2.7.2", + "ws": "^8.18.0" + } + }, + "node_modules/@interopio/desktop": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/@interopio/desktop/-/desktop-6.18.0.tgz", + "integrity": "sha512-YqRHRiCymbY2fOCT2HHJnLY4780JSRI1fUtaWEoIa5Z3djZk/3xRgVxIjOVw9Y/TAFGCwyIeW142a7HYnSGD5Q==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/schemas": "^10.1.0", + "@interopio/utils": "^1.4.2", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.1" + } + }, + "node_modules/@interopio/schemas": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@interopio/schemas/-/schemas-10.1.0.tgz", + "integrity": "sha512-8uDEoOAZenTr4a3O8vLq6JyS/LutkT/gh9EjuOrS9fOmHEUfJaS2u+qPo5em9/8MtjKgblZEJStSsW1gr34CtQ==", + "license": "ISC", + "dependencies": { + "ajv": "^6.12.6", + "ajv-keywords": "^3.4.1" + }, + "peerDependencies": { + "log4js": "^6.4.2" + }, + "peerDependenciesMeta": { + "log4js": { + "optional": true + } + } + }, + "node_modules/@interopio/search-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@interopio/search-api/-/search-api-3.2.1.tgz", + "integrity": "sha512-raUZzqBQoidm/6Mvgao2wFWlTDu9D4jghiX1dqor1LdsIfUpelJkkuFGeDl0z/3DWneaxDF8Vc/uoBtLz7qJLw==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1" + } + }, + "node_modules/@interopio/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@interopio/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-14Bb2WI9Cwf9zjhTurP4qP9AVY4cxR1AOrwrOtHrTGAeeHp88mALFWfMEv1QnRhlQ06To2vQcRgebNrPlHDZ8Q==", + "license": "ISC", + "dependencies": { + "decoder-validate": "^0.0.2" + } + }, + "node_modules/@interopio/workspaces-api": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@interopio/workspaces-api/-/workspaces-api-4.2.3.tgz", + "integrity": "sha512-5wrR1yhETKuX4txVrmS5q3G+8KI6GW4yOxsrVdf5qErO2HxN938XUdiAHIesarwlQoncrgnVx7uTn6IeOWUoXg==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/callback-registry": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/callback-registry/-/callback-registry-2.7.2.tgz", + "integrity": "sha512-VVrtF21DaH0VHeNMkLDd4VGuxsYM3V3l3lwYneKVMU/6X3TRtcQszUwlAcqj2HrLcbP1NyS12LsanUwCykaz/Q==", + "license": "ISC" + }, + "node_modules/decoder-validate": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/decoder-validate/-/decoder-validate-0.0.2.tgz", + "integrity": "sha512-9BsqAH9Zq6CvlxKHkSrZrH2iYlhuhHcrh6uTnDvcsa9P5YEweEzt1ci+X/9STgSCE7b9BA7/QIiwhfUDDWmjxw==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/javascript/start/clients/package.json b/javascript/start/clients/package.json new file mode 100644 index 0000000..693ae4d --- /dev/null +++ b/javascript/start/clients/package.json @@ -0,0 +1,14 @@ +{ + "name": "clients", + "version": "1.0.0", + "scripts": { + "start": "vite --port 9000" + }, + "dependencies": { + "@interopio/browser-platform": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } +} diff --git a/javascript/start/clients/plugins/applicationsPlugin.js b/javascript/start/clients/plugins/applicationsPlugin.js index df38567..b5d44ab 100644 --- a/javascript/start/clients/plugins/applicationsPlugin.js +++ b/javascript/start/clients/plugins/applicationsPlugin.js @@ -5,6 +5,6 @@ const fetchAppDefinitions = async (url) => { return appDefinitions; }; -const setupApplications = async (io, { url }) => { +export const setupApplications = async (io, { url }) => { // TODO Chapter 8.2 }; \ No newline at end of file diff --git a/javascript/start/clients/plugins/layoutsPlugin.js b/javascript/start/clients/plugins/layoutsPlugin.js index 58857e3..913db31 100644 --- a/javascript/start/clients/plugins/layoutsPlugin.js +++ b/javascript/start/clients/plugins/layoutsPlugin.js @@ -5,6 +5,6 @@ const fetchWorkspaceLayoutDefinitions = async (url) => { return layoutDefinitions; }; -const setupLayouts = async (io, { url }) => { +export const setupLayouts = async (io, { url }) => { // TODO Chapter 9.2 }; \ No newline at end of file diff --git a/javascript/start/package.json b/javascript/start/package.json index a4db5bd..85abbf4 100644 --- a/javascript/start/package.json +++ b/javascript/start/package.json @@ -3,18 +3,13 @@ "version": "1.0.0", "description": "io.Connect Browser JavaScript Tutorial", "scripts": { - "start:clients": "http-server ./Clients -p 9000 -c-1", - "start:stocks": "http-server ./Stocks -p 9100 -c-1", - "start:clientDetails": "http-server ./client-details -p 9200 -c-1", - "start:workspace": "http-server ./workspace -p 9300 -c-1", - "start:downloader": "http-server ./portfolio-downloader -p 9400 -c-1", - "start": "concurrently \"npm run start:clients\" \"npm run start:stocks\" \"npm run start:clientDetails\" \"npm run start:workspace\" \"npm run start:downloader\"" + "install:apps": "concurrently \"cd clients && npm install\" \"cd stocks && npm install\" \"cd client-details && npm install\" \"cd workspace && npm install\" \"cd portfolio-downloader && npm install\"", + "start": "concurrently \"cd clients && npm start\" \"cd stocks && npm start\" \"cd client-details && npm start\" \"cd workspace && npm start\" \"cd portfolio-downloader && npm start\"" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { - "concurrently": "^5.3.0", - "http-server": "^0.12.3" + "concurrently": "^5.3.0" } -} \ No newline at end of file +} diff --git a/javascript/start/portfolio-downloader/index.html b/javascript/start/portfolio-downloader/index.html index 0816398..051192a 100644 --- a/javascript/start/portfolio-downloader/index.html +++ b/javascript/start/portfolio-downloader/index.html @@ -8,8 +8,7 @@ Portfolio Downloader - - + diff --git a/javascript/start/portfolio-downloader/index.js b/javascript/start/portfolio-downloader/index.js index 715d807..fa26777 100644 --- a/javascript/start/portfolio-downloader/index.js +++ b/javascript/start/portfolio-downloader/index.js @@ -1,3 +1,6 @@ +// TODO: Chapter 2 +// import IOBrowser from '@interopio/browser'; + const intentHandler = (context) => { if (!context) { return; diff --git a/javascript/start/portfolio-downloader/lib/browser.umd.js b/javascript/start/portfolio-downloader/lib/browser.umd.js deleted file mode 100644 index a5e6fcb..0000000 --- a/javascript/start/portfolio-downloader/lib/browser.umd.js +++ /dev/null @@ -1,17399 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.browser = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs$1 (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) - }; - - function isNonNullObject(value) { - return !!value && typeof value === 'object' - } - - function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); - - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) - } - - // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 - var canUseSymbol = typeof Symbol === 'function' && Symbol.for; - var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; - - function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE - } - - function emptyTarget(val) { - return Array.isArray(val) ? [] : {} - } - - function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value - } - - function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) - } - - function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge - } - - function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return Object.propertyIsEnumerable.call(target, symbol) - }) - : [] - } - - function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) - } - - function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } - } - - // Protects from prototype poisoning and unexpected merging up the prototype chain. - function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. - } - - function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } - - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination - } - - function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; - - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } - } - - deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } - - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) - }; - - var deepmerge_1 = deepmerge; - - var cjs = deepmerge_1; - - var deepmerge$1 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$2 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$2 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$2 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$2 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$2 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$2 = function (f, r) { - return r.ok === true ? ok$2(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$2(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$2 = function (f, r) { - return r.ok === true ? r : err$2(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$2 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$2 = function() { - __assign$2 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - - function __rest$2(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$2(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$2(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$2(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$2 = function (json) { return Array.isArray(json); }; - var isJsonObject$2 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$2(json); - }; - var typeString$2 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$2 = function (expected, got) { - return "expected " + expected + ", got " + typeString$2(got); - }; - var printPath$2 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$2 = function (newAt, _a) { - var at = _a.at, rest = __rest$2(_a, ["at"]); - return (__assign$2({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$2 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$2(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$2(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$2(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$2(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$2(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$2(json) - : err$2({ message: expectedGot$2('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$2(json) - : err$2({ message: expectedGot$2('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$2(json) - : err$2({ message: expectedGot$2('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$2(json, value) - ? ok$2(value) - : err$2({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$2(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$2({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else if (isJsonObject$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$2(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$2(function (err$$1) { return prependAt$2("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$2([])); - } - else if (isJsonArray$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$2(json)) { - if (json.length !== decoders.length) { - return err$2({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$2(prependAt$2("[" + i + "]", nth.error)); - } - } - return ok$2(result); - } - else { - return err$2({ message: expectedGot$2("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$2(Object.assign, acc, decoder.decode(json)); }, ok$2({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$2(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$2(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$2(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$2(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$2({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$2(withDefault$2(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$2(function (error) { - return jsonAtPath === undefined - ? { at: printPath$2(paths), message: 'path does not exist' } - : prependAt$2(printPath$2(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$2(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$2({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$2 = Decoder$2.string; - /** See `Decoder.number` */ - var number$2 = Decoder$2.number; - /** See `Decoder.boolean` */ - var boolean$2 = Decoder$2.boolean; - /** See `Decoder.anyJson` */ - var anyJson$2 = Decoder$2.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$2.unknownJson; - /** See `Decoder.constant` */ - var constant$2 = Decoder$2.constant; - /** See `Decoder.object` */ - var object$2 = Decoder$2.object; - /** See `Decoder.array` */ - var array$2 = Decoder$2.array; - /** See `Decoder.tuple` */ - Decoder$2.tuple; - /** See `Decoder.dict` */ - Decoder$2.dict; - /** See `Decoder.optional` */ - var optional$2 = Decoder$2.optional; - /** See `Decoder.oneOf` */ - var oneOf$1 = Decoder$2.oneOf; - /** See `Decoder.union` */ - var union$1 = Decoder$2.union; - /** See `Decoder.intersection` */ - var intersection = Decoder$2.intersection; - /** See `Decoder.withDefault` */ - Decoder$2.withDefault; - /** See `Decoder.valueAt` */ - Decoder$2.valueAt; - /** See `Decoder.succeed` */ - Decoder$2.succeed; - /** See `Decoder.fail` */ - Decoder$2.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder$2.lazy; - - const defaultConfig = { - gateway: { webPlatform: {} }, - libraries: [], - exposeAPI: true, - }; - const defaultWidgetConfig = { - awaitFactory: true, - enable: false, - timeout: 5 * 1000, - restoreLastKnownPosition: true, - }; - const defaultModalsConfig = { - alerts: { - enabled: false - }, - dialogs: { - enabled: false - }, - awaitFactory: true, - timeout: 5 * 1000, - }; - const defaultIntentResolverConfig = { - enable: false, - timeout: 5 * 1000, - awaitFactory: true, - }; - - const Glue42CoreMessageTypes = { - platformUnload: { name: "platformUnload" }, - transportSwitchRequest: { name: "transportSwitchRequest" }, - transportSwitchResponse: { name: "transportSwitchResponse" }, - getCurrentTransport: { name: "getCurrentTransport" }, - getCurrentTransportResponse: { name: "getCurrentTransportResponse" }, - checkPreferredLogic: { name: "checkPreferredLogic" }, - checkPreferredConnection: { name: "checkPreferredConnection" }, - checkPreferredLogicResponse: { name: "checkPreferredLogicResponse" }, - checkPreferredConnectionResponse: { name: "checkPreferredConnectionResponse" } - }; - const webPlatformTransportName = "web-platform"; - const latestFDC3Type = "latest_fdc3_type"; - const errorChannel = new MessageChannel(); - const REQUEST_WIDGET_READY = "requestWidgetFactoryReady"; - const REQUEST_MODALS_UI_FACTORY_READY = "requestModalsUIFactoryReady"; - const MAX_SET_TIMEOUT_DELAY = 2147483647; - const REQUEST_INTENT_RESOLVER_UI_FACTORY_READY = "requestIntentResolverUIFactoryReady"; - const READONLY_PROPERTY_DESCRIPTOR = { - configurable: false, - enumerable: true, - writable: false, - }; - - const extractErrorMsg = (error) => { - if (typeof error === "string") { - return error; - } - if (error?.message) { - return typeof error.message === "string" ? error.message : JSON.stringify(error.message); - } - return JSON.stringify(error); - }; - const runDecoderWithIOError = (decoder, json) => { - try { - const result = decoder.runWithException(json); - return result; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const getSupportedOperationsNames = (operations) => { - return Object.keys(operations).filter((operation) => (operations)[operation].execute); - }; - const handleOperationCheck = (supportedOperations, operationName) => { - const isSupported = supportedOperations.some((operation) => operation.toLowerCase() === operationName.toLowerCase()); - return { isSupported }; - }; - const getSafeTimeoutDelay = (delay) => { - return Math.min(delay, MAX_SET_TIMEOUT_DELAY); - }; - const wrapPromise = () => { - let wrapperResolve; - let wrapperReject; - const promise = new Promise((resolve, reject) => { - wrapperResolve = resolve; - wrapperReject = reject; - }); - return { promise, resolve: wrapperResolve, reject: wrapperReject }; - }; - - class IOError { - raiseError(error, shouldThrowOriginalError) { - const errorMessage = extractErrorMsg(error); - errorChannel.port1.postMessage(errorMessage); - if (shouldThrowOriginalError) { - throw error; - } - throw new Error(errorMessage); - } - } - const ioError = new IOError(); - - const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"]; - const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"]; - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$1 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$1 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$1 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$1 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$1 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$1 = function (f, r) { - return r.ok === true ? ok$1(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$1 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$1(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$1 = function (f, r) { - return r.ok === true ? r : err$1(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$1 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$1 = function() { - __assign$1 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - - function __rest$1(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$1(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$1(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$1(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$1 = function (json) { return Array.isArray(json); }; - var isJsonObject$1 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$1(json); - }; - var typeString$1 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$1 = function (expected, got) { - return "expected " + expected + ", got " + typeString$1(got); - }; - var printPath$1 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$1 = function (newAt, _a) { - var at = _a.at, rest = __rest$1(_a, ["at"]); - return (__assign$1({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$1 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$1(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$1(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$1(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$1(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$1(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$1(json) - : err$1({ message: expectedGot$1('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$1(json) - : err$1({ message: expectedGot$1('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$1(json) - : err$1({ message: expectedGot$1('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$1(json, value) - ? ok$1(value) - : err$1({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$1(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$1({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else if (isJsonObject$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$1(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$1(function (err$$1) { return prependAt$1("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$1(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$1([])); - } - else if (isJsonArray$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$1(json)) { - if (json.length !== decoders.length) { - return err$1({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$1(prependAt$1("[" + i + "]", nth.error)); - } - } - return ok$1(result); - } - else { - return err$1({ message: expectedGot$1("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$1(Object.assign, acc, decoder.decode(json)); }, ok$1({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$1(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$1(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$1(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$1(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$1({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$1(withDefault$1(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$1(function (error) { - return jsonAtPath === undefined - ? { at: printPath$1(paths), message: 'path does not exist' } - : prependAt$1(printPath$1(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$1(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$1({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$1 = Decoder$1.string; - /** See `Decoder.number` */ - var number$1 = Decoder$1.number; - /** See `Decoder.boolean` */ - var boolean$1 = Decoder$1.boolean; - /** See `Decoder.anyJson` */ - var anyJson$1 = Decoder$1.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$1.unknownJson; - /** See `Decoder.constant` */ - var constant$1 = Decoder$1.constant; - /** See `Decoder.object` */ - var object$1 = Decoder$1.object; - /** See `Decoder.array` */ - var array$1 = Decoder$1.array; - /** See `Decoder.tuple` */ - Decoder$1.tuple; - /** See `Decoder.dict` */ - var dict = Decoder$1.dict; - /** See `Decoder.optional` */ - var optional$1 = Decoder$1.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder$1.oneOf; - /** See `Decoder.union` */ - Decoder$1.union; - /** See `Decoder.intersection` */ - Decoder$1.intersection; - /** See `Decoder.withDefault` */ - Decoder$1.withDefault; - /** See `Decoder.valueAt` */ - Decoder$1.valueAt; - /** See `Decoder.succeed` */ - Decoder$1.succeed; - /** See `Decoder.fail` */ - Decoder$1.fail; - /** See `Decoder.lazy` */ - Decoder$1.lazy; - - const nonEmptyStringDecoder$3 = string$1().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$3 = number$1().where((num) => num >= 0, "Expected a non-negative number"); - const regexDecoder = anyJson$1().andThen((value) => { - return value instanceof RegExp ? anyJson$1() : fail(`expected a regex, got a ${typeof value}`); - }); - - const intentDefinitionDecoder$1 = object$1({ - name: nonEmptyStringDecoder$3, - displayName: optional$1(string$1()), - contexts: optional$1(array$1(string$1())), - customConfig: optional$1(object$1()) - }); - const v2TypeDecoder = oneOf(constant$1("web"), constant$1("native"), constant$1("citrix"), constant$1("onlineNative"), constant$1("other")); - const v2DetailsDecoder = object$1({ - url: nonEmptyStringDecoder$3 - }); - const v2IconDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3) - }); - const v2ScreenshotDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3), - label: optional$1(nonEmptyStringDecoder$3) - }); - const v2ListensForIntentDecoder = object$1({ - contexts: array$1(nonEmptyStringDecoder$3), - displayName: optional$1(nonEmptyStringDecoder$3), - resultType: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(anyJson$1()) - }); - const v2IntentsDecoder = object$1({ - listensFor: optional$1(dict(v2ListensForIntentDecoder)), - raises: optional$1(dict(array$1(nonEmptyStringDecoder$3))) - }); - const v2UserChannelDecoder = object$1({ - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2AppChannelDecoder = object$1({ - name: nonEmptyStringDecoder$3, - description: optional$1(nonEmptyStringDecoder$3), - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2InteropDecoder = object$1({ - intents: optional$1(v2IntentsDecoder), - userChannels: optional$1(v2UserChannelDecoder), - appChannels: optional$1(array$1(v2AppChannelDecoder)) - }); - const glue42ApplicationDetailsDecoder = object$1({ - url: optional$1(nonEmptyStringDecoder$3), - top: optional$1(number$1()), - left: optional$1(number$1()), - width: optional$1(nonNegativeNumberDecoder$3), - height: optional$1(nonNegativeNumberDecoder$3) - }); - const glue42HostManifestsBrowserDecoder = object$1({ - name: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3.where((s) => s === "window", "Expected a value of window")), - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - customProperties: optional$1(anyJson$1()), - icon: optional$1(string$1()), - caption: optional$1(string$1()), - details: optional$1(glue42ApplicationDetailsDecoder), - intents: optional$1(array$1(intentDefinitionDecoder$1)), - hidden: optional$1(boolean$1()) - }); - const v1DefinitionDecoder = object$1({ - name: nonEmptyStringDecoder$3, - appId: nonEmptyStringDecoder$3, - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - manifest: nonEmptyStringDecoder$3, - manifestType: nonEmptyStringDecoder$3, - tooltip: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - images: optional$1(array$1(object$1({ url: optional$1(nonEmptyStringDecoder$3) }))), - icons: optional$1(array$1(object$1({ icon: optional$1(nonEmptyStringDecoder$3) }))), - customConfig: anyJson$1(), - intents: optional$1(array$1(intentDefinitionDecoder$1)) - }); - const v2LocalizedDefinitionDecoder = object$1({ - appId: optional$1(nonEmptyStringDecoder$3), - name: optional$1(nonEmptyStringDecoder$3), - details: optional$1(v2DetailsDecoder), - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder) - }); - const v2DefinitionDecoder = object$1({ - appId: nonEmptyStringDecoder$3, - name: optional$1(nonEmptyStringDecoder$3), - type: v2TypeDecoder, - details: v2DetailsDecoder, - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder), - localizedVersions: optional$1(dict(v2LocalizedDefinitionDecoder)) - }); - const allDefinitionsDecoder = oneOf(v1DefinitionDecoder, v2DefinitionDecoder); - - const parseDecoderErrorToStringMessage = (error) => { - return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`; - }; - - class FDC3Service { - fdc3ToDesktopDefinitionType = { - web: "window", - native: "exe", - citrix: "citrix", - onlineNative: "clickonce", - other: "window" - }; - toApi() { - return { - isFdc3Definition: this.isFdc3Definition.bind(this), - parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this), - parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this) - }; - } - isFdc3Definition(definition) { - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - return { isFdc3: false, reason: parseDecoderErrorToStringMessage(decodeRes.error) }; - } - if (definition.appId && definition.details) { - return { isFdc3: true, version: "2.0" }; - } - if (definition.manifest) { - return { isFdc3: true, version: "1.2" }; - } - return { isFdc3: false, reason: "The passed definition is not FDC3" }; - } - parseToBrowserBaseAppData(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - const userProperties = this.getUserPropertiesFromDefinition(definition, version); - const createOptions = { url: this.getUrl(definition, version) }; - const baseApplicationData = { - name: definition.appId, - type: "window", - createOptions, - userProperties: { - ...userProperties, - intents: version === "1.2" - ? userProperties.intents - : this.getIntentsFromV2AppDefinition(definition), - details: createOptions - }, - title: definition.title, - version: definition.version, - icon: this.getIconFromDefinition(definition, version), - caption: definition.description, - fdc3: version === "2.0" ? { ...definition, definitionVersion: "2.0" } : undefined, - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return baseApplicationData; - } - const ioDefinitionDecodeRes = glue42HostManifestsBrowserDecoder.run(ioConnectDefinition); - if (!ioDefinitionDecodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(ioDefinitionDecodeRes.error)}`); - } - if (!Object.keys(ioDefinitionDecodeRes.result).length) { - return baseApplicationData; - } - return this.mergeBaseAppDataWithGlueManifest(baseApplicationData, ioDefinitionDecodeRes.result); - } - parseToDesktopAppConfig(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - if (version === "1.2") { - const fdc3v1Definition = definition; - return { - name: fdc3v1Definition.appId, - type: "window", - details: { - url: this.getUrl(definition, version) - }, - version: fdc3v1Definition.version, - title: fdc3v1Definition.title, - tooltip: fdc3v1Definition.tooltip, - caption: fdc3v1Definition.description, - icon: fdc3v1Definition.icons?.[0].icon, - intents: fdc3v1Definition.intents, - customProperties: { - manifestType: fdc3v1Definition.manifestType, - images: fdc3v1Definition.images, - contactEmail: fdc3v1Definition.contactEmail, - supportEmail: fdc3v1Definition.supportEmail, - publisher: fdc3v1Definition.publisher, - icons: fdc3v1Definition.icons, - customConfig: fdc3v1Definition.customConfig - } - }; - } - const fdc3v2Definition = definition; - const desktopDefinition = { - name: fdc3v2Definition.appId, - type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type], - details: fdc3v2Definition.details, - version: fdc3v2Definition.version, - title: fdc3v2Definition.title, - tooltip: fdc3v2Definition.tooltip, - caption: fdc3v2Definition.description, - icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"), - intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition), - fdc3: { ...fdc3v2Definition, definitionVersion: "2.0" } - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return desktopDefinition; - } - if (typeof ioConnectDefinition !== "object" || Array.isArray(ioConnectDefinition)) { - throw new Error(`Invalid '${definition.hostManifests.ioConnect ? "hostManifests.ioConnect" : "hostManifests['Glue42']"}' key`); - } - return this.mergeDesktopConfigWithGlueManifest(desktopDefinition, ioConnectDefinition); - } - getUserPropertiesFromDefinition(definition, version) { - if (version === "1.2") { - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key))); - } - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key))); - } - getUrl(definition, version) { - let url; - if (version === "1.2") { - const parsedManifest = JSON.parse(definition.manifest); - url = parsedManifest.details?.url || parsedManifest.url; - } - else { - url = definition.details?.url; - } - if (!url || typeof url !== "string") { - throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`); - } - return url; - } - getIntentsFromV2AppDefinition(definition) { - const fdc3Intents = definition.interop?.intents?.listensFor; - if (!fdc3Intents) { - return; - } - const intents = Object.entries(fdc3Intents).map((fdc3Intent) => { - const [intentName, intentData] = fdc3Intent; - return { - name: intentName, - ...intentData - }; - }); - return intents; - } - getIconFromDefinition(definition, version) { - if (version === "1.2") { - return definition.icons?.find((iconDef) => iconDef.icon)?.icon || undefined; - } - return definition.icons?.find((iconDef) => iconDef.src)?.src || undefined; - } - mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) { - let baseApplicationDefinition = baseAppData; - if (hostManifestDefinition.customProperties) { - baseApplicationDefinition.userProperties = { ...baseAppData.userProperties, ...hostManifestDefinition.customProperties }; - } - if (hostManifestDefinition.details) { - const details = { ...baseAppData.createOptions, ...hostManifestDefinition.details }; - baseApplicationDefinition.createOptions = details; - baseApplicationDefinition.userProperties.details = details; - } - if (Array.isArray(hostManifestDefinition.intents)) { - baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents); - } - baseApplicationDefinition = { ...baseApplicationDefinition, ...hostManifestDefinition }; - delete baseApplicationDefinition.details; - delete baseApplicationDefinition.intents; - return baseApplicationDefinition; - } - mergeDesktopConfigWithGlueManifest(config, desktopDefinition) { - const appConfig = Object.assign({}, config, desktopDefinition, { details: { ...config.details, ...desktopDefinition.details } }); - if (Array.isArray(desktopDefinition.intents)) { - appConfig.intents = (config.intents || []).concat(desktopDefinition.intents); - } - return appConfig; - } - } - - const decoders$1 = { - common: { - nonEmptyStringDecoder: nonEmptyStringDecoder$3, - nonNegativeNumberDecoder: nonNegativeNumberDecoder$3, - regexDecoder - }, - fdc3: { - allDefinitionsDecoder, - v1DefinitionDecoder, - v2DefinitionDecoder - } - }; - - var INTENTS_ERRORS; - (function (INTENTS_ERRORS) { - INTENTS_ERRORS["USER_CANCELLED"] = "User Closed Intents Resolver UI without choosing a handler"; - INTENTS_ERRORS["CALLER_NOT_DEFINED"] = "Caller Id is not defined"; - INTENTS_ERRORS["TIMEOUT_HIT"] = "Timeout hit"; - INTENTS_ERRORS["INTENT_NOT_FOUND"] = "Cannot find Intent"; - INTENTS_ERRORS["HANDLER_NOT_FOUND"] = "Cannot find Intent Handler"; - INTENTS_ERRORS["TARGET_INSTANCE_UNAVAILABLE"] = "Cannot start Target Instance"; - INTENTS_ERRORS["INTENT_DELIVERY_FAILED"] = "Target Instance did not add a listener"; - INTENTS_ERRORS["RESOLVER_UNAVAILABLE"] = "Intents Resolver UI unavailable"; - INTENTS_ERRORS["RESOLVER_TIMEOUT"] = "User did not choose a handler"; - INTENTS_ERRORS["INVALID_RESOLVER_RESPONSE"] = "Intents Resolver UI returned invalid response"; - INTENTS_ERRORS["INTENT_HANDLER_REJECTION"] = "Intent Handler function processing the raised intent threw an error or rejected the promise it returned"; - })(INTENTS_ERRORS || (INTENTS_ERRORS = {})); - - let IoC$1 = class IoC { - _fdc3; - _decoders = decoders$1; - _errors = { - intents: INTENTS_ERRORS - }; - get fdc3() { - if (!this._fdc3) { - this._fdc3 = new FDC3Service().toApi(); - } - return this._fdc3; - } - get decoders() { - return this._decoders; - } - get errors() { - return this._errors; - } - }; - - const ioc = new IoC$1(); - ioc.fdc3; - const decoders = ioc.decoders; - ioc.errors; - - const nonEmptyStringDecoder$2 = string$2().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$2 = number$2().where((num) => num >= 0, "Expected a non-negative number"); - const optionalNonEmptyStringDecoder = optional$2(nonEmptyStringDecoder$2); - const libDomainDecoder = oneOf$1(constant$2("system"), constant$2("windows"), constant$2("appManager"), constant$2("layouts"), constant$2("intents"), constant$2("notifications"), constant$2("channels"), constant$2("extension"), constant$2("themes"), constant$2("prefs"), constant$2("ui")); - const windowOperationTypesDecoder = oneOf$1(constant$2("openWindow"), constant$2("windowHello"), constant$2("windowAdded"), constant$2("windowRemoved"), constant$2("getBounds"), constant$2("getFrameBounds"), constant$2("getUrl"), constant$2("moveResize"), constant$2("focus"), constant$2("close"), constant$2("getTitle"), constant$2("setTitle"), constant$2("focusChange"), constant$2("getChannel"), constant$2("notifyChannelsChanged"), constant$2("setZoomFactor"), constant$2("zoomFactorChange"), constant$2("refresh"), constant$2("operationCheck")); - const appManagerOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("appDirectoryStateChange"), constant$2("instanceStarted"), constant$2("instanceStopped"), constant$2("applicationStart"), constant$2("instanceStop"), constant$2("clear"), constant$2("operationCheck")); - const layoutsOperationTypesDecoder = oneOf$1(constant$2("layoutAdded"), constant$2("layoutChanged"), constant$2("layoutRemoved"), constant$2("layoutRenamed"), constant$2("get"), constant$2("getAll"), constant$2("export"), constant$2("import"), constant$2("remove"), constant$2("rename"), constant$2("clientSaveRequest"), constant$2("getGlobalPermissionState"), constant$2("checkGlobalActivated"), constant$2("requestGlobalPermission"), constant$2("getDefaultGlobal"), constant$2("setDefaultGlobal"), constant$2("clearDefaultGlobal"), constant$2("updateMetadata"), constant$2("operationCheck"), constant$2("getCurrent"), constant$2("defaultLayoutChanged"), constant$2("layoutRestored")); - const notificationsOperationTypesDecoder = oneOf$1(constant$2("raiseNotification"), constant$2("requestPermission"), constant$2("notificationShow"), constant$2("notificationClick"), constant$2("getPermission"), constant$2("list"), constant$2("notificationRaised"), constant$2("notificationClosed"), constant$2("click"), constant$2("clear"), constant$2("clearAll"), constant$2("configure"), constant$2("getConfiguration"), constant$2("configurationChanged"), constant$2("setState"), constant$2("clearOld"), constant$2("activeCountChange"), constant$2("stateChange"), constant$2("operationCheck"), constant$2("getActiveCount")); - const systemOperationTypesDecoder = oneOf$1(constant$2("getEnvironment"), constant$2("getBase"), constant$2("platformShutdown"), constant$2("isFdc3DataWrappingSupported"), constant$2("clientError"), constant$2("systemHello"), constant$2("operationCheck")); - const windowRelativeDirectionDecoder = oneOf$1(constant$2("top"), constant$2("left"), constant$2("right"), constant$2("bottom")); - const windowBoundsDecoder = object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }); - const windowOpenSettingsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - context: optional$2(anyJson$2()), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - windowId: optional$2(nonEmptyStringDecoder$2), - layoutComponentId: optional$2(nonEmptyStringDecoder$2) - })); - const openWindowConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2, - options: windowOpenSettingsDecoder - }); - const windowHelloDecoder = object$2({ - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const coreWindowDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleWindowDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const helloSuccessDecoder = object$2({ - windows: array$2(coreWindowDataDecoder), - isWorkspaceFrame: boolean$2() - }); - const windowTitleConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - title: string$2() - }); - const focusEventDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - hasFocus: boolean$2() - }); - const windowMoveResizeConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relative: optional$2(boolean$2()) - }); - const windowBoundsResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const frameWindowBoundsResultDecoder = object$2({ - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const windowUrlResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2 - }); - const windowZoomFactorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - factorIndex: nonNegativeNumberDecoder$2 - }); - const anyDecoder = anyJson$2(); - const boundsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2) - }); - const instanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - applicationName: nonEmptyStringDecoder$2 - }); - const iframePermissionsPolicyConfigDecoder = object$2({ - flags: string$2() - }); - const workspacesSandboxDecoder = object$2({ - flags: string$2() - }); - const requestChannelSelectorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelsNames: array$2(nonEmptyStringDecoder$2) - }); - const channelSelectorDecoder$1 = object$2({ - enabled: boolean$2(), - }); - const applicationDetailsDecoder = object$2({ - url: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - workspacesSandbox: optional$2(workspacesSandboxDecoder), - channelSelector: optional$2(channelSelectorDecoder$1), - iframePermissionsPolicy: optional$2(iframePermissionsPolicyConfigDecoder) - }); - const intentDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - displayName: optional$2(string$2()), - contexts: optional$2(array$2(string$2())), - customConfig: optional$2(object$2()), - resultType: optional$2(string$2()) - }); - const applicationDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - customProperties: optional$2(anyJson$2()), - icon: optional$2(string$2()), - caption: optional$2(string$2()), - details: applicationDetailsDecoder, - intents: optional$2(array$2(intentDefinitionDecoder)), - hidden: optional$2(boolean$2()), - fdc3: optional$2(decoders.fdc3.v2DefinitionDecoder) - }); - const appRemoveConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const appsExportOperationDecoder = object$2({ - definitions: array$2(applicationDefinitionDecoder) - }); - const applicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - instances: array$2(instanceDataDecoder), - userProperties: optional$2(anyJson$2()), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const baseApplicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - userProperties: anyJson$2(), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const appDirectoryStateChangeDecoder = object$2({ - appsAdded: array$2(baseApplicationDataDecoder), - appsChanged: array$2(baseApplicationDataDecoder), - appsRemoved: array$2(baseApplicationDataDecoder) - }); - const appHelloSuccessDecoder = object$2({ - apps: array$2(applicationDataDecoder), - initialChannelId: optional$2(nonEmptyStringDecoder$2) - }); - const basicInstanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const layoutTypeDecoder = oneOf$1(constant$2("Global"), constant$2("Activity"), constant$2("ApplicationDefault"), constant$2("Swimlane"), constant$2("Workspace")); - const componentTypeDecoder = oneOf$1(constant$2("application"), constant$2("activity")); - const windowComponentStateDecoder = object$2({ - context: optional$2(anyJson$2()), - bounds: windowBoundsDecoder, - createArgs: object$2({ - name: optional$2(nonEmptyStringDecoder$2), - url: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - instanceId: nonEmptyStringDecoder$2, - isCollapsed: optional$2(boolean$2()), - isSticky: optional$2(boolean$2()), - restoreSettings: object$2({ - groupId: optional$2(nonEmptyStringDecoder$2), - groupZOrder: optional$2(number$2()) - }), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const windowLayoutComponentDecoder = object$2({ - type: constant$2("window"), - componentType: optional$2(componentTypeDecoder), - application: nonEmptyStringDecoder$2, - state: windowComponentStateDecoder - }); - const windowLayoutItemDecoder = object$2({ - type: constant$2("window"), - config: object$2({ - appName: nonEmptyStringDecoder$2, - url: optional$2(nonEmptyStringDecoder$2), - title: optional$2(string$2()), - allowExtract: optional$2(boolean$2()), - allowReorder: optional$2(boolean$2()), - showCloseButton: optional$2(boolean$2()), - isMaximized: optional$2(boolean$2()) - }) - }); - const groupLayoutItemDecoder = object$2({ - type: constant$2("group"), - config: anyJson$2(), - children: array$2(oneOf$1(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object$2({ - type: constant$2("column"), - config: anyJson$2(), - children: array$2(oneOf$1(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object$2({ - type: constant$2("row"), - config: anyJson$2(), - children: array$2(oneOf$1(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutComponentStateDecoder = object$2({ - config: anyJson$2(), - context: anyJson$2(), - children: array$2(oneOf$1(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }); - const workspaceLayoutComponentDecoder = object$2({ - type: constant$2("Workspace"), - application: optional$2(nonEmptyStringDecoder$2), - state: workspaceLayoutComponentStateDecoder - }); - const workspaceFrameComponentStateDecoder = object$2({ - bounds: windowBoundsDecoder, - instanceId: nonEmptyStringDecoder$2, - selectedWorkspace: nonNegativeNumberDecoder$2, - workspaces: array$2(workspaceLayoutComponentStateDecoder), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }); - const workspaceFrameComponentDecoder = object$2({ - type: constant$2("workspaceFrame"), - application: nonEmptyStringDecoder$2, - componentType: optional$2(componentTypeDecoder), - state: workspaceFrameComponentStateDecoder - }); - const glueLayoutDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()) - }); - const renamedLayoutNotificationDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()), - prevName: nonEmptyStringDecoder$2 - }); - const newLayoutOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - instances: optional$2(array$2(nonEmptyStringDecoder$2)), - ignoreInstances: optional$2(array$2(nonEmptyStringDecoder$2)), - setAsCurrent: optional$2(boolean$2()), - ignoreContexts: optional$2(boolean$2()) - }); - const restoreOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - closeRunningInstance: optional$2(boolean$2()), - closeMe: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2) - }); - const layoutSummaryDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()) - }); - const simpleLayoutConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder - }); - const saveLayoutConfigDecoder = object$2({ - layout: newLayoutOptionsDecoder - }); - const renameLayoutConfigDecoder = object$2({ - layout: glueLayoutDecoder, - newName: nonEmptyStringDecoder$2 - }); - const layoutResultDecoder = object$2({ - status: nonEmptyStringDecoder$2 - }); - const updateLayoutMetadataConfigDecoder = object$2({ - layout: glueLayoutDecoder, - }); - const restoreLayoutConfigDecoder = object$2({ - layout: restoreOptionsDecoder - }); - const getAllLayoutsConfigDecoder = object$2({ - type: layoutTypeDecoder - }); - const allLayoutsFullConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder) - }); - const defaultGlobalChangedDecoder = optional$2(object$2({ - name: nonEmptyStringDecoder$2 - })); - const importModeDecoder = oneOf$1(constant$2("replace"), constant$2("merge")); - const layoutsImportConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder), - mode: importModeDecoder, - skipManagerRequest: optional$2(boolean$2()) - }); - const allLayoutsSummariesResultDecoder = object$2({ - summaries: array$2(layoutSummaryDecoder) - }); - const simpleLayoutResultDecoder = object$2({ - layout: glueLayoutDecoder - }); - const optionalSimpleLayoutResult = object$2({ - layout: optional$2(glueLayoutDecoder) - }); - const setDefaultGlobalConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const intentsOperationTypesDecoder = oneOf$1(constant$2("findIntent"), constant$2("getIntents"), constant$2("getIntentsByHandler"), constant$2("raise"), constant$2("filterHandlers")); - const intentHandlerDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2, - applicationTitle: optional$2(string$2()), - applicationDescription: optional$2(string$2()), - applicationIcon: optional$2(string$2()), - type: oneOf$1(constant$2("app"), constant$2("instance")), - displayName: optional$2(string$2()), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - instanceId: optional$2(string$2()), - instanceTitle: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - object$2({ - applicationName: string$2(), - applicationIcon: optional$2(string$2()), - instanceId: optional$2(string$2()), - }); - object$2({ - intent: nonEmptyStringDecoder$2, - handler: intentHandlerDecoder - }); - const intentDecoder = object$2({ - name: nonEmptyStringDecoder$2, - handlers: array$2(intentHandlerDecoder) - }); - const intentTargetDecoder = oneOf$1(constant$2("startNew"), constant$2("reuse"), object$2({ - app: optional$2(nonEmptyStringDecoder$2), - instance: optional$2(nonEmptyStringDecoder$2) - })); - const intentContextDecoder = object$2({ - type: optional$2(nonEmptyStringDecoder$2), - data: optional$2(anyJson$2()) - }); - const intentsDecoder = array$2(intentDecoder); - const wrappedIntentsDecoder = object$2({ - intents: intentsDecoder - }); - const intentFilterDecoder = object$2({ - name: optional$2(nonEmptyStringDecoder$2), - contextType: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const findFilterDecoder = oneOf$1(nonEmptyStringDecoder$2, intentFilterDecoder); - const wrappedIntentFilterDecoder = object$2({ - filter: optional$2(intentFilterDecoder) - }); - const applicationStartOptionsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const intentRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - target: optional$2(intentTargetDecoder), - context: optional$2(intentContextDecoder), - options: optional$2(applicationStartOptionsDecoder), - handlers: optional$2(array$2(intentHandlerDecoder)), - timeout: optional$2(nonNegativeNumberDecoder$2), - waitUserResponseIndefinitely: optional$2(boolean$2()), - clearSavedHandler: optional$2(boolean$2()) - }); - const originAppDecoder = object$2({ - interopInstance: nonEmptyStringDecoder$2, - name: optional$2(nonEmptyStringDecoder$2) - }); - const startReasonDecoder = object$2({ - originApp: originAppDecoder, - intentRequest: optional$2(intentRequestDecoder) - }); - const applicationStartConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - waitForAGMReady: boolean$2(), - id: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()), - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - forceChromeTab: optional$2(boolean$2()), - layoutComponentId: optional$2(nonEmptyStringDecoder$2), - channelId: optional$2(nonEmptyStringDecoder$2), - startReason: startReasonDecoder - }); - const raiseRequestDecoder = oneOf$1(nonEmptyStringDecoder$2, intentRequestDecoder); - const resolverConfigDecoder = object$2({ - enabled: boolean$2(), - appName: nonEmptyStringDecoder$2, - waitResponseTimeout: number$2() - }); - const handlerExclusionCriteriaApplicationNameDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaInstanceIdDecoder = object$2({ - instanceId: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaDecoder = oneOf$1(handlerExclusionCriteriaApplicationNameDecoder, handlerExclusionCriteriaInstanceIdDecoder); - const handlerFilterDecoder = object$2({ - title: optional$2(nonEmptyStringDecoder$2), - openResolver: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2), - intent: optional$2(nonEmptyStringDecoder$2), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - resultType: optional$2(nonEmptyStringDecoder$2), - applicationNames: optional$2(array$2(nonEmptyStringDecoder$2)), - excludeList: optional$2(array$2(handlerExclusionCriteriaDecoder)) - }); - const embeddedResolverConfigDecoder = object$2({ - enabled: boolean$2(), - initialCaller: object$2({ instanceId: nonEmptyStringDecoder$2 }), - }); - const raiseIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const intentResultDecoder = object$2({ - request: intentRequestDecoder, - handler: intentHandlerDecoder, - result: anyJson$2() - }); - const filterHandlersResultDecoder = object$2({ - handlers: array$2(intentHandlerDecoder) - }); - const filterHandlersWithResolverConfigDecoder = object$2({ - filterHandlersRequest: handlerFilterDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const AddIntentListenerRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - displayName: optional$2(string$2()), - icon: optional$2(string$2()), - description: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - const AddIntentListenerDecoder = oneOf$1(nonEmptyStringDecoder$2, AddIntentListenerRequestDecoder); - const intentInfoDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - description: optional$2(nonEmptyStringDecoder$2), - displayName: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const getIntentsResultDecoder = object$2({ - intents: array$2(intentInfoDecoder) - }); - const channelNameDecoder = (channelNames) => { - return nonEmptyStringDecoder$2.where(s => channelNames.includes(s), "Expected a valid channel name"); - }; - const fdc3OptionsDecoder = object$2({ - contextType: optional$2(nonEmptyStringDecoder$2) - }); - const publishOptionsDecoder = optional$2(oneOf$1(nonEmptyStringDecoder$2, object$2({ - name: optional$2(nonEmptyStringDecoder$2), - fdc3: optional$2(boolean$2()) - }))); - const leaveChannelsConfig = object$2({ - windowId: optionalNonEmptyStringDecoder, - channel: optionalNonEmptyStringDecoder - }); - const fdc3ContextDecoder = anyJson$2().where((value) => typeof value.type === "string", "Expected a valid FDC3 Context with compulsory 'type' field"); - const interopActionSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$2, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("all"), constant$2("best"))) - }); - const glue42NotificationActionDecoder = object$2({ - action: string$2(), - title: nonEmptyStringDecoder$2, - icon: optional$2(string$2()), - interop: optional$2(interopActionSettingsDecoder) - }); - const notificationStateDecoder = oneOf$1(constant$2("Active"), constant$2("Acknowledged"), constant$2("Seen"), constant$2("Closed"), constant$2("Stale"), constant$2("Snoozed"), constant$2("Processing")); - const activeNotificationsCountChangeDecoder = object$2({ - count: number$2() - }); - const notificationDefinitionDecoder = object$2({ - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())) - }); - const glue42NotificationOptionsDecoder = object$2({ - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const notificationSetStateRequestDecoder = object$2({ - id: nonEmptyStringDecoder$2, - state: notificationStateDecoder - }); - object$2().where((value) => value.fdc3 ? typeof value.fdc3.type === "string" : true, "Expected a valid FDC3 Context with compulsory 'type' field"); - const channelFDC3DisplayMetadataDecoder = object$2({ - color: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - name: optional$2(nonEmptyStringDecoder$2), - glyph: optional$2(nonEmptyStringDecoder$2) - }); - const channelFdc3MetaDecoder = object$2({ - id: nonEmptyStringDecoder$2, - displayMetadata: optional$2(channelFDC3DisplayMetadataDecoder) - }); - const channelMetaDecoder = object$2({ - color: nonEmptyStringDecoder$2, - fdc3: optional$2(channelFdc3MetaDecoder) - }); - const channelDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - meta: channelMetaDecoder, - data: optional$2(object$2()), - }); - const pathValueDecoder = object$2({ - path: nonEmptyStringDecoder$2, - value: anyJson$2() - }); - const pathsValueDecoder = array$2(pathValueDecoder); - const removeChannelDataDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const channelRestrictionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const channelRestrictionConfigWithWindowIdDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: nonEmptyStringDecoder$2 - }); - const restrictionConfigDataDecoder = object$2({ - config: channelRestrictionConfigWithWindowIdDecoder - }); - const restrictionsDecoder = object$2({ - channels: array$2(channelRestrictionsDecoder) - }); - const getRestrictionsDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const restrictionsConfigDecoder = object$2({ - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const restrictAllDataDecoder = object$2({ - restrictions: restrictionsConfigDecoder - }); - const raiseNotificationDecoder = object$2({ - settings: glue42NotificationOptionsDecoder, - id: nonEmptyStringDecoder$2 - }); - const raiseNotificationResultDecoder = object$2({ - settings: glue42NotificationOptionsDecoder - }); - const permissionRequestResultDecoder = object$2({ - permissionGranted: boolean$2() - }); - const permissionQueryResultDecoder = object$2({ - permission: oneOf$1(constant$2("default"), constant$2("granted"), constant$2("denied")) - }); - const notificationEventPayloadDecoder = object$2({ - definition: notificationDefinitionDecoder, - action: optional$2(string$2()), - id: optional$2(nonEmptyStringDecoder$2) - }); - const notificationFilterDecoder = object$2({ - allowed: optional$2(array$2(nonEmptyStringDecoder$2)), - blocked: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const notificationsConfigurationDecoder = object$2({ - enable: optional$2(boolean$2()), - enableToasts: optional$2(boolean$2()), - sourceFilter: optional$2(notificationFilterDecoder), - showNotificationBadge: optional$2(boolean$2()) - }); - const notificationsConfigurationProtocolDecoder = object$2({ - configuration: notificationsConfigurationDecoder - }); - const strictNotificationsConfigurationProtocolDecoder = object$2({ - configuration: object$2({ - enable: boolean$2(), - enableToasts: boolean$2(), - sourceFilter: object$2({ - allowed: array$2(nonEmptyStringDecoder$2), - blocked: array$2(nonEmptyStringDecoder$2) - }) - }) - }); - const platformSaveRequestConfigDecoder = object$2({ - layoutType: oneOf$1(constant$2("Global"), constant$2("Workspace")), - layoutName: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()) - }); - const saveRequestClientResponseDecoder = object$2({ - windowContext: optional$2(anyJson$2()), - }); - const permissionStateResultDecoder = object$2({ - state: oneOf$1(constant$2("prompt"), constant$2("denied"), constant$2("granted")) - }); - const simpleAvailabilityResultDecoder = object$2({ - isAvailable: boolean$2() - }); - const simpleItemIdDecoder = object$2({ - itemId: nonEmptyStringDecoder$2 - }); - const operationCheckResultDecoder = object$2({ - isSupported: boolean$2() - }); - const operationCheckConfigDecoder = object$2({ - operation: nonEmptyStringDecoder$2 - }); - const workspaceFrameBoundsResultDecoder = object$2({ - bounds: windowBoundsDecoder - }); - const themeDecoder = object$2({ - displayName: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleThemeResponseDecoder = object$2({ - theme: themeDecoder - }); - const allThemesResponseDecoder = object$2({ - themes: array$2(themeDecoder) - }); - const selectThemeConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const notificationsDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const simpleNotificationDataDecoder = object$2({ - notification: notificationsDataDecoder - }); - const allNotificationsDataDecoder = object$2({ - notifications: array$2(notificationsDataDecoder) - }); - const simpleNotificationSelectDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelResultDecoder = object$2({ - windowIds: array$2(nonEmptyStringDecoder$2) - }); - const channelsOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("addChannel"), constant$2("getMyChannel"), constant$2("getWindowIdsOnChannel"), constant$2("getWindowIdsWithChannels"), constant$2("joinChannel"), constant$2("restrict"), constant$2("getRestrictions"), constant$2("restrictAll"), constant$2("notifyChannelsChanged"), constant$2("leaveChannel"), constant$2("getMode"), constant$2("operationCheck")); - const modeDecoder = oneOf$1(constant$2("single"), constant$2("multi")); - const getChannelsModeDecoder = object$2({ - mode: modeDecoder - }); - const channelsAppHelloDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const channelsAppHelloSuccessDecoder = object$2({ - mode: modeDecoder, - channels: array$2(nonEmptyStringDecoder$2), - restrictions: array$2(channelRestrictionsDecoder) - }); - const getMyChanelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2) - }); - const windowWithChannelFilterDecoder = object$2({ - application: optional$2(nonEmptyStringDecoder$2), - channels: optional$2(array$2(nonEmptyStringDecoder$2)), - windowIds: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const wrappedWindowWithChannelFilterDecoder = object$2({ - filter: optional$2(windowWithChannelFilterDecoder) - }); - const getWindowIdsWithChannelsResultDecoder = object$2({ - windowIdsWithChannels: array$2(object$2({ - application: nonEmptyStringDecoder$2, - channel: optional$2(nonEmptyStringDecoder$2), - windowId: nonEmptyStringDecoder$2 - })) - }); - const startApplicationContextDecoder = optional$2(anyJson$2()); - const startApplicationOptionsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - reuseId: optional$2(nonEmptyStringDecoder$2), - originIntentRequest: optional$2(intentRequestDecoder) - })); - const joinChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2, - windowId: nonEmptyStringDecoder$2 - }); - const leaveChannelDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelName: optional$2(nonEmptyStringDecoder$2) - }); - const channelsChangedDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelNames: array$2(nonEmptyStringDecoder$2) - }); - const windowChannelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2), - }); - const prefsOperationTypesDecoder = oneOf$1(constant$2("clear"), constant$2("clearAll"), constant$2("get"), constant$2("getAll"), constant$2("set"), constant$2("update"), constant$2("prefsChanged"), constant$2("prefsHello"), constant$2("operationCheck"), constant$2("registerSubscriber")); - const appPreferencesDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - lastUpdate: optional$2(nonEmptyStringDecoder$2), - }); - const basePrefsConfigDecoder = object$2({ - app: nonEmptyStringDecoder$2, - }); - const getPrefsResultDecoder = object$2({ - prefs: appPreferencesDecoder, - }); - const getAllPrefsResultDecoder = object$2({ - all: array$2(appPreferencesDecoder), - }); - const subscriberRegisterConfigDecoder = object$2({ - interopId: nonEmptyStringDecoder$2, - appName: optional$2(nonEmptyStringDecoder$2) - }); - const changePrefsDataDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - }); - const prefsHelloSuccessDecoder = object$2({ - platform: object$2({ - app: nonEmptyStringDecoder$2, - }), - validNonExistentApps: optional$2(array$2(nonEmptyStringDecoder$2)), - }); - const clientErrorDataDecoder = object$2({ - message: nonEmptyStringDecoder$2 - }); - const systemHelloSuccessDecoder = object$2({ - isClientErrorOperationSupported: boolean$2() - }); - - const nonEmptyStringDecoder$1 = decoders.common.nonEmptyStringDecoder; - const nonNegativeNumberDecoder$1 = decoders.common.nonNegativeNumberDecoder; - const widgetSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const modalsSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const intentResolverSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const channelSelectorTypeDecoder = oneOf$1(constant$2("directional"), constant$2("default")); - const channelSelectorDecoder = object$2({ - type: optional$2(channelSelectorTypeDecoder), - enable: optional$2(boolean$2()) - }); - const positionDecoder = oneOf$1(constant$2("top-left"), constant$2("top-center"), constant$2("top-right"), constant$2("center-left"), constant$2("center-right"), constant$2("bottom-left"), constant$2("bottom-center"), constant$2("bottom-right")); - const displayModeDecoder = oneOf$1(constant$2("all"), constant$2("fdc3")); - const widgetChannelsDecoder = object$2({ - selector: optional$2(channelSelectorDecoder), - displayMode: optional$2(displayModeDecoder) - }); - const platformWidgetDefaultConfigDecoder = object$2({ - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const widgetConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const modalsConfigDecoder = object$2({ - alerts: optional$2(object$2({ - enabled: boolean$2() - })), - dialogs: optional$2(object$2({ - enabled: boolean$2() - })), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - }); - const uiOperationTypesDecoder = oneOf$1(constant$2("getResources"), constant$2("operationCheck"), constant$2("showAlert"), constant$2("showDialog"), constant$2("alertInteropAction"), constant$2("showResolver")); - const getResourcesDataDecoder = object$2({ - origin: nonEmptyStringDecoder$1 - }); - const blockedResourcesDecoder = object$2({ - blockedOrigin: constant$2(true) - }); - const availableWidgetResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - config: platformWidgetDefaultConfigDecoder, - sources: widgetSourcesDecoder - }); - const widgetResourcesDecoder = union$1(blockedResourcesDecoder, availableWidgetResourcesDecoder); - const availableModalsResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: modalsSourcesDecoder - }); - const modalsResourcesDecoder = union$1(blockedResourcesDecoder, availableModalsResourcesDecoder); - const availableIntentResolverResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: intentResolverSourcesDecoder - }); - const intentResolverResourcesDecoder = union$1(blockedResourcesDecoder, availableIntentResolverResourcesDecoder); - const resourcesDecoder = object$2({ - widget: optional$2(widgetResourcesDecoder), - modals: optional$2(modalsResourcesDecoder), - intentResolver: optional$2(intentResolverResourcesDecoder) - }); - const getResourcesResultDecoder = object$2({ - resources: resourcesDecoder, - }); - const alertsInteropSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$1, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("best"), constant$2("all"), nonEmptyStringDecoder$1)) - }); - const modalRequestTargetDecoder = oneOf$1(constant$2("Global"), constant$2("WindowContainer"), nonEmptyStringDecoder$1); - const modalRequestMessageTargetDecoder = object$2({ - instance: nonEmptyStringDecoder$1, - container: optional$2(oneOf$1(constant$2("Global"), constant$2("WindowContainer"))) - }); - const alertRequestConfigDecoder = object$2({ - variant: oneOf$1(constant$2("default"), constant$2("success"), constant$2("critical"), constant$2("info"), constant$2("warning")), - text: nonEmptyStringDecoder$1, - showCloseButton: optional$2(boolean$2()), - clickInterop: optional$2(alertsInteropSettingsDecoder), - onCloseInterop: optional$2(alertsInteropSettingsDecoder), - actions: optional$2(array$2(object$2({ - id: nonEmptyStringDecoder$1, - title: nonEmptyStringDecoder$1, - clickInterop: alertsInteropSettingsDecoder - }))), - data: optional$2(anyJson$2()), - ttl: optional$2(nonNegativeNumberDecoder$1), - target: optional$2(modalRequestTargetDecoder) - }); - const uiAlertRequestMessageDecoder = object$2({ - config: alertRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const dialogRequestConfigDecoder = object$2({ - templateName: nonEmptyStringDecoder$1, - variables: anyJson$2(), - target: optional$2(modalRequestTargetDecoder), - timer: optional$2(object$2({ - duration: nonNegativeNumberDecoder$1 - })), - size: optional$2(object$2({ - width: nonNegativeNumberDecoder$1, - height: nonNegativeNumberDecoder$1 - })), - movable: optional$2(boolean$2()), - transparent: optional$2(boolean$2()) - }); - const dialogResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - isEnterPressed: optional$2(boolean$2()), - responseButtonClicked: optional$2(object$2({ - id: nonEmptyStringDecoder$1, - text: nonEmptyStringDecoder$1 - })), - inputs: optional$2(array$2(object$2({ - type: oneOf$1(constant$2("checkbox"), constant$2("email"), constant$2("number"), constant$2("password"), constant$2("text")), - id: nonEmptyStringDecoder$1, - checked: optional$2(boolean$2()), - value: optional$2(string$2()) - }))) - }); - object$2({ - result: dialogResponseDecoder - }); - const uiDialogRequestMessageDecoder = object$2({ - config: dialogRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const openAlertResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const openDialogResultDecoder = object$2({ - id: nonEmptyStringDecoder$1, - responsePromise: anyJson$2() - }); - const dialogOnCompletionConfigDecoder = object$2({ - response: dialogResponseDecoder - }); - const alertInteropActionDecoder = object$2({ - name: nonEmptyStringDecoder$1, - settings: alertsInteropSettingsDecoder - }); - const alertOnClickConfigDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const alertInteropActionDataDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const intentResolverConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1) - }); - const openResolverResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const userSettingsDecoder = object$2({ - preserveChoice: boolean$2() - }); - const userChoiceResponseDecoder = object$2({ - intent: nonEmptyStringDecoder$1, - handler: intentHandlerDecoder, - userSettings: userSettingsDecoder - }); - const intentResolverResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - userChoice: optional$2(userChoiceResponseDecoder) - }); - const onUserResponseResponseDecoder = object$2({ - response: intentResolverResponseDecoder - }); - const openConfigWithIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder - }); - const openConfigWithHandlerFilterDecoder = object$2({ - handlerFilter: handlerFilterDecoder - }); - const intentResolverOpenConfigDecoder = union$1(openConfigWithIntentRequestDecoder, openConfigWithHandlerFilterDecoder); - const uiResolverRequestMessageConfigDecoder = intersection(intentResolverOpenConfigDecoder, object$2({ timeout: nonNegativeNumberDecoder$1 })); - const uiResolverRequestMessageDecoder = object$2({ - config: uiResolverRequestMessageConfigDecoder - }); - const uiResolverResponseMessageDecoder = object$2({ - result: intentResolverResponseDecoder - }); - - const parseConfig = (config = {}) => { - const isPlatformInternal = !!config?.gateway?.webPlatform?.port; - const decodedWidgetConfigResult = optional$2(widgetConfigDecoder).run(config.widget); - if (!decodedWidgetConfigResult.ok) { - throw ioError.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(decodedWidgetConfigResult.error)}`); - } - const decodedModalsConfigResult = optional$2(modalsConfigDecoder).run(config.modals); - if (!decodedModalsConfigResult.ok) { - throw ioError.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(decodedModalsConfigResult.error)}`); - } - const decodedIntentResolverConfigResult = optional$2(intentResolverConfigDecoder).run(config.intentResolver); - if (!decodedIntentResolverConfigResult.ok) { - throw ioError.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(decodedIntentResolverConfigResult.error)}`); - } - const combined = { - ...defaultConfig, - ...config, - isPlatformInternal, - logger: config.systemLogger?.level ?? "info", - customLogger: config.systemLogger?.customLogger, - widget: deepmerge$1(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}), - modals: deepmerge$1(defaultModalsConfig, decodedModalsConfigResult.result ?? {}), - intentResolver: deepmerge$1(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}), - }; - return combined; - }; - - const checkSingleton = () => { - const ioConnectBrowserNamespace = window.glue42core || window.iobrowser; - if (ioConnectBrowserNamespace && ioConnectBrowserNamespace.webStarted) { - return ioError.raiseError("IoConnect Browser has already been started for this application."); - } - if (!ioConnectBrowserNamespace) { - window.iobrowser = { webStarted: true }; - return; - } - ioConnectBrowserNamespace.webStarted = true; - }; - - const enterprise = (config) => { - const enterpriseConfig = { - windows: true, - layouts: "full", - appManager: "full", - channels: true, - libraries: config?.libraries ?? [], - logger: config?.systemLogger?.level ?? "warn" - }; - const injectedFactory = window.IODesktop || window.Glue; - return injectedFactory(enterpriseConfig); - }; - - const operations$a = { - openWindow: { name: "openWindow", dataDecoder: openWindowConfigDecoder, resultDecoder: coreWindowDataDecoder }, - windowHello: { name: "windowHello", dataDecoder: windowHelloDecoder, resultDecoder: helloSuccessDecoder }, - windowAdded: { name: "windowAdded", dataDecoder: coreWindowDataDecoder }, - windowRemoved: { name: "windowRemoved", dataDecoder: simpleWindowDecoder }, - getBounds: { name: "getBounds", dataDecoder: simpleWindowDecoder, resultDecoder: windowBoundsResultDecoder }, - getFrameBounds: { name: "getFrameBounds", dataDecoder: simpleWindowDecoder, resultDecoder: frameWindowBoundsResultDecoder }, - getUrl: { name: "getUrl", dataDecoder: simpleWindowDecoder, resultDecoder: windowUrlResultDecoder }, - moveResize: { name: "moveResize", dataDecoder: windowMoveResizeConfigDecoder }, - focus: { name: "focus", dataDecoder: simpleWindowDecoder }, - close: { name: "close", dataDecoder: simpleWindowDecoder }, - getTitle: { name: "getTitle", dataDecoder: simpleWindowDecoder, resultDecoder: windowTitleConfigDecoder }, - setTitle: { name: "setTitle", dataDecoder: windowTitleConfigDecoder }, - focusChange: { name: "focusChange", dataDecoder: focusEventDataDecoder }, - getChannel: { name: "getChannel", dataDecoder: simpleWindowDecoder, resultDecoder: windowChannelResultDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - setZoomFactor: { name: "setZoomFactor", dataDecoder: windowZoomFactorConfigDecoder }, - zoomFactorChange: { name: "zoomFactorChange", dataDecoder: windowZoomFactorConfigDecoder }, - refresh: { name: "refresh", dataDecoder: simpleWindowDecoder }, - operationCheck: { name: "operationCheck" } - }; - - function createRegistry$1(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry$1.default = createRegistry$1; - var lib$1 = createRegistry$1; - - - var CallbackRegistryFactory$1 = /*@__PURE__*/getDefaultExportFromCjs$1(lib$1); - - const ZOOM_FACTORS = Object.freeze({ - 0: 24, - 1: 33, - 2: 50, - 3: 67, - 4: 75, - 5: 80, - 6: 90, - 7: 100, - 8: 110, - 9: 125, - 10: 150, - 11: 175, - 12: 200, - 13: 250, - 14: 300, - 15: 400, - 16: 500 - }); - - class WebWindowModel { - _id; - _name; - _bridge; - _logger; - registry = CallbackRegistryFactory$1(); - myCtxKey; - ctxUnsubscribe; - zoomFactorIndex = 7; - me; - constructor(_id, _name, _bridge, _logger) { - this._id = _id; - this._name = _name; - this._bridge = _bridge; - this._logger = _logger; - this.myCtxKey = `___window___${this.id}`; - } - get id() { - return this._id.slice(); - } - get name() { - return this._name.slice(); - } - get zoomFactor() { - return ZOOM_FACTORS[this.zoomFactorIndex]; - } - clean() { - if (this.ctxUnsubscribe) { - this.ctxUnsubscribe(); - } - } - processSelfFocusEvent(hasFocus) { - this.me.isFocused = hasFocus; - this.registry.execute("focus-change", this.me); - } - processChannelsChangedEvent(channelNames) { - this.registry.execute("channels-changed", channelNames); - } - processSelfZoomFactorChangedEvent(factorIndex) { - this.zoomFactorIndex = factorIndex; - this.registry.execute("zoom-factor-changed", this.me); - } - async toApi() { - this.ctxUnsubscribe = await this._bridge.contextLib.subscribe(this.myCtxKey, (data) => this.registry.execute("context-updated", data)); - this.me = { - id: this.id, - name: this.name, - isFocused: false, - zoomFactor: this.zoomFactor, - getURL: this.getURL.bind(this), - moveResize: this.moveResize.bind(this), - resizeTo: this.resizeTo.bind(this), - moveTo: this.moveTo.bind(this), - focus: this.focus.bind(this), - close: this.close.bind(this), - getTitle: this.getTitle.bind(this), - setTitle: this.setTitle.bind(this), - getBounds: this.getBounds.bind(this), - getContext: this.getContext.bind(this), - updateContext: this.updateContext.bind(this), - setContext: this.setContext.bind(this), - refresh: this.refresh.bind(this), - onContextUpdated: this.onContextUpdated.bind(this), - onFocusChanged: this.onFocusChanged.bind(this), - getChannel: this.getChannel.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - zoomIn: this.zoomIn.bind(this), - zoomOut: this.zoomOut.bind(this), - setZoomFactor: this.setZoomFactor.bind(this), - onZoomFactorChanged: this.onZoomFactorChanged.bind(this), - }; - Object.defineProperties(this.me, { - id: READONLY_PROPERTY_DESCRIPTOR, - name: READONLY_PROPERTY_DESCRIPTOR, - zoomFactor: { - get: () => { - return this.zoomFactor; - }, - enumerable: true, - }, - }); - return this.me; - } - async getURL() { - const result = await this._bridge.send("windows", operations$a.getUrl, { windowId: this.id }); - return result.url; - } - onFocusChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - return this.registry.add("focus-change", callback); - } - async moveResize(dimension) { - const targetBounds = runDecoderWithIOError(boundsDecoder, dimension); - const commandArgs = Object.assign({}, targetBounds, { windowId: this.id, relative: false }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async resizeTo(width, height) { - if (typeof width === "undefined" && typeof height === "undefined") { - return this.me; - } - if (typeof width !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, width); - } - if (typeof height !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, height); - } - const commandArgs = Object.assign({}, { width, height }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async moveTo(top, left) { - if (typeof top === "undefined" && typeof left === "undefined") { - return this.me; - } - if (typeof top !== "undefined") { - runDecoderWithIOError(number$2(), top); - } - if (typeof left !== "undefined") { - runDecoderWithIOError(number$2(), left); - } - const commandArgs = Object.assign({}, { top, left }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async focus() { - if (this.name === "Platform") { - window.open(undefined, this.id); - } - else { - await this._bridge.send("windows", operations$a.focus, { windowId: this.id }); - } - return this.me; - } - async close() { - await this._bridge.send("windows", operations$a.close, { windowId: this.id }); - return this.me; - } - async getTitle() { - const result = await this._bridge.send("windows", operations$a.getTitle, { windowId: this.id }); - return result.title; - } - async setTitle(title) { - const ttl = runDecoderWithIOError(nonEmptyStringDecoder$2, title); - await this._bridge.send("windows", operations$a.setTitle, { windowId: this.id, title: ttl }); - return this.me; - } - async getBounds() { - const result = await this._bridge.send("windows", operations$a.getBounds, { windowId: this.id }); - return result.bounds; - } - async getContext() { - const ctx = await this._bridge.contextLib.get(this.myCtxKey); - const { ___io___, ...rest } = ctx; - return rest; - } - async updateContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - await this._bridge.contextLib.update(this.myCtxKey, ctx); - return this.me; - } - async setContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - const current = await this._bridge.contextLib.get(this.myCtxKey); - const newCtx = current.___io___ ? { ...ctx, ___io___: current.___io___ } : ctx; - await this._bridge.contextLib.set(this.myCtxKey, newCtx); - return this.me; - } - onContextUpdated(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - const wrappedCallback = (data) => { - const { ___io___, ...rest } = data; - callback(rest, this.me); - }; - return this.registry.add("context-updated", wrappedCallback); - } - async getChannel() { - const result = await this._bridge.send("windows", operations$a.getChannel, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return result.channel; - } - onChannelsChanged(callback) { - return this.registry.add("channels-changed", callback); - } - getClosestZoomFactorIndex(factor) { - const closestIndex = Object.entries(ZOOM_FACTORS).reduce((closestIndex, [currentIndex, currentValue]) => { - return (Math.abs(currentValue - factor) <= Math.abs(ZOOM_FACTORS[closestIndex] - factor) ? parseInt(currentIndex) : closestIndex); - }, 0); - const closestFactor = ZOOM_FACTORS[closestIndex]; - if (closestFactor !== factor) { - this._logger.warn(`Zoom factor ${factor} is not available, using closest value ${closestFactor} instead.`); - } - return closestIndex; - } - async zoom(factorIndex) { - if (factorIndex === this.zoomFactorIndex || !(factorIndex in ZOOM_FACTORS)) { - return; - } - await this._bridge.send("windows", operations$a.setZoomFactor, { windowId: this.id, factorIndex }, undefined, { includeOperationCheck: true }); - this.zoomFactorIndex = factorIndex; - } - async zoomIn() { - await this.zoom(this.zoomFactorIndex + 1); - return this.me; - } - async zoomOut() { - await this.zoom(this.zoomFactorIndex - 1); - return this.me; - } - async setZoomFactor(factor) { - const targetZoomFactor = runDecoderWithIOError(number$2(), factor); - const closestZoomFactorIndex = this.getClosestZoomFactorIndex(targetZoomFactor); - await this.zoom(closestZoomFactorIndex); - return this.me; - } - onZoomFactorChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"); - } - return this.registry.add("zoom-factor-changed", callback); - } - async refresh() { - await this._bridge.send("windows", operations$a.refresh, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return this.me; - } - } - - const commonOperations = { - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - getWorkspaceWindowFrameBounds: { name: "getWorkspaceWindowFrameBounds", resultDecoder: workspaceFrameBoundsResultDecoder, dataDecoder: simpleItemIdDecoder } - }; - - const PromiseWrap = (callback, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - callback() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - const PromisePlus$1 = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WindowsController { - supportedOperationsNames = []; - focusEventHandler; - registry = CallbackRegistryFactory$1(); - platformRegistration; - ioc; - bridge; - publicWindowId; - allWindowProjections = []; - me; - logger; - isWorkspaceFrame; - instanceId; - channelsController; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("windows.controller.web"); - this.logger.trace("starting the web windows controller"); - this.publicWindowId = ioc.publicWindowId; - this.addWindowOperationExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.instanceId = coreGlue.interop.instance.instance; - this.channelsController = ioc.channelsController; - this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`); - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - await this.initializeFocusTracking(); - this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning"); - const api = this.toApi(); - coreGlue.windows = api; - } - handlePlatformShutdown() { - this.registry.clear(); - this.allWindowProjections = []; - if (!this.focusEventHandler) { - return; - } - document.removeEventListener("visibilityChange", this.focusEventHandler); - window.removeEventListener("focus", this.focusEventHandler); - window.removeEventListener("blur", this.focusEventHandler); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(windowOperationTypesDecoder, args.operation); - const operation = operations$a[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async open(name, url, options) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(nonEmptyStringDecoder$2, url); - const settings = runDecoderWithIOError(windowOpenSettingsDecoder, options); - const windowSuccess = await this.bridge.send("windows", operations$a.openWindow, { name, url, options: settings }); - return this.waitForWindowAdded(windowSuccess.windowId); - } - list() { - return this.allWindowProjections.map((projection) => projection.api); - } - findById(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - return this.allWindowProjections.find((projection) => projection.id === id)?.api; - } - toApi() { - return { - open: this.open.bind(this), - my: this.my.bind(this), - list: this.list.bind(this), - findById: this.findById.bind(this), - onWindowAdded: this.onWindowAdded.bind(this), - onWindowRemoved: this.onWindowRemoved.bind(this), - onWindowGotFocus: this.onWindowGotFocus.bind(this), - onWindowLostFocus: this.onWindowLostFocus.bind(this) - }; - } - addWindowOperationExecutors() { - operations$a.focusChange.execute = this.handleFocusChangeEvent.bind(this); - operations$a.windowAdded.execute = this.handleWindowAdded.bind(this); - operations$a.windowRemoved.execute = this.handleWindowRemoved.bind(this); - operations$a.getBounds.execute = this.handleGetBounds.bind(this); - operations$a.getFrameBounds.execute = this.handleGetBounds.bind(this); - operations$a.getTitle.execute = this.handleGetTitle.bind(this); - operations$a.getUrl.execute = this.handleGetUrl.bind(this); - operations$a.moveResize.execute = this.handleMoveResize.bind(this); - operations$a.setTitle.execute = this.handleSetTitle.bind(this); - operations$a.getChannel.execute = this.handleGetChannel.bind(this); - operations$a.notifyChannelsChanged.execute = this.handleChannelsChanged.bind(this); - operations$a.setZoomFactor.execute = this.handleSetZoomFactor.bind(this); - operations$a.zoomFactorChange.execute = this.handleZoomFactorChanged.bind(this); - operations$a.refresh.execute = this.handleRefresh.bind(this); - operations$a.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$a); - } - my() { - return Object.assign({}, this.me); - } - onWindowAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"); - } - return this.registry.add("window-added", callback); - } - onWindowRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"); - } - return this.registry.add("window-removed", callback); - } - onWindowGotFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-got-focus", callback); - } - onWindowLostFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-lost-focus", callback); - } - async sayHello() { - const helloSuccess = await this.bridge.send("windows", operations$a.windowHello, { windowId: this.publicWindowId }); - return helloSuccess; - } - async registerWithPlatform() { - const { windows, isWorkspaceFrame } = await this.sayHello(); - this.isWorkspaceFrame = isWorkspaceFrame; - this.logger.trace("the platform responded to the hello message"); - if (!this.isWorkspaceFrame && this.publicWindowId) { - this.logger.trace("i am not treated as a workspace frame, setting my window"); - const myWindow = windows.find((w) => w.windowId === this.publicWindowId); - if (!myWindow) { - const windowsInfo = windows.map(w => `${w.windowId}:${w.name}`).join(", "); - return ioError.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${windowsInfo}`); - } - const myProjection = await this.ioc.buildWebWindow(this.publicWindowId, myWindow.name, this.logger); - this.me = myProjection.api; - this.allWindowProjections.push(myProjection); - } - const currentWindows = await Promise.all(windows - .filter((w) => w.windowId !== this.publicWindowId) - .map((w) => this.ioc.buildWebWindow(w.windowId, w.name, this.logger))); - this.logger.trace("all windows projections are completed, building the list collection"); - this.allWindowProjections.push(...currentWindows); - } - async handleFocusChangeEvent(focusData) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === focusData.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfFocusEvent(focusData.hasFocus); - const keyToExecute = focusData.hasFocus ? "window-got-focus" : "window-lost-focus"; - this.registry.execute(keyToExecute, foundProjection.api); - } - async handleWindowAdded(data) { - if (this.allWindowProjections.some((projection) => projection.id === data.windowId)) { - return; - } - const webWindowProjection = await this.ioc.buildWebWindow(data.windowId, data.name, this.logger); - this.allWindowProjections.push(webWindowProjection); - this.registry.execute("window-added", webWindowProjection.api); - } - async handleWindowRemoved(data) { - const removed = this.allWindowProjections.find((w) => w.id === data.windowId); - if (!removed) { - return; - } - this.allWindowProjections = this.allWindowProjections.filter((w) => w.id !== data.windowId); - removed.model.clean(); - this.registry.execute("window-removed", removed.api); - } - async handleGetBounds() { - if (!this.me && !this.isWorkspaceFrame) { - return ioError.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.isWorkspaceFrame ? "noop" : this.me.id, - bounds: { - top: window.screenTop, - left: window.screenLeft, - width: window.innerWidth, - height: window.innerHeight - } - }; - } - async handleGetTitle() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - title: document.title - }; - } - async handleGetUrl() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - url: window.location.href - }; - } - async handleMoveResize(config) { - const targetTop = typeof config.top === "number" ? config.top : - config.relative ? 0 : window.screenTop; - const targetLeft = typeof config.left === "number" ? config.left : - config.relative ? 0 : window.screenLeft; - const targetHeight = typeof config.height === "number" ? config.height : - config.relative ? 0 : window.innerHeight; - const targetWidth = typeof config.width === "number" ? config.width : - config.relative ? 0 : window.innerWidth; - const moveMethod = config.relative ? window.moveBy : window.moveTo; - const resizeMethod = config.relative ? window.resizeBy : window.resizeTo; - moveMethod(targetLeft, targetTop); - resizeMethod(targetWidth, targetHeight); - } - async handleSetTitle(config) { - document.title = config.title; - } - async initializeFocusTracking() { - if (this.isWorkspaceFrame) { - this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame"); - return; - } - try { - await this.bridge.send("windows", commonOperations.operationCheck, { operation: "focusChange" }); - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client."); - return; - } - const hasFocus = document.hasFocus(); - await this.transmitFocusChange(true); - if (!hasFocus) { - await this.transmitFocusChange(false); - } - this.defineEventListeners(); - } - processFocusEvent() { - const hasFocus = document.hasFocus(); - this.transmitFocusChange(hasFocus); - } - waitForWindowAdded(windowId) { - const foundWindow = this.allWindowProjections.find((projection) => projection.id === windowId); - if (foundWindow) { - return Promise.resolve(foundWindow.api); - } - return PromisePlus$1((resolve) => { - const unsubscribe = this.onWindowAdded((addedWindow) => { - if (addedWindow.id === windowId) { - unsubscribe(); - resolve(addedWindow); - } - }); - }, 30000, `Timed out waiting for ${windowId} to be announced`); - } - async transmitFocusChange(hasFocus) { - const eventData = { - windowId: this.me?.id || `iframe-${this.instanceId}`, - hasFocus - }; - if (this.me) { - this.me.isFocused = hasFocus; - } - await this.bridge.send("windows", operations$a.focusChange, eventData); - } - defineEventListeners() { - this.focusEventHandler = this.processFocusEvent.bind(this); - document.addEventListener("visibilityChange", this.focusEventHandler); - window.addEventListener("focus", this.focusEventHandler); - window.addEventListener("blur", this.focusEventHandler); - } - async handleGetChannel() { - if (!this.me) { - return ioError.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe"); - } - const channel = this.channelsController.my(); - return { - ...(channel ? { channel } : {}), - }; - } - async handleRefresh() { - if (!this.me) { - return ioError.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe"); - } - setTimeout(() => { - window.location.reload(); - }, 0); - } - async handleChannelsChanged(data) { - const windowProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - windowProjection?.model.processChannelsChangedEvent(data.channelNames); - } - async handleSetZoomFactor(config) { - if (!this.me) { - return ioError.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe"); - } - document.body.style.zoom = `${ZOOM_FACTORS[config.factorIndex]}%`; - } - async handleZoomFactorChanged(data) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfZoomFactorChangedEvent(data.factorIndex); - } - } - - const GlueWebPlatformControlName = "T42.Web.Platform.Control"; - const GlueWebPlatformStreamName = "T42.Web.Platform.Stream"; - const GlueClientControlName = "T42.Web.Client.Control"; - const GlueCorePlusThemesStream = "T42.Core.Plus.Themes.Stream"; - - class GlueBridge { - coreGlue; - communicationId; - platformMethodTimeoutMs = 10000; - controllers; - sub; - running; - constructor(coreGlue, communicationId) { - this.coreGlue = coreGlue; - this.communicationId = communicationId; - } - get contextLib() { - return this.coreGlue.contexts; - } - get interopInstance() { - return this.coreGlue.interop.instance.instance; - } - async stop() { - this.running = false; - this.sub.close(); - await this.coreGlue.interop.unregister(GlueClientControlName); - } - async start(controllers) { - this.running = true; - this.controllers = controllers; - await Promise.all([ - this.checkWaitMethod(GlueWebPlatformControlName), - this.checkWaitMethod(GlueWebPlatformStreamName) - ]); - const systemId = this.communicationId; - const [sub] = await Promise.all([ - this.coreGlue.interop.subscribe(GlueWebPlatformStreamName, systemId ? { target: { instance: this.communicationId } } : undefined), - this.coreGlue.interop.registerAsync(GlueClientControlName, (args, _, success, error) => this.passMessageController(args, success, error)) - ]); - this.sub = sub; - this.sub.onData((pkg) => this.passMessageController(pkg.data)); - } - getInteropInstance(windowId) { - const result = this.coreGlue.interop.servers().find((s) => s.windowId && s.windowId === windowId); - return { - application: result?.application, - applicationName: result?.applicationName, - peerId: result?.peerId, - instance: result?.instance, - windowId: result?.windowId - }; - } - async send(domain, operation, operationData, options, webOptions) { - if (operation.dataDecoder) { - try { - operation.dataDecoder.runWithException(operationData); - } - catch (error) { - return ioError.raiseError(`Unexpected Web->Platform outgoing validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - } - const operationSupported = webOptions?.includeOperationCheck ? - (await this.checkOperationSupported(domain, operation)).isSupported : - true; - if (!operationSupported) { - return ioError.raiseError(`Cannot complete operation: ${operation.name} for domain: ${domain} because this client is connected to a platform which does not support it`); - } - try { - const operationResult = await this.transmitMessage(domain, operation, operationData, options); - if (operation.resultDecoder) { - operation.resultDecoder.runWithException(operationResult); - } - return operationResult; - } - catch (error) { - if (error?.kind) { - return ioError.raiseError(`Unexpected Web<-Platform incoming validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - return ioError.raiseError(error); - } - } - async createNotificationsSteam() { - const streamExists = this.coreGlue.interop.methods().some((method) => method.name === GlueCorePlusThemesStream); - if (!streamExists) { - return ioError.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus."); - } - return this.coreGlue.interop.subscribe(GlueCorePlusThemesStream, this.communicationId ? { target: { instance: this.communicationId } } : undefined); - } - async checkOperationSupported(domain, operation) { - try { - const result = await this.send(domain, commonOperations.operationCheck, { operation: operation.name }); - return result; - } - catch (error) { - return { isSupported: false }; - } - } - checkWaitMethod(name) { - return PromisePlus$1((resolve) => { - const hasMethod = this.coreGlue.interop.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = this.communicationId ? - method.getServers().some((server) => server.instance === this.communicationId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - return resolve(); - } - const unSub = this.coreGlue.interop.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = this.communicationId ? - server.instance === this.communicationId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }, this.platformMethodTimeoutMs, `Cannot initiate Glue Web, because a system method's discovery timed out: ${name}`); - } - passMessageController(args, success, error) { - const decodeResult = libDomainDecoder.run(args.domain); - if (!decodeResult.ok) { - if (error) { - error(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(decodeResult.error)}`); - } - return; - } - const domain = decodeResult.result; - this.controllers[domain] - .handleBridgeMessage(args) - .then((resolutionData) => { - if (success) { - success(resolutionData); - } - }) - .catch((err) => { - if (error) { - error(err); - } - console.warn(err); - }); - } - async transmitMessage(domain, operation, data, options) { - const messageData = { domain, data, operation: operation.name }; - let invocationResult; - const baseErrorMessage = `Internal Platform Communication Error. Attempted operation: ${JSON.stringify(operation.name)} with data: ${JSON.stringify(data)}. `; - const systemId = this.communicationId; - try { - if (!this.running) { - throw new Error("Cannot send a control message, because the platform shut down"); - } - invocationResult = await this.coreGlue.interop.invoke(GlueWebPlatformControlName, messageData, systemId ? { instance: this.communicationId } : undefined, options); - if (!invocationResult) { - throw new Error("Received unsupported result from the platform - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from the platform - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - } - - const operations$9 = { - appHello: { name: "appHello", dataDecoder: windowHelloDecoder, resultDecoder: appHelloSuccessDecoder }, - appDirectoryStateChange: { name: "appDirectoryStateChange", dataDecoder: appDirectoryStateChangeDecoder }, - instanceStarted: { name: "instanceStarted", dataDecoder: instanceDataDecoder }, - instanceStopped: { name: "instanceStopped", dataDecoder: instanceDataDecoder }, - applicationStart: { name: "applicationStart", dataDecoder: applicationStartConfigDecoder, resultDecoder: instanceDataDecoder }, - instanceStop: { name: "instanceStop", dataDecoder: basicInstanceDataDecoder }, - import: { name: "import" }, - remove: { name: "remove", dataDecoder: appRemoveConfigDecoder }, - export: { name: "export", resultDecoder: appsExportOperationDecoder }, - clear: { name: "clear" }, - operationCheck: { name: "operationCheck" } - }; - - class AppManagerController { - me; - supportedOperationsNames = []; - baseApplicationsTimeoutMS = 60000; - appImportTimeoutMS = 20; - registry = CallbackRegistryFactory$1(); - ioc; - bridge; - publicWindowId; - applications = []; - instances = []; - platformRegistration; - logger; - channelsController; - interop; - initialChannelId; - handlePlatformShutdown() { - this.registry.clear(); - this.applications = []; - this.instances = []; - delete this.me; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("appManger.controller.web"); - this.logger.trace("starting the web appManager controller"); - this.publicWindowId = ioc.publicWindowId; - this.addOperationsExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.interop = coreGlue.interop; - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning"); - const api = this.toApi(); - coreGlue.appManager = api; - } - async postStart() { - if (!this.initialChannelId) { - return; - } - await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(appManagerOperationTypesDecoder, args.operation); - const operation = operations$9[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStarted requires a single argument of type function"); - } - return this.registry.add("instance-started", callback, this.instances); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStopped requires a single argument of type function"); - } - return this.registry.add("instance-stopped", callback); - } - async startApplication(appName, context, options) { - const channels = await this.channelsController.all(); - if (options?.channelId && !channels.includes(options.channelId)) { - return ioError.raiseError(`The channel with name "${options.channelId}" doesn't exist!`); - } - const startOptions = { - name: appName, - waitForAGMReady: options?.waitForAGMReady ?? true, - context, - top: options?.top, - left: options?.left, - width: options?.width, - height: options?.height, - relativeTo: options?.relativeTo, - relativeDirection: options?.relativeDirection, - id: options?.reuseId, - forceChromeTab: options?.forceTab, - layoutComponentId: options?.layoutComponentId, - channelId: options?.channelId, - startReason: { - originApp: { - name: this.me?.application.name, - interopInstance: this.interop.instance.instance - } - } - }; - if (options?.originIntentRequest) { - startOptions.startReason.intentRequest = options.originIntentRequest; - } - const openResult = await this.bridge.send("appManager", operations$9.applicationStart, startOptions); - const app = this.applications.find((a) => a.name === openResult.applicationName); - return this.ioc.buildInstance(openResult, app); - } - getApplication(name) { - const verifiedName = runDecoderWithIOError(nonEmptyStringDecoder$2, name); - return this.applications.find((app) => app.name === verifiedName); - } - getInstances() { - return this.instances.slice(); - } - onAppAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppAdded requires a single argument of type function"); - } - return this.registry.add("application-added", callback, this.applications); - } - onAppRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppRemoved requires a single argument of type function"); - } - return this.registry.add("application-removed", callback); - } - toApi() { - const api = { - myInstance: this.me, - inMemory: { - import: this.importApps.bind(this), - remove: this.remove.bind(this), - export: this.exportApps.bind(this), - clear: this.clear.bind(this) - }, - application: this.getApplication.bind(this), - applications: this.getApplications.bind(this), - instances: this.getInstances.bind(this), - onAppAdded: this.onAppAdded.bind(this), - onAppChanged: this.onAppChanged.bind(this), - onAppRemoved: this.onAppRemoved.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - return api; - } - addOperationsExecutors() { - operations$9.appDirectoryStateChange.execute = this.handleAppDirectoryStateChange.bind(this); - operations$9.instanceStarted.execute = this.handleInstanceStartedMessage.bind(this); - operations$9.instanceStopped.execute = this.handleInstanceStoppedMessage.bind(this); - operations$9.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$9); - } - async handleAppDirectoryStateChange(data) { - data.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)); - data.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)); - data.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this)); - } - onAppChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppChanged requires a single argument of type function"); - } - return this.registry.add("application-changed", callback); - } - async handleApplicationAddedMessage(appData) { - if (this.applications.some((app) => app.name === appData.name)) { - return; - } - const app = await this.ioc.buildApplication(appData, []); - const instances = this.instances.filter((instance) => instance.application.name === app.name); - app.instances.push(...instances); - this.applications.push(app); - this.registry.execute("application-added", app); - } - async handleApplicationRemovedMessage(appData) { - const appIndex = this.applications.findIndex((app) => app.name === appData.name); - if (appIndex < 0) { - return; - } - const app = this.applications[appIndex]; - this.applications.splice(appIndex, 1); - this.registry.execute("application-removed", app); - } - async handleApplicationChangedMessage(appData) { - const app = this.applications.find((app) => app.name === appData.name); - if (!app) { - return this.handleApplicationAddedMessage(appData); - } - app.title = appData.title; - app.version = appData.version; - app.icon = appData.icon; - app.caption = appData.caption; - app.userProperties = appData.userProperties; - this.registry.execute("application-changed", app); - } - async handleInstanceStartedMessage(instanceData) { - if (this.instances.some((instance) => instance.id === instanceData.id)) { - return; - } - const application = this.applications.find((app) => app.name === instanceData.applicationName); - if (!application) { - return ioError.raiseError(`Cannot add instance: ${instanceData.id}, because there is no application definition associated with it`); - } - const instance = this.ioc.buildInstance(instanceData, application); - this.instances.push(instance); - application.instances.push(instance); - this.registry.execute("instance-started", instance); - } - async handleInstanceStoppedMessage(instanceData) { - const instance = this.instances.find((i) => i.id === instanceData.id); - if (instance) { - const instIdx = this.instances.findIndex((inst) => inst.id === instanceData.id); - this.instances.splice(instIdx, 1); - } - const application = this.applications.find((app) => app.instances.some((inst) => inst.id === instanceData.id)); - if (application) { - const instIdxApps = application.instances.findIndex((inst) => inst.id === instanceData.id); - application.instances.splice(instIdxApps, 1); - } - if (!instance) { - return; - } - this.registry.execute("instance-stopped", instance); - } - async importApps(definitions, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(definitions)) { - return ioError.raiseError("Import must be called with an array of definitions"); - } - if (definitions.length > 10000) { - return ioError.raiseError("Cannot import more than 10000 app definitions in Glue42 Core."); - } - const parseResult = definitions.reduce((soFar, definition) => { - const { isValid, error } = this.isValidDefinition(definition); - if (!isValid) { - soFar.invalid.push({ app: definition?.name, error: error ?? `Provided definition is invalid ${JSON.stringify(definition)}` }); - } - else { - soFar.valid.push(definition); - } - return soFar; - }, { valid: [], invalid: [] }); - const responseTimeout = this.baseApplicationsTimeoutMS + this.appImportTimeoutMS * parseResult.valid.length; - await this.bridge.send("appManager", operations$9.import, { definitions: parseResult.valid, mode }, { methodResponseTimeoutMs: responseTimeout }); - return { - imported: parseResult.valid.map((valid) => valid.name), - errors: parseResult.invalid - }; - } - isValidDefinition(definition) { - const isFdc3V2Definition = definition?.appId && definition?.details; - if (isFdc3V2Definition) { - const decodeResult = decoders.fdc3.v2DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v2 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const isFdc3V1Definition = definition?.appId && definition?.manifest; - if (isFdc3V1Definition) { - const decodeResult = decoders.fdc3.v1DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v1 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const decodeResult = applicationDefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("appManager", operations$9.remove, { name }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async clear() { - await this.bridge.send("appManager", operations$9.clear, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async exportApps() { - const response = await this.bridge.send("appManager", operations$9.export, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - return response.definitions; - } - getApplications() { - return this.applications.slice(); - } - async registerWithPlatform() { - const result = await this.bridge.send("appManager", operations$9.appHello, { windowId: this.publicWindowId }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - this.logger.trace("the platform responded to the hello message with a full list of apps"); - this.applications = await Promise.all(result.apps.map((app) => this.ioc.buildApplication(app, app.instances))); - this.instances = this.applications.reduce((instancesSoFar, app) => { - instancesSoFar.push(...app.instances); - return instancesSoFar; - }, []); - this.me = this.findMyInstance(); - this.logger.trace(`all applications were parsed and saved. I am ${this.me ? "NOT a" : "a"} valid instance`); - this.initialChannelId = result.initialChannelId; - } - findMyInstance() { - for (const app of this.applications) { - const foundInstance = app.instances.find((instance) => instance.id === this.publicWindowId); - if (foundInstance) { - return foundInstance; - } - } - return undefined; - } - } - - class InstanceModel { - data; - bridge; - application; - me; - myCtxKey; - constructor(data, bridge, application) { - this.data = data; - this.bridge = bridge; - this.application = application; - this.myCtxKey = `___instance___${this.data.id}`; - } - toApi() { - const agm = this.bridge.getInteropInstance(this.data.id); - const api = { - id: this.data.id, - agm, - application: this.application, - stop: this.stop.bind(this), - getContext: this.getContext.bind(this) - }; - this.me = Object.freeze(api); - return this.me; - } - async getContext() { - return this.bridge.contextLib.get(this.myCtxKey); - } - async stop() { - await this.bridge.send("appManager", operations$9.instanceStop, { id: this.data.id }); - } - } - - class ApplicationModel { - data; - instances; - controller; - me; - constructor(data, instances, controller) { - this.data = data; - this.instances = instances; - this.controller = controller; - } - toApi() { - const api = { - name: this.data.name, - title: this.data.title, - version: this.data.version, - icon: this.data.icon, - caption: this.data.caption, - userProperties: this.data.userProperties, - instances: this.instances, - start: this.start.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - this.me = api; - return this.me; - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStarted((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStopped((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - async start(context, options) { - const verifiedContext = runDecoderWithIOError(startApplicationContextDecoder, context); - const verifiedOptions = runDecoderWithIOError(startApplicationOptionsDecoder, options); - return this.controller.startApplication(this.data.name, verifiedContext, verifiedOptions); - } - } - - const operations$8 = { - layoutAdded: { name: "layoutAdded", dataDecoder: glueLayoutDecoder }, - layoutChanged: { name: "layoutChanged", dataDecoder: glueLayoutDecoder }, - layoutRemoved: { name: "layoutRemoved", dataDecoder: glueLayoutDecoder }, - layoutRestored: { name: "layoutRestored", dataDecoder: glueLayoutDecoder }, - defaultLayoutChanged: { name: "defaultLayoutChanged", dataDecoder: defaultGlobalChangedDecoder }, - layoutRenamed: { name: "layoutRenamed", dataDecoder: renamedLayoutNotificationDecoder }, - get: { name: "get", dataDecoder: simpleLayoutConfigDecoder, resultDecoder: optionalSimpleLayoutResult }, - getAll: { name: "getAll", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsSummariesResultDecoder }, - export: { name: "export", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsFullConfigDecoder }, - import: { name: "import", dataDecoder: layoutsImportConfigDecoder }, - remove: { name: "remove", dataDecoder: simpleLayoutConfigDecoder }, - rename: { name: "rename", dataDecoder: renameLayoutConfigDecoder, resultDecoder: layoutResultDecoder }, - save: { name: "save", dataDecoder: saveLayoutConfigDecoder, resultDecoder: simpleLayoutResultDecoder }, - restore: { name: "restore", dataDecoder: restoreLayoutConfigDecoder }, - clientSaveRequest: { name: "clientSaveRequest", dataDecoder: platformSaveRequestConfigDecoder, resultDecoder: saveRequestClientResponseDecoder }, - getGlobalPermissionState: { name: "getGlobalPermissionState", resultDecoder: permissionStateResultDecoder }, - requestGlobalPermission: { name: "requestGlobalPermission", resultDecoder: simpleAvailabilityResultDecoder }, - checkGlobalActivated: { name: "checkGlobalActivated", resultDecoder: simpleAvailabilityResultDecoder }, - getDefaultGlobal: { name: "getDefaultGlobal", resultDecoder: optionalSimpleLayoutResult }, - setDefaultGlobal: { name: "setDefaultGlobal", dataDecoder: setDefaultGlobalConfigDecoder }, - clearDefaultGlobal: { name: "clearDefaultGlobal" }, - getCurrent: { name: "getCurrent", resultDecoder: optionalSimpleLayoutResult }, - updateMetadata: { name: "updateMetadata", dataDecoder: updateLayoutMetadataConfigDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class LayoutsController { - supportedOperationsNames = []; - defaultLayoutRestoreTimeoutMS = 120000; - registry = CallbackRegistryFactory$1(); - bridge; - logger; - windowsController; - saveRequestSubscription; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("layouts.controller.web"); - this.logger.trace("starting the web layouts controller"); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.addOperationsExecutors(); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"); - coreGlue.layouts = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(layoutsOperationTypesDecoder, args.operation); - const operation = operations$8[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - get: this.get.bind(this), - getAll: this.getAll.bind(this), - getCurrentLayout: this.getCurrentLayout.bind(this), - export: this.exportLayouts.bind(this), - import: this.importLayouts.bind(this), - save: this.save.bind(this), - restore: this.restore.bind(this), - remove: this.remove.bind(this), - onAdded: this.onAdded.bind(this), - onChanged: this.onChanged.bind(this), - onRemoved: this.onRemoved.bind(this), - onDefaultGlobalChanged: this.onDefaultGlobalChanged.bind(this), - onSaveRequested: this.subscribeOnSaveRequested.bind(this), - getMultiScreenPermissionState: this.getGlobalPermissionState.bind(this), - requestMultiScreenPermission: this.requestGlobalPermission.bind(this), - getGlobalTypeState: this.checkGlobalActivated.bind(this), - getDefaultGlobal: this.getDefaultGlobal.bind(this), - setDefaultGlobal: this.setDefaultGlobal.bind(this), - clearDefaultGlobal: this.clearDefaultGlobal.bind(this), - rename: this.rename.bind(this), - onRenamed: this.onRenamed.bind(this), - onRestored: this.onRestored.bind(this), - updateMetadata: this.updateMetadata.bind(this) - }; - return Object.freeze(api); - } - addOperationsExecutors() { - operations$8.layoutAdded.execute = this.handleOnAdded.bind(this); - operations$8.layoutChanged.execute = this.handleOnChanged.bind(this); - operations$8.layoutRemoved.execute = this.handleOnRemoved.bind(this); - operations$8.layoutRenamed.execute = this.handleOnRenamed.bind(this); - operations$8.layoutRestored.execute = this.handleOnRestored.bind(this); - operations$8.defaultLayoutChanged.execute = this.handleOnDefaultChanged.bind(this); - operations$8.clientSaveRequest.execute = this.handleSaveRequest.bind(this); - operations$8.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$8); - } - async get(name, type) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.get, { name, type }); - return result.layout; - } - async getCurrentLayout() { - const result = await this.bridge.send("layouts", operations$8.getCurrent, undefined); - return result.layout; - } - async getAll(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.getAll, { type }); - return result.summaries; - } - async exportLayouts(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.export, { type }); - return result.layouts; - } - async importLayouts(layouts, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(layouts)) { - return ioError.raiseError("Import must be called with an array of layouts"); - } - if (layouts.length > 1000) { - return ioError.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core."); - } - const parseResult = layouts.reduce((soFar, layout) => { - const decodeResult = glueLayoutDecoder.run(layout); - if (decodeResult.ok) { - soFar.valid.push(layout); - } - else { - this.logger.warn(`A layout with name: ${layout.name} was not imported, because of error: ${JSON.stringify(decodeResult.error)}`); - } - return soFar; - }, { valid: [] }); - const layoutsToImport = layouts.filter((layout) => parseResult.valid.some((validLayout) => validLayout.name === layout.name)); - await this.bridge.send("layouts", operations$8.import, { layouts: layoutsToImport, mode }); - } - async save(layout) { - runDecoderWithIOError(newLayoutOptionsDecoder, layout); - const saveResult = await this.bridge.send("layouts", operations$8.save, { layout }); - return saveResult.layout; - } - async restore(options) { - runDecoderWithIOError(restoreOptionsDecoder, options); - const invocationTimeout = options.timeout ? options.timeout * 2 : this.defaultLayoutRestoreTimeoutMS; - await this.bridge.send("layouts", operations$8.restore, { layout: options }, { methodResponseTimeoutMs: invocationTimeout }); - } - async remove(type, name) { - runDecoderWithIOError(layoutTypeDecoder, type); - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.remove, { type, name }); - } - async handleSaveRequest(config) { - const response = {}; - if (this.saveRequestSubscription) { - try { - const onSaveRequestResponse = this.saveRequestSubscription(config); - response.windowContext = onSaveRequestResponse?.windowContext; - } - catch (error) { - this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(error)}`); - } - } - return response; - } - async getGlobalPermissionState() { - const requestResult = await this.bridge.send("layouts", operations$8.getGlobalPermissionState, undefined); - return requestResult; - } - async requestGlobalPermission() { - const currentState = (await this.getGlobalPermissionState()).state; - if (currentState === "denied") { - return { permissionGranted: false }; - } - if (currentState === "granted") { - return { permissionGranted: true }; - } - const myWindow = this.windowsController.my(); - const globalNamespace = window.glue42core || window.iobrowser; - const amIWorkspaceFrame = globalNamespace.isPlatformFrame; - if (myWindow.name !== "Platform" && !amIWorkspaceFrame) { - return ioError.raiseError("Cannot request permission for multi-window placement from any app other than the Platform."); - } - const requestResult = await this.bridge.send("layouts", operations$8.requestGlobalPermission, undefined, { methodResponseTimeoutMs: 180000 }); - return { permissionGranted: requestResult.isAvailable }; - } - async checkGlobalActivated() { - const requestResult = await this.bridge.send("layouts", operations$8.checkGlobalActivated, undefined); - return { activated: requestResult.isAvailable }; - } - async getDefaultGlobal() { - const requestResult = await this.bridge.send("layouts", operations$8.getDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - return requestResult.layout; - } - async setDefaultGlobal(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.setDefaultGlobal, { name }, undefined, { includeOperationCheck: true }); - } - async clearDefaultGlobal() { - await this.bridge.send("layouts", operations$8.clearDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - } - async rename(layout, newName) { - runDecoderWithIOError(glueLayoutDecoder, layout); - runDecoderWithIOError(nonEmptyStringDecoder$2, newName); - const result = await this.bridge.send("layouts", operations$8.rename, { layout, newName }, undefined, { includeOperationCheck: true }); - return result; - } - async updateMetadata(layout) { - runDecoderWithIOError(glueLayoutDecoder, layout); - await this.bridge.send("layouts", operations$8.updateMetadata, { layout }, undefined, { includeOperationCheck: true }); - } - onAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"); - } - this.exportLayouts("Global").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - this.exportLayouts("Workspace").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - return this.registry.add(operations$8.layoutAdded.name, callback); - } - onChanged(callback) { - return this.registry.add(operations$8.layoutChanged.name, callback); - } - onDefaultGlobalChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"); - } - this.getDefaultGlobal().then((layout) => callback(layout ? { name: layout.name } : undefined)).catch(() => { }); - return this.registry.add(operations$8.defaultLayoutChanged.name, callback); - } - onRemoved(callback) { - return this.registry.add(operations$8.layoutRemoved.name, callback); - } - onRenamed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRenamed.name, callback); - } - onRestored(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRestored.name, callback); - } - subscribeOnSaveRequested(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."); - } - if (this.saveRequestSubscription) { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."); - } - this.saveRequestSubscription = callback; - return () => { - delete this.saveRequestSubscription; - }; - } - async handleOnAdded(layout) { - this.registry.execute(operations$8.layoutAdded.name, layout); - } - async handleOnChanged(layout) { - this.registry.execute(operations$8.layoutChanged.name, layout); - } - async handleOnDefaultChanged(layout) { - this.registry.execute(operations$8.defaultLayoutChanged.name, layout); - } - async handleOnRemoved(layout) { - this.registry.execute(operations$8.layoutRemoved.name, layout); - } - async handleOnRestored(layout) { - this.registry.execute(operations$8.layoutRestored.name, layout); - } - async handleOnRenamed(renamedData) { - const { prevName, ...layout } = renamedData; - this.registry.execute(operations$8.layoutRenamed.name, layout, { name: prevName }); - } - } - - const operations$7 = { - raiseNotification: { name: "raiseNotification", dataDecoder: raiseNotificationDecoder, resultDecoder: raiseNotificationResultDecoder }, - requestPermission: { name: "requestPermission", resultDecoder: permissionRequestResultDecoder }, - notificationShow: { name: "notificationShow", dataDecoder: notificationEventPayloadDecoder }, - notificationClick: { name: "notificationClick", dataDecoder: notificationEventPayloadDecoder }, - getPermission: { name: "getPermission", resultDecoder: permissionQueryResultDecoder }, - list: { name: "list", resultDecoder: allNotificationsDataDecoder }, - notificationRaised: { name: "notificationRaised", dataDecoder: simpleNotificationDataDecoder }, - notificationClosed: { name: "notificationClosed", dataDecoder: simpleNotificationSelectDecoder }, - click: { name: "click" }, - clear: { name: "clear" }, - clearAll: { name: "clearAll" }, - clearOld: { name: "clearOld" }, - configure: { name: "configure", dataDecoder: notificationsConfigurationProtocolDecoder }, - getConfiguration: { name: "getConfiguration", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - getActiveCount: { name: "getActiveCount", resultDecoder: activeNotificationsCountChangeDecoder }, - configurationChanged: { name: "configurationChanged", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - setState: { name: "setState", dataDecoder: notificationSetStateRequestDecoder }, - activeCountChange: { name: "activeCountChange", resultDecoder: activeNotificationsCountChangeDecoder }, - stateChange: { name: "stateChange", resultDecoder: notificationSetStateRequestDecoder }, - operationCheck: { name: "operationCheck" } - }; - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet$1 = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid$1 = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet$1[(Math.random() * 64) | 0]; - } - return id - }; - - class NotificationsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - bridge; - notificationsSettings; - notifications = {}; - coreGlue; - buildNotificationFunc; - notificationsConfiguration; - notificationsActiveCount = 0; - handlePlatformShutdown() { - this.notifications = {}; - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("notifications.controller.web"); - this.logger.trace("starting the web notifications controller"); - this.bridge = ioc.bridge; - this.coreGlue = coreGlue; - this.notificationsSettings = ioc.config.notifications; - this.buildNotificationFunc = ioc.buildNotification; - this.notificationsConfiguration = await this.getConfiguration(); - this.notificationsActiveCount = await this.getActiveCount(); - const api = this.toApi(); - this.addOperationExecutors(); - coreGlue.notifications = api; - this.logger.trace("notifications are ready"); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(notificationsOperationTypesDecoder, args.operation); - const operation = operations$7[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - requestPermission: this.requestPermission.bind(this), - getPermission: this.getPermission.bind(this), - list: this.list.bind(this), - onRaised: this.onRaised.bind(this), - onClosed: this.onClosed.bind(this), - click: this.click.bind(this), - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearOld: this.clearOld.bind(this), - configure: this.configure.bind(this), - getConfiguration: this.getConfiguration.bind(this), - getFilter: this.getFilter.bind(this), - setFilter: this.setFilter.bind(this), - setState: this.setState.bind(this), - onConfigurationChanged: this.onConfigurationChanged.bind(this), - onActiveCountChanged: this.onActiveCountChanged.bind(this), - onCounterChanged: this.onActiveCountChanged.bind(this), - onStateChanged: this.onStateChanged.bind(this) - }; - return Object.freeze(api); - } - async getPermission() { - const queryResult = await this.bridge.send("notifications", operations$7.getPermission, undefined); - return queryResult.permission; - } - async requestPermission() { - const permissionResult = await this.bridge.send("notifications", operations$7.requestPermission, undefined); - return permissionResult.permissionGranted; - } - async raise(options) { - const settings = runDecoderWithIOError(glue42NotificationOptionsDecoder, options); - settings.showToast = typeof settings.showToast === "boolean" ? settings.showToast : true; - settings.showInPanel = typeof settings.showInPanel === "boolean" ? settings.showInPanel : true; - const permissionGranted = await this.requestPermission(); - if (!permissionGranted) { - return ioError.raiseError("Cannot raise the notification, because the user has declined the permission request"); - } - const id = nanoid$1(10); - const raiseResult = await this.bridge.send("notifications", operations$7.raiseNotification, { settings, id }); - const notification = this.buildNotificationFunc(raiseResult.settings, id); - this.notifications[id] = notification; - return notification; - } - async list() { - const bridgeResponse = await this.bridge.send("notifications", operations$7.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.notifications; - } - onRaised(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onRaised expects a callback of type function"); - } - return this.registry.add("notification-raised", callback); - } - onClosed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onClosed expects a callback of type function"); - } - return this.registry.add("notification-closed", callback); - } - async click(id, action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - if (action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, action); - } - await this.bridge.send("notifications", operations$7.click, { id, action }, undefined, { includeOperationCheck: true }); - } - async clear(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - await this.bridge.send("notifications", operations$7.clear, { id }, undefined, { includeOperationCheck: true }); - } - async clearAll() { - await this.bridge.send("notifications", operations$7.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearOld() { - await this.bridge.send("notifications", operations$7.clearOld, undefined, undefined, { includeOperationCheck: true }); - } - async configure(config) { - const verifiedConfig = runDecoderWithIOError(notificationsConfigurationDecoder, config); - await this.bridge.send("notifications", operations$7.configure, { configuration: verifiedConfig }, undefined, { includeOperationCheck: true }); - } - async getConfiguration() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration; - } - async getActiveCount() { - try { - const response = await this.bridge.send("notifications", operations$7.getActiveCount, undefined, undefined, { includeOperationCheck: true }); - return response.count; - } - catch (error) { - console.warn("Failed to get accurate active notifications count", error); - return 0; - } - } - async getFilter() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration.sourceFilter; - } - async setFilter(filter) { - const verifiedFilter = runDecoderWithIOError(notificationFilterDecoder, filter); - await this.bridge.send("notifications", operations$7.configure, { configuration: { sourceFilter: verifiedFilter } }, undefined, { includeOperationCheck: true }); - return verifiedFilter; - } - async setState(id, state) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - runDecoderWithIOError(notificationStateDecoder, state); - await this.bridge.send("notifications", operations$7.setState, { id, state }, undefined, { includeOperationCheck: true }); - } - onConfigurationChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"); - } - setTimeout(() => callback(this.notificationsConfiguration), 0); - return this.registry.add("notifications-config-changed", callback); - } - onActiveCountChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"); - } - setTimeout(() => callback({ count: this.notificationsActiveCount }), 0); - return this.registry.add("notifications-active-count-changed", callback); - } - onStateChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"); - } - return this.registry.add("notification-state-changed", callback); - } - addOperationExecutors() { - operations$7.notificationShow.execute = this.handleNotificationShow.bind(this); - operations$7.notificationClick.execute = this.handleNotificationClick.bind(this); - operations$7.notificationRaised.execute = this.handleNotificationRaised.bind(this); - operations$7.notificationClosed.execute = this.handleNotificationClosed.bind(this); - operations$7.configurationChanged.execute = this.handleConfigurationChanged.bind(this); - operations$7.activeCountChange.execute = this.handleActiveCountChanged.bind(this); - operations$7.stateChange.execute = this.handleNotificationStateChanged.bind(this); - operations$7.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$7); - } - async handleConfigurationChanged(data) { - this.notificationsConfiguration = data.configuration; - this.registry.execute("notifications-config-changed", data.configuration); - } - async handleActiveCountChanged(data) { - this.notificationsActiveCount = data.count; - this.registry.execute("notifications-active-count-changed", data); - } - async handleNotificationStateChanged(data) { - this.registry.execute("notification-state-changed", { id: data.id }, data.state); - } - async handleNotificationShow(data) { - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onshow) { - notification.onshow(); - } - } - async handleNotificationClick(data) { - if (!data.action && this.notificationsSettings?.defaultClick) { - this.notificationsSettings.defaultClick(this.coreGlue, data.definition); - } - if (data.action && this.notificationsSettings?.actionClicks?.some((actionDef) => actionDef.action === data.action)) { - const foundHandler = this.notificationsSettings?.actionClicks?.find((actionDef) => actionDef.action === data.action); - foundHandler.handler(this.coreGlue, data.definition); - } - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onclick) { - notification.onclick(); - delete this.notifications[data.id]; - } - } - async handleNotificationRaised(data) { - this.registry.execute("notification-raised", data.notification); - } - async handleNotificationClosed(data) { - this.registry.execute("notification-closed", data); - } - } - - const operations$6 = { - getIntents: { name: "getIntents", resultDecoder: wrappedIntentsDecoder }, - findIntent: { name: "findIntent", dataDecoder: wrappedIntentFilterDecoder, resultDecoder: wrappedIntentsDecoder }, - raise: { name: "raise", dataDecoder: raiseIntentRequestDecoder, resultDecoder: intentResultDecoder }, - filterHandlers: { name: "filterHandlers", dataDecoder: filterHandlersWithResolverConfigDecoder, resultDecoder: filterHandlersResultDecoder }, - getIntentsByHandler: { name: "getIntentsByHandler", dataDecoder: intentHandlerDecoder, resultDecoder: getIntentsResultDecoder } - }; - - const GLUE42_FDC3_INTENTS_METHOD_PREFIX = "Tick42.FDC3.Intents."; - const INTENTS_RESOLVER_APP_NAME = "intentsResolver"; - const DEFAULT_RESOLVER_RESPONSE_TIMEOUT = 60 * 1000; - const ADDITIONAL_BRIDGE_OPERATION_TIMEOUT = 30 * 1000; - const DEFAULT_PICK_HANDLER_BY_TIMEOUT = 90 * 1000; - - class IntentsController { - bridge; - logger; - interop; - appManagerController; - windowsController; - myIntents = new Set(); - prefsController; - uiController; - useIntentsResolverUI = true; - intentsResolverAppName; - intentResolverResponseTimeout = DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - unregisterIntentPromises = []; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("intents.controller.web"); - this.logger.trace("starting the web intents controller"); - this.bridge = ioc.bridge; - this.interop = coreGlue.interop; - this.appManagerController = ioc.appManagerController; - this.windowsController = ioc.windowsController; - this.prefsController = ioc.prefsController; - this.uiController = ioc.uiController; - this.checkIfIntentsResolverIsEnabled(ioc.config); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"); - coreGlue.intents = api; - } - handlePlatformShutdown() { - this.myIntents = new Set(); - this.unregisterIntentPromises = []; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(intentsOperationTypesDecoder, args.operation); - const operation = operations$6[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - all: this.all.bind(this), - addIntentListener: this.addIntentListener.bind(this), - register: this.register.bind(this), - find: this.find.bind(this), - filterHandlers: this.filterHandlers.bind(this), - getIntents: this.getIntentsByHandler.bind(this), - clearSavedHandlers: this.clearSavedHandlers.bind(this), - onHandlerAdded: this.onHandlerAdded.bind(this), - onHandlerRemoved: this.onHandlerRemoved.bind(this) - }; - return api; - } - async raise(request) { - const validatedIntentRequest = runDecoderWithIOError(raiseRequestDecoder, request); - const intentRequest = typeof validatedIntentRequest === "string" - ? { intent: validatedIntentRequest } - : validatedIntentRequest; - await Promise.all(this.unregisterIntentPromises); - if (intentRequest.clearSavedHandler) { - this.logger.trace(`User removes saved handler for intent ${intentRequest.intent}`); - await this.removeRememberedHandler(intentRequest.intent); - } - const resultFromRememberedHandler = await this.checkHandleRaiseWithRememberedHandler(intentRequest); - if (resultFromRememberedHandler) { - return resultFromRememberedHandler; - } - const requestWithResolverInfo = { - intentRequest, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - const methodResponseTimeoutMs = intentRequest.waitUserResponseIndefinitely - ? MAX_SET_TIMEOUT_DELAY - : (intentRequest.timeout || this.intentResolverResponseTimeout) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(request)} and method response timeout of ${methodResponseTimeoutMs}ms`); - const response = await this.bridge.send("intents", operations$6.raise, requestWithResolverInfo, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }); - this.logger.trace(`Raise operation completed with response: ${JSON.stringify(response)}`); - return response; - } - getLegacyResolverConfigByRequest(filter) { - if (filter.handlerFilter) { - return { - enabled: typeof filter.handlerFilter?.openResolver === "boolean" ? filter.handlerFilter?.openResolver : this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout: filter.handlerFilter?.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT - }; - } - const waitResponseTimeout = filter.intentRequest?.waitUserResponseIndefinitely ? MAX_SET_TIMEOUT_DELAY : this.intentResolverResponseTimeout; - return { - enabled: this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout - }; - } - getEmbeddedResolverConfig() { - return { - enabled: this.uiController.isIntentResolverEnabled(), - initialCaller: { instanceId: this.interop.instance.instance } - }; - } - async all() { - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.getIntents, undefined); - return result.intents; - } - addIntentListener(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - let registerPromise; - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - const result = { - unsubscribe: () => { - this.myIntents.delete(intentName); - registerPromise - .then(() => this.interop.unregister(methodName)) - .catch((err) => this.logger.trace(`Unregistration of a method with name ${methodName} failed with reason: ${err}`)); - } - }; - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - registerPromise = this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - return handler(rest); - } - }); - registerPromise.catch(err => { - this.myIntents.delete(intentName); - this.logger.warn(`Registration of a method with name ${methodName} failed with reason: ${err}`); - }); - return result; - } - async register(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - await Promise.all(this.unregisterIntentPromises); - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - try { - await this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - const caller = this.interop.servers().find((server) => server.instance === _initialCallerId); - return handler(rest, caller); - } - }); - } - catch (err) { - this.myIntents.delete(intentName); - return ioError.raiseError(`Registration of a method with name ${methodName} failed with reason: ${JSON.stringify(err)}`); - } - return { - unsubscribe: () => this.unsubscribeIntent(intentName) - }; - } - async find(intentFilter) { - let data = undefined; - if (typeof intentFilter !== "undefined") { - const intentFilterObj = runDecoderWithIOError(findFilterDecoder, intentFilter); - if (typeof intentFilterObj === "string") { - data = { - filter: { - name: intentFilterObj - } - }; - } - else if (typeof intentFilterObj === "object") { - data = { - filter: intentFilterObj - }; - } - } - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.findIntent, data); - return result.intents; - } - onHandlerAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!"); - } - const unOnAppAdded = this.subscribeForAppEvent("onAppAdded", callback); - const unOnServerMethodAdded = this.subscribeForServerMethodEvent("serverMethodAdded", callback); - return () => { - unOnAppAdded(); - unOnServerMethodAdded(); - }; - } - onHandlerRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!"); - } - const unOnAppRemoved = this.subscribeForAppEvent("onAppRemoved", callback); - const unOnServerMethodRemoved = this.subscribeForServerMethodEvent("serverMethodRemoved", callback); - return () => { - unOnAppRemoved(); - unOnServerMethodRemoved(); - }; - } - subscribeForAppEvent(method, callback) { - return this.appManagerController[method]((app) => { - const appIntents = app.userProperties.intents; - if (!appIntents?.length) { - return; - } - appIntents.forEach((intent) => { - const handler = this.buildIntentHandlerFromApp(app, intent); - callback(handler, intent.name); - }); - }); - } - subscribeForServerMethodEvent(eventMethod, callback) { - return this.interop[eventMethod](async ({ server, method }) => { - if (!method.name.startsWith(GLUE42_FDC3_INTENTS_METHOD_PREFIX)) { - return; - } - const intentName = method.name.replace(GLUE42_FDC3_INTENTS_METHOD_PREFIX, ""); - const handler = await this.buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName); - callback(handler, intentName); - }); - } - buildIntentHandlerFromApp(app, intent) { - const handler = { - applicationName: app.name, - type: "app", - applicationDescription: app.caption, - applicationIcon: app.icon, - applicationTitle: app.title, - contextTypes: intent.contexts, - displayName: intent.displayName, - resultType: intent.resultType, - customConfig: intent.customConfig - }; - return handler; - } - async buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName) { - const info = method.flags.intent; - const app = this.appManagerController.getApplication(server.application || server.applicationName); - let title; - if (eventMethod === "serverMethodAdded" && server.windowId) { - title = await (this.windowsController.findById(server.windowId))?.getTitle(); - } - const appIntent = app?.userProperties?.intents?.find((intent) => intent.name === intentName); - const handler = { - applicationName: server.application || server.applicationName || "", - instanceId: server.windowId || server.instance, - type: "instance", - applicationIcon: info?.icon || app?.icon, - applicationTitle: app?.title, - applicationDescription: info?.description || app?.caption, - contextTypes: info?.contextTypes || appIntent?.contexts, - instanceTitle: title, - displayName: info?.displayName || appIntent?.displayName, - resultType: info?.resultType || appIntent?.resultType, - customConfig: info?.customConfig - }; - return handler; - } - async clearSavedHandlers() { - this.logger.trace("Removing all saved handlers from prefs storage for current app"); - await this.prefsController.update({ intents: undefined }); - } - checkIfIntentsResolverIsEnabled(options) { - this.useIntentsResolverUI = typeof options.intents?.enableIntentsResolverUI === "boolean" - ? options.intents.enableIntentsResolverUI - : true; - this.intentsResolverAppName = options.intents?.intentsResolverAppName ?? INTENTS_RESOLVER_APP_NAME; - this.intentResolverResponseTimeout = options.intents?.methodResponseTimeoutMs ?? DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - } - clearUnregistrationPromise(promiseToRemove) { - this.unregisterIntentPromises = this.unregisterIntentPromises.filter(promise => promise !== promiseToRemove); - } - buildInteropMethodName(intentName) { - return `${GLUE42_FDC3_INTENTS_METHOD_PREFIX}${intentName}`; - } - unsubscribeIntent(intentName) { - this.myIntents.delete(intentName); - const methodName = this.buildInteropMethodName(intentName); - const unregisterPromise = this.interop.unregister(methodName); - this.unregisterIntentPromises.push(unregisterPromise); - unregisterPromise - .then(() => { - this.clearUnregistrationPromise(unregisterPromise); - }) - .catch((err) => { - this.logger.error(`Unregistration of a method with name ${methodName} failed with reason: ${err}`); - this.clearUnregistrationPromise(unregisterPromise); - }); - } - async filterHandlers(handlerFilter) { - runDecoderWithIOError(handlerFilterDecoder, handlerFilter); - this.checkIfAtLeastOneFilterIsPresent(handlerFilter); - const embeddedResolverConfig = this.getEmbeddedResolverConfig(); - if (handlerFilter.openResolver && !this.useIntentsResolverUI && !embeddedResolverConfig.enabled) { - return ioError.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled"); - } - const methodResponseTimeoutMs = (handlerFilter.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - const filterHandlersRequestWithResolverConfig = { - filterHandlersRequest: handlerFilter, - resolverConfig: this.getLegacyResolverConfigByRequest({ handlerFilter }), - embeddedResolverConfig - }; - const result = await this.bridge.send("intents", operations$6.filterHandlers, filterHandlersRequestWithResolverConfig, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }, { includeOperationCheck: true }); - return result; - } - checkIfAtLeastOneFilterIsPresent(filter) { - const errorMsg = "Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'"; - if (!Object.keys(filter).length) { - return ioError.raiseError(errorMsg); - } - const { intent, resultType, contextTypes, applicationNames } = filter; - const existingValidContextTypes = contextTypes?.length; - const existingValidApplicationNames = applicationNames?.length; - if (!intent && !resultType && !existingValidContextTypes && !existingValidApplicationNames) { - return ioError.raiseError(errorMsg); - } - } - async getIntentsByHandler(handler) { - runDecoderWithIOError(intentHandlerDecoder, handler); - const result = await this.bridge.send("intents", operations$6.getIntentsByHandler, handler, undefined, { includeOperationCheck: true }); - return result; - } - async removeRememberedHandler(intentName) { - this.logger.trace(`Removing saved handler from prefs storage for intent ${intentName}`); - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const intentPrefs = prefs.data?.intents; - if (!intentPrefs) { - this.logger.trace("No app prefs found for current app"); - return; - } - delete intentPrefs[intentName]; - const updatedPrefs = { - ...prefs.data, - intents: intentPrefs - }; - try { - await this.prefsController.update(updatedPrefs); - } - catch (error) { - this.logger.warn(`prefs.update() threw the following error: ${error}`); - return; - } - this.logger.trace(`Handler saved choice for intent ${intentName} removed successfully`); - } - async checkForRememberedHandler(intentRequest) { - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const prefsForIntent = prefs.data?.intents?.[intentRequest.intent]; - return prefsForIntent?.handler; - } - async checkHandleRaiseWithRememberedHandler(intentRequest) { - if (intentRequest.target) { - return; - } - const rememberedHandler = await this.checkForRememberedHandler(intentRequest); - if (!rememberedHandler) { - return; - } - const operationData = { - intentRequest: { - ...intentRequest, - target: { - app: rememberedHandler.applicationName, - instance: rememberedHandler.instanceId - } - }, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - try { - const response = await this.bridge.send("intents", operations$6.raise, operationData); - return response; - } - catch (error) { - this.logger.trace(`Could not raise intent to remembered handler. Reason: ${error}. Removing it from Prefs store`); - await this.removeRememberedHandler(intentRequest.intent); - } - } - } - - const operations$5 = { - appHello: { name: "appHello", dataDecoder: channelsAppHelloDataDecoder, resultDecoder: channelsAppHelloSuccessDecoder }, - addChannel: { name: "addChannel", dataDecoder: channelDefinitionDecoder }, - removeChannel: { name: "removeChannel", dataDecoder: removeChannelDataDecoder }, - getMyChannel: { name: "getMyChannel", resultDecoder: getMyChanelResultDecoder }, - getWindowIdsOnChannel: { name: "getWindowIdsOnChannel", dataDecoder: getWindowIdsOnChannelDataDecoder, resultDecoder: getWindowIdsOnChannelResultDecoder }, - getWindowIdsWithChannels: { name: "getWindowIdsWithChannels", dataDecoder: wrappedWindowWithChannelFilterDecoder, resultDecoder: getWindowIdsWithChannelsResultDecoder }, - joinChannel: { name: "joinChannel", dataDecoder: joinChannelDataDecoder }, - restrict: { name: "restrict", dataDecoder: restrictionConfigDataDecoder }, - getRestrictions: { name: "getRestrictions", dataDecoder: getRestrictionsDataDecoder, resultDecoder: restrictionsDecoder }, - restrictAll: { name: "restrictAll", dataDecoder: restrictAllDataDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - leaveChannel: { name: "leaveChannel", dataDecoder: leaveChannelDataDecoder }, - requestChannelSelector: { name: "requestChannelSelector", dataDecoder: requestChannelSelectorConfigDecoder }, - getMode: { name: "getMode", resultDecoder: getChannelsModeDecoder }, - operationCheck: { name: "operationCheck" }, - }; - - const DEFAULT_MODE = "single"; - const CHANNELS_PREFIX = "___channel___"; - const SUBS_KEY = "subs"; - const CHANGED_KEY = "changed"; - const CHANNELS_CHANGED = "channels_changed"; - const STORAGE_NAMESPACE = "io_connect_channels"; - const DEFAULT_STORAGE_MODE = "inMemory"; - - class ChannelsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - contexts; - interop; - bridge; - windowsController; - _mode; - myWindowId; - storage; - handlePlatformShutdown() { - this.registry.clear(); - this.storage.clear(); - } - addOperationsExecutors() { - operations$5.getMyChannel.execute = this.handleGetMyChannel.bind(this); - operations$5.joinChannel.execute = this.handleJoinChannel.bind(this); - operations$5.leaveChannel.execute = this.handleLeaveChannel.bind(this); - operations$5.restrict.execute = this.handleRestrict.bind(this); - operations$5.getRestrictions.execute = ({ windowId }) => this.getRestrictions(windowId); - operations$5.restrictAll.execute = this.handleRestrictAll.bind(this); - operations$5.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$5); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("channels.controller.web"); - this.logger.trace("starting the web channels controller"); - this.contexts = coreGlue.contexts; - this.interop = coreGlue.interop; - this.addOperationsExecutors(); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.storage = ioc.channelsStorage; - this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"); - this.myWindowId = this.windowsController.my().id ?? this.interop.instance.instance; - await this.initialize(); - const api = this.toApi(); - coreGlue.channels = api; - } - async postStart(io, ioc) { - try { - await this.requestChannelSelector(io.appManager.myInstance); - } - catch (error) { - this.logger.warn(`Failed to display channel selector: ${extractErrorMsg(error)}`); - } - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(channelsOperationTypesDecoder, args.operation); - const operation = operations$5[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async list() { - const channelNames = this.getAllChannelNames(); - const channelContexts = await Promise.all(channelNames.map((channelName) => this.get(channelName))); - return channelContexts; - } - my() { - return this.current(); - } - async handleGetMyChannel() { - const channel = this.my(); - return channel ? { channel } : {}; - } - async join(name, windowId) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const joinData = { channel: name, windowId: windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.joinChannel, joinData, undefined, { includeOperationCheck: true }); - } - handleJoinChannel({ channel }) { - if (this._mode === "single") { - return this.switchToChannel(channel); - } - return this.joinAdditionalChannel(channel); - } - onChanged(callback) { - return this.changed(callback); - } - async leave(config = {}) { - runDecoderWithIOError(leaveChannelsConfig, config); - if (config.channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.channel); - } - const leaveData = { channelName: config.channel, windowId: config.windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.leaveChannel, leaveData, undefined, { includeOperationCheck: true }); - } - async handleAppManagerInitialChannelId(channel) { - if (this.storage.mode === "inMemory") { - return; - } - if (this.storage.getSessionStorageData()) { - return; - } - return this.handleJoinChannel({ channel, windowId: this.myWindowId }); - } - async handleLeaveChannel({ channelName }) { - const channelNamesToLeave = channelName ? [channelName] : this.storage.channels; - channelNamesToLeave.forEach((name) => this.storage.invokeUnsubscribes(name)); - this.storage.channels = this.storage.channels.filter((channelName) => !channelNamesToLeave.includes(channelName)); - this.executeChangedEvents(); - await this.notifyChannelsChanged(); - } - toApi() { - const api = { - mode: this._mode, - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - publish: this.publish.bind(this), - all: this.all.bind(this), - list: this.list.bind(this), - get: this.get.bind(this), - getMyChannels: this.getMyChannels.bind(this), - myChannels: this.myChannels.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - join: this.join.bind(this), - leave: this.leave.bind(this), - current: this.current.bind(this), - my: this.my.bind(this), - changed: this.changed.bind(this), - onChanged: this.onChanged.bind(this), - add: this.add.bind(this), - remove: this.remove.bind(this), - getMy: this.getMy.bind(this), - getWindowsOnChannel: this.getWindowsOnChannel.bind(this), - getWindowsWithChannels: this.getWindowsWithChannels.bind(this), - restrict: this.restrict.bind(this), - getRestrictions: this.getRestrictions.bind(this), - restrictAll: this.restrictAll.bind(this), - clearChannelData: this.clearChannelData.bind(this), - setPath: this.setPath.bind(this), - setPaths: this.setPaths.bind(this) - }; - return Object.freeze(api); - } - createContextName(channelName) { - return `${CHANNELS_PREFIX}${channelName}`; - } - getAllChannelNames() { - const contextNames = this.contexts.all(); - const channelContextNames = contextNames.filter((contextName) => contextName.startsWith(CHANNELS_PREFIX)); - const channelNames = channelContextNames.map((channelContextName) => channelContextName.replace(CHANNELS_PREFIX, "")); - return channelNames; - } - async joinAdditionalChannel(name) { - if (this.storage.channels.includes(name)) { - return; - } - this.storage.channels = [...this.storage.channels, name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - async switchToChannel(name) { - const currentChannel = this.storage.channels[0]; - if (name === currentChannel) { - return; - } - this.storage.invokeUnsubscribes(currentChannel); - this.storage.channels = [name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - executeChangedEvents(name) { - this.registry.execute(CHANGED_KEY, name); - this.registry.execute(CHANNELS_CHANGED, this.storage.channels); - } - async notifyChannelsChanged() { - const windowId = this.windowsController.my().id; - if (!windowId) { - return; - } - try { - await this.bridge.send("channels", operations$5.notifyChannelsChanged, { channelNames: this.storage.channels, windowId }, undefined, { includeOperationCheck: true }); - } - catch (error) { - this.logger.warn(`Failed to notify channel changed: ${extractErrorMsg(error)}`); - } - } - async updateData(name, data) { - const contextName = this.createContextName(name); - const fdc3Type = this.getFDC3Type(data); - if (this.contexts.setPathSupported) { - const pathValues = Object.keys(data).map((key) => { - return { - path: `data.${key}`, - value: data[key] - }; - }); - if (fdc3Type) { - pathValues.push({ path: latestFDC3Type, value: fdc3Type }); - } - await this.contexts.setPaths(contextName, pathValues); - } - else { - if (fdc3Type) { - data[latestFDC3Type] = fdc3Type; - } - await this.contexts.update(contextName, { data }); - } - } - getFDC3Type(data) { - const fdc3PropsArr = Object.keys(data).filter((key) => key.indexOf("fdc3_") === 0); - if (fdc3PropsArr.length === 0) { - return; - } - if (fdc3PropsArr.length > 1) { - return ioError.raiseError("FDC3 does not support updating of multiple context keys"); - } - return fdc3PropsArr[0].split("_").slice(1).join("_"); - } - subscribe(callback, options) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels, because the provided callback is not a function!"); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const currentChannel = this.current(); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - if (currentChannel) { - this.replaySubscribe(wrappedCallback, currentChannel); - } - return this.registry.add(SUBS_KEY, wrappedCallback); - } - async subscribeFor(name, callback, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (typeof callback !== "function") { - return ioError.raiseError(`Cannot subscribe to channel ${name}, because the provided callback is not a function!`); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - wrappedCallback(context.data, context, delta, extraData?.updaterId); - }); - } - async publish(data, options) { - if (typeof data !== "object") { - return ioError.raiseError("Cannot publish to channel, because the provided data is not an object!"); - } - runDecoderWithIOError(publishOptionsDecoder, options); - if (typeof options === "object") { - return this.publishWithOptions(data, options); - } - if (typeof options === "string") { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options); - } - if (!options && this.storage.channels.length > 1) { - return this.publishOnMultipleChannels(data); - } - const channelName = typeof options === "string" ? options : this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - return this.updateData(channelName, data); - } - async all() { - const channelNames = this.getAllChannelNames(); - return channelNames; - } - async get(name, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const channelContext = await this.contexts.get(contextName); - if (options?.contextType) { - return this.getContextForFdc3Type(channelContext, options.contextType); - } - if (channelContext.latest_fdc3_type) { - return this.getContextWithFdc3Data(channelContext); - } - return channelContext; - } - async getMyChannels() { - return Promise.all(this.storage.channels.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.get(contextName); - })); - } - myChannels() { - return this.storage.channels; - } - getContextForFdc3Type(channelContext, searchedType) { - const encodedType = `fdc3_${searchedType.split(".").join("&")}`; - if (!channelContext.data[encodedType]) { - return { - name: channelContext.name, - meta: channelContext.meta, - data: {} - }; - } - const fdc3Context = { type: searchedType, ...channelContext.data[encodedType] }; - return { - name: channelContext.name, - meta: channelContext.meta, - data: { fdc3: fdc3Context } - }; - } - getContextWithFdc3Data(channelContext) { - const { latest_fdc3_type, ...rest } = channelContext; - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Context = { type: parsedType, ...rest.data[`fdc3_${latest_fdc3_type}`] }; - delete rest.data[`fdc3_${latest_fdc3_type}`]; - const context = { - name: channelContext.name, - meta: channelContext.meta, - data: { - ...rest.data, - fdc3: fdc3Context - } - }; - return context; - } - current() { - return this.storage.channels[0]; - } - changed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"); - } - return this.registry.add(CHANGED_KEY, callback); - } - async add(info) { - const channelContext = runDecoderWithIOError(channelDefinitionDecoder, info); - const channelWithSuchNameExists = this.getAllChannelNames().includes(channelContext.name); - if (channelWithSuchNameExists) { - return ioError.raiseError("There's an already existing channel with such name"); - } - await this.bridge.send("channels", operations$5.addChannel, channelContext); - return { - name: channelContext.name, - meta: channelContext.meta, - data: channelContext.data || {} - }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - const channelWithSuchNameExists = this.getAllChannelNames().includes(name); - if (!channelWithSuchNameExists) { - return ioError.raiseError("There's no channel with such name"); - } - await this.bridge.send("channels", operations$5.removeChannel, { name }, undefined, { includeOperationCheck: true }); - } - replaySubscribe = (callback, channelId) => { - this.get(channelId) - .then((channelContext) => { - if (!channelContext) { - return undefined; - } - const contextName = this.createContextName(channelContext.name); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - callback(context.data, context, delta, extraData?.updaterId); - }); - }) - .then((un) => un?.()) - .catch(err => this.logger.trace(err)); - }; - async getMy(options) { - if (!this.storage.channels.length) { - return; - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - return this.get(this.storage.channels[this.storage.channels.length - 1], options); - } - async getWindowsOnChannel(channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), channel); - const { windowIds } = await this.bridge.send("channels", operations$5.getWindowIdsOnChannel, { channel }, undefined, { includeOperationCheck: true }); - const result = windowIds.reduce((windows, windowId) => { - const window = this.windowsController.findById(windowId); - return window ? [...windows, window] : windows; - }, []); - return result; - } - async getWindowsWithChannels(filter) { - const operationData = filter !== undefined - ? { filter: runDecoderWithIOError(windowWithChannelFilterDecoder, filter) } - : {}; - const { windowIdsWithChannels } = await this.bridge.send("channels", operations$5.getWindowIdsWithChannels, operationData, undefined, { includeOperationCheck: true }); - const result = windowIdsWithChannels.reduce((windowsWithChannels, { application, channel, windowId }) => { - const window = this.windowsController.findById(windowId); - return window ? [...windowsWithChannels, { application, channel, window }] : windowsWithChannels; - }, []); - return result; - } - async clearChannelData(name) { - const paths = [ - { path: "data", value: {} }, - { path: "latest_fdc3_type", value: null }, - ]; - await this.handleSetPaths("clearChannelData", paths, name); - } - async restrict(config) { - runDecoderWithIOError(channelRestrictionsDecoder, config); - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.name); - const configData = { - config: { - ...config, - windowId: config.windowId ?? this.myWindowId - } - }; - await this.bridge.send("channels", operations$5.restrict, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrict({ config }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateRestriction(config); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateRestriction(config); - const isForCurrentChannel = config.name === currentChannel.name; - if (!isForCurrentChannel || prevReadAllowed || !config.read) { - return; - } - this.replaySubscribeCallback(config.name); - } - updateRestriction(config) { - const exists = this.storage.restrictions.some((r) => r.name === config.name); - this.storage.restrictions = exists - ? this.storage.restrictions.map((restriction) => restriction.name === config.name ? config : restriction) - : this.storage.restrictions.concat(config); - } - updateAllRestrictions(config) { - const allChannelNames = this.getAllChannelNames(); - this.storage.restrictions = allChannelNames.map((name) => ({ name, ...config })); - } - async getRestrictions(windowId) { - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const forAnotherClient = windowId && windowId !== this.interop.instance.instance; - if (windowId && forAnotherClient) { - return this.bridge.send("channels", operations$5.getRestrictions, { windowId }, undefined, { includeOperationCheck: true }); - } - return { channels: this.storage.restrictions }; - } - async restrictAll(restrictions) { - runDecoderWithIOError(restrictionsConfigDecoder, restrictions); - const configData = { - restrictions: { - ...restrictions, - windowId: restrictions.windowId ?? this.myWindowId - } - }; - return this.bridge.send("channels", operations$5.restrictAll, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrictAll({ restrictions }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateAllRestrictions(restrictions); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateAllRestrictions(restrictions); - if (prevReadAllowed || !restrictions.read) { - return; - } - this.replaySubscribeCallback(currentChannel.name); - } - async setPath(path, name) { - const validatedPath = runDecoderWithIOError(pathValueDecoder, path); - const paths = [{ path: `data.${validatedPath.path}`, value: validatedPath.value }]; - await this.handleSetPaths("setPath", paths, name); - } - async setPaths(paths, name) { - const validatedPaths = runDecoderWithIOError(pathsValueDecoder, paths); - const dataPaths = validatedPaths.map(({ path, value }) => ({ path: `data.${path}`, value })); - await this.handleSetPaths("setPaths", dataPaths, name); - } - async handleSetPaths(operation, paths, name) { - const channelNamesToUpdate = name ? [name] : this.storage.channels; - if (!channelNamesToUpdate.length) { - return ioError.raiseError(`Cannot complete ${operation} operation, because channel is not specified. Either join one or pass a channel name as second argument!`); - } - this.validateChannelNames(channelNamesToUpdate); - const { allowed, forbidden } = this.groupChannelsByPermission("write", channelNamesToUpdate); - if (channelNamesToUpdate.length === forbidden.length) { - return ioError.raiseError(`Cannot complete ${operation} operation due to write restrictions to the following channels: ${channelNamesToUpdate.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Cannot set paths on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} due to write restrictions`); - } - await Promise.all(allowed.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.setPaths(contextName, paths); - })); - } - validateChannelNames(names) { - const allChannelNames = this.getAllChannelNames(); - names.forEach((name) => runDecoderWithIOError(channelNameDecoder(allChannelNames), name)); - } - groupChannelsByPermission(action, channelNames) { - return channelNames.reduce((byFar, channelName) => { - const isAllowed = this.isAllowedByRestrictions(channelName, action); - if (isAllowed) { - byFar.allowed.push(channelName); - } - else { - byFar.forbidden.push(channelName); - } - return byFar; - }, { allowed: [], forbidden: [] }); - } - isAllowedByRestrictions(channelName, action) { - const restriction = this.storage.restrictions.find((restriction) => restriction.name === channelName); - return restriction ? restriction[action] : true; - } - replaySubscribeCallback(channelName) { - const contextName = this.createContextName(channelName); - this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }).then((unsub) => { - if (unsub && typeof unsub === "function") { - unsub(); - } - }).catch(err => this.logger.error(err)); - } - async publishWithOptions(data, options) { - if (options.name) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options.name); - } - const publishOnMultipleChannels = options.name ? false : this.storage.channels.length > 1; - if (publishOnMultipleChannels) { - return this.publishOnMultipleChannels(data, options.fdc3); - } - const channelName = options.name || this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - if (!options.fdc3) { - return this.updateData(channelName, data); - } - return this.publishFdc3Data(channelName, data); - } - async publishOnMultipleChannels(data, isFdc3) { - const { allowed, forbidden } = this.groupChannelsByPermission("write", this.storage.channels); - if (this.storage.channels.length === forbidden.length) { - return ioError.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Data on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} won't be published due to write restrictions`); - } - const publishMethod = isFdc3 ? this.publishFdc3Data.bind(this) : this.updateData.bind(this); - await Promise.all(allowed.map((channelName) => publishMethod(channelName, data))); - } - async publishFdc3Data(channelName, data) { - runDecoderWithIOError(fdc3ContextDecoder, data); - const { type, ...rest } = data; - const parsedType = type.split(".").join("&"); - const fdc3DataToPublish = { [`fdc3_${parsedType}`]: rest }; - return this.updateData(channelName, fdc3DataToPublish); - } - getWrappedSubscribeCallback(callback) { - const wrappedCallback = (channelData, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const latestTypePropName = `fdc3_${latest_fdc3_type}`; - if (!latest_fdc3_type || (delta.data && !delta.data[latestTypePropName])) { - callback(channelData, context, updaterId); - return; - } - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Data = { type: parsedType, ...data[latestTypePropName] }; - const { [latestTypePropName]: latestFDC3Type, ...rest } = channelData; - callback({ ...rest, fdc3: fdc3Data }, context, updaterId); - }; - return wrappedCallback; - } - getWrappedSubscribeCallbackWithFdc3Type(callback, fdc3Type) { - const didReplay = { replayed: false }; - const wrappedCallback = (_, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const searchedType = `fdc3_${fdc3Type.split(".").join("&")}`; - if (!data[searchedType] || (delta.data && !delta.data[searchedType])) { - return; - } - if (didReplay.replayed) { - return this.parseDataAndInvokeSubscribeCallback({ latestFdc3TypeEncoded: latest_fdc3_type, searchedType: fdc3Type, callback, context, updaterId }); - } - const fdc3Data = { type: fdc3Type, ...data[searchedType] }; - callback({ fdc3: fdc3Data }, context, updaterId); - didReplay.replayed = true; - }; - return wrappedCallback; - } - parseDataAndInvokeSubscribeCallback(args) { - const { latestFdc3TypeEncoded, searchedType, callback, context, updaterId } = args; - const latestPublishedType = latestFdc3TypeEncoded.split("&").join("."); - if (latestPublishedType !== searchedType) { - return; - } - const fdc3Data = { type: searchedType, ...context.data[`fdc3_${latestFdc3TypeEncoded}`] }; - callback({ fdc3: fdc3Data }, context, updaterId); - } - async requestChannelSelector(myInstance) { - if (!myInstance) { - return; - } - const myApplicationData = myInstance.application; - const myAppDetails = myApplicationData.userProperties?.details; - if (!myAppDetails) { - return; - } - if (!myAppDetails?.channelSelector?.enabled) { - return; - } - const windowId = myInstance.id; - const requestChannelSelectorConfig = { windowId, channelsNames: this.storage.channels }; - await this.bridge.send("channels", operations$5.requestChannelSelector, requestChannelSelectorConfig, undefined, { includeOperationCheck: true }); - } - async getPlatformChannelsMode() { - try { - const result = await this.bridge.send("channels", operations$5.getMode, {}, undefined, { includeOperationCheck: true }); - return result.mode; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - return DEFAULT_MODE; - } - } - onChannelsChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"); - } - return this.registry.add(CHANNELS_CHANGED, callback); - } - async initialize() { - const isAppHelloSupported = await this.checkIfAppHelloSupported(); - if (!isAppHelloSupported) { - return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions"); - } - const { success, error } = await this.sendAppHello(); - if (error) { - return this.handleAppHelloFailure(error); - } - this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(success)}`); - const { mode, channels, restrictions } = success; - this.storage.mode = "inMemory"; - this._mode = mode; - this.storage.channels = channels; - this.storage.restrictions = restrictions; - } - async handleAppHelloFailure(errorMsg) { - this.logger.trace(errorMsg); - this.storage.mode = "sessionStorage"; - this._mode = await this.getPlatformChannelsMode(); - } - async sendAppHello() { - try { - const result = await this.bridge.send("channels", operations$5.appHello, { windowId: this.myWindowId }, undefined, { includeOperationCheck: true }); - return { success: result, error: undefined }; - } - catch (error) { - return { error: `Failed to get initial state from platform. Error: ${extractErrorMsg(error)}`, success: undefined }; - } - } - async checkIfAppHelloSupported() { - try { - const { isSupported } = await this.bridge.send("channels", operations$5.operationCheck, { operation: operations$5.appHello.name }, undefined, { includeOperationCheck: true }); - return isSupported; - } - catch (error) { - this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${extractErrorMsg(error)}`); - return false; - } - } - } - - const operations$4 = { - getEnvironment: { name: "getEnvironment", resultDecoder: anyDecoder }, - getBase: { name: "getBase", resultDecoder: anyDecoder }, - platformShutdown: { name: "platformShutdown" }, - isFdc3DataWrappingSupported: { name: "isFdc3DataWrappingSupported" }, - clientError: { name: "clientError", dataDecoder: clientErrorDataDecoder }, - systemHello: { name: "systemHello", resultDecoder: systemHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class SystemController { - supportedOperationsNames = []; - bridge; - ioc; - logger; - errorPort = errorChannel.port2; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("system.controller.web"); - this.logger.trace("starting the web system controller"); - this.bridge = ioc.bridge; - this.ioc = ioc; - this.addOperationsExecutors(); - let isClientErrorOperationSupported = false; - try { - const systemHelloSuccess = await this.bridge.send("system", operations$4.systemHello, undefined, undefined, { includeOperationCheck: true }); - isClientErrorOperationSupported = systemHelloSuccess.isClientErrorOperationSupported; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support some system operations."); - } - this.errorPort.onmessage = async (event) => { - if (!isClientErrorOperationSupported) { - return; - } - await this.bridge.send("system", operations$4.clientError, { message: event.data }, undefined, { includeOperationCheck: true }); - }; - await this.setEnvironment(); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(systemOperationTypesDecoder, args.operation); - const operation = operations$4[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async processPlatformShutdown() { - Object.values(this.ioc.controllers).forEach((controller) => controller.handlePlatformShutdown ? controller.handlePlatformShutdown() : null); - this.ioc.preferredConnectionController.stop(); - this.ioc.eventsDispatcher.stop(); - await this.bridge.stop(); - } - async setEnvironment() { - const environment = await this.bridge.send("system", operations$4.getEnvironment, undefined); - const base = await this.bridge.send("system", operations$4.getBase, undefined); - const globalNamespace = window.glue42core || window.iobrowser; - const globalNamespaceName = window.glue42core ? "glue42core" : "iobrowser"; - const globalObj = Object.assign({}, globalNamespace, base, { environment }); - window[globalNamespaceName] = globalObj; - } - addOperationsExecutors() { - operations$4.platformShutdown.execute = this.processPlatformShutdown.bind(this); - operations$4.isFdc3DataWrappingSupported.execute = this.handleIsFdc3DataWrappingSupported.bind(this); - operations$4.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$4); - } - async handleIsFdc3DataWrappingSupported() { - return { isSupported: true }; - } - } - - class Notification { - onclick = () => { }; - onshow = () => { }; - id; - title; - badge; - body; - data; - dir; - icon; - image; - lang; - renotify; - requireInteraction; - silent; - tag; - timestamp; - vibrate; - clickInterop; - actions; - focusPlatformOnDefaultClick; - severity; - showToast; - showInPanel; - state; - constructor(config, id) { - this.id = id; - this.badge = config.badge; - this.body = config.body; - this.data = config.data; - this.dir = config.dir; - this.icon = config.icon; - this.image = config.image; - this.lang = config.lang; - this.renotify = config.renotify; - this.requireInteraction = config.requireInteraction; - this.silent = config.silent; - this.tag = config.tag; - this.timestamp = config.timestamp; - this.vibrate = config.vibrate; - this.title = config.title; - this.clickInterop = config.clickInterop; - this.actions = config.actions; - this.focusPlatformOnDefaultClick = config.focusPlatformOnDefaultClick; - this.severity = config.severity; - this.showToast = config.showToast; - this.showInPanel = config.showInPanel; - this.state = config.state; - } - } - - oneOf$1(constant$2("clientHello")); - const extensionConfigDecoder = object$2({ - widget: object$2({ - inject: boolean$2() - }) - }); - - const operations$3 = { - clientHello: { name: "clientHello", resultDecoder: extensionConfigDecoder } - }; - - class ExtController { - windowId; - logger; - bridge; - eventsDispatcher; - channelsController; - config; - channels = []; - unsubFuncs = []; - contentCommands = { - widgetVisualizationPermission: { name: "widgetVisualizationPermission", handle: this.handleWidgetVisualizationPermission.bind(this) }, - changeChannel: { name: "changeChannel", handle: this.handleChangeChannel.bind(this) } - }; - handlePlatformShutdown() { - this.unsubFuncs.forEach((unsub) => unsub()); - this.channels = []; - this.unsubFuncs = []; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("extension.controller.web"); - this.windowId = ioc.publicWindowId; - this.logger.trace("starting the extension web controller"); - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.eventsDispatcher = ioc.eventsDispatcher; - try { - await this.registerWithPlatform(); - } - catch (error) { - return; - } - this.channels = await this.channelsController.list(); - const unsubDispatcher = this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)); - const unsubChannels = this.channelsController.onChanged((channel) => { - this.eventsDispatcher.sendContentMessage({ command: "channelChange", newChannel: channel }); - }); - this.unsubFuncs.push(unsubDispatcher); - this.unsubFuncs.push(unsubChannels); - } - async handleBridgeMessage(_) { - } - handleContentMessage(message) { - if (!message || typeof message.command !== "string") { - return; - } - const foundHandler = this.contentCommands[message.command]; - if (!foundHandler) { - return; - } - foundHandler.handle(message); - } - async registerWithPlatform() { - this.logger.trace("registering with the platform"); - this.config = await this.bridge.send("extension", operations$3.clientHello, { windowId: this.windowId }); - this.logger.trace("the platform responded to the hello message with a valid extension config"); - } - async handleWidgetVisualizationPermission() { - if (!this.config?.widget.inject) { - return this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: false }); - } - const currentChannel = this.channels.find((channel) => channel.name === this.channelsController.my()); - this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: true, channels: this.channels, currentChannel }); - } - async handleChangeChannel(message) { - if (message.name === "no-channel") { - await this.channelsController.leave(); - return; - } - await this.channelsController.join(message.name); - } - } - - class EventsDispatcher { - config; - glue; - registry = CallbackRegistryFactory$1(); - glue42EventName = "Glue42"; - _handleMessage; - _resolveWidgetReadyPromise; - _resolveModalsUIFactoryReadyPromise; - _resolveIntentResolverUIFactoryReadyPromise; - constructor(config) { - this.config = config; - } - events = { - notifyStarted: { name: "notifyStarted", handle: this.handleNotifyStarted.bind(this) }, - contentInc: { name: "contentInc", handle: this.handleContentInc.bind(this) }, - requestGlue: { name: "requestGlue", handle: this.handleRequestGlue.bind(this) }, - widgetFactoryReady: { name: "widgetFactoryReady", handle: this.handleWidgetReady.bind(this) }, - modalsUIFactoryReady: { name: "modalsUIFactoryReady", handle: this.handleModalsUIFactoryReady.bind(this) }, - intentResolverUIFactoryReady: { name: "intentResolverUIFactoryReady", handle: this.handleIntentResolverUIFactoryReady.bind(this) }, - }; - stop() { - window.removeEventListener(this.glue42EventName, this._handleMessage); - } - start(glue) { - this.glue = glue; - this.wireCustomEventListener(); - this.announceStarted(); - } - sendContentMessage(message) { - this.send("contentOut", "glue42core", message); - } - onContentMessage(callback) { - return this.registry.add("content-inc", callback); - } - async widgetReady() { - const widgetReadyPromise = new Promise((resolve) => { - this._resolveWidgetReadyPromise = resolve; - }); - this.requestWidgetReady(); - return widgetReadyPromise; - } - async modalsUIFactoryReady() { - const modalsUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveModalsUIFactoryReadyPromise = resolve; - }); - this.requestModalsUIFactoryReady(); - return modalsUIFactoryReadyPromise; - } - async intentResolverUIFactoryReady() { - const intentResolverUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveIntentResolverUIFactoryReadyPromise = resolve; - }); - this.requestIntentResolverUIFactoryReady(); - return intentResolverUIFactoryReadyPromise; - } - wireCustomEventListener() { - this._handleMessage = this.handleMessage.bind(this); - window.addEventListener(this.glue42EventName, this._handleMessage); - } - handleMessage(event) { - const data = event.detail; - const namespace = data?.glue42 ?? data?.glue42core; - if (!namespace) { - return; - } - const glue42Event = namespace.event; - const foundHandler = this.events[glue42Event]; - if (!foundHandler) { - return; - } - foundHandler.handle(namespace.message); - } - announceStarted() { - this.send("start", "glue42"); - } - handleRequestGlue() { - if (!this.config.exposeAPI) { - this.send("requestGlueResponse", "glue42", { error: "Will not give access to the underlying Glue API, because it was explicitly denied upon initialization." }); - return; - } - this.send("requestGlueResponse", "glue42", { glue: this.glue }); - } - handleNotifyStarted() { - this.announceStarted(); - } - handleContentInc(message) { - this.registry.execute("content-inc", message); - } - requestWidgetReady() { - this.send(REQUEST_WIDGET_READY, "glue42"); - } - handleWidgetReady() { - this._resolveWidgetReadyPromise?.(); - } - requestModalsUIFactoryReady() { - this.send(REQUEST_MODALS_UI_FACTORY_READY, "glue42"); - } - handleModalsUIFactoryReady() { - this._resolveModalsUIFactoryReadyPromise?.(); - } - requestIntentResolverUIFactoryReady() { - this.send(REQUEST_INTENT_RESOLVER_UI_FACTORY_READY, "glue42"); - } - handleIntentResolverUIFactoryReady() { - this._resolveIntentResolverUIFactoryReadyPromise?.(); - } - send(eventName, namespace, message) { - const payload = {}; - payload[namespace] = { event: eventName, message }; - const event = new CustomEvent(this.glue42EventName, { detail: payload }); - window.dispatchEvent(event); - } - } - - class PreferredConnectionController { - coreGlue; - transactionTimeout = 15000; - transactionLocks = {}; - webPlatformTransport; - webPlatformMessagesUnsubscribe; - reconnectCounter = 0; - logger; - constructor(coreGlue) { - this.coreGlue = coreGlue; - this.logger = this.coreGlue.logger.subLogger("web.preferred.connection.controller"); - } - stop() { - if (!this.webPlatformMessagesUnsubscribe) { - return; - } - this.webPlatformMessagesUnsubscribe(); - } - async start(coreConfig) { - if (coreConfig.isPlatformInternal) { - this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic."); - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - if (!isConnectedToPlatform) { - return ioError.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport."); - } - if (!this.coreGlue.connection.transport.isPreferredActivated) { - this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization."); - return; - } - this.webPlatformTransport = this.coreGlue.connection.transport; - this.webPlatformMessagesUnsubscribe = this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this)); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - handleWebPlatformMessage(msg) { - if (typeof msg === "string") { - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - const type = msg.type; - const args = msg.args; - const transactionId = msg.transactionId; - if (type === Glue42CoreMessageTypes.transportSwitchRequest.name) { - return this.handleTransportSwitchRequest(args, transactionId); - } - if (type === Glue42CoreMessageTypes.platformUnload.name && !isConnectedToPlatform) { - return this.handlePlatformUnload(); - } - if (type === Glue42CoreMessageTypes.getCurrentTransportResponse.name) { - return this.handleGetCurrentTransportResponse(args, transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredLogic.name) { - return this.handleCheckPreferredLogic(transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredConnection.name) { - return this.handleCheckPreferredConnection(args, transactionId); - } - } - async reEstablishPlatformPort() { - try { - await this.webPlatformTransport.connect(); - } - catch (error) { - this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(error)}`); - --this.reconnectCounter; - if (this.reconnectCounter > 0) { - return this.reEstablishPlatformPort(); - } - this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform."); - } - this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."); - this.reconnectCounter = 0; - this.webPlatformTransport.close(); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - async checkSwitchTransport(config) { - const myCurrentTransportName = this.coreGlue.connection.transport.name(); - if (myCurrentTransportName === config.transportName) { - this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary"); - return; - } - this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${myCurrentTransportName}, but it should reconnect to ${JSON.stringify(config)}`); - const result = await this.coreGlue.connection.switchTransport(config); - this.setConnected(); - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - } - async getCurrentPlatformTransportState() { - this.logger.trace("Requesting the current transport state of the platform."); - const transaction = this.setTransaction(Glue42CoreMessageTypes.getCurrentTransport.name); - this.sendPlatformMessage(Glue42CoreMessageTypes.getCurrentTransport.name, transaction.id); - const transportState = await transaction.lock; - this.logger.trace(`The platform responded with transport state: ${JSON.stringify(transportState)}`); - return transportState; - } - setTransaction(operation) { - const transaction = {}; - const transactionId = nanoid$1(10); - const transactionLock = new Promise((resolve, reject) => { - let transactionLive = true; - transaction.lift = (args) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - resolve(args); - }; - transaction.fail = (reason) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - reject(reason); - }; - setTimeout(() => { - if (!transactionLive) { - return; - } - transactionLive = false; - this.logger.warn(`Transaction for operation: ${operation} timed out.`); - delete this.transactionLocks[transactionId]; - reject(`Transaction for operation: ${operation} timed out.`); - }, this.transactionTimeout); - }); - transaction.lock = transactionLock; - transaction.id = transactionId; - this.transactionLocks[transactionId] = transaction; - return transaction; - } - sendPlatformMessage(type, transactionId, args) { - this.logger.trace(`Sending a platform message of type: ${type}, id: ${transactionId} and args: ${JSON.stringify(args)}`); - this.webPlatformTransport.sendObject({ - glue42core: { type, args, transactionId } - }); - } - handleTransportSwitchRequest(args, transactionId) { - this.logger.trace(`Received a transport switch request with id: ${transactionId} and data: ${JSON.stringify(args)}`); - this.coreGlue.connection.switchTransport(args.switchSettings) - .then((result) => { - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - this.setConnected(); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: result.success }); - }) - .catch((error) => { - this.logger.error(error); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: false }); - }); - } - handlePlatformUnload() { - this.reconnectCounter = 5; - this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."); - this.reEstablishPlatformPort(); - } - handleGetCurrentTransportResponse(args, transactionId) { - this.logger.trace(`Got a current transport response from the platform with id: ${transactionId} and data: ${JSON.stringify(args)}`); - const transportState = args.transportState; - const transaction = this.transactionLocks[transactionId]; - transaction?.lift(transportState); - } - handleCheckPreferredLogic(transactionId) { - setTimeout(() => this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredLogicResponse.name, transactionId), 0); - } - handleCheckPreferredConnection(args, transactionId) { - const url = args.url; - this.logger.trace(`Testing the possible connection to: ${url}`); - this.checkPreferredConnection(url) - .then((result) => { - this.logger.trace(`The connection to ${url} is possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, result); - }) - .catch((error) => { - this.logger.trace(`The connection to ${url} is not possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, { error }); - }); - } - checkPreferredConnection(url) { - return new Promise((resolve) => { - const ws = new WebSocket(url); - ws.onerror = () => resolve({ live: false }); - ws.onopen = () => { - ws.close(); - resolve({ live: true }); - }; - }); - } - setConnected() { - this.webPlatformTransport.manualSetReadyState(); - } - } - - const operations$2 = { - getCurrent: { name: "getCurrent", resultDecoder: simpleThemeResponseDecoder }, - list: { name: "list", resultDecoder: allThemesResponseDecoder }, - select: { name: "select", dataDecoder: selectThemeConfigDecoder } - }; - - class ThemesController { - logger; - bridge; - registry = CallbackRegistryFactory$1(); - themesSubscription; - activeThemeSubs = 0; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("themes.controller.web"); - this.logger.trace("starting the web themes controller"); - this.bridge = ioc.bridge; - const api = this.toApi(); - coreGlue.themes = api; - this.logger.trace("themes are ready"); - } - handlePlatformShutdown() { - this.registry.clear(); - this.activeThemeSubs = 0; - this.themesSubscription?.close(); - delete this.themesSubscription; - } - async handleBridgeMessage() { - } - toApi() { - const api = { - getCurrent: this.getCurrent.bind(this), - list: this.list.bind(this), - select: this.select.bind(this), - onChanged: this.onChanged.bind(this) - }; - return Object.freeze(api); - } - async getCurrent() { - const bridgeResponse = await this.bridge.send("themes", operations$2.getCurrent, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.theme; - } - async list() { - const bridgeResponse = await this.bridge.send("themes", operations$2.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.themes; - } - async select(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("themes", operations$2.select, { name }, undefined, { includeOperationCheck: true }); - } - async onChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onChanged requires a callback of type function"); - } - const subReady = this.themesSubscription ? - Promise.resolve() : - this.configureThemeSubscription(); - await subReady; - ++this.activeThemeSubs; - const unsubFunc = this.registry.add("on-theme-change", callback); - return () => this.themeUnsub(unsubFunc); - } - async configureThemeSubscription() { - if (this.themesSubscription) { - return; - } - this.themesSubscription = await this.bridge.createNotificationsSteam(); - this.themesSubscription.onData((data) => { - const eventData = data.data; - const validation = simpleThemeResponseDecoder.run(eventData); - if (!validation.ok) { - this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`); - return; - } - const themeChanged = validation.result; - this.registry.execute("on-theme-change", themeChanged.theme); - }); - this.themesSubscription.onClosed(() => { - this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"); - this.registry.clear(); - this.activeThemeSubs = 0; - delete this.themesSubscription; - }); - } - themeUnsub(registryUnsub) { - registryUnsub(); - --this.activeThemeSubs; - if (this.activeThemeSubs) { - return; - } - this.themesSubscription?.close(); - delete this.themesSubscription; - } - } - - class ChannelsStorage { - sessionStorage = window.sessionStorage; - _mode = DEFAULT_STORAGE_MODE; - inMemoryChannels = []; - inMemoryRestrictions = []; - _unsubscribeDict = {}; - clear() { - this._mode = DEFAULT_STORAGE_MODE; - this.inMemoryChannels = []; - this.inMemoryRestrictions = []; - this._unsubscribeDict = {}; - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify([])); - } - get mode() { - return this._mode; - } - set mode(mode) { - this._mode = mode; - } - get channels() { - if (this.mode === "inMemory") { - return this.inMemoryChannels.slice(); - } - return this.getSessionStorageData()?.channels ?? []; - } - set channels(channels) { - if (this.mode === "inMemory") { - this.inMemoryChannels = channels; - } - this.setSessionStorageChannels(channels); - } - get restrictions() { - if (this.mode === "inMemory") { - return this.inMemoryRestrictions.slice(); - } - return this.getSessionStorageData()?.restrictions ?? []; - } - set restrictions(restrictions) { - if (this.mode === "inMemory") { - this.inMemoryRestrictions = restrictions; - } - this.setSessionStorageRestrictions(restrictions); - } - getSessionStorageData() { - return JSON.parse(this.sessionStorage.getItem(STORAGE_NAMESPACE) || "null"); - } - addUnsubscribe(channel, unsubscribe) { - this._unsubscribeDict[channel] = unsubscribe; - } - invokeUnsubscribes(channel) { - if (channel) { - this._unsubscribeDict[channel]?.(); - delete this._unsubscribeDict[channel]; - return; - } - Object.values(this._unsubscribeDict).forEach((unsub) => unsub()); - this._unsubscribeDict = {}; - } - setSessionStorageChannels(channels) { - const data = this.getSessionStorageData(); - if (data?.channels) { - data.channels = channels; - return this.setSessionStorageData(data); - } - const newData = { channels, restrictions: data?.restrictions ?? [] }; - return this.setSessionStorageData(newData); - } - setSessionStorageRestrictions(restrictions) { - const data = this.getSessionStorageData(); - if (data?.restrictions) { - data.restrictions = restrictions; - return this.setSessionStorageData(data); - } - const newData = { channels: data?.channels ?? [], restrictions }; - return this.setSessionStorageData(newData); - } - setSessionStorageData(data) { - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify(data)); - } - } - - const operations$1 = { - clear: { name: "clear", dataDecoder: basePrefsConfigDecoder }, - clearAll: { name: "clearAll" }, - get: { name: "get", dataDecoder: basePrefsConfigDecoder, resultDecoder: getPrefsResultDecoder }, - getAll: { name: "getAll", resultDecoder: getAllPrefsResultDecoder }, - set: { name: "set", dataDecoder: changePrefsDataDecoder }, - update: { name: "update", dataDecoder: changePrefsDataDecoder }, - prefsChanged: { name: "prefsChanged", dataDecoder: getPrefsResultDecoder }, - prefsHello: { name: "prefsHello", resultDecoder: prefsHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" }, - registerSubscriber: { name: "registerSubscriber", dataDecoder: subscriberRegisterConfigDecoder }, - }; - - class PrefsController { - supportedOperationsNames = []; - bridge; - config; - logger; - appManagerController; - platformAppName; - registry = CallbackRegistryFactory$1(); - validNonExistentApps; - signaledSubscription = false; - interopId; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("prefs.controller.web"); - this.logger.trace("starting the web prefs controller"); - this.addOperationsExecutors(); - this.interopId = coreGlue.interop.instance.instance; - this.bridge = ioc.bridge; - this.config = ioc.config; - this.appManagerController = ioc.appManagerController; - try { - const prefsHelloSuccess = await this.bridge.send("prefs", operations$1.prefsHello, undefined, undefined, { includeOperationCheck: true }); - this.platformAppName = prefsHelloSuccess.platform.app; - this.validNonExistentApps = prefsHelloSuccess.validNonExistentApps ?? []; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support Prefs API."); - return; - } - this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning"); - const api = this.toApi(); - coreGlue.prefs = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(prefsOperationTypesDecoder, args.operation); - const operation = operations$1[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async get(app) { - const verifiedApp = app === undefined || app === null ? this.getMyAppName() : runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const { prefs } = await this.bridge.send("prefs", operations$1.get, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - return prefs; - } - async update(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.updateFor(app, data); - } - addOperationsExecutors() { - operations$1.prefsChanged.execute = this.handleOnChanged.bind(this); - operations$1.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$1); - } - toApi() { - const api = { - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearFor: this.clearFor.bind(this), - get: this.get.bind(this), - getAll: this.getAll.bind(this), - set: this.set.bind(this), - setFor: this.setFor.bind(this), - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - update: this.update.bind(this), - updateFor: this.updateFor.bind(this), - }; - return api; - } - async clear() { - const app = this.getMyAppName(); - await this.clearFor(app); - } - async clearAll() { - await this.bridge.send("prefs", operations$1.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearFor(app) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - await this.bridge.send("prefs", operations$1.clear, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - } - async getAll() { - const result = await this.bridge.send("prefs", operations$1.getAll, undefined, undefined, { includeOperationCheck: true }); - return result; - } - async set(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.setFor(app, data); - } - async setFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.set, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - subscribe(callback) { - const app = this.getMyAppName(); - return this.subscribeFor(app, callback); - } - subscribeFor(app, callback) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const applications = this.appManagerController.getApplications(); - const isValidApp = verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp); - if (!isValidApp) { - return ioError.raiseError(`The provided app name "${app}" is not valid.`); - } - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!"); - } - if (!this.signaledSubscription) { - this.bridge.send("prefs", operations$1.registerSubscriber, { interopId: this.interopId, appName: verifiedApp }, undefined, { includeOperationCheck: true }) - .catch((error) => { - this.logger.warn("Failed to register subscriber for prefs"); - this.logger.error(error); - }); - this.signaledSubscription = true; - } - const subscriptionKey = this.getSubscriptionKey(verifiedApp); - this.get(verifiedApp).then(callback); - return this.registry.add(subscriptionKey, callback); - } - async updateFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.update, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - getMyAppName() { - const myAppName = this.config.isPlatformInternal ? this.platformAppName : this.appManagerController.me?.application.name; - if (!myAppName) { - return ioError.raiseError("App Preferences operations can not be executed for windows that do not have app!"); - } - return myAppName; - } - getSubscriptionKey(app) { - return `prefs-changed-${app}`; - } - async handleOnChanged({ prefs }) { - const subscriptionKey = this.getSubscriptionKey(prefs.app); - this.registry.execute(subscriptionKey, prefs); - } - } - - const operations = { - getResources: { name: "getResources", dataDecoder: getResourcesDataDecoder, resultDecoder: getResourcesResultDecoder }, - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - showAlert: { name: "showAlert", dataDecoder: uiAlertRequestMessageDecoder }, - showDialog: { name: "showDialog", dataDecoder: uiDialogRequestMessageDecoder }, - alertInteropAction: { name: "alertInteropAction", dataDecoder: alertInteropActionDataDecoder }, - showResolver: { name: "showResolver", dataDecoder: uiResolverRequestMessageDecoder, resultDecoder: uiResolverResponseMessageDecoder }, - }; - - const DEFAULT_ALERT_TTL = 5 * 1000; - const MODALS_SHADOW_HOST_ID = "io-modals-shadow-host"; - const MODALS_ROOT_ELEMENT_ID = "io-modals-root"; - const WIDGET_SHADOW_HOST_ID = "io-widget-shadow-host"; - const WIDGET_ROOT_ELEMENT_ID = "io-widget-root"; - const INTENT_RESOLVER_SHADOW_HOST_ID = "io-intent-resolver-shadow-host"; - const INTENT_RESOLVER_ROOT_ELEMENT_ID = "io-intent-resolver-root"; - const SHADOW_ROOT_ELEMENT_CLASSNAME = "io-body io-variables"; - - class UIController { - ioc; - supportedOperationsNames = []; - logger; - bridge; - config; - zIndexDictionary = { - [WIDGET_SHADOW_HOST_ID]: "100", - [MODALS_SHADOW_HOST_ID]: "101", - [INTENT_RESOLVER_SHADOW_HOST_ID]: "100" - }; - widgetResources; - modalsResources; - intentResolverResources; - modalsUiApi; - isDialogOpen = false; - intentResolverUiApi; - isIntentResolverOpen = false; - constructor(ioc) { - this.ioc = ioc; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("ui.controller.web"); - this.logger.trace("starting the ui controller"); - this.bridge = ioc.bridge; - this.config = ioc.config; - this.addOperationsExecutors(); - const resources = await this.getResources(); - if (!resources) { - this.logger.trace("No UI elements to display - platform is not initialized with any UI resources"); - return; - } - this.logger.trace(`Received UI resources from platform: ${JSON.stringify(resources)}`); - this.setResources(resources); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(uiOperationTypesDecoder, args.operation); - const operation = operations[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async showComponents(io) { - const initializeWidgetPromise = this.widgetResources ? this.initializeWidget(io, this.widgetResources) : Promise.resolve(); - const initializeModalsPromise = this.modalsResources ? this.initializeModalsUi(io, this.modalsResources) : Promise.resolve(); - const initializeIntentResolverPromise = this.intentResolverResources ? this.initializeIntentResolverUI(io, this.intentResolverResources) : Promise.resolve(); - await Promise.all([ - this.config.widget.awaitFactory ? initializeWidgetPromise : Promise.resolve(), - this.config.modals.awaitFactory ? initializeModalsPromise : Promise.resolve(), - this.config.intentResolver.awaitFactory ? initializeIntentResolverPromise : Promise.resolve(), - ]); - } - isIntentResolverEnabled() { - return !!this.intentResolverResources && this.config.intentResolver.enable; - } - addOperationsExecutors() { - operations.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - operations.showAlert.execute = this.handleShowAlert.bind(this); - operations.showDialog.execute = this.handleShowDialog.bind(this); - operations.showResolver.execute = this.handleShowResolver.bind(this); - this.supportedOperationsNames = getSupportedOperationsNames(operations); - } - async handleShowAlert({ config }) { - if (!this.config.modals.alerts.enabled) { - return ioError.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showAlert operation because modalsUiApi is missing."); - } - const { promise: closePromise, resolve: resolveClosePromise } = wrapPromise(); - const onClick = (config) => { - const decodedConfig = alertOnClickConfigDecoder.run(config); - if (!decodedConfig.ok) { - this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(decodedConfig.error)}.`); - return; - } - const { interopAction } = decodedConfig.result; - this.bridge.send("ui", operations.alertInteropAction, { interopAction }, undefined, { includeOperationCheck: true }) - .catch((error) => this.logger.warn(extractErrorMsg(error))); - }; - let result; - try { - this.logger.trace(`Open alert with config: ${JSON.stringify(config)}`); - result = modalsUiApi.alerts.open({ ...config, onClick, onClose: resolveClosePromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openAlertResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - const timeoutId = setTimeout(() => { - resolveClosePromise(); - }, getSafeTimeoutDelay(config.ttl ?? DEFAULT_ALERT_TTL)); - closePromise.then(() => { - clearTimeout(timeoutId); - try { - modalsUiApi.alerts.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close alert with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - }); - } - async handleShowDialog({ config }) { - if (!this.config.modals.dialogs.enabled) { - return ioError.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showDialog operation because modalsUiApi is missing."); - } - if (this.isDialogOpen) { - return ioError.raiseError("Cannot open a dialog because another one is already open."); - } - const { promise: completionPromise, resolve: resolveCompletionPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open dialog with config: ${JSON.stringify(config)}`); - result = modalsUiApi.dialogs.open({ ...config, onCompletion: resolveCompletionPromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openDialogResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - this.isDialogOpen = true; - let timeoutId; - if (config.timer) { - timeoutId = setTimeout(() => { - resolveCompletionPromise({ response: { isExpired: true } }); - }, getSafeTimeoutDelay(config.timer.duration)); - } - const response = await completionPromise; - clearTimeout(timeoutId); - this.isDialogOpen = false; - try { - modalsUiApi.dialogs.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close dialog with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodeResponse = dialogOnCompletionConfigDecoder.run(response); - if (!decodeResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodeResponse.error)}.`); - } - return { result: decodeResponse.result.response }; - } - async handleShowResolver({ config }) { - this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(config)}`); - if (!this.config.intentResolver.enable) { - return ioError.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config."); - } - const intentResolverApi = this.intentResolverUiApi; - if (!intentResolverApi) { - return ioError.raiseError("Unable to perform showResolver operation because intentResolverApi is missing."); - } - if (this.isIntentResolverOpen) { - return ioError.raiseError("Cannot open the intent resolver because another one is already open."); - } - const { promise: completionPromise, resolve: resolveIntentResolverPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open intent resolver with config: ${JSON.stringify(config)}`); - result = intentResolverApi.open({ ...config, onUserResponse: resolveIntentResolverPromise }); - } - catch (error) { - return ioError.raiseError(`intentResolverUI.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodedOpenResult = openResolverResultDecoder.run(result); - if (!decodedOpenResult.ok) { - return ioError.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(decodedOpenResult.error)}.`); - } - const timer = setTimeout(() => resolveIntentResolverPromise({ response: { isExpired: true } }), getSafeTimeoutDelay(config.timeout)); - const response = await completionPromise; - clearTimeout(timer); - this.isIntentResolverOpen = false; - try { - intentResolverApi.close({ id: decodedOpenResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close intent resolver with id ${decodedOpenResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodedResponse = onUserResponseResponseDecoder.run(response); - if (!decodedResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodedResponse.error)}.`); - } - return { result: decodedResponse.result.response }; - } - async getResources() { - const data = { - origin: window.origin - }; - try { - const result = await this.bridge.send("ui", operations.getResources, data, undefined, { includeOperationCheck: true }); - return result.resources; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - } - } - appendModalsResources(resources) { - this.logger.trace("Appending modals resources"); - return this.appendResources(MODALS_SHADOW_HOST_ID, MODALS_ROOT_ELEMENT_ID, resources.sources); - } - appendWidgetResources(resources) { - this.logger.trace("Appending widget resources"); - return this.appendResources(WIDGET_SHADOW_HOST_ID, WIDGET_ROOT_ELEMENT_ID, resources.sources); - } - appendIntentResolverResources(resources) { - this.logger.trace("Appending intent resolver resources"); - return this.appendResources(INTENT_RESOLVER_SHADOW_HOST_ID, INTENT_RESOLVER_ROOT_ELEMENT_ID, resources.sources); - } - appendResources(shadowHostId, rootElementId, sources) { - const { bundle, fonts = [], styles } = sources; - const shadowHost = document.createElement("div"); - shadowHost.id = shadowHostId; - shadowHost.style.position = "fixed"; - shadowHost.style.zIndex = this.zIndexDictionary[shadowHostId]; - const shadowRoot = shadowHost.attachShadow({ mode: "open" }); - const script = document.createElement("script"); - script.src = bundle; - script.type = "module"; - shadowRoot.appendChild(script); - const rootElement = document.createElement("div"); - rootElement.id = rootElementId; - rootElement.className = SHADOW_ROOT_ELEMENT_CLASSNAME; - shadowRoot.appendChild(rootElement); - styles.forEach((style) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = style; - shadowRoot.appendChild(link); - }); - fonts.forEach((font) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = font; - document.head.insertBefore(link, document.head.firstChild); - }); - document.body.appendChild(shadowHost); - return { rootElement }; - } - async initializeWidget(io, resources) { - this.logger.trace("Initializing IOBrowserWidget."); - const { rootElement } = this.appendWidgetResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...deepmerge$1(resources.config, this.config.widget), - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.widgetReady(); - this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(config)}`); - await window.IOBrowserWidget(io, config); - this.logger.trace("IOBrowserWidget was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserWidget to initialize.`); - } - async initializeModalsUi(io, resources) { - this.logger.trace("Initializing IOBrowserModalsUI."); - const { rootElement } = this.appendModalsResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.modals, - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.modalsUIFactoryReady(); - this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.modalsUiApi = await window.IOBrowserModalsUI(io, config); - this.logger.trace("IOBrowserModalsUI was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`); - } - async initializeIntentResolverUI(io, resources) { - this.logger.trace("Initializing IOBrowserIntentResolverUI."); - const { rootElement } = this.appendIntentResolverResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.intentResolver, - rootElement - }; - const timeout = config.timeout; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(); - this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.intentResolverUiApi = await window.IOBrowserIntentResolverUI(io, config); - this.logger.trace("IOBrowserIntentResolverUI initialized successfully."); - }, timeout, `Timeout of ${timeout}ms hit waiting for IOBrowserIntentResolverUI to initialize.`); - } - setResources(resources) { - this.setWidgetResources(resources.widget); - this.setModalsUiResources(resources.modals); - this.setIntentResolverResources(resources.intentResolver); - } - setWidgetResources(resources) { - const baseMsg = "Widget won't be displayed. Reason: "; - const decodedConfig = widgetConfigDecoder.run(this.config.widget); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid widget config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.widget.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'widget: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`); - return; - } - this.widgetResources = resources; - } - setModalsUiResources(resources) { - const baseMsg = "Modals won't be displayed. Reason: "; - const decodedConfig = modalsConfigDecoder.run(this.config.modals); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid modals config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.modals.alerts.enabled && !this.config.modals.dialogs.enabled) { - this.logger.trace(`${baseMsg} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`); - return; - } - this.modalsResources = resources; - } - setIntentResolverResources(resources) { - const baseMsg = "Intent Resolver UI won't be displayed. Reason: "; - const decodedConfig = intentResolverConfigDecoder.run(this.config.intentResolver); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid intent resolver config. Error: ${JSON.stringify(decodedConfig.error)}`); - return; - } - if (!this.config.intentResolver.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'intentResolver: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`); - return; - } - this.intentResolverResources = resources; - } - subscribeForThemeChanges(io, element) { - const themesApi = io.themes; - if (!themesApi) { - return; - } - const changeTheme = async (theme) => { - if (element.classList.contains(theme.name)) { - return; - } - const allThemes = await themesApi.list(); - element.classList.remove(...allThemes.map(({ name }) => name)); - element.classList.add(theme.name); - }; - themesApi.onChanged(changeTheme); - themesApi.getCurrent().then(changeTheme); - } - } - - class IoC { - _coreGlue; - _communicationId; - _publicWindowId; - _webConfig; - _windowsControllerInstance; - _appManagerControllerInstance; - _layoutsControllerInstance; - _notificationsControllerInstance; - _intentsControllerInstance; - _channelsControllerInstance; - _themesControllerInstance; - _extensionController; - _systemControllerInstance; - _bridgeInstance; - _eventsDispatcher; - _preferredConnectionController; - _channelsStorage; - _prefsControllerInstance; - _uiController; - controllers = { - windows: this.windowsController, - appManager: this.appManagerController, - layouts: this.layoutsController, - notifications: this.notificationsController, - intents: this.intentsController, - channels: this.channelsController, - system: this.systemController, - extension: this.extensionController, - themes: this.themesController, - prefs: this.prefsController, - ui: this.uiController - }; - get communicationId() { - return this._communicationId; - } - get publicWindowId() { - return this._publicWindowId; - } - get windowsController() { - if (!this._windowsControllerInstance) { - this._windowsControllerInstance = new WindowsController(); - } - return this._windowsControllerInstance; - } - get uiController() { - if (!this._uiController) { - this._uiController = new UIController(this); - } - return this._uiController; - } - get appManagerController() { - if (!this._appManagerControllerInstance) { - this._appManagerControllerInstance = new AppManagerController(); - } - return this._appManagerControllerInstance; - } - get layoutsController() { - if (!this._layoutsControllerInstance) { - this._layoutsControllerInstance = new LayoutsController(); - } - return this._layoutsControllerInstance; - } - get themesController() { - if (!this._themesControllerInstance) { - this._themesControllerInstance = new ThemesController(); - } - return this._themesControllerInstance; - } - get notificationsController() { - if (!this._notificationsControllerInstance) { - this._notificationsControllerInstance = new NotificationsController(); - } - return this._notificationsControllerInstance; - } - get intentsController() { - if (!this._intentsControllerInstance) { - this._intentsControllerInstance = new IntentsController(); - } - return this._intentsControllerInstance; - } - get systemController() { - if (!this._systemControllerInstance) { - this._systemControllerInstance = new SystemController(); - } - return this._systemControllerInstance; - } - get channelsController() { - if (!this._channelsControllerInstance) { - this._channelsControllerInstance = new ChannelsController(); - } - return this._channelsControllerInstance; - } - get prefsController() { - if (!this._prefsControllerInstance) { - this._prefsControllerInstance = new PrefsController(); - } - return this._prefsControllerInstance; - } - get extensionController() { - if (!this._extensionController) { - this._extensionController = new ExtController(); - } - return this._extensionController; - } - get eventsDispatcher() { - if (!this._eventsDispatcher) { - this._eventsDispatcher = new EventsDispatcher(this.config); - } - return this._eventsDispatcher; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new GlueBridge(this._coreGlue, this.communicationId); - } - return this._bridgeInstance; - } - get preferredConnectionController() { - if (!this._preferredConnectionController) { - this._preferredConnectionController = new PreferredConnectionController(this._coreGlue); - } - return this._preferredConnectionController; - } - get channelsStorage() { - if (!this._channelsStorage) { - this._channelsStorage = new ChannelsStorage(); - } - return this._channelsStorage; - } - get config() { - return this._webConfig; - } - defineGlue(coreGlue) { - this._coreGlue = coreGlue; - this._publicWindowId = coreGlue.connection.transport.publicWindowId; - const globalNamespace = window.glue42core || window.iobrowser; - this._communicationId = coreGlue.connection.transport.communicationId || globalNamespace.communicationId; - } - defineConfig(config) { - this._webConfig = config; - } - async buildWebWindow(id, name, logger) { - const model = new WebWindowModel(id, name, this.bridge, logger); - const api = await model.toApi(); - return { id, model, api }; - } - buildNotification(config, id) { - return new Notification(config, id); - } - async buildApplication(app, applicationInstances) { - const application = (new ApplicationModel(app, [], this.appManagerController)).toApi(); - const instances = applicationInstances.map((instanceData) => this.buildInstance(instanceData, application)); - application.instances.push(...instances); - return application; - } - buildInstance(instanceData, app) { - return (new InstanceModel(instanceData, this.bridge, app)).toApi(); - } - } - - var version$1 = "4.2.4"; - - const setupGlobalSystem = (io, bridge) => { - return { - getContainerInfo: async () => { - if (window === window.parent) { - return; - } - if (window.name.includes("#wsp")) { - return { - workspaceFrame: { - id: "N/A" - } - }; - } - return window.parent === window.top ? - { top: {} } : - { parent: {} }; - }, - getProfileData: async () => { - if (!bridge) { - throw new Error("Bridge is not available and cannot fetch the profile data"); - } - const data = await bridge.send("system", { name: "getProfileData" }, undefined); - return data; - } - }; - }; - - const createFactoryFunction = (coreFactoryFunction) => { - let cachedApiPromise; - const initAPI = async (config) => { - const ioc = new IoC(); - const glue = await PromiseWrap(() => coreFactoryFunction(config, { version: version$1 }), 30000, "Glue Web initialization timed out, because core didn't resolve"); - const logger = glue.logger.subLogger("web.main.controller"); - ioc.defineGlue(glue); - await ioc.preferredConnectionController.start(config); - await ioc.bridge.start(ioc.controllers); - ioc.defineConfig(config); - logger.trace("the bridge has been started, initializing all controllers"); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.start(glue, ioc))); - logger.trace("all controllers reported started, starting all additional libraries"); - try { - await Promise.all(config.libraries.map((lib) => lib(glue, config))); - logger.trace("all libraries were started"); - ioc.eventsDispatcher.start(glue); - logger.trace("start event dispatched, glue is ready, returning it"); - await ioc.uiController.showComponents(glue).catch((err) => logger.warn(err?.message ? err.message : JSON.stringify(err))); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.postStart ? controller.postStart(glue, ioc) : Promise.resolve())); - window.iobrowser.system = setupGlobalSystem(glue, ioc.bridge); - window.iobrowser = Object.freeze({ ...window.iobrowser }); - return glue; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const factory = (userConfig) => { - if (window.glue42gd || window.iodesktop) { - return enterprise(userConfig); - } - const config = parseConfig(userConfig); - try { - checkSingleton(); - } - catch (error) { - return typeof cachedApiPromise === "undefined" ? Promise.reject(new Error(error)) : cachedApiPromise; - } - const apiPromise = initAPI(config); - cachedApiPromise = userConfig?.memoizeAPI ? apiPromise : undefined; - return apiPromise; - }; - return factory; - }; - - var MetricTypes = { - STRING: 1, - NUMBER: 2, - TIMESTAMP: 3, - OBJECT: 4 - }; - - function getMetricTypeByValue(metric) { - if (metric.type === MetricTypes.TIMESTAMP) { - return "timestamp"; - } - else if (metric.type === MetricTypes.NUMBER) { - return "number"; - } - else if (metric.type === MetricTypes.STRING) { - return "string"; - } - else if (metric.type === MetricTypes.OBJECT) { - return "object"; - } - return "unknown"; - } - function getTypeByValue(value) { - if (value.constructor === Date) { - return "timestamp"; - } - else if (typeof value === "number") { - return "number"; - } - else if (typeof value === "string") { - return "string"; - } - else if (typeof value === "object") { - return "object"; - } - else { - return "string"; - } - } - function serializeMetric(metric) { - const serializedMetrics = {}; - const type = getMetricTypeByValue(metric); - if (type === "object") { - const values = Object.keys(metric.value).reduce((memo, key) => { - const innerType = getTypeByValue(metric.value[key]); - if (innerType === "object") { - const composite = defineNestedComposite(metric.value[key]); - memo[key] = { - type: "object", - description: "", - context: {}, - composite, - }; - } - else { - memo[key] = { - type: innerType, - description: "", - context: {}, - }; - } - return memo; - }, {}); - serializedMetrics.composite = values; - } - serializedMetrics.name = normalizeMetricName(metric.path.join("/") + "/" + metric.name); - serializedMetrics.type = type; - serializedMetrics.description = metric.description; - serializedMetrics.context = {}; - return serializedMetrics; - } - function defineNestedComposite(values) { - return Object.keys(values).reduce((memo, key) => { - const type = getTypeByValue(values[key]); - if (type === "object") { - memo[key] = { - type: "object", - description: "", - context: {}, - composite: defineNestedComposite(values[key]), - }; - } - else { - memo[key] = { - type, - description: "", - context: {}, - }; - } - return memo; - }, {}); - } - function normalizeMetricName(name) { - if (typeof name !== "undefined" && name.length > 0 && name[0] !== "/") { - return "/" + name; - } - else { - return name; - } - } - function getMetricValueByType(metric) { - const type = getMetricTypeByValue(metric); - if (type === "timestamp") { - return Date.now(); - } - else { - return publishNestedComposite(metric.value); - } - } - function publishNestedComposite(values) { - if (typeof values !== "object") { - return values; - } - return Object.keys(values).reduce((memo, key) => { - const value = values[key]; - if (typeof value === "object" && value.constructor !== Date) { - memo[key] = publishNestedComposite(value); - } - else if (value.constructor === Date) { - memo[key] = new Date(value).getTime(); - } - else if (value.constructor === Boolean) { - memo[key] = value.toString(); - } - else { - memo[key] = value; - } - return memo; - }, {}); - } - function flatten(arr) { - return arr.reduce((flat, toFlatten) => { - return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); - }, []); - } - function getHighestState(arr) { - return arr.sort((a, b) => { - if (!a.state) { - return 1; - } - if (!b.state) { - return -1; - } - return b.state - a.state; - })[0]; - } - function aggregateDescription(arr) { - let msg = ""; - arr.forEach((m, idx, a) => { - const path = m.path.join("."); - if (idx === a.length - 1) { - msg += path + "." + m.name + ": " + m.description; - } - else { - msg += path + "." + m.name + ": " + m.description + ","; - } - }); - if (msg.length > 100) { - return msg.slice(0, 100) + "..."; - } - else { - return msg; - } - } - function composeMsgForRootStateMetric(system) { - const aggregatedState = system.root.getAggregateState(); - const merged = flatten(aggregatedState); - const highestState = getHighestState(merged); - const aggregateDesc = aggregateDescription(merged); - return { - description: aggregateDesc, - value: highestState.state, - }; - } - - function gw3 (connection, config) { - if (!connection || typeof connection !== "object") { - throw new Error("Connection is required parameter"); - } - let joinPromise; - let session; - const init = (repo) => { - let resolveReadyPromise; - joinPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - session = connection.domain("metrics"); - session.onJoined((reconnect) => { - if (!reconnect && resolveReadyPromise) { - resolveReadyPromise(); - resolveReadyPromise = undefined; - } - const rootStateMetric = { - name: "/State", - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const defineRootMetricsMsg = { - type: "define", - metrics: [rootStateMetric], - }; - session.sendFireAndForget(defineRootMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(err)}`); - }); - if (reconnect) { - replayRepo(repo); - } - }); - session.join({ - system: config.system, - service: config.service, - instance: config.instance - }); - }; - const replayRepo = (repo) => { - replaySystem(repo.root); - }; - const replaySystem = (system) => { - createSystem(system); - system.metrics.forEach((m) => { - createMetric(m); - }); - system.subSystems.forEach((ss) => { - replaySystem(ss); - }); - }; - const createSystem = async (system) => { - if (system.parent === undefined) { - return; - } - await joinPromise; - const metric = { - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const createMetricsMsg = { - type: "define", - metrics: [metric], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const updateSystem = async (system, state) => { - await joinPromise; - const shadowedUpdateMetric = { - type: "publish", - values: [{ - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - value: { - Description: state.description, - Value: state.state, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(shadowedUpdateMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - const stateObj = composeMsgForRootStateMetric(system); - const rootMetric = { - type: "publish", - peer_id: connection.peerId, - values: [{ - name: "/State", - value: { - Description: stateObj.description, - Value: stateObj.value, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(rootMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for root state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const createMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - const m = serializeMetric(metricClone); - const createMetricsMsg = { - type: "define", - metrics: [m], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for metric ${metric.name}: ${JSON.stringify(err)}`); - }); - if (typeof metricClone.value !== "undefined") { - updateMetricCore(metricClone); - } - }; - const updateMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - updateMetricCore(metricClone); - }; - const updateMetricCore = (metric) => { - if (canUpdate()) { - const value = getMetricValueByType(metric); - const publishMetricsMsg = { - type: "publish", - values: [{ - name: normalizeMetricName(metric.path.join("/") + "/" + metric.name), - value, - timestamp: Date.now(), - }], - }; - return session.sendFireAndForget(publishMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to publish metric ${metric.name}: ${JSON.stringify(err)}`); - }); - } - return Promise.resolve(); - }; - const cloneMetric = (metric) => { - const metricClone = { ...metric }; - if (typeof metric.value === "object" && metric.value !== null) { - metricClone.value = { ...metric.value }; - } - return metricClone; - }; - const canUpdate = () => { - try { - const func = config.canUpdateMetric ?? (() => true); - return func(); - } - catch { - return true; - } - }; - return { - init, - createSystem, - updateSystem, - createMetric, - updateMetric, - }; - } - - var Helpers = { - validate: (definition, parent, transport) => { - if (definition === null || typeof definition !== "object") { - throw new Error("Missing definition"); - } - if (parent === null || typeof parent !== "object") { - throw new Error("Missing parent"); - } - if (transport === null || typeof transport !== "object") { - throw new Error("Missing transport"); - } - }, - }; - - class BaseMetric { - definition; - system; - transport; - value; - type; - path = []; - name; - description; - get repo() { - return this.system?.repo; - } - get id() { return `${this.system.path}/${name}`; } - constructor(definition, system, transport, value, type) { - this.definition = definition; - this.system = system; - this.transport = transport; - this.value = value; - this.type = type; - Helpers.validate(definition, system, transport); - this.path = system.path.slice(0); - this.path.push(system.name); - this.name = definition.name; - this.description = definition.description; - transport.createMetric(this); - } - update(newValue) { - this.value = newValue; - return this.transport.updateMetric(this); - } - } - - class NumberMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.NUMBER); - } - incrementBy(num) { - this.update(this.value + num); - } - increment() { - this.incrementBy(1); - } - decrement() { - this.incrementBy(-1); - } - decrementBy(num) { - this.incrementBy(num * -1); - } - } - - class ObjectMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.OBJECT); - } - update(newValue) { - this.mergeValues(newValue); - return this.transport.updateMetric(this); - } - mergeValues(values) { - return Object.keys(this.value).forEach((k) => { - if (typeof values[k] !== "undefined") { - this.value[k] = values[k]; - } - }); - } - } - - class StringMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.STRING); - } - } - - class TimestampMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.TIMESTAMP); - } - now() { - this.update(new Date()); - } - } - - function system(name, repo, protocol, parent, description) { - if (!repo) { - throw new Error("Repository is required"); - } - if (!protocol) { - throw new Error("Transport is required"); - } - const _transport = protocol; - const _name = name; - const _description = description || ""; - const _repo = repo; - const _parent = parent; - const _path = _buildPath(parent); - let _state = {}; - const id = _arrayToString(_path, "/") + name; - const root = repo.root; - const _subSystems = []; - const _metrics = []; - function subSystem(nameSystem, descriptionSystem) { - if (!nameSystem || nameSystem.length === 0) { - throw new Error("name is required"); - } - const match = _subSystems.filter((s) => s.name === nameSystem); - if (match.length > 0) { - return match[0]; - } - const _system = system(nameSystem, _repo, _transport, me, descriptionSystem); - _subSystems.push(_system); - return _system; - } - function setState(state, stateDescription) { - _state = { state, description: stateDescription }; - _transport.updateSystem(me, _state); - } - function stringMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.STRING, value, (metricDef) => new StringMetric(metricDef, me, _transport, value)); - } - function numberMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.NUMBER, value, (metricDef) => new NumberMetric(metricDef, me, _transport, value)); - } - function objectMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.OBJECT, value, (metricDef) => new ObjectMetric(metricDef, me, _transport, value)); - } - function timestampMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.TIMESTAMP, value, (metricDef) => new TimestampMetric(metricDef, me, _transport, value)); - } - function _getOrCreateMetric(metricObject, expectedType, value, createMetric) { - let metricDef = { name: "" }; - if (typeof metricObject === "string") { - metricDef = { name: metricObject }; - } - else { - metricDef = metricObject; - } - const matching = _metrics.filter((shadowedMetric) => shadowedMetric.name === metricDef.name); - if (matching.length > 0) { - const existing = matching[0]; - if (existing.type !== expectedType) { - throw new Error(`A metric named ${metricDef.name} is already defined with different type.`); - } - if (typeof value !== "undefined") { - existing - .update(value) - .catch(() => { }); - } - return existing; - } - const metric = createMetric(metricDef); - _metrics.push(metric); - return metric; - } - function _buildPath(shadowedSystem) { - if (!shadowedSystem || !shadowedSystem.parent) { - return []; - } - const path = _buildPath(shadowedSystem.parent); - path.push(shadowedSystem.name); - return path; - } - function _arrayToString(path, separator) { - return ((path && path.length > 0) ? path.join(separator) : ""); - } - function getAggregateState() { - const aggState = []; - if (Object.keys(_state).length > 0) { - aggState.push({ - name: _name, - path: _path, - state: _state.state, - description: _state.description, - }); - } - _subSystems.forEach((shadowedSubSystem) => { - const result = shadowedSubSystem.getAggregateState(); - if (result.length > 0) { - aggState.push(...result); - } - }); - return aggState; - } - const me = { - get name() { - return _name; - }, - get description() { - return _description; - }, - get repo() { - return _repo; - }, - get parent() { - return _parent; - }, - path: _path, - id, - root, - get subSystems() { - return _subSystems; - }, - get metrics() { - return _metrics; - }, - subSystem, - getState: () => { - return _state; - }, - setState, - stringMetric, - timestampMetric, - objectMetric, - numberMetric, - getAggregateState, - }; - _transport.createSystem(me); - return me; - } - - class Repository { - root; - constructor(options, protocol) { - protocol.init(this); - this.root = system("", this, protocol); - this.addSystemMetrics(this.root, options.clickStream || options.clickStream === undefined); - } - addSystemMetrics(rootSystem, useClickStream) { - if (typeof navigator !== "undefined") { - rootSystem.stringMetric("UserAgent", navigator.userAgent); - } - if (useClickStream && typeof document !== "undefined") { - const clickStream = rootSystem.subSystem("ClickStream"); - const documentClickHandler = (e) => { - if (!e.target) { - return; - } - const target = e.target; - const className = target ? target.getAttribute("class") ?? "" : ""; - clickStream.objectMetric("LastBrowserEvent", { - type: "click", - timestamp: new Date(), - target: { - className, - id: target.id, - type: "<" + target.tagName.toLowerCase() + ">", - href: target.href || "", - }, - }); - }; - clickStream.objectMetric("Page", { - title: document.title, - page: window.location.href, - }); - if (document.addEventListener) { - document.addEventListener("click", documentClickHandler); - } - else { - document.attachEvent("onclick", documentClickHandler); - } - } - rootSystem.stringMetric("StartTime", (new Date()).toString()); - const urlMetric = rootSystem.stringMetric("StartURL", ""); - const appNameMetric = rootSystem.stringMetric("AppName", ""); - if (typeof window !== "undefined") { - if (typeof window.location !== "undefined") { - const startUrl = window.location.href; - urlMetric.update(startUrl); - } - if (typeof window.glue42gd !== "undefined") { - appNameMetric.update(window.glue42gd.appName); - } - } - } - } - - class NullProtocol { - init(repo) { - } - createSystem(system) { - return Promise.resolve(); - } - updateSystem(metric, state) { - return Promise.resolve(); - } - createMetric(metric) { - return Promise.resolve(); - } - updateMetric(metric) { - return Promise.resolve(); - } - } - - class PerfTracker { - api; - lastCount = 0; - initialPublishTimeout = 10 * 1000; - publishInterval = 60 * 1000; - system; - constructor(api, initialPublishTimeout, publishInterval) { - this.api = api; - this.initialPublishTimeout = initialPublishTimeout ?? this.initialPublishTimeout; - this.publishInterval = publishInterval ?? this.publishInterval; - this.scheduleCollection(); - this.system = this.api.subSystem("performance", "Performance data published by the web application"); - } - scheduleCollection() { - setTimeout(() => { - this.collect(); - setInterval(() => { - this.collect(); - }, this.publishInterval); - }, this.initialPublishTimeout); - } - collect() { - try { - this.collectMemory(); - this.collectEntries(); - } - catch { - } - } - collectMemory() { - const memory = window.performance.memory; - this.system.stringMetric("memory", JSON.stringify({ - totalJSHeapSize: memory.totalJSHeapSize, - usedJSHeapSize: memory.usedJSHeapSize - })); - } - collectEntries() { - const allEntries = window.performance.getEntries(); - if (allEntries.length <= this.lastCount) { - return; - } - this.lastCount = allEntries.length; - const jsonfiedEntries = allEntries.map((i) => i.toJSON()); - this.system.stringMetric("entries", JSON.stringify(jsonfiedEntries)); - } - } - - var metrics = (options) => { - let protocol; - if (!options.connection || typeof options.connection !== "object") { - protocol = new NullProtocol(); - } - else { - protocol = gw3(options.connection, options); - } - const repo = new Repository(options, protocol); - let rootSystem = repo.root; - if (!options.disableAutoAppSystem) { - rootSystem = rootSystem.subSystem("App"); - } - const api = addFAVSupport(rootSystem); - initPerf(api, options.pagePerformanceMetrics); - return api; - }; - function initPerf(api, config) { - if (typeof window === "undefined") { - return; - } - const perfConfig = window?.glue42gd?.metrics?.pagePerformanceMetrics; - if (perfConfig) { - config = perfConfig; - } - if (config?.enabled) { - new PerfTracker(api, config.initialPublishTimeout, config.publishInterval); - } - } - function addFAVSupport(system) { - const reportingSystem = system.subSystem("reporting"); - const def = { - name: "features" - }; - let featureMetric; - const featureMetricFunc = (name, action, payload) => { - if (typeof name === "undefined" || name === "") { - throw new Error("name is mandatory"); - } - else if (typeof action === "undefined" || action === "") { - throw new Error("action is mandatory"); - } - else if (typeof payload === "undefined" || payload === "") { - throw new Error("payload is mandatory"); - } - if (!featureMetric) { - featureMetric = reportingSystem.objectMetric(def, { name, action, payload }); - } - else { - featureMetric.update({ - name, - action, - payload - }); - } - }; - system.featureMetric = featureMetricFunc; - return system; - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackRegistryFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - class InProcTransport { - gw; - registry = CallbackRegistryFactory(); - client; - constructor(settings, logger) { - this.gw = settings.facade; - this.gw.connect((_client, message) => { - this.messageHandler(message); - }).then((client) => { - this.client = client; - }); - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - if (this.client) { - this.client.send(msg); - return Promise.resolve(undefined); - } - else { - return Promise.reject(`not connected`); - } - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "in-memory"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class SharedWorkerTransport { - logger; - worker; - registry = CallbackRegistryFactory(); - constructor(workerFile, logger) { - this.logger = logger; - this.worker = new SharedWorker(workerFile); - this.worker.port.onmessage = (e) => { - this.messageHandler(e.data); - }; - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - this.worker.port.postMessage(msg); - return Promise.resolve(); - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "shared-worker"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class Utils { - static isNode() { - if (typeof Utils._isNode !== "undefined") { - return Utils._isNode; - } - if (typeof window !== "undefined") { - Utils._isNode = false; - return false; - } - try { - Utils._isNode = Object.prototype.toString.call(global.process) === "[object process]"; - } - catch (e) { - Utils._isNode = false; - } - return Utils._isNode; - } - static _isNode; - } - - class PromiseWrapper { - static delay(time) { - return new Promise((resolve) => setTimeout(resolve, time)); - } - resolve; - reject; - promise; - rejected = false; - resolved = false; - get ended() { - return this.rejected || this.resolved; - } - constructor() { - this.promise = new Promise((resolve, reject) => { - this.resolve = (t) => { - this.resolved = true; - resolve(t); - }; - this.reject = (err) => { - this.rejected = true; - reject(err); - }; - }); - } - } - - const timers = {}; - function getAllTimers() { - return timers; - } - function timer (timerName) { - const existing = timers[timerName]; - if (existing) { - return existing; - } - const marks = []; - function now() { - return new Date().getTime(); - } - const startTime = now(); - mark("start", startTime); - let endTime; - let period; - function stop() { - endTime = now(); - mark("end", endTime); - period = endTime - startTime; - return period; - } - function mark(name, time) { - const currentTime = time ?? now(); - let diff = 0; - if (marks.length > 0) { - diff = currentTime - marks[marks.length - 1].time; - } - marks.push({ name, time: currentTime, diff }); - } - const timerObj = { - get startTime() { - return startTime; - }, - get endTime() { - return endTime; - }, - get period() { - return period; - }, - stop, - mark, - marks - }; - timers[timerName] = timerObj; - return timerObj; - } - - const WebSocketConstructor = Utils.isNode() ? null : window.WebSocket; - class WS { - ws; - logger; - settings; - startupTimer = timer("connection"); - _running = true; - _registry = CallbackRegistryFactory(); - wsRequests = []; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - if (!this.settings.ws) { - throw new Error("ws is missing"); - } - } - onMessage(callback) { - return this._registry.add("onMessage", callback); - } - send(msg, options) { - return new Promise((resolve, reject) => { - this.waitForSocketConnection(() => { - try { - this.ws?.send(msg); - resolve(); - } - catch (e) { - reject(e); - } - }, reject); - }); - } - open() { - this.logger.info("opening ws..."); - this._running = true; - return new Promise((resolve, reject) => { - this.waitForSocketConnection(resolve, reject); - }); - } - close() { - this._running = false; - if (this.ws) { - this.ws.close(); - } - return Promise.resolve(); - } - onConnectedChanged(callback) { - return this._registry.add("onConnectedChanged", callback); - } - name() { - return this.settings.ws; - } - reconnect() { - this.ws?.close(); - const pw = new PromiseWrapper(); - this.waitForSocketConnection(() => { - pw.resolve(); - }); - return pw.promise; - } - waitForSocketConnection(callback, failed) { - failed = failed ?? (() => { }); - if (!this._running) { - failed(`wait for socket on ${this.settings.ws} failed - socket closed by user`); - return; - } - if (this.ws?.readyState === 1) { - callback(); - return; - } - this.wsRequests.push({ callback, failed }); - if (this.wsRequests.length > 1) { - return; - } - this.openSocket(); - } - async openSocket(retryInterval, retriesLeft) { - this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${retryInterval}, retriesLeft: ${retriesLeft}...`); - this.startupTimer.mark("opening-socket"); - if (retryInterval === undefined) { - retryInterval = this.settings.reconnectInterval; - } - if (typeof retriesLeft === "undefined") { - retriesLeft = this.settings.reconnectAttempts; - } - if (retriesLeft !== undefined) { - if (retriesLeft === 0) { - this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`); - return; - } - this.logger.debug(`will retry ${retriesLeft} more times (every ${retryInterval} ms)`); - } - try { - await this.initiateSocket(); - this.startupTimer.mark("socket-initiated"); - this.notifyForSocketState(); - } - catch { - setTimeout(() => { - const retries = retriesLeft === undefined ? undefined : retriesLeft - 1; - this.openSocket(retryInterval, retries); - }, retryInterval); - } - } - initiateSocket() { - const pw = new PromiseWrapper(); - this.logger.debug(`initiating ws to ${this.settings.ws}...`); - this.ws = new WebSocketConstructor(this.settings.ws ?? ""); - let wasOpen = false; - this.ws.onerror = (err) => { - let reason; - try { - reason = JSON.stringify(err); - } - catch (error) { - const seen = new WeakSet(); - const replacer = (key, value) => { - if (typeof value === "object" && value !== null) { - if (seen.has(value)) { - return; - } - seen.add(value); - } - if (value instanceof Error) { - return { - message: value.message, - name: value.name, - stack: value.stack - }; - } - return value; - }; - reason = JSON.stringify(err, replacer); - } - this.logger.info(`ws error - reason: ${reason}`); - pw.reject("error"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("error"); - } - this.notifyStatusChanged(false, reason); - }; - this.ws.onclose = (err) => { - this.logger.info(`ws closed - code: ${err?.code} reason: ${err?.reason}`); - pw.reject("closed"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("closed"); - } - this.notifyStatusChanged(false); - }; - this.ws.onopen = () => { - this.startupTimer.mark("ws-opened"); - this.logger.info(`ws opened ${this.settings.identity?.application}`); - pw.resolve(); - wasOpen = true; - this.notifyStatusChanged(true); - }; - this.ws.onmessage = (message) => { - this._registry.execute("onMessage", message.data); - }; - return pw.promise; - } - notifyForSocketState(error) { - this.wsRequests.forEach((wsRequest) => { - if (error) { - if (wsRequest.failed) { - wsRequest.failed(error); - } - } - else { - wsRequest.callback(); - } - }); - this.wsRequests = []; - } - notifyStatusChanged(status, reason) { - this._registry.execute("onConnectedChanged", status, reason); - } - } - - class MessageReplayerImpl { - specs; - specsNames = []; - messages = {}; - isDone; - subs = {}; - subsRefCount = {}; - connection; - constructor(specs) { - this.specs = {}; - for (const spec of specs) { - this.specs[spec.name] = spec; - this.specsNames.push(spec.name); - } - } - init(connection) { - this.connection = connection; - for (const name of this.specsNames) { - for (const type of this.specs[name].types) { - let refCount = this.subsRefCount[type]; - if (!refCount) { - refCount = 0; - } - refCount += 1; - this.subsRefCount[type] = refCount; - if (refCount > 1) { - continue; - } - const sub = connection.on(type, (msg) => this.processMessage(type, msg)); - this.subs[type] = sub; - } - } - } - processMessage(type, msg) { - if (this.isDone || !msg) { - return; - } - for (const name of this.specsNames) { - if (this.specs[name].types.indexOf(type) !== -1) { - const messages = this.messages[name] || []; - this.messages[name] = messages; - messages.push(msg); - } - } - } - drain(name, callback) { - if (callback) { - (this.messages[name] || []).forEach(callback); - } - delete this.messages[name]; - for (const type of this.specs[name].types) { - this.subsRefCount[type] -= 1; - if (this.subsRefCount[type] <= 0) { - this.connection?.off(this.subs[type]); - delete this.subs[type]; - delete this.subsRefCount[type]; - } - } - delete this.specs[name]; - if (!this.specs.length) { - this.isDone = true; - } - } - } - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet[(Math.random() * 64) | 0]; - } - return id - }; - - const PromisePlus = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WebPlatformTransport { - settings; - logger; - identity; - isPreferredActivated; - _connectionProtocolVersion; - _communicationId; - publicWindowId; - selfAssignedWindowId; - iAmConnected = false; - parentReady = false; - rejected = false; - parentPingResolve; - parentPingInterval; - connectionResolve; - extConnectionResolve; - extConnectionReject; - connectionReject; - port; - myClientId; - extContentAvailable = false; - extContentConnecting = false; - extContentConnected = false; - parentWindowId; - parentInExtMode = false; - webNamespace = "g42_core_web"; - parent; - parentType; - parentPingTimeout = 5000; - connectionRequestTimeout = 7000; - defaultTargetString = "*"; - registry = CallbackRegistryFactory(); - messages = { - connectionAccepted: { name: "connectionAccepted", handle: this.handleConnectionAccepted.bind(this) }, - connectionRejected: { name: "connectionRejected", handle: this.handleConnectionRejected.bind(this) }, - connectionRequest: { name: "connectionRequest", handle: this.handleConnectionRequest.bind(this) }, - parentReady: { - name: "parentReady", handle: () => { - } - }, - parentPing: { name: "parentPing", handle: this.handleParentPing.bind(this) }, - platformPing: { name: "platformPing", handle: this.handlePlatformPing.bind(this) }, - platformReady: { name: "platformReady", handle: this.handlePlatformReady.bind(this) }, - clientUnload: { name: "clientUnload", handle: () => { } }, - manualUnload: { name: "manualUnload", handle: this.handleManualUnload.bind(this) }, - extConnectionResponse: { name: "extConnectionResponse", handle: this.handleExtConnectionResponse.bind(this) }, - extSetupRequest: { name: "extSetupRequest", handle: this.handleExtSetupRequest.bind(this) }, - gatewayDisconnect: { name: "gatewayDisconnect", handle: this.handleGatewayDisconnect.bind(this) }, - gatewayInternalConnect: { name: "gatewayInternalConnect", handle: this.handleGatewayInternalConnect.bind(this) } - }; - constructor(settings, logger, identity) { - this.settings = settings; - this.logger = logger; - this.identity = identity; - this.extContentAvailable = !!window.glue42ext; - this.setUpMessageListener(); - this.setUpUnload(); - this.setupPlatformUnloadListener(); - this.parentType = window.name.includes("#wsp") ? "workspace" : undefined; - } - manualSetReadyState() { - this.iAmConnected = true; - this.parentReady = true; - } - get transportWindowId() { - return this.publicWindowId; - } - get communicationId() { - return this._communicationId; - } - async sendObject(msg) { - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: msg }, window.origin); - } - if (!this.port) { - throw new Error("Cannot send message, because the port was not opened yet"); - } - this.port.postMessage(msg); - } - get isObjectBasedTransport() { - return true; - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - send() { - return Promise.reject("not supported"); - } - onConnectedChanged(callback) { - return this.registry.add("onConnectedChanged", callback); - } - async open() { - this.logger.debug("opening a connection to the web platform gateway."); - await this.connect(); - this.notifyStatusChanged(true); - } - close() { - this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId || "unknown"}, client connected: ${this.iAmConnected}`); - const message = { - glue42core: { - type: this.messages.gatewayDisconnect.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.port?.postMessage(message); - this.parentReady = false; - this.notifyStatusChanged(false, "manual reconnection"); - return Promise.resolve(); - } - name() { - return "web-platform"; - } - async reconnect() { - await this.close(); - return Promise.resolve(); - } - initiateInternalConnection() { - return new Promise((resolve, reject) => { - this.logger.debug("opening an internal web platform connection"); - this.port = this.settings.port; - if (this.iAmConnected) { - this.logger.warn("cannot open a new connection, because this client is currently connected"); - return; - } - this.port.onmessage = (event) => { - if (this.iAmConnected && !event.data?.glue42core) { - this.registry.execute("onMessage", event.data); - return; - } - const data = event.data?.glue42core; - if (!data) { - return; - } - if (data.type === this.messages.gatewayInternalConnect.name && data.success) { - this.publicWindowId = this.settings.windowId; - if (this.identity && this.publicWindowId) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.publicWindowId; - } - resolve(); - } - if (data.type === this.messages.gatewayInternalConnect.name && data.error) { - reject(data.error); - } - }; - this.port.postMessage({ - glue42core: { - type: this.messages.gatewayInternalConnect.name - } - }); - }); - } - initiateRemoteConnection(target) { - return PromisePlus((resolve, reject) => { - this.connectionResolve = resolve; - this.connectionReject = reject; - this.myClientId = this.myClientId ?? nanoid(10); - const bridgeInstanceId = this.getMyWindowId() || nanoid(10); - const request = { - glue42core: { - type: this.messages.connectionRequest.name, - clientId: this.myClientId, - clientType: "child", - bridgeInstanceId, - selfAssignedWindowId: this.selfAssignedWindowId - } - }; - this.logger.debug(`sending connection request - clientId: ${this.myClientId}`); - if (this.extContentConnecting) { - request.glue42core.clientType = "child"; - request.glue42core.bridgeInstanceId = this.myClientId; - request.glue42core.parentWindowId = this.parentWindowId; - return window.postMessage(request, window.origin); - } - if (!target) { - throw new Error("Cannot send a connection request, because no glue target was specified!"); - } - target.postMessage(request, this.defaultTargetString); - }, this.connectionRequestTimeout, "The connection to the target glue window timed out"); - } - async isParentCheckSuccess(parentCheck) { - try { - await parentCheck; - return { success: true }; - } - catch (error) { - return { success: false }; - } - } - setUpMessageListener() { - if (this.settings.port) { - this.logger.debug("skipping generic message listener, because this is an internal client"); - return; - } - this.logger.debug("setting up window message listener"); - window.addEventListener("message", (event) => { - const data = event.data?.glue42core; - if (!data || this.rejected) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - if (!this.checkMessageTypeValid(data.type)) { - this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${data.type}`); - return; - } - const messageType = data.type; - this.logger.debug(`received valid glue42core message of type: ${messageType}`); - this.messages[messageType].handle(event); - }); - } - setUpUnload() { - if (this.settings.port) { - this.logger.debug("skipping unload event listener, because this is an internal client"); - return; - } - this.logger.debug("setting up unload event listeners"); - window.addEventListener("beforeunload", () => { - if (this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - window.addEventListener("pagehide", () => { - if (!this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - } - signalClientDisappearing() { - if (this.extContentConnected) { - return; - } - this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.parent?.postMessage(message, this.defaultTargetString); - this.port?.postMessage(message); - } - handlePlatformReady(event) { - this.logger.debug("the web platform gave the ready signal"); - this.parentReady = true; - if (this.parentPingResolve) { - this.parentPingResolve(); - delete this.parentPingResolve; - } - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - this.parent = event.source; - this.parentType = window.name.includes("#wsp") ? "workspace" : "window"; - } - handleConnectionAccepted(event) { - const data = event.data?.glue42core; - if (this.myClientId !== data.clientId) { - return this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${data.clientId}`); - } - return this.handleAcceptanceOfMyRequest(data); - } - handleAcceptanceOfMyRequest(data) { - this.logger.debug("handling a connection accepted signal targeted at me."); - this.isPreferredActivated = data.isPreferredActivated; - if (this.extContentConnecting) { - return this.processExtContentConnection(data); - } - if (!data.port) { - this.logger.error("cannot set up my connection, because I was not provided with a port"); - return; - } - this._connectionProtocolVersion = data.connectionProtocolVersion; - this.publicWindowId = this.getMyWindowId(); - if (this.identity) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.identity.instance ? this.identity.instance : this.publicWindowId || nanoid(10); - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - this._communicationId = data.communicationId; - this.port = data.port; - this.port.onmessage = (e) => this.registry.execute("onMessage", e.data); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - this.logger.error("unable to call the connection resolve, because no connection promise was found"); - } - processExtContentConnection(data) { - this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."); - this.extContentConnecting = false; - this.extContentConnected = true; - this.publicWindowId = this.parentWindowId || this.myClientId; - if (this.extContentConnecting && this.identity) { - this.identity.windowId = this.publicWindowId; - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - window.addEventListener("message", (event) => { - const extData = event.data?.glue42ExtInc; - if (!extData) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - this.registry.execute("onMessage", extData); - }); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - } - handleConnectionRejected(event) { - this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"); - if (!this.connectionReject) { - return; - } - const errorMsg = typeof event.data.glue42core?.error === "string" - ? `Connection was rejected. ${event.data.glue42core?.error}` - : "The platform connection was rejected. Most likely because this window was not created by a glue API call"; - this.connectionReject(errorMsg); - delete this.connectionReject; - } - handleConnectionRequest() { - if (this.extContentConnecting) { - this.logger.debug("This connection request event is targeted at the extension content"); - return; - } - } - handleParentPing(event) { - if (!this.parentReady) { - this.logger.debug("my parent is not ready, I am ignoring the parent ping"); - return; - } - if (!this.iAmConnected) { - this.logger.debug("i am not fully connected yet, I am ignoring the parent ping"); - return; - } - const message = { - glue42core: { - type: this.messages.parentReady.name - } - }; - if (this.extContentConnected) { - message.glue42core.extMode = { windowId: this.myClientId }; - } - const source = event.source; - this.logger.debug("responding to a parent ping with a ready message"); - source.postMessage(message, event.origin); - } - setupPlatformUnloadListener() { - this.logger.debug("setting up platform unload listener"); - this.onMessage((msg) => { - if (msg.type === "platformUnload") { - this.logger.debug("detected a web platform unload"); - this.parentReady = false; - this.notifyStatusChanged(false, "Gateway unloaded"); - } - }); - } - handleManualUnload() { - this.logger.debug("handling manual unload"); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: message }, window.origin); - } - this.port?.postMessage(message); - } - handlePlatformPing() { - return; - } - notifyStatusChanged(status, reason) { - this.logger.debug(`status changed - connected: ${status}, reason: ${reason || "none"}`); - this.iAmConnected = status; - this.registry.execute("onConnectedChanged", status, reason); - } - checkMessageTypeValid(typeToValidate) { - return typeof typeToValidate === "string" && !!this.messages[typeToValidate]; - } - requestConnectionPermissionFromExt() { - return this.waitForContentScript() - .then(() => PromisePlus((resolve, reject) => { - this.extConnectionResolve = resolve; - this.extConnectionReject = reject; - const message = { - glue42core: { - type: "extSetupRequest" - } - }; - this.logger.debug("permission request to the extension content script was sent"); - window.postMessage(message, window.origin); - }, this.parentPingTimeout, "Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")); - } - handleExtConnectionResponse(event) { - const data = event.data?.glue42core; - if (!data.approved) { - return this.extConnectionReject ? this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected") : undefined; - } - if (this.extConnectionResolve) { - this.extConnectionResolve(); - delete this.extConnectionResolve; - } - this.extContentConnecting = true; - this.parentType = "extension"; - this.logger.debug("The extension connection was approved, proceeding."); - } - handleExtSetupRequest() { - return; - } - handleGatewayDisconnect() { - return; - } - handleGatewayInternalConnect() { - return; - } - waitForContentScript() { - const contentReady = !!window.glue42ext?.content; - if (contentReady) { - return Promise.resolve(); - } - return PromisePlus((resolve) => { - window.addEventListener("Glue42EXTReady", () => { - resolve(); - }); - }, this.connectionRequestTimeout, "The content script was available, but was never heard to be ready"); - } - async connect() { - if (this.settings.port) { - await this.initiateInternalConnection(); - this.logger.debug("internal web platform connection completed"); - return; - } - this.logger.debug("opening a client web platform connection"); - await this.findParent(); - await this.initiateRemoteConnection(this.parent); - this.logger.debug("the client is connected"); - } - async findParent() { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const myInsideParents = this.getPossibleParentsInWindow(window); - const myOutsideParents = this.getPossibleParentsOutsideWindow(window.top?.opener, window.top); - const uniqueParents = new Set([...myInsideParents, ...myOutsideParents]); - if (!uniqueParents.size && !this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - if (!uniqueParents.size && this.extContentAvailable) { - await this.requestConnectionPermissionFromExt(); - return; - } - const defaultParentCheck = await this.isParentCheckSuccess(this.confirmParent(Array.from(uniqueParents))); - if (defaultParentCheck.success) { - this.logger.debug("The default parent was found!"); - return; - } - if (!this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - await this.requestConnectionPermissionFromExt(); - } - getPossibleParentsInWindow(currentWindow) { - return (!currentWindow?.parent || currentWindow === currentWindow.parent) ? [] : [currentWindow.parent, ...this.getPossibleParentsInWindow(currentWindow.parent)]; - } - getPossibleParentsOutsideWindow(opener, current) { - return (!opener || !current || opener === current) ? [] : [opener, ...this.getPossibleParentsInWindow(opener), ...this.getPossibleParentsOutsideWindow(opener.opener, opener)]; - } - confirmParent(targets) { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const parentCheck = PromisePlus((resolve) => { - this.parentPingResolve = resolve; - const message = { - glue42core: { - type: this.messages.platformPing.name - } - }; - this.parentPingInterval = setInterval(() => { - targets.forEach((target) => { - target.postMessage(message, this.defaultTargetString); - }); - }, 1000); - }, this.parentPingTimeout, connectionNotPossibleMsg); - parentCheck.catch(() => { - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - }); - return parentCheck; - } - getMyWindowId() { - if (this.parentType === "workspace") { - return window.name.substring(0, window.name.indexOf("#wsp")); - } - if (window !== window.top) { - return; - } - if (window.name?.includes("g42")) { - return window.name; - } - this.selfAssignedWindowId = this.selfAssignedWindowId || `g42-${nanoid(10)}`; - return this.selfAssignedWindowId; - } - } - - const waitForInvocations = (invocations, callback) => { - let left = invocations; - return () => { - left--; - if (left === 0) { - callback(); - } - }; - }; - - class AsyncSequelizer { - minSequenceInterval; - queue = []; - isExecutingQueue = false; - constructor(minSequenceInterval = 0) { - this.minSequenceInterval = minSequenceInterval; - } - enqueue(action) { - return new Promise((resolve, reject) => { - this.queue.push({ action, resolve, reject }); - this.executeQueue(); - }); - } - async executeQueue() { - if (this.isExecutingQueue) { - return; - } - this.isExecutingQueue = true; - while (this.queue.length) { - const operation = this.queue.shift(); - if (!operation) { - this.isExecutingQueue = false; - return; - } - try { - const actionResult = await operation.action(); - operation.resolve(actionResult); - } - catch (error) { - operation.reject(error); - } - await this.intervalBreak(); - } - this.isExecutingQueue = false; - } - intervalBreak() { - return new Promise((res) => setTimeout(res, this.minSequenceInterval)); - } - } - - function domainSession (domain, connection, logger, successMessages, errorMessages) { - if (domain == null) { - domain = "global"; - } - successMessages = successMessages ?? ["success"]; - errorMessages = errorMessages ?? ["error"]; - let isJoined = domain === "global"; - let tryReconnecting = false; - let _latestOptions; - let _connectionOn = false; - const callbacks = CallbackRegistryFactory(); - connection.disconnected(handleConnectionDisconnected); - connection.loggedIn(handleConnectionLoggedIn); - connection.on("success", (msg) => handleSuccessMessage(msg)); - connection.on("error", (msg) => handleErrorMessage(msg)); - connection.on("result", (msg) => handleSuccessMessage(msg)); - if (successMessages) { - successMessages.forEach((sm) => { - connection.on(sm, (msg) => handleSuccessMessage(msg)); - }); - } - if (errorMessages) { - errorMessages.forEach((sm) => { - connection.on(sm, (msg) => handleErrorMessage(msg)); - }); - } - const requestsMap = {}; - function join(options) { - _latestOptions = options; - return new Promise((resolve, reject) => { - if (isJoined) { - resolve({}); - return; - } - let joinPromise; - if (domain === "global") { - joinPromise = _connectionOn ? Promise.resolve({}) : Promise.reject("not connected to gateway"); - } - else { - logger.debug(`joining domain ${domain}`); - const joinMsg = { - type: "join", - destination: domain, - domain: "global", - options, - }; - joinPromise = send(joinMsg); - } - joinPromise - .then(() => { - handleJoined(); - resolve({}); - }) - .catch((err) => { - logger.debug("error joining " + domain + " domain: " + JSON.stringify(err)); - reject(err); - }); - }); - } - function leave() { - if (domain === "global") { - return Promise.resolve(); - } - logger.debug("stopping session " + domain + "..."); - const leaveMsg = { - type: "leave", - destination: domain, - domain: "global", - }; - tryReconnecting = false; - return send(leaveMsg) - .then(() => { - isJoined = false; - callbacks.execute("onLeft"); - }) - .catch(() => { - isJoined = false; - callbacks.execute("onLeft"); - }); - } - function handleJoined() { - logger.debug("did join " + domain); - isJoined = true; - const wasReconnect = tryReconnecting; - tryReconnecting = false; - callbacks.execute("onJoined", wasReconnect); - } - function handleConnectionDisconnected() { - logger.debug("connection is down"); - _connectionOn = false; - isJoined = false; - tryReconnecting = true; - Object.keys(requestsMap).forEach(requestId => { - const request = requestsMap[requestId]; - if (request) { - logger.trace(`failing pending request ${requestId} due to connection lost`); - request.error({ - err: "Connection lost - gateway connection was disconnected" - }); - } - }); - callbacks.execute("onLeft", { disconnected: true }); - } - async function handleConnectionLoggedIn() { - _connectionOn = true; - if (tryReconnecting) { - logger.debug("connection is now up - trying to reconnect..."); - try { - await join(_latestOptions); - } - catch { - logger.trace(`failed to reconnect`); - } - } - } - function onJoined(callback) { - if (isJoined) { - callback(false); - } - return callbacks.add("onJoined", callback); - } - function onLeft(callback) { - if (!isJoined) { - callback(); - } - return callbacks.add("onLeft", callback); - } - function handleErrorMessage(msg) { - if (domain !== msg.domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.error(msg); - } - function handleSuccessMessage(msg) { - if (msg.domain !== domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.success(msg); - } - function getNextRequestId() { - return nanoid(10); - } - let queuedCalls = []; - function send(msg, tag, options) { - const ignore = ["hello", "join"]; - if (msg.type && ignore.indexOf(msg.type) === -1) { - if (!isJoined) { - console.warn(`trying to send a message (${msg.domain} ${msg.type}) but not connected, will queue`); - const pw = new PromiseWrapper(); - queuedCalls.push({ msg, tag, options, pw }); - if (queuedCalls.length === 1) { - const unsubscribe = onJoined(() => { - logger.info(`joined - will now send queued messages (${queuedCalls.length} -> [${queuedCalls.map((m) => m.msg.type)}])`); - queuedCalls.forEach((qm) => { - send(qm.msg, qm.tag, qm.options) - .then((t) => qm.pw.resolve(t)) - .catch((e) => qm.pw.reject(e)); - }); - queuedCalls = []; - unsubscribe(); - }); - } - return pw.promise; - } - } - options = options ?? {}; - msg.request_id = msg.request_id ?? getNextRequestId(); - msg.domain = msg.domain ?? domain; - if (!options.skipPeerId) { - msg.peer_id = connection.peerId; - } - const requestId = msg.request_id; - return new Promise((resolve, reject) => { - requestsMap[requestId] = { - success: (successMsg) => { - delete requestsMap[requestId]; - successMsg._tag = tag; - resolve(successMsg); - }, - error: (errorMsg) => { - console.warn(`Gateway error - ${JSON.stringify(errorMsg)}`); - delete requestsMap[requestId]; - errorMsg._tag = tag; - reject(errorMsg); - }, - }; - connection - .send(msg, options) - .catch((err) => { - requestsMap[requestId]?.error({ err }); - }); - }); - } - function sendFireAndForget(msg) { - msg.request_id = msg.request_id ? msg.request_id : getNextRequestId(); - msg.domain = msg.domain ?? domain; - msg.peer_id = connection.peerId; - return connection.send(msg); - } - return { - join, - leave, - onJoined, - onLeft, - send, - sendFireAndForget, - on: (type, callback) => { - connection.on(type, (msg) => { - if (msg.domain !== domain) { - return; - } - try { - callback(msg); - } - catch (e) { - logger.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(msg)}`, e); - } - }); - }, - loggedIn: (callback) => connection.loggedIn(callback), - connected: (callback) => connection.connected(callback), - disconnected: (callback) => connection.disconnected(callback), - get peerId() { - return connection.peerId; - }, - get domain() { - return domain; - }, - }; - } - - class Connection { - settings; - logger; - protocolVersion = 3; - peerId; - token; - info; - resolvedIdentity; - availableDomains; - gatewayToken; - replayer; - messageHandlers = {}; - ids = 1; - registry = CallbackRegistryFactory(); - _connected = false; - isTrace = false; - transport; - _defaultTransport; - _defaultAuth; - _targetTransport; - _targetAuth; - _swapTransport = false; - _switchInProgress = false; - _transportSubscriptions = []; - datePrefix = "#T42_DATE#"; - datePrefixLen = this.datePrefix.length; - dateMinLen = this.datePrefixLen + 1; - datePrefixFirstChar = this.datePrefix[0]; - _sequelizer = new AsyncSequelizer(); - _isLoggedIn = false; - shouldTryLogin = true; - pingTimer; - sessions = []; - globalDomain; - initialLogin = true; - initialLoginAttempts = 3; - loginConfig; - loginRetryInProgress = false; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - settings = settings || {}; - settings.reconnectAttempts = settings.reconnectAttempts ?? 10; - settings.reconnectInterval = settings.reconnectInterval ?? 1000; - if (settings.inproc) { - this.transport = new InProcTransport(settings.inproc, logger.subLogger("inMemory")); - } - else if (settings.sharedWorker) { - this.transport = new SharedWorkerTransport(settings.sharedWorker, logger.subLogger("shared-worker")); - } - else if (settings.webPlatform) { - this.transport = new WebPlatformTransport(settings.webPlatform, logger.subLogger("web-platform"), settings.identity); - } - else if (settings.ws !== undefined) { - this.transport = new WS(settings, logger.subLogger("ws")); - } - else { - throw new Error("No connection information specified"); - } - this.isTrace = logger.canPublish("trace"); - logger.debug(`starting with ${this.transport.name()} transport`); - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - this._defaultTransport = this.transport; - this.ping(); - } - async switchTransport(settings) { - return this._sequelizer.enqueue(async () => { - if (!settings || typeof settings !== "object") { - throw new Error("Cannot switch transports, because the settings are missing or invalid."); - } - if (typeof settings.type === "undefined") { - throw new Error("Cannot switch the transport, because the type is not defined"); - } - this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(settings)}`); - const switchTargetTransport = settings.type === "secondary" ? this.getNewSecondaryTransport(settings) : this._defaultTransport; - this._targetTransport = switchTargetTransport; - this._targetAuth = settings.type === "secondary" ? this.getNewSecondaryAuth(settings) : this._defaultAuth; - const verifyPromise = this.verifyConnection(); - this._swapTransport = true; - this._switchInProgress = true; - this.logger.trace("The new transport has been set, closing the current transport"); - await this.transport.close(); - try { - await verifyPromise; - const isSwitchSuccess = this.transport === switchTargetTransport; - this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${isSwitchSuccess}`); - this._switchInProgress = false; - return { success: isSwitchSuccess }; - } - catch (error) { - this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."); - this.switchTransport({ type: "default" }); - this._switchInProgress = false; - return { success: false }; - } - }); - } - onLibReAnnounced(callback) { - return this.registry.add("libReAnnounced", callback); - } - setLibReAnnounced(lib) { - this.registry.execute("libReAnnounced", lib); - } - send(message, options) { - if (this.transport.sendObject && - this.transport.isObjectBasedTransport) { - const msg = this.createObjectMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${JSON.stringify(msg)}`); - } - return this.transport.sendObject(msg, options); - } - else { - const strMessage = this.createStringMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${strMessage}`); - } - return this.transport.send(strMessage, options); - } - } - on(type, messageHandler) { - type = type.toLowerCase(); - if (this.messageHandlers[type] === undefined) { - this.messageHandlers[type] = {}; - } - const id = this.ids++; - this.messageHandlers[type][id] = messageHandler; - return { - type, - id, - }; - } - off(info) { - delete this.messageHandlers[info.type.toLowerCase()][info.id]; - } - get isConnected() { - return this._isLoggedIn; - } - connected(callback) { - return this.loggedIn(() => { - const currentServer = this.transport.name(); - callback(currentServer); - }); - } - disconnected(callback) { - return this.registry.add("disconnected", callback); - } - async login(authRequest, reconnect) { - this.logger.debug(`Login initiated - reconnect: ${reconnect}, transport: ${this.transport.name()}`); - if (!this._defaultAuth) { - this._defaultAuth = authRequest; - } - if (this._swapTransport) { - this.logger.trace("Detected a transport swap, swapping transports"); - const newAuth = this.transportSwap(); - authRequest = newAuth ?? authRequest; - } - try { - await this.transport.open(); - this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`); - timer("connection").mark("transport-opened"); - const identity = await this.loginCore(authRequest, reconnect); - this.logger.debug(`Logged in with identity: ${JSON.stringify(identity)}`); - timer("connection").mark("protocol-logged-in"); - return identity; - } - catch (error) { - if (this._switchInProgress) { - this.logger.debug("An error while logging in after a transport swap, preparing a default swap."); - this.prepareDefaultSwap(); - } - throw new Error(error); - } - } - async logout() { - await this.logoutCore(); - await this.transport.close(); - } - loggedIn(callback) { - if (this._isLoggedIn) { - callback(); - } - return this.registry.add("onLoggedIn", callback); - } - domain(domain, successMessages, errorMessages) { - let session = this.sessions.find((s) => s.domain === domain); - if (!session) { - session = domainSession(domain, this, this.logger.subLogger(`domain=${domain}`), successMessages, errorMessages); - this.sessions.push(session); - } - return session; - } - authToken() { - const createTokenReq = { - domain: "global", - type: "create-token" - }; - if (!this.globalDomain) { - return Promise.reject(new Error("no global domain session")); - } - return this.globalDomain.send(createTokenReq) - .then((res) => { - return res.token; - }); - } - reconnect() { - return this.transport.reconnect(); - } - setLoggedIn(value) { - this._isLoggedIn = value; - if (this._isLoggedIn) { - this.initialLogin = false; - this.registry.execute("onLoggedIn"); - } - } - distributeMessage(message, type) { - const handlers = this.messageHandlers[type.toLowerCase()]; - if (handlers !== undefined) { - Object.keys(handlers).forEach((handlerId) => { - const handler = handlers[handlerId]; - if (handler !== undefined) { - try { - handler(message); - } - catch (error) { - try { - this.logger.error(`Message handler failed with ${error.stack}`, error); - } - catch (loggerError) { - console.log("Message handler failed", error); - } - } - } - }); - } - } - handleConnectionChanged(connected) { - if (this._connected === connected) { - this.logger.trace("connection state unchanged, skipping"); - return; - } - this.logger.info(`connection state changed to ${connected ? "connected" : "disconnected"}`); - this._connected = connected; - if (connected) { - if (this.settings?.replaySpecs?.length) { - this.replayer = new MessageReplayerImpl(this.settings.replaySpecs); - this.replayer.init(this); - } - this.registry.execute("connected"); - } - else { - this.setLoggedIn(false); - if (this.shouldTryLogin) { - this.attemptLoginWithRetry(); - } - this.registry.execute("disconnected"); - } - } - async attemptLoginWithRetry() { - if (!this.loginConfig) { - throw new Error("no login info"); - } - if (this.loginRetryInProgress) { - this.logger.debug("login attempt already in progress, ignoring request..."); - return; - } - if (this._isLoggedIn) { - this.logger.debug("already logged in, ignoring request..."); - return; - } - if (this.initialLogin) { - this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`); - if (this.initialLoginAttempts <= 0) { - this.logger.info("maximum initial login attempts reached, will not try to login again"); - return; - } - this.initialLoginAttempts--; - } - try { - this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`); - this.loginRetryInProgress = true; - await this.login(this.loginConfig, true); - } - catch (e) { - this.logger.error(`error trying to login: ${e?.message}`, e); - setTimeout(this.attemptLoginWithRetry.bind(this), this.settings.reconnectInterval ?? 1000); - } - finally { - this.loginRetryInProgress = false; - } - } - handleTransportMessage(msg) { - let msgObj; - if (typeof msg === "string") { - msgObj = this.processStringMessage(msg); - } - else { - msgObj = this.processObjectMessage(msg); - } - if (this.isTrace) { - this.logger.trace(`<< ${JSON.stringify(msgObj)}`); - } - this.distributeMessage(msgObj.msg, msgObj.msgType); - } - verifyConnection() { - return PromisePlus((resolve) => { - let unsub; - const ready = waitForInvocations(2, () => { - if (unsub) { - unsub(); - } - resolve(); - }); - unsub = this.onLibReAnnounced((lib) => { - if (lib.name === "interop") { - return ready(); - } - if (lib.name === "contexts") { - return ready(); - } - }); - }, 10000, "Transport switch timed out waiting for all libraries to be re-announced"); - } - getNewSecondaryTransport(settings) { - if (!settings.transportConfig?.url) { - throw new Error("Missing secondary transport URL."); - } - return new WS(Object.assign({}, this.settings, { ws: settings.transportConfig.url, reconnectAttempts: 1 }), this.logger.subLogger("ws-secondary")); - } - getNewSecondaryAuth(settings) { - if (!settings.transportConfig?.auth) { - throw new Error("Missing secondary transport auth information."); - } - return settings.transportConfig.auth; - } - transportSwap() { - this._swapTransport = false; - if (!this._targetTransport || !this._targetAuth) { - this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`); - return; - } - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport = this._targetTransport; - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - return this._targetAuth; - } - prepareDefaultSwap() { - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport.close().catch((error) => this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(error)}`)); - this._targetTransport = this._defaultTransport; - this._targetAuth = this._defaultAuth; - this._swapTransport = true; - } - processStringMessage(message) { - const msg = JSON.parse(message, (key, value) => { - if (typeof value !== "string") { - return value; - } - if (value.length < this.dateMinLen) { - return value; - } - if (!value.startsWith(this.datePrefixFirstChar)) { - return value; - } - if (value.substring(0, this.datePrefixLen) !== this.datePrefix) { - return value; - } - try { - const milliseconds = parseInt(value.substring(this.datePrefixLen, value.length), 10); - if (isNaN(milliseconds)) { - return value; - } - return new Date(milliseconds); - } - catch (ex) { - return value; - } - }); - return { - msg, - msgType: msg.type, - }; - } - createStringMessage(message) { - const oldToJson = Date.prototype.toJSON; - try { - const datePrefix = this.datePrefix; - Date.prototype.toJSON = function () { - return datePrefix + this.getTime(); - }; - const result = JSON.stringify(message); - return result; - } - finally { - Date.prototype.toJSON = oldToJson; - } - } - processObjectMessage(message) { - if (!message.type) { - throw new Error("Object should have type property"); - } - return { - msg: message, - msgType: message.type, - }; - } - createObjectMessage(message) { - return message; - } - async loginCore(config, reconnect) { - this.loginConfig = config; - if (!this.loginConfig) { - this.loginConfig = { username: "", password: "" }; - } - this.shouldTryLogin = true; - const authentication = await this.setupAuthConfig(config, reconnect); - const helloMsg = { - type: "hello", - identity: this.settings.identity, - authentication - }; - if (config.sessionId) { - helloMsg.request_id = config.sessionId; - } - if (!this.globalDomain) { - this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [ - "welcome", - "token", - "authentication-request" - ]); - } - const sendOptions = { skipPeerId: true }; - if (this.initialLogin) { - sendOptions.retryInterval = this.settings.reconnectInterval; - sendOptions.maxRetries = this.settings.reconnectAttempts; - } - try { - const welcomeMsg = await this.tryAuthenticate(this.globalDomain, helloMsg, sendOptions, config); - this.logger.info("login successful with peerId " + welcomeMsg.peer_id); - this.peerId = welcomeMsg.peer_id; - this.resolvedIdentity = welcomeMsg.resolved_identity; - this.availableDomains = welcomeMsg.available_domains; - if (welcomeMsg.options) { - this.token = welcomeMsg.options.access_token; - this.info = welcomeMsg.options.info; - } - this.setLoggedIn(true); - return welcomeMsg.resolved_identity; - } - catch (err) { - this.logger.error("error sending hello message - " + (err.message || err.msg || err.reason || err), err); - throw err; - } - finally { - if (config?.flowCallback && config.sessionId) { - config.flowCallback(config.sessionId, null); - } - } - } - async tryAuthenticate(globalDomain, helloMsg, sendOptions, config) { - let welcomeMsg; - while (true) { - const msg = await globalDomain.send(helloMsg, undefined, sendOptions); - if (msg.type === "authentication-request") { - const token = Buffer.from(msg.authentication.token, "base64"); - if (config.flowCallback && config.sessionId) { - helloMsg.authentication.token = - (await config.flowCallback(config.sessionId, token)) - .data - .toString("base64"); - } - helloMsg.request_id = config.sessionId; - } - else if (msg.type === "welcome") { - welcomeMsg = msg; - break; - } - else if (msg.type === "error") { - throw new Error("Authentication failed: " + msg.reason); - } - else { - throw new Error("Unexpected message type during authentication: " + msg.type); - } - } - return welcomeMsg; - } - async setupAuthConfig(config, reconnect) { - const authentication = {}; - this.gatewayToken = config.gatewayToken; - if (config.gatewayToken) { - if (reconnect) { - try { - config.gatewayToken = await this.getNewGWToken(); - } - catch (e) { - this.logger.warn(`failed to get GW token when reconnecting ${e?.message || e}`); - } - } - authentication.method = "gateway-token"; - authentication.token = config.gatewayToken; - this.gatewayToken = config.gatewayToken; - } - else if (config.flowName === "sspi") { - authentication.provider = "win"; - authentication.method = "access-token"; - if (config.flowCallback && config.sessionId) { - authentication.token = - (await config.flowCallback(config.sessionId, null)) - .data - .toString("base64"); - } - else { - throw new Error("Invalid SSPI config"); - } - } - else if (config.token) { - authentication.method = "access-token"; - authentication.token = config.token; - } - else if (config.username) { - authentication.method = "secret"; - authentication.login = config.username; - authentication.secret = config.password; - } - else if (config.provider) { - authentication.provider = config.provider; - authentication.providerContext = config.providerContext; - } - else { - throw new Error("invalid auth message" + JSON.stringify(config)); - } - return authentication; - } - async logoutCore() { - this.logger.debug("core logging out..."); - this.shouldTryLogin = false; - if (this.pingTimer) { - clearTimeout(this.pingTimer); - } - const promises = this.sessions.map((session) => { - return session.leave(); - }); - await Promise.all(promises); - } - getNewGWToken() { - if (typeof window !== "undefined") { - const glue42gd = window.glue42gd; - if (glue42gd) { - return glue42gd.getGWToken(); - } - } - return Promise.reject(new Error("not running in GD")); - } - ping() { - if (!this.shouldTryLogin) { - return; - } - if (this._isLoggedIn) { - this.send({ type: "ping" }); - } - this.pingTimer = setTimeout(() => { - this.ping(); - }, 30 * 1000); - } - } - - const order = ["trace", "debug", "info", "warn", "error", "off"]; - class Logger { - name; - parent; - static Interop; - static InteropMethodName = "T42.AppLogger.Log"; - static Instance; - path; - subLoggers = []; - _consoleLevel; - _publishLevel; - loggerFullName; - includeTimeAndLevel; - logFn = console; - customLogFn = false; - constructor(name, parent, logFn) { - this.name = name; - this.parent = parent; - this.name = name; - if (parent) { - this.path = `${parent.path}.${name}`; - } - else { - this.path = name; - } - this.loggerFullName = `[${this.path}]`; - this.includeTimeAndLevel = !logFn; - if (logFn) { - this.logFn = logFn; - this.customLogFn = true; - } - } - subLogger(name) { - const existingSub = this.subLoggers.filter((subLogger) => { - return subLogger.name === name; - })[0]; - if (existingSub !== undefined) { - return existingSub; - } - Object.keys(this).forEach((key) => { - if (key === name) { - throw new Error("This sub logger name is not allowed."); - } - }); - const sub = new Logger(name, this, this.customLogFn ? this.logFn : undefined); - this.subLoggers.push(sub); - return sub; - } - publishLevel(level) { - if (level) { - this._publishLevel = level; - } - return this._publishLevel || this.parent?.publishLevel(); - } - consoleLevel(level) { - if (level) { - this._consoleLevel = level; - } - return this._consoleLevel || this.parent?.consoleLevel(); - } - log(message, level, error) { - this.publishMessage(level || "info", message, error); - } - trace(message) { - this.log(message, "trace"); - } - debug(message) { - this.log(message, "debug"); - } - info(message) { - this.log(message, "info"); - } - warn(message) { - this.log(message, "warn"); - } - error(message, err) { - this.log(message, "error", err); - } - canPublish(level, compareWith) { - const levelIdx = order.indexOf(level); - const restrictionIdx = order.indexOf(compareWith || this.consoleLevel() || "trace"); - return levelIdx >= restrictionIdx; - } - publishMessage(level, message, error) { - const loggerName = this.loggerFullName; - if (level === "error" && !error) { - const e = new Error(); - if (e.stack) { - message = - message + - "\n" + - e.stack - .split("\n") - .slice(4) - .join("\n"); - } - } - if (this.canPublish(level, this.publishLevel())) { - const interop = Logger.Interop; - if (interop) { - try { - if (interop.methods({ name: Logger.InteropMethodName }).length > 0) { - const args = { - msg: message, - logger: loggerName, - level - }; - if (error && error instanceof Error) { - args.error = { - message: error.message, - stack: error.stack ?? "" - }; - } - interop.invoke(Logger.InteropMethodName, args) - .catch((e) => { - this.logFn.error(`Unable to send log message to the platform: ${e.message}`, e); - }); - } - } - catch { - } - } - } - if (this.canPublish(level)) { - let prefix = ""; - if (this.includeTimeAndLevel) { - const date = new Date(); - const time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`; - prefix = `[${time}] [${level}] `; - } - const toPrint = `${prefix}${loggerName}: ${message}`; - switch (level) { - case "trace": - this.logFn.debug(toPrint); - break; - case "debug": - if (this.logFn.debug) { - this.logFn.debug(toPrint); - } - else { - this.logFn.log(toPrint); - } - break; - case "info": - this.logFn.info(toPrint); - break; - case "warn": - this.logFn.warn(toPrint); - break; - case "error": - if (error) { - this.logFn.error(toPrint, error); - } - else { - this.logFn.error(toPrint); - } - break; - } - } - } - } - - const GW_MESSAGE_CREATE_CONTEXT = "create-context"; - const GW_MESSAGE_ACTIVITY_CREATED = "created"; - const GW_MESSAGE_ACTIVITY_DESTROYED = "destroyed"; - const GW_MESSAGE_CONTEXT_CREATED = "context-created"; - const GW_MESSAGE_CONTEXT_ADDED = "context-added"; - const GW_MESSAGE_SUBSCRIBE_CONTEXT = "subscribe-context"; - const GW_MESSAGE_SUBSCRIBED_CONTEXT = "subscribed-context"; - const GW_MESSAGE_UNSUBSCRIBE_CONTEXT = "unsubscribe-context"; - const GW_MESSAGE_DESTROY_CONTEXT = "destroy-context"; - const GW_MESSAGE_CONTEXT_DESTROYED = "context-destroyed"; - const GW_MESSAGE_UPDATE_CONTEXT = "update-context"; - const GW_MESSAGE_CONTEXT_UPDATED = "context-updated"; - const GW_MESSAGE_JOINED_ACTIVITY = "joined"; - - const ContextMessageReplaySpec = { - get name() { - return "context"; - }, - get types() { - return [ - GW_MESSAGE_CREATE_CONTEXT, - GW_MESSAGE_ACTIVITY_CREATED, - GW_MESSAGE_ACTIVITY_DESTROYED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_SUBSCRIBE_CONTEXT, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - GW_MESSAGE_DESTROY_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_UPDATE_CONTEXT, - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_JOINED_ACTIVITY - ]; - } - }; - - var version = "6.8.1"; - - function prepareConfig (configuration, ext, glue42gd) { - let nodeStartingContext; - if (Utils.isNode()) { - const startingContextString = process.env._GD_STARTING_CONTEXT_; - if (startingContextString) { - try { - nodeStartingContext = JSON.parse(startingContextString); - } - catch { - } - } - } - function getConnection() { - const gwConfig = configuration.gateway; - const protocolVersion = gwConfig?.protocolVersion ?? 3; - const reconnectInterval = gwConfig?.reconnectInterval; - const reconnectAttempts = gwConfig?.reconnectAttempts; - const defaultWs = "ws://localhost:8385"; - let ws = gwConfig?.ws; - const sharedWorker = gwConfig?.sharedWorker; - const inproc = gwConfig?.inproc; - const webPlatform = gwConfig?.webPlatform ?? undefined; - if (glue42gd) { - ws = glue42gd.gwURL; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) { - ws = nodeStartingContext.gwURL; - } - if (!ws && !sharedWorker && !inproc) { - ws = defaultWs; - } - let instanceId; - let windowId; - let pid; - let environment; - let region; - const appName = getApplication(); - let uniqueAppName = appName; - if (typeof glue42gd !== "undefined") { - windowId = glue42gd.windowId; - pid = glue42gd.pid; - if (glue42gd.env) { - environment = glue42gd.env.env; - region = glue42gd.env.region; - } - uniqueAppName = glue42gd.application ?? "glue-app"; - instanceId = glue42gd.appInstanceId; - } - else if (Utils.isNode()) { - pid = process.pid; - if (nodeStartingContext) { - environment = nodeStartingContext.env; - region = nodeStartingContext.region; - instanceId = nodeStartingContext.instanceId; - } - } - else if (typeof window?.glue42electron !== "undefined") { - windowId = window?.glue42electron.instanceId; - pid = window?.glue42electron.pid; - environment = window?.glue42electron.env; - region = window?.glue42electron.region; - uniqueAppName = window?.glue42electron.application ?? "glue-app"; - instanceId = window?.glue42electron.instanceId; - } - else ; - const replaySpecs = configuration.gateway?.replaySpecs ?? []; - replaySpecs.push(ContextMessageReplaySpec); - let identity = { - application: uniqueAppName, - applicationName: appName, - windowId, - instance: instanceId, - process: pid, - region, - environment, - api: ext.version || version - }; - if (configuration.identity) { - identity = Object.assign(identity, configuration.identity); - } - return { - identity, - reconnectInterval, - ws, - sharedWorker, - webPlatform, - inproc, - protocolVersion, - reconnectAttempts, - replaySpecs, - }; - } - function getContexts() { - const defaultConfig = { - reAnnounceKnownContexts: true, - subscribeOnUpdate: true, - subscribeOnGet: true, - onlyReAnnounceSubscribedContexts: true - }; - if (typeof configuration.contexts === "undefined") { - return defaultConfig; - } - if (typeof configuration.contexts === "boolean" && configuration.contexts) { - return defaultConfig; - } - if (typeof configuration.contexts === "object") { - return { ...defaultConfig, ...configuration.contexts }; - } - return false; - } - function getApplication() { - if (configuration.application) { - return configuration.application; - } - if (glue42gd) { - return glue42gd.applicationName; - } - if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") { - return window.glue42electron.application; - } - const uid = nanoid(10); - if (Utils.isNode()) { - if (nodeStartingContext) { - return nodeStartingContext.applicationConfig.name; - } - return "NodeJS" + uid; - } - if (typeof window !== "undefined" && typeof document !== "undefined") { - return document.title + ` (${uid})`; - } - return uid; - } - function getAuth() { - if (typeof configuration.auth === "string") { - return { - token: configuration.auth - }; - } - if (configuration.auth) { - return configuration.auth; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) { - return { - gatewayToken: nodeStartingContext.gwToken - }; - } - if (configuration.gateway?.webPlatform) { - return { - username: "glue42", - password: "" - }; - } - } - function getLogger() { - let config = configuration.logger; - const defaultLevel = "warn"; - if (!config) { - config = defaultLevel; - } - let gdConsoleLevel; - if (glue42gd) { - gdConsoleLevel = glue42gd.consoleLogLevel; - } - if (typeof config === "string") { - return { console: gdConsoleLevel ?? config, publish: defaultLevel }; - } - return { - console: gdConsoleLevel ?? config.console ?? defaultLevel, - publish: config.publish ?? defaultLevel - }; - } - const connection = getConnection(); - let application = getApplication(); - if (typeof window !== "undefined") { - const windowAsAny = window; - const containerApplication = windowAsAny.htmlContainer ? - `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` : - windowAsAny?.glue42gd?.application; - if (containerApplication) { - application = containerApplication; - } - } - return { - bus: configuration.bus ?? false, - application, - auth: getAuth(), - logger: getLogger(), - connection, - metrics: configuration.metrics ?? true, - contexts: getContexts(), - version: ext.version || version, - libs: ext.libs ?? [], - customLogger: configuration.customLogger - }; - } - - class GW3ContextData { - name; - contextId; - context; - isAnnounced; - createdByUs; - joinedActivity; - updateCallbacks = {}; - activityId; - sentExplicitSubscription; - get hasReceivedSnapshot() { - return this.snapshotPromiseWrapper.resolved; - } - set hasReceivedSnapshot(has) { - if (has) { - this.snapshotPromiseWrapper.resolve(); - } - else { - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - } - get snapshotPromise() { - return this.snapshotPromiseWrapper.promise; - } - snapshotPromiseWrapper; - constructor(contextId, name, isAnnounced, activityId) { - this.contextId = contextId; - this.name = name; - this.isAnnounced = isAnnounced; - this.activityId = activityId; - this.context = {}; - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - hasCallbacks() { - return Object.keys(this.updateCallbacks).length > 0; - } - getState() { - if (this.isAnnounced && this.hasCallbacks()) { - return 3; - } - if (this.isAnnounced) { - return 2; - } - if (this.hasCallbacks()) { - return 1; - } - return 0; - } - } - - var lodash_clonedeep = {exports: {}}; - - /** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - lodash_clonedeep.exports; - - (function (module, exports) { - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** - * Adds the key-value `pair` to `map`. - * - * @private - * @param {Object} map The map to modify. - * @param {Array} pair The key-value pair to add. - * @returns {Object} Returns `map`. - */ - function addMapEntry(map, pair) { - // Don't return `map.set` because it's not chainable in IE 11. - map.set(pair[0], pair[1]); - return map; - } - - /** - * Adds `value` to `set`. - * - * @private - * @param {Object} set The set to modify. - * @param {*} value The value to add. - * @returns {Object} Returns `set`. - */ - function addSetEntry(set, value) { - // Don't return `set.add` because it's not chainable in IE 11. - set.add(value); - return set; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array ? array.length : 0; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array ? array.length : 0; - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ - function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var objectToString = objectProto.toString; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined, - Symbol = root.Symbol, - Uint8Array = root.Uint8Array, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeKeys = overArg(Object.keys, Object); - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'), - Map = getNative(root, 'Map'), - Promise = getNative(root, 'Promise'), - Set = getNative(root, 'Set'), - WeakMap = getNative(root, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - this.__data__ = new ListCache(entries); - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - return this.__data__['delete'](key); - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var cache = this.__data__; - if (cache instanceof ListCache) { - var pairs = cache.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - return this; - } - cache = this.__data__ = new MapCache(pairs); - } - cache.set(key, value); - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - - var length = result.length, - skipIndexes = !!length; - - for (var key in value) { - if ((hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {boolean} [isFull] Specify a clone including symbols. - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, isFull, customizer, key, object, stack) { - var result; - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - if (isHostObject(value)) { - return object ? value : {}; - } - result = initCloneObject(isFunc ? {} : value); - if (!isDeep) { - return copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, baseClone, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (!isArr) { - var props = isFull ? getAllKeys(value) : keys(value); - } - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(proto) { - return isObject(proto) ? objectCreate(proto) : {}; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - return objectToString.call(value); - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var result = new buffer.constructor(buffer.length); - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `map`. - * - * @private - * @param {Object} map The map to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned map. - */ - function cloneMap(map, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); - return arrayReduce(array, addMapEntry, new map.constructor); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of `set`. - * - * @private - * @param {Object} set The set to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned set. - */ - function cloneSet(set, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); - return arrayReduce(array, addSetEntry, new set.constructor); - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = undefined; - - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; - } - - /** - * Copies own symbol properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * Creates an array of the own enumerable symbol properties of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11, - // for data views in Edge < 14, and promises in Node.js. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = objectToString.call(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : undefined; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, cloneFunc, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return cloneMap(object, isDeep, cloneFunc); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return cloneSet(object, isDeep, cloneFunc); - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, true, true); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return !!value && typeof value == 'object'; - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - module.exports = cloneDeep; - } (lodash_clonedeep, lodash_clonedeep.exports)); - - var lodash_clonedeepExports = lodash_clonedeep.exports; - var cloneDeep = /*@__PURE__*/getDefaultExportFromCjs(lodash_clonedeepExports); - - function applyContextDelta(context, delta, logger) { - try { - if (logger?.canPublish("trace")) { - logger?.trace(`applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`); - } - if (!delta) { - return context; - } - if (delta.reset) { - context = { ...delta.reset }; - return context; - } - context = deepClone(context, undefined); - if (delta.commands) { - for (const command of delta.commands) { - if (command.type === "remove") { - deletePath(context, command.path); - } - else if (command.type === "set") { - setValueToPath(context, command.value, command.path); - } - } - return context; - } - const added = delta.added; - const updated = delta.updated; - const removed = delta.removed; - if (added) { - Object.keys(added).forEach((key) => { - context[key] = added[key]; - }); - } - if (updated) { - Object.keys(updated).forEach((key) => { - mergeObjectsProperties(key, context, updated); - }); - } - if (removed) { - removed.forEach((key) => { - delete context[key]; - }); - } - return context; - } - catch (e) { - logger?.error(`error applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`, e); - return context; - } - } - function deepClone(obj, hash) { - return cloneDeep(obj); - } - const mergeObjectsProperties = (key, what, withWhat) => { - const right = withWhat[key]; - if (right === undefined) { - return what; - } - const left = what[key]; - if (!left || !right) { - what[key] = right; - return what; - } - if (typeof left === "string" || - typeof left === "number" || - typeof left === "boolean" || - typeof right === "string" || - typeof right === "number" || - typeof right === "boolean" || - Array.isArray(left) || - Array.isArray(right)) { - what[key] = right; - return what; - } - what[key] = Object.assign({}, left, right); - return what; - }; - function deepEqual(x, y) { - if (x === y) { - return true; - } - if (!(x instanceof Object) || !(y instanceof Object)) { - return false; - } - if (x.constructor !== y.constructor) { - return false; - } - for (const p in x) { - if (!x.hasOwnProperty(p)) { - continue; - } - if (!y.hasOwnProperty(p)) { - return false; - } - if (x[p] === y[p]) { - continue; - } - if (typeof (x[p]) !== "object") { - return false; - } - if (!deepEqual(x[p], y[p])) { - return false; - } - } - for (const p in y) { - if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) { - return false; - } - } - return true; - } - function setValueToPath(obj, value, path) { - const pathArr = path.split("."); - const forbiddenKeys = ["__proto__", "constructor", "prototype"]; - let i; - for (i = 0; i < pathArr.length - 1; i++) { - const key = pathArr[i]; - if (forbiddenKeys.includes(key)) { - throw new Error(`The provided path ${path} is invalid. It cannot contain segment/key that is equal to one of the following values: ${forbiddenKeys}.`); - } - if (!obj[key]) { - obj[key] = {}; - } - if (typeof obj[key] !== "object") { - obj[key] = {}; - } - obj = obj[key]; - } - obj[pathArr[i]] = value; - } - function isSubset(superObj, subObj) { - return Object.keys(subObj).every((ele) => { - if (typeof subObj[ele] === "object") { - return isSubset(superObj?.[ele] || {}, subObj[ele] || {}); - } - return subObj[ele] === superObj?.[ele]; - }); - } - function deletePath(obj, path) { - const pathArr = path.split("."); - let i; - for (i = 0; i < pathArr.length - 1; i++) { - if (!obj[pathArr[i]]) { - return; - } - obj = obj[pathArr[i]]; - } - delete obj[pathArr[i]]; - } - - class GW3Bridge { - ERROR_URI_FAILURE = "global.errors.failure"; - ERROR_URI_INVALID_CONTEXT = "global.errors.invalid_context"; - _logger; - _connection; - _trackAllContexts; - _reAnnounceKnownContexts; - _subscribeOnUpdate; - _subscribeOnGet; - _onlyReAnnounceSubscribedContexts; - _gw3Session; - _contextNameToData = {}; - _gw3Subscriptions = []; - _nextCallbackSubscriptionNumber = 0; - _creationPromises = {}; - _contextNameToId = {}; - _contextIdToName = {}; - _protocolVersion = undefined; - _contextsTempCache = {}; - _contextsSubscriptionsCache = []; - _systemContextsSubKey; - get protocolVersion() { - if (!this._protocolVersion) { - const contextsDomainInfo = this._connection.availableDomains.find((d) => d.uri === "context"); - this._protocolVersion = contextsDomainInfo?.version ?? 1; - } - return this._protocolVersion; - } - get setPathSupported() { - return this.protocolVersion >= 2; - } - constructor(config) { - this._connection = config.connection; - this._logger = config.logger; - this._trackAllContexts = config.trackAllContexts; - this._reAnnounceKnownContexts = config.reAnnounceKnownContexts; - this._subscribeOnUpdate = config.subscribeOnUpdate ?? true; - this._subscribeOnGet = config.subscribeOnGet ?? true; - this._onlyReAnnounceSubscribedContexts = config.onlyReAnnounceSubscribedContexts ?? true; - this._gw3Session = this._connection.domain("global", [ - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_CONTEXT_UPDATED, - ]); - this._gw3Session.disconnected(this.resetState.bind(this)); - this._gw3Session.onJoined((wasReconnect) => { - if (!wasReconnect) { - return; - } - if (!this._reAnnounceKnownContexts) { - this._contextsTempCache = {}; - return this._connection.setLibReAnnounced({ name: "contexts" }); - } - this.reInitiateState() - .then(() => this._connection.setLibReAnnounced({ name: "contexts" })) - .catch((err) => { - this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(err)}`); - }); - }); - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - } - dispose() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - this._gw3Subscriptions.length = 0; - for (const contextName in this._contextNameToData) { - if (this._contextNameToId.hasOwnProperty(contextName)) { - delete this._contextNameToData[contextName]; - } - } - } - createContext(name, data) { - if (name in this._creationPromises) { - return this._creationPromises[name]; - } - this._creationPromises[name] = - this._gw3Session - .send({ - type: GW_MESSAGE_CREATE_CONTEXT, - domain: "global", - name, - data, - lifetime: "retained", - }) - .then((createContextMsg) => { - this._contextNameToId[name] = createContextMsg.context_id; - this._contextIdToName[createContextMsg.context_id] = name; - const contextData = this._contextNameToData[name] || new GW3ContextData(createContextMsg.context_id, name, true, undefined); - contextData.isAnnounced = true; - contextData.name = name; - contextData.contextId = createContextMsg.context_id; - contextData.context = createContextMsg.data || deepClone(data); - contextData.hasReceivedSnapshot = true; - this._contextNameToData[name] = contextData; - delete this._creationPromises[name]; - contextData.sentExplicitSubscription = true; - contextData.createdByUs = true; - this.subscribe(name, () => { }); - return createContextMsg.context_id; - }); - return this._creationPromises[name]; - } - all() { - return Object.keys(this._contextNameToData) - .filter((name) => this._contextNameToData[name].isAnnounced); - } - async update(name, delta) { - if (delta) { - delta = deepClone(delta); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - await this.createContext(name, delta); - return; - } - const currentContext = await this.get(contextData.name); - const calculatedDelta = this.setPathSupported ? - this.calculateContextDeltaV2(currentContext, delta) : - this.calculateContextDeltaV1(currentContext, delta); - if (!Object.keys(calculatedDelta.added).length - && !Object.keys(calculatedDelta.updated).length - && !calculatedDelta.removed.length - && !calculatedDelta.commands?.length) { - return Promise.resolve(); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: calculatedDelta, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, calculatedDelta, { - updaterId: gwResponse.peer_id - }); - } - } - async set(name, data) { - if (data) { - data = deepClone(data); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - return this.createContext(name, data); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { reset: data }, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - this.handleUpdated(contextData, { - reset: data, - added: {}, - removed: [], - updated: {} - }, { - updaterId: gwResponse.peer_id - }); - } - } - setPath(name, path, value) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later"); - } - return this.setPaths(name, [{ path, value }]); - } - async setPaths(name, pathValues) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later"); - } - if (pathValues) { - pathValues = deepClone(pathValues); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - const obj = {}; - for (const pathValue of pathValues) { - setValueToPath(obj, pathValue.value, pathValue.path); - } - return this.createContext(name, obj); - } - const commands = []; - for (const pathValue of pathValues) { - if (pathValue.value === null) { - commands.push({ type: "remove", path: pathValue.path }); - } - else { - commands.push({ type: "set", path: pathValue.path, value: pathValue.value }); - } - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { commands } - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, { - added: {}, - removed: [], - updated: {}, - commands - }, { - updaterId: gwResponse.peer_id - }); - } - } - async get(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - if (!contextData && this._subscribeOnGet) { - this.subscribe(name, () => { }); - } - return Promise.resolve({}); - } - if (contextData && !contextData.sentExplicitSubscription) { - return new Promise((resolve, reject) => { - this.subscribe(name, (data, _d, _r, un) => { - if (!this._subscribeOnGet) { - this.unsubscribe(un); - } - resolve(data); - }).catch((e) => { - if (this.isInvalidContextError(e)) { - resolve({}); - return; - } - reject(e); - }); - }); - } - await contextData.snapshotPromise; - const context = contextData?.context ?? {}; - return Promise.resolve(deepClone(context)); - } - isInvalidContextError(e) { - return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT - || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id")); - } - async subscribe(name, callback, subscriptionKey) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const thisCallbackSubscriptionNumber = typeof subscriptionKey === "undefined" ? this._nextCallbackSubscriptionNumber : subscriptionKey; - if (typeof subscriptionKey === "undefined") { - this._nextCallbackSubscriptionNumber += 1; - this._contextsSubscriptionsCache.push({ contextName: name, subKey: thisCallbackSubscriptionNumber, callback }); - } - let contextData = this._contextNameToData[name]; - if (!contextData || - !contextData.isAnnounced) { - contextData = contextData || new GW3ContextData(undefined, name, false, undefined); - this._contextNameToData[name] = contextData; - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - return Promise.resolve(thisCallbackSubscriptionNumber); - } - const hadCallbacks = contextData.hasCallbacks(); - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - if (!hadCallbacks) { - if (!contextData.joinedActivity && !contextData.createdByUs) { - if (contextData.context && contextData.sentExplicitSubscription) { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - return this.sendSubscribe(contextData) - .then(() => thisCallbackSubscriptionNumber, () => { - this.unsubscribe(thisCallbackSubscriptionNumber, true); - return thisCallbackSubscriptionNumber; - }); - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - unsubscribe(subscriptionKey, keepInSubscriptionsCache) { - if (!keepInSubscriptionsCache) { - this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter(x => x.subKey !== subscriptionKey); - } - for (const name of Object.keys(this._contextNameToData)) { - const contextData = this._contextNameToData[name]; - if (!contextData) { - continue; - } - const hadCallbacks = contextData.hasCallbacks(); - delete contextData.updateCallbacks[subscriptionKey]; - if (contextData.isAnnounced && - hadCallbacks && - !contextData.hasCallbacks() && - contextData.sentExplicitSubscription) { - contextData.hasReceivedSnapshot = false; - contextData.context = {}; - this.sendUnsubscribe(contextData).catch(() => { }); - } - if (!contextData.isAnnounced && - !contextData.hasCallbacks()) { - delete this._contextNameToData[name]; - delete this._contextNameToId[name]; - if (contextData.contextId) { - delete this._contextIdToName[contextData.contextId]; - } - } - } - } - async destroy(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - const contextId = contextData?.contextId; - if (!contextData || !contextId) { - return Promise.reject(`context with ${name} does not exist`); - } - return this._gw3Session - .send({ - type: GW_MESSAGE_DESTROY_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }).then(() => undefined); - } - handleUpdated(contextData, delta, extraData) { - const oldContext = contextData.context; - contextData.context = applyContextDelta(contextData.context, delta, this._logger); - if (this._contextNameToData[contextData.name] === contextData && - !deepEqual(oldContext, contextData.context)) { - this.invokeUpdateCallbacks(contextData, delta, extraData); - } - } - subscribeToContextCreatedMessages() { - const createdMessageTypes = [ - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_ACTIVITY_CREATED, - ]; - for (const createdMessageType of createdMessageTypes) { - const sub = this._connection.on(createdMessageType, this.handleContextCreatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextCreatedMessage(contextCreatedMsg) { - const createdMessageType = contextCreatedMsg.type; - if (createdMessageType === GW_MESSAGE_ACTIVITY_CREATED) { - this._contextNameToId[contextCreatedMsg.activity_id] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.activity_id; - } - else if (createdMessageType === GW_MESSAGE_CONTEXT_ADDED) { - this._contextNameToId[contextCreatedMsg.name] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.name; - } - else ; - const name = this._contextIdToName[contextCreatedMsg.context_id]; - if (!name) { - throw new Error("Received created event for context with unknown name: " + contextCreatedMsg.context_id); - } - if (!this._contextNameToId[name]) { - throw new Error("Received created event for context with unknown id: " + contextCreatedMsg.context_id); - } - let contextData = this._contextNameToData[name]; - if (contextData) { - if (contextData.isAnnounced) { - return; - } - else { - if (!contextData.hasCallbacks()) { - throw new Error("Assertion failure: contextData.hasCallbacks()"); - } - contextData.isAnnounced = true; - contextData.contextId = contextCreatedMsg.context_id; - contextData.activityId = contextCreatedMsg.activity_id; - if (!contextData.sentExplicitSubscription) { - this.sendSubscribe(contextData).catch(() => { }); - } - } - } - else { - this._contextNameToData[name] = contextData = - new GW3ContextData(contextCreatedMsg.context_id, name, true, contextCreatedMsg.activity_id); - if (this._trackAllContexts) { - this.subscribe(name, () => { }).then((subKey) => this._systemContextsSubKey = subKey); - } - } - } - subscribeToContextUpdatedMessages() { - const updatedMessageTypes = [ - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_JOINED_ACTIVITY, - ]; - for (const updatedMessageType of updatedMessageTypes) { - const sub = this._connection.on(updatedMessageType, this.handleContextUpdatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextUpdatedMessage(contextUpdatedMsg) { - const updatedMessageType = contextUpdatedMsg.type; - const contextId = contextUpdatedMsg.context_id; - let contextData = this._contextNameToData[this._contextIdToName[contextId]]; - const justSeen = !contextData || !contextData.isAnnounced; - if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - if (!contextData) { - contextData = - this._contextNameToData[contextUpdatedMsg.activity_id] || - new GW3ContextData(contextId, contextUpdatedMsg.activity_id, true, contextUpdatedMsg.activity_id); - } - this._contextNameToData[contextUpdatedMsg.activity_id] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.activity_id; - this._contextNameToId[contextUpdatedMsg.activity_id] = contextId; - contextData.contextId = contextId; - contextData.isAnnounced = true; - contextData.activityId = contextUpdatedMsg.activity_id; - contextData.joinedActivity = true; - } - else { - if (!contextData || !contextData.isAnnounced) { - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData = contextData || new GW3ContextData(contextId, contextUpdatedMsg.name, true, undefined); - contextData.sentExplicitSubscription = true; - this._contextNameToData[contextUpdatedMsg.name] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.name; - this._contextNameToId[contextUpdatedMsg.name] = contextId; - } - else { - this._logger.error(`Received 'update' for unknown context: ${contextId}`); - } - return; - } - } - const oldContext = contextData.context; - contextData.hasReceivedSnapshot = true; - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData.context = contextUpdatedMsg.data ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - contextData.context = contextUpdatedMsg.context_snapshot ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_CONTEXT_UPDATED) { - contextData.context = applyContextDelta(contextData.context, contextUpdatedMsg.delta, this._logger); - } - else { - throw new Error("Unrecognized context update message " + updatedMessageType); - } - if (justSeen || - !deepEqual(contextData.context, oldContext) || - updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta, { updaterId: contextUpdatedMsg.updater_id }); - } - } - invokeUpdateCallbacks(contextData, delta, extraData) { - delta = delta || { added: {}, updated: {}, reset: {}, removed: [] }; - if (delta.commands) { - delta.added = delta.updated = delta.reset = {}; - delta.removed = []; - for (const command of delta.commands) { - if (command.type === "remove") { - if (command.path.indexOf(".") === -1) { - delta.removed.push(command.path); - } - setValueToPath(delta.updated, null, command.path); - } - else if (command.type === "set") { - setValueToPath(delta.updated, command.value, command.path); - } - } - } - for (const updateCallbackIndex in contextData.updateCallbacks) { - if (contextData.updateCallbacks.hasOwnProperty(updateCallbackIndex)) { - try { - const updateCallback = contextData.updateCallbacks[updateCallbackIndex]; - updateCallback(deepClone(contextData.context), deepClone(Object.assign({}, delta.added || {}, delta.updated || {}, delta.reset || {})), delta.removed, parseInt(updateCallbackIndex, 10), extraData); - } - catch (err) { - this._logger.debug("callback error: " + JSON.stringify(err)); - } - } - } - } - subscribeToContextDestroyedMessages() { - const destroyedMessageTypes = [ - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_ACTIVITY_DESTROYED, - ]; - for (const destroyedMessageType of destroyedMessageTypes) { - const sub = this._connection.on(destroyedMessageType, this.handleContextDestroyedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextDestroyedMessage(destroyedMsg) { - const destroyedMessageType = destroyedMsg.type; - let contextId; - let name; - if (destroyedMessageType === GW_MESSAGE_ACTIVITY_DESTROYED) { - name = destroyedMsg.activity_id; - contextId = this._contextNameToId[name]; - if (!contextId) { - this._logger.error(`Received 'destroyed' for unknown activity: ${destroyedMsg.activity_id}`); - return; - } - } - else { - contextId = destroyedMsg.context_id; - name = this._contextIdToName[contextId]; - if (!name) { - this._logger.error(`Received 'destroyed' for unknown context: ${destroyedMsg.context_id}`); - return; - } - } - delete this._contextIdToName[contextId]; - delete this._contextNameToId[name]; - const contextData = this._contextNameToData[name]; - delete this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - this._logger.error(`Received 'destroyed' for unknown context: ${contextId}`); - return; - } - } - async sendSubscribe(contextData) { - contextData.sentExplicitSubscription = true; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_SUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = false; - throw error; - } - } - async sendUnsubscribe(contextData) { - const prev = contextData.sentExplicitSubscription; - contextData.sentExplicitSubscription = false; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = prev; - throw error; - } - } - calculateContextDeltaV1(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined }; - if (from) { - for (const x of Object.keys(from)) { - if (Object.keys(to).indexOf(x) !== -1 - && to[x] !== null - && !deepEqual(from[x], to[x])) { - delta.updated[x] = to[x]; - } - } - } - for (const x of Object.keys(to)) { - if (!from || (Object.keys(from).indexOf(x) === -1)) { - if (to[x] !== null) { - delta.added[x] = to[x]; - } - } - else if (to[x] === null) { - delta.removed.push(x); - } - } - return delta; - } - calculateContextDeltaV2(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined, commands: [] }; - for (const x of Object.keys(to)) { - if (to[x] !== null) { - const fromX = from ? from[x] : null; - if (!deepEqual(fromX, to[x])) { - delta.commands?.push({ type: "set", path: x, value: to[x] }); - } - } - else { - delta.commands?.push({ type: "remove", path: x }); - } - } - return delta; - } - resetState() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - if (this._systemContextsSubKey) { - this.unsubscribe(this._systemContextsSubKey, true); - delete this._systemContextsSubKey; - } - this._gw3Subscriptions = []; - this._contextNameToId = {}; - this._contextIdToName = {}; - delete this._protocolVersion; - this._contextsTempCache = Object.keys(this._contextNameToData).reduce((cacheSoFar, ctxName) => { - const contextData = this._contextNameToData[ctxName]; - const addToCache = !this._onlyReAnnounceSubscribedContexts || contextData.hasReceivedSnapshot; - if (addToCache) { - cacheSoFar[ctxName] = this._contextNameToData[ctxName].context; - } - return cacheSoFar; - }, {}); - this._contextNameToData = {}; - } - async reInitiateState() { - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - await Promise.all(this._contextsSubscriptionsCache.map((subscription) => this.subscribe(subscription.contextName, subscription.callback, subscription.subKey))); - await this.flushQueue(); - for (const ctxName in this._contextsTempCache) { - if (typeof this._contextsTempCache[ctxName] !== "object" || Object.keys(this._contextsTempCache[ctxName]).length === 0) { - continue; - } - const lastKnownData = this._contextsTempCache[ctxName]; - this._logger.info(`Re-announcing known context: ${ctxName}`); - await this.flushQueue(); - await this.update(ctxName, lastKnownData); - } - this._contextsTempCache = {}; - this._logger.info("Contexts are re-announced"); - } - flushQueue() { - return new Promise((resolve) => setTimeout(() => resolve(), 0)); - } - } - - class ContextsModule { - initTime; - initStartTime; - initEndTime; - _bridge; - constructor(config) { - this._bridge = new GW3Bridge(config); - } - all() { - return this._bridge.all(); - } - update(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.update(name, data); - } - set(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.set(name, data); - } - setPath(name, path, data) { - this.checkName(name); - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(data); - return this.set(name, data); - } - return this._bridge.setPath(name, path, data); - } - setPaths(name, paths) { - this.checkName(name); - if (!Array.isArray(paths)) { - throw new Error("Please provide the paths as an array of PathValues!"); - } - for (const { path, value } of paths) { - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(value); - } - } - return this._bridge.setPaths(name, paths); - } - subscribe(name, callback) { - this.checkName(name); - if (typeof callback !== "function") { - throw new Error("Please provide the callback as a function!"); - } - return this._bridge - .subscribe(name, (data, delta, removed, key, extraData) => callback(data, delta, removed, () => this._bridge.unsubscribe(key), extraData)) - .then((key) => () => { - this._bridge.unsubscribe(key); - }); - } - get(name) { - this.checkName(name); - return this._bridge.get(name); - } - ready() { - return Promise.resolve(this); - } - destroy(name) { - this.checkName(name); - return this._bridge.destroy(name); - } - get setPathSupported() { - return this._bridge.setPathSupported; - } - checkName(name) { - if (typeof name !== "string" || name === "") { - throw new Error("Please provide the name as a non-empty string!"); - } - } - checkPath(path) { - if (typeof path !== "string") { - throw new Error("Please provide the path as a dot delimited string!"); - } - } - checkData(data) { - if (typeof data !== "object") { - throw new Error("Please provide the data as an object!"); - } - } - } - - function promisify (promise, successCallback, errorCallback) { - if (typeof successCallback !== "function" && typeof errorCallback !== "function") { - return promise; - } - if (typeof successCallback !== "function") { - successCallback = () => { }; - } - else if (typeof errorCallback !== "function") { - errorCallback = () => { }; - } - return promise.then(successCallback, errorCallback); - } - - function rejectAfter(ms = 0, promise, error) { - let timeout; - const clearTimeoutIfThere = () => { - if (timeout) { - clearTimeout(timeout); - } - }; - promise - .then(() => { - clearTimeoutIfThere(); - }) - .catch(() => { - clearTimeoutIfThere(); - }); - return new Promise((resolve, reject) => { - timeout = setTimeout(() => reject(error), ms); - }); - } - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - Decoder.oneOf; - /** See `Decoder.union` */ - var union = Decoder.union; - /** See `Decoder.intersection` */ - Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - var fail$1 = Decoder.fail; - /** See `Decoder.lazy` */ - Decoder.lazy; - - const functionCheck = (input, propDescription) => { - const providedType = typeof input; - return providedType === "function" ? - anyJson() : - fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${typeof providedType}`); - }; - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number or 0"); - const methodDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - objectTypes: optional(array(nonEmptyStringDecoder)), - displayName: optional(nonEmptyStringDecoder), - accepts: optional(nonEmptyStringDecoder), - returns: optional(nonEmptyStringDecoder), - description: optional(nonEmptyStringDecoder), - version: optional(nonNegativeNumberDecoder), - supportsStreaming: optional(boolean()), - flags: optional(object()), - getServers: optional(anyJson().andThen((result) => functionCheck(result, "method definition getServers"))) - }); - const methodFilterDecoder = union(nonEmptyStringDecoder, methodDefinitionDecoder); - const instanceDecoder = object({ - application: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - pid: optional(nonNegativeNumberDecoder), - machine: optional(nonEmptyStringDecoder), - user: optional(nonEmptyStringDecoder), - environment: optional(nonEmptyStringDecoder), - region: optional(nonEmptyStringDecoder), - service: optional(nonEmptyStringDecoder), - instance: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - peerId: optional(nonEmptyStringDecoder), - isLocal: optional(boolean()), - api: optional(nonEmptyStringDecoder), - getMethods: optional(anyJson().andThen((result) => functionCheck(result, "instance getMethods"))), - getStreams: optional(anyJson().andThen((result) => functionCheck(result, "instance getStreams"))) - }); - const targetDecoder = union(constant("best"), constant("all"), constant("skipMine"), instanceDecoder, array(instanceDecoder)); - const invokeOptionsDecoder = object({ - waitTimeoutMs: optional(nonNegativeNumberDecoder), - methodResponseTimeoutMs: optional(nonNegativeNumberDecoder) - }); - - var InvokeStatus; - (function (InvokeStatus) { - InvokeStatus[InvokeStatus["Success"] = 0] = "Success"; - InvokeStatus[InvokeStatus["Error"] = 1] = "Error"; - })(InvokeStatus || (InvokeStatus = {})); - class Client { - protocol; - repo; - instance; - configuration; - constructor(protocol, repo, instance, configuration) { - this.protocol = protocol; - this.repo = repo; - this.instance = instance; - this.configuration = configuration; - } - subscribe(method, options, successCallback, errorCallback, existingSub) { - const callProtocolSubscribe = (targetServers, stream, successProxy, errorProxy) => { - options.methodResponseTimeout = options.methodResponseTimeout ?? options.waitTimeoutMs; - this.protocol.client.subscribe(stream, options, targetServers, successProxy, errorProxy, existingSub); - }; - const promise = new Promise((resolve, reject) => { - const successProxy = (sub) => { - resolve(sub); - }; - const errorProxy = (err) => { - reject(err); - }; - if (!method) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - let methodDef; - if (typeof method === "string") { - methodDef = { name: method }; - } - else { - methodDef = method; - } - if (!methodDef.name) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - if (options === undefined) { - options = {}; - } - let target = options.target; - if (target === undefined) { - target = "best"; - } - if (typeof target === "string" && target !== "all" && target !== "best") { - reject(new Error(`"${target}" is not a valid target. Valid targets are "all", "best", or an instance.`)); - return; - } - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = options.method_response_timeout; - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = this.configuration.methodResponseTimeout; - } - } - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = options.wait_for_method_timeout; - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - const delayStep = 500; - let delayTillNow = 0; - let currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - callProtocolSubscribe(currentServers, currentServers[0].methods[0], successProxy, errorProxy); - } - else { - const retry = () => { - if (!target || !(options.waitTimeoutMs)) { - return; - } - delayTillNow += delayStep; - currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - const streamInfo = currentServers[0].methods[0]; - callProtocolSubscribe(currentServers, streamInfo, successProxy, errorProxy); - } - else if (delayTillNow >= options.waitTimeoutMs) { - const def = typeof method === "string" ? { name: method } : method; - callProtocolSubscribe(currentServers, def, successProxy, errorProxy); - } - else { - setTimeout(retry, delayStep); - } - }; - setTimeout(retry, delayStep); - } - }); - return promisify(promise, successCallback, errorCallback); - } - servers(methodFilter) { - const filterCopy = methodFilter === undefined - ? undefined - : { ...methodFilter }; - return this.getServers(filterCopy).map((serverMethodMap) => { - return serverMethodMap.server.instance; - }); - } - methods(methodFilter) { - if (typeof methodFilter === "string") { - methodFilter = { name: methodFilter }; - } - else { - methodFilter = { ...methodFilter }; - } - return this.getMethods(methodFilter); - } - methodsForInstance(instance) { - return this.getMethodsForInstance(instance); - } - methodAdded(callback) { - return this.repo.onMethodAdded(callback); - } - methodRemoved(callback) { - return this.repo.onMethodRemoved(callback); - } - serverAdded(callback) { - return this.repo.onServerAdded(callback); - } - serverRemoved(callback) { - return this.repo.onServerRemoved((server, reason) => { - callback(server, reason); - }); - } - serverMethodAdded(callback) { - return this.repo.onServerMethodAdded((server, method) => { - callback({ server, method }); - }); - } - serverMethodRemoved(callback) { - return this.repo.onServerMethodRemoved((server, method) => { - callback({ server, method }); - }); - } - async invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - const getInvokePromise = async () => { - const methodDefinition = typeof methodFilter === "string" ? { name: methodFilter } : { ...methodFilter }; - if (!argumentObj) { - argumentObj = {}; - } - if (!target) { - target = "best"; - } - if (!additionalOptions) { - additionalOptions = {}; - } - const methodFilterDecoderResult = methodFilterDecoder.run(methodDefinition); - if (!methodFilterDecoderResult.ok) { - const message = `The provided 'method' argument is invalid. Error: ${JSON.stringify(methodFilterDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (typeof argumentObj !== "object") { - const message = "The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const targetDecoderResult = targetDecoder.run(target); - if (!targetDecoderResult.ok) { - const message = `The provided 'target' argument is invalid. Error: ${JSON.stringify(targetDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const invokeOptionsDecoderResult = invokeOptionsDecoder.run(additionalOptions); - if (!invokeOptionsDecoderResult.ok) { - const message = `The provided 'options' argument is invalid. Error: ${JSON.stringify(invokeOptionsDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (success && typeof success !== "function") { - const message = "The provided 'success' function is invalid. Error: The success should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (error && typeof error !== "function") { - const message = "The provided 'error' function is invalid. Error: The error should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = additionalOptions.method_response_timeout; - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = this.configuration.methodResponseTimeout; - } - } - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = additionalOptions.wait_for_method_timeout; - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - let serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length === 0) { - try { - serversMethodMap = await this.tryToAwaitForMethods(methodDefinition, target, additionalOptions); - } - catch (err) { - const message = `Can not find a method matching ${JSON.stringify(methodFilter)} with server filter ${JSON.stringify(target)}`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - } - const timeout = additionalOptions.methodResponseTimeoutMs; - const additionalOptionsCopy = additionalOptions; - const invokePromises = serversMethodMap.map((serversMethodPair) => { - const invId = nanoid(10); - const method = serversMethodPair.methods[0]; - const server = serversMethodPair.server; - const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy); - return Promise.race([ - invokePromise, - rejectAfter(timeout, invokePromise, { - invocationId: invId, - message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`, - status: InvokeStatus.Error, - }) - ]); - }); - const invocationMessages = await Promise.all(invokePromises); - const results = this.getInvocationResultObj(invocationMessages, methodDefinition, argumentObj); - const allRejected = invocationMessages.every((result) => result.status === InvokeStatus.Error); - if (allRejected) { - return Promise.reject(results); - } - return results; - }; - return promisify(getInvokePromise(), success, error); - } - generateInvalidInputInvocationResult(message, methodDefinition, argumentObj) { - const method = { - ...methodDefinition, - getServers: () => [], - supportsStreaming: false, - objectTypes: methodDefinition.objectTypes ?? [], - flags: methodDefinition.flags?.metadata ?? {} - }; - const invokeResultMessage = { - invocationId: nanoid(10), - status: InvokeStatus.Error, - message - }; - return this.getInvocationResultObj([invokeResultMessage], method, argumentObj); - } - getInvocationResultObj(invocationResults, method, calledWith) { - const all_return_values = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Success) - .reduce((allValues, currentValue) => { - allValues = [ - ...allValues, - { - executed_by: currentValue.instance, - returned: currentValue.result, - called_with: calledWith, - method, - message: currentValue.message, - status: currentValue.status, - } - ]; - return allValues; - }, []); - const all_errors = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Error) - .reduce((allErrors, currError) => { - allErrors = [ - ...allErrors, - { - executed_by: currError.instance, - called_with: calledWith, - name: method.name, - message: currError.message, - } - ]; - return allErrors; - }, []); - const invResult = invocationResults[0]; - const result = { - method, - called_with: calledWith, - returned: invResult.result, - executed_by: invResult.instance, - all_return_values, - all_errors, - message: invResult.message, - status: invResult.status - }; - return result; - } - tryToAwaitForMethods(methodDefinition, target, additionalOptions) { - return new Promise((resolve, reject) => { - if (additionalOptions.waitTimeoutMs === 0) { - reject(); - return; - } - const delayStep = 500; - let delayTillNow = 0; - const retry = () => { - delayTillNow += delayStep; - const serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length > 0) { - clearInterval(interval); - resolve(serversMethodMap); - } - else if (delayTillNow >= (additionalOptions.waitTimeoutMs || 10000)) { - clearInterval(interval); - reject(); - return; - } - }; - const interval = setInterval(retry, delayStep); - }); - } - filterByTarget(target, serverMethodMap) { - if (typeof target === "string") { - if (target === "all") { - return [...serverMethodMap]; - } - else if (target === "best") { - const localMachine = serverMethodMap - .find((s) => s.server.instance.isLocal); - if (localMachine) { - return [localMachine]; - } - if (serverMethodMap[0] !== undefined) { - return [serverMethodMap[0]]; - } - } - else if (target === "skipMine") { - return serverMethodMap.filter(({ server }) => server.instance.peerId !== this.instance.peerId); - } - } - else { - let targetArray; - if (!Array.isArray(target)) { - targetArray = [target]; - } - else { - targetArray = target; - } - const allServersMatching = targetArray.reduce((matches, filter) => { - const myMatches = serverMethodMap.filter((serverMethodPair) => { - return this.instanceMatch(filter, serverMethodPair.server.instance); - }); - return matches.concat(myMatches); - }, []); - return allServersMatching; - } - return []; - } - instanceMatch(instanceFilter, instanceDefinition) { - if (instanceFilter?.peerId && instanceFilter?.instance) { - instanceFilter = { ...instanceFilter }; - delete instanceFilter.peerId; - } - return this.containsProps(instanceFilter, instanceDefinition); - } - methodMatch(methodFilter, methodDefinition) { - return this.containsProps(methodFilter, methodDefinition); - } - containsProps(filter, repoMethod) { - const filterProps = Object.keys(filter) - .filter((prop) => { - return filter[prop] !== undefined - && filter[prop] !== null - && typeof filter[prop] !== "function" - && prop !== "object_types" - && prop !== "display_name" - && prop !== "id" - && prop !== "gatewayId" - && prop !== "identifier" - && prop[0] !== "_"; - }); - return filterProps.every((prop) => { - let isMatch; - const filterValue = filter[prop]; - const repoMethodValue = repoMethod[prop]; - switch (prop) { - case "objectTypes": - isMatch = (filterValue || []).every((filterValueEl) => { - return (repoMethodValue || []).includes(filterValueEl); - }); - break; - case "flags": - isMatch = isSubset(repoMethodValue || {}, filterValue || {}); - break; - default: - isMatch = String(filterValue).toLowerCase() === String(repoMethodValue).toLowerCase(); - } - return isMatch; - }); - } - getMethods(methodFilter) { - if (methodFilter === undefined) { - return this.repo.getMethods(); - } - const methods = this.repo.getMethods().filter((method) => { - return this.methodMatch(methodFilter, method); - }); - return methods; - } - getMethodsForInstance(instanceFilter) { - const allServers = this.repo.getServers(); - const matchingServers = allServers.filter((server) => { - return this.instanceMatch(instanceFilter, server.instance); - }); - if (matchingServers.length === 0) { - return []; - } - let resultMethodsObject = {}; - if (matchingServers.length === 1) { - resultMethodsObject = matchingServers[0].methods; - } - else { - matchingServers.forEach((server) => { - Object.keys(server.methods).forEach((methodKey) => { - const method = server.methods[methodKey]; - resultMethodsObject[method.identifier] = method; - }); - }); - } - return Object.keys(resultMethodsObject) - .map((key) => { - return resultMethodsObject[key]; - }); - } - getServers(methodFilter) { - const servers = this.repo.getServers(); - if (methodFilter === undefined) { - return servers.map((server) => { - return { server, methods: [] }; - }); - } - return servers.reduce((prev, current) => { - const methodsForServer = Object.values(current.methods); - const matchingMethods = methodsForServer.filter((method) => { - return this.methodMatch(methodFilter, method); - }); - if (matchingMethods.length > 0) { - prev.push({ server: current, methods: matchingMethods }); - } - return prev; - }, []); - } - getServerMethodsByFilterAndTarget(methodFilter, target) { - const serversMethodMap = this.getServers(methodFilter); - return this.filterByTarget(target, serversMethodMap); - } - } - - class ServerSubscription { - protocol; - repoMethod; - subscription; - constructor(protocol, repoMethod, subscription) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.subscription = subscription; - } - get stream() { - if (!this.repoMethod.stream) { - throw new Error("no stream"); - } - return this.repoMethod.stream; - } - get arguments() { return this.subscription.arguments || {}; } - get branchKey() { return this.subscription.branchKey; } - get instance() { - if (!this.subscription.instance) { - throw new Error("no instance"); - } - return this.subscription.instance; - } - close() { - this.protocol.server.closeSingleSubscription(this.repoMethod, this.subscription); - } - push(data) { - this.protocol.server.pushDataToSingle(this.repoMethod, this.subscription, data); - } - } - - class Request { - protocol; - repoMethod; - requestContext; - arguments; - instance; - constructor(protocol, repoMethod, requestContext) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.requestContext = requestContext; - this.arguments = requestContext.arguments; - this.instance = requestContext.instance; - } - accept() { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, ""); - } - acceptOnBranch(branch) { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, branch); - } - reject(reason) { - this.protocol.server.rejectRequest(this.requestContext, this.repoMethod, reason); - } - } - - let ServerStreaming$1 = class ServerStreaming { - protocol; - server; - constructor(protocol, server) { - this.protocol = protocol; - this.server = server; - protocol.server.onSubRequest((rc, rm) => this.handleSubRequest(rc, rm)); - protocol.server.onSubAdded((sub, rm) => this.handleSubAdded(sub, rm)); - protocol.server.onSubRemoved((sub, rm) => this.handleSubRemoved(sub, rm)); - } - handleSubRequest(requestContext, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRequestHandler === "function")) { - return; - } - const request = new Request(this.protocol, repoMethod, requestContext); - repoMethod.streamCallbacks.subscriptionRequestHandler(request); - } - handleSubAdded(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionAddedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionAddedHandler(sub); - } - handleSubRemoved(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRemovedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionRemovedHandler(sub); - } - }; - - class ServerBranch { - key; - protocol; - repoMethod; - constructor(key, protocol, repoMethod) { - this.key = key; - this.protocol = protocol; - this.repoMethod = repoMethod; - } - subscriptions() { - const subList = this.protocol.server.getSubscriptionList(this.repoMethod, this.key); - return subList.map((sub) => { - return new ServerSubscription(this.protocol, this.repoMethod, sub); - }); - } - close() { - this.protocol.server.closeAllSubscriptions(this.repoMethod, this.key); - } - push(data) { - this.protocol.server.pushData(this.repoMethod, data, [this.key]); - } - } - - class ServerStream { - _protocol; - _repoMethod; - _server; - name; - constructor(_protocol, _repoMethod, _server) { - this._protocol = _protocol; - this._repoMethod = _repoMethod; - this._server = _server; - this.name = this._repoMethod.definition.name; - } - branches(key) { - const bList = this._protocol.server.getBranchList(this._repoMethod); - if (key) { - if (bList.indexOf(key) > -1) { - return new ServerBranch(key, this._protocol, this._repoMethod); - } - return undefined; - } - else { - return bList.map((branchKey) => { - return new ServerBranch(branchKey, this._protocol, this._repoMethod); - }); - } - } - branch(key) { - return this.branches(key); - } - subscriptions() { - const subList = this._protocol.server.getSubscriptionList(this._repoMethod); - return subList.map((sub) => { - return new ServerSubscription(this._protocol, this._repoMethod, sub); - }); - } - get definition() { - const def2 = this._repoMethod.definition; - return { - accepts: def2.accepts, - description: def2.description, - displayName: def2.displayName, - name: def2.name, - objectTypes: def2.objectTypes, - returns: def2.returns, - supportsStreaming: def2.supportsStreaming, - flags: def2.flags?.metadata, - }; - } - close() { - this._protocol.server.closeAllSubscriptions(this._repoMethod); - this._server.unregister(this._repoMethod.definition, true); - } - push(data, branches) { - if (typeof branches !== "string" && !Array.isArray(branches) && branches !== undefined) { - throw new Error("invalid branches should be string or string array"); - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - this._protocol.server.pushData(this._repoMethod, data, branches); - } - updateRepoMethod(repoMethod) { - this._repoMethod = repoMethod; - } - } - - class Server { - protocol; - serverRepository; - streaming; - invocations = 0; - currentlyUnregistering = {}; - constructor(protocol, serverRepository) { - this.protocol = protocol; - this.serverRepository = serverRepository; - this.streaming = new ServerStreaming$1(protocol, this); - this.protocol.server.onInvoked(this.onMethodInvoked.bind(this)); - } - createStream(streamDef, callbacks, successCallback, errorCallback, existingStream) { - const promise = new Promise((resolve, reject) => { - if (!streamDef) { - reject("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream."); - return; - } - let streamMethodDefinition; - if (typeof streamDef === "string") { - streamMethodDefinition = { name: "" + streamDef }; - } - else { - streamMethodDefinition = { ...streamDef }; - } - if (!streamMethodDefinition.name) { - return reject(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(streamMethodDefinition)}`); - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === streamMethodDefinition.name); - if (nameAlreadyExists) { - return reject(`A stream with the name "${streamMethodDefinition.name}" already exists! Please, provide a unique name for the stream.`); - } - streamMethodDefinition.supportsStreaming = true; - if (!callbacks) { - callbacks = {}; - } - if (typeof callbacks.subscriptionRequestHandler !== "function") { - callbacks.subscriptionRequestHandler = (request) => { - request.accept(); - }; - } - const repoMethod = this.serverRepository.add({ - definition: streamMethodDefinition, - streamCallbacks: callbacks, - protocolState: {}, - }); - this.protocol.server.createStream(repoMethod) - .then(() => { - let streamUserObject; - if (existingStream) { - streamUserObject = existingStream; - existingStream.updateRepoMethod(repoMethod); - } - else { - streamUserObject = new ServerStream(this.protocol, repoMethod, this); - } - repoMethod.stream = streamUserObject; - resolve(streamUserObject); - }) - .catch((err) => { - if (repoMethod.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - reject(err); - }); - }); - return promisify(promise, successCallback, errorCallback); - } - register(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallbackFunction = async (context, resultCallback) => { - try { - const result = callback(context.args, context.instance); - if (result && typeof result.then === "function") { - const resultValue = await result; - resultCallback(undefined, resultValue); - } - else { - resultCallback(undefined, result); - } - } - catch (e) { - resultCallback(e ?? "", e ?? ""); - } - }; - wrappedCallbackFunction.userCallback = callback; - return this.registerCore(methodDefinition, wrappedCallbackFunction); - } - registerAsync(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallback = async (context, resultCallback) => { - try { - let resultCalled = false; - const success = (result) => { - if (!resultCalled) { - resultCallback(undefined, result); - } - resultCalled = true; - }; - const error = (e) => { - if (!resultCalled) { - if (!e) { - e = ""; - } - resultCallback(e, e); - } - resultCalled = true; - }; - const methodResult = callback(context.args, context.instance, success, error); - if (methodResult && typeof methodResult.then === "function") { - methodResult - .then(success) - .catch(error); - } - } - catch (e) { - resultCallback(e, undefined); - } - }; - wrappedCallback.userCallbackAsync = callback; - return this.registerCore(methodDefinition, wrappedCallback); - } - async unregister(methodFilter, forStream = false) { - if (methodFilter === undefined) { - return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property."); - } - if (typeof methodFilter === "function") { - await this.unregisterWithPredicate(methodFilter, forStream); - return; - } - let methodDefinition; - if (typeof methodFilter === "string") { - methodDefinition = { name: methodFilter }; - } - else { - methodDefinition = methodFilter; - } - if (methodDefinition.name === undefined) { - return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!"); - } - const methodToBeRemoved = this.serverRepository.getList().find((serverMethod) => { - return serverMethod.definition.name === methodDefinition.name - && (serverMethod.definition.supportsStreaming || false) === forStream; - }); - if (!methodToBeRemoved) { - return Promise.reject(`Method with a name "${methodDefinition.name}" does not exist or is not registered by your application!`); - } - await this.removeMethodsOrStreams([methodToBeRemoved]); - } - async unregisterWithPredicate(filterPredicate, forStream) { - const methodsOrStreamsToRemove = this.serverRepository.getList() - .filter((sm) => filterPredicate(sm.definition)) - .filter((serverMethod) => (serverMethod.definition.supportsStreaming || false) === forStream); - if (!methodsOrStreamsToRemove || methodsOrStreamsToRemove.length === 0) { - return Promise.reject(`Could not find a ${forStream ? "stream" : "method"} matching the specified condition!`); - } - await this.removeMethodsOrStreams(methodsOrStreamsToRemove); - } - removeMethodsOrStreams(methodsToRemove) { - const methodUnregPromises = []; - methodsToRemove.forEach((method) => { - const promise = this.protocol.server.unregister(method) - .then(() => { - if (method.repoId) { - this.serverRepository.remove(method.repoId); - } - }); - methodUnregPromises.push(promise); - this.addAsCurrentlyUnregistering(method.definition.name, promise); - }); - return Promise.all(methodUnregPromises); - } - async addAsCurrentlyUnregistering(methodName, promise) { - const timeout = new Promise((resolve) => setTimeout(resolve, 5000)); - this.currentlyUnregistering[methodName] = Promise.race([promise, timeout]).then(() => { - delete this.currentlyUnregistering[methodName]; - }); - } - async registerCore(method, theFunction) { - let methodDefinition; - if (typeof method === "string") { - methodDefinition = { name: "" + method }; - } - else { - methodDefinition = { ...method }; - } - if (!methodDefinition.name) { - return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(method)}`); - } - const unregisterInProgress = this.currentlyUnregistering[methodDefinition.name]; - if (typeof unregisterInProgress !== "undefined") { - await unregisterInProgress; - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === methodDefinition.name); - if (nameAlreadyExists) { - return Promise.reject(`A method with the name "${methodDefinition.name}" already exists! Please, provide a unique name for the method.`); - } - if (methodDefinition.supportsStreaming) { - return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${methodDefinition.name}” to be a stream, please use the “glue.interop.createStream()” method.`); - } - const repoMethod = this.serverRepository.add({ - definition: methodDefinition, - theFunction, - protocolState: {}, - }); - return this.protocol.server.register(repoMethod) - .catch((err) => { - if (repoMethod?.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - throw err; - }); - } - onMethodInvoked(methodToExecute, invocationId, invocationArgs) { - if (!methodToExecute || !methodToExecute.theFunction) { - return; - } - methodToExecute.theFunction(invocationArgs, (err, result) => { - if (err !== undefined && err !== null) { - if (err.message && typeof err.message === "string") { - err = err.message; - } - else if (typeof err !== "string") { - try { - err = JSON.stringify(err); - } - catch (unStrException) { - err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`; - } - } - } - if (!result) { - result = {}; - } - else if (typeof result !== "object" || Array.isArray(result)) { - result = { _value: result }; - } - this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result); - }); - } - } - - class InstanceWrapper { - wrapped = {}; - constructor(API, instance, connection) { - this.wrapped.getMethods = function () { - return API.methodsForInstance(this); - }; - this.wrapped.getStreams = function () { - return API.methodsForInstance(this).filter((m) => m.supportsStreaming); - }; - if (instance) { - this.refreshWrappedObject(instance); - } - if (connection) { - connection.loggedIn(() => { - this.refresh(connection); - }); - this.refresh(connection); - } - } - unwrap() { - return this.wrapped; - } - refresh(connection) { - if (!connection) { - return; - } - const resolvedIdentity = connection?.resolvedIdentity; - const instance = Object.assign({}, resolvedIdentity ?? {}, { peerId: connection?.peerId }); - this.refreshWrappedObject(instance); - } - refreshWrappedObject(resolvedIdentity) { - Object.keys(resolvedIdentity).forEach((key) => { - this.wrapped[key] = resolvedIdentity[key]; - }); - this.wrapped.user = resolvedIdentity.user; - this.wrapped.instance = resolvedIdentity.instance; - this.wrapped.application = resolvedIdentity.application ?? nanoid(10); - this.wrapped.applicationName = resolvedIdentity.applicationName; - this.wrapped.pid = resolvedIdentity.pid ?? resolvedIdentity.process ?? Math.floor(Math.random() * 10000000000); - this.wrapped.machine = resolvedIdentity.machine; - this.wrapped.environment = resolvedIdentity.environment; - this.wrapped.region = resolvedIdentity.region; - this.wrapped.windowId = resolvedIdentity.windowId; - this.wrapped.isLocal = resolvedIdentity.isLocal ?? true; - this.wrapped.api = resolvedIdentity.api; - this.wrapped.service = resolvedIdentity.service; - this.wrapped.peerId = resolvedIdentity.peerId; - } - } - - const hideMethodSystemFlags = (method) => { - return { - ...method, - flags: method.flags.metadata || {} - }; - }; - class ClientRepository { - logger; - API; - servers = {}; - myServer; - methodsCount = {}; - callbacks = CallbackRegistryFactory(); - constructor(logger, API) { - this.logger = logger; - this.API = API; - const peerId = this.API.instance.peerId; - this.myServer = { - id: peerId, - methods: {}, - instance: this.API.instance, - wrapper: this.API.unwrappedInstance, - }; - this.servers[peerId] = this.myServer; - } - addServer(info, serverId) { - this.logger.debug(`adding server ${serverId}`); - const current = this.servers[serverId]; - if (current) { - return current.id; - } - const wrapper = new InstanceWrapper(this.API, info); - const serverEntry = { - id: serverId, - methods: {}, - instance: wrapper.unwrap(), - wrapper, - }; - this.servers[serverId] = serverEntry; - this.callbacks.execute("onServerAdded", serverEntry.instance); - return serverId; - } - removeServerById(id, reason) { - const server = this.servers[id]; - if (!server) { - this.logger.warn(`not aware of server ${id}, my state ${JSON.stringify(Object.keys(this.servers))}`); - return; - } - else { - this.logger.debug(`removing server ${id}`); - } - Object.keys(server.methods).forEach((methodId) => { - this.removeServerMethod(id, methodId); - }); - delete this.servers[id]; - this.callbacks.execute("onServerRemoved", server.instance, reason); - } - addServerMethod(serverId, method) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - if (server.methods[method.id]) { - return; - } - const identifier = this.createMethodIdentifier(method); - const that = this; - const methodDefinition = { - identifier, - gatewayId: method.id, - name: method.name, - displayName: method.display_name, - description: method.description, - version: method.version, - objectTypes: method.object_types || [], - accepts: method.input_signature, - returns: method.result_signature, - supportsStreaming: typeof method.flags !== "undefined" ? method.flags.streaming : false, - flags: method.flags ?? {}, - getServers: () => { - return that.getServersByMethod(identifier); - } - }; - methodDefinition.object_types = methodDefinition.objectTypes; - methodDefinition.display_name = methodDefinition.displayName; - methodDefinition.version = methodDefinition.version; - server.methods[method.id] = methodDefinition; - const clientMethodDefinition = hideMethodSystemFlags(methodDefinition); - if (!this.methodsCount[identifier]) { - this.methodsCount[identifier] = 0; - this.callbacks.execute("onMethodAdded", clientMethodDefinition); - } - this.methodsCount[identifier] = this.methodsCount[identifier] + 1; - this.callbacks.execute("onServerMethodAdded", server.instance, clientMethodDefinition); - return methodDefinition; - } - removeServerMethod(serverId, methodId) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - const method = server.methods[methodId]; - delete server.methods[methodId]; - const clientMethodDefinition = hideMethodSystemFlags(method); - this.methodsCount[method.identifier] = this.methodsCount[method.identifier] - 1; - if (this.methodsCount[method.identifier] === 0) { - this.callbacks.execute("onMethodRemoved", clientMethodDefinition); - } - this.callbacks.execute("onServerMethodRemoved", server.instance, clientMethodDefinition); - } - getMethods() { - return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags); - } - getServers() { - return Object.values(this.servers).map(this.hideServerMethodSystemFlags); - } - onServerAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerAdded", callback); - const serversWithMethodsToReplay = this.getServers().map((s) => s.instance); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, serversWithMethodsToReplay, callback); - } - onMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodAdded", callback); - const methodsToReplay = this.getMethods(); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, methodsToReplay, callback); - } - onServerMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodAdded", callback); - let unsubCalled = false; - const servers = this.getServers(); - setTimeout(() => { - servers.forEach((server) => { - const methods = server.methods; - Object.keys(methods).forEach((methodId) => { - if (!unsubCalled) { - callback(server.instance, methods[methodId]); - } - }); - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - onMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodRemoved", callback); - return unsubscribeFunc; - } - onServerRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerRemoved", callback); - return unsubscribeFunc; - } - onServerMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodRemoved", callback); - return unsubscribeFunc; - } - getServerById(id) { - const server = this.servers[id]; - if (!server) { - return undefined; - } - return this.hideServerMethodSystemFlags(this.servers[id]); - } - reset() { - Object.keys(this.servers).forEach((key) => { - this.removeServerById(key, "reset"); - }); - this.servers = { - [this.myServer.id]: this.myServer - }; - this.methodsCount = {}; - } - createMethodIdentifier(methodInfo) { - const accepts = methodInfo.input_signature ?? ""; - const returns = methodInfo.result_signature ?? ""; - return (methodInfo.name + accepts + returns).toLowerCase(); - } - getServersByMethod(identifier) { - const allServers = []; - Object.values(this.servers).forEach((server) => { - Object.values(server.methods).forEach((method) => { - if (method.identifier === identifier) { - allServers.push(server.instance); - } - }); - }); - return allServers; - } - returnUnsubWithDelayedReplay(unsubscribeFunc, collectionToReplay, callback) { - let unsubCalled = false; - setTimeout(() => { - collectionToReplay.forEach((item) => { - if (!unsubCalled) { - callback(item); - } - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - hideServerMethodSystemFlags(server) { - const clientMethods = {}; - Object.entries(server.methods).forEach(([name, method]) => { - clientMethods[name] = hideMethodSystemFlags(method); - }); - return { - ...server, - methods: clientMethods - }; - } - extractMethodsFromServers(servers) { - const methods = Object.values(servers).reduce((clientMethods, server) => { - return [...clientMethods, ...Object.values(server.methods)]; - }, []); - return methods; - } - } - - class ServerRepository { - nextId = 0; - methods = []; - add(method) { - method.repoId = String(this.nextId); - this.nextId += 1; - this.methods.push(method); - return method; - } - remove(repoId) { - if (typeof repoId !== "string") { - return new TypeError("Expecting a string"); - } - this.methods = this.methods.filter((m) => { - return m.repoId !== repoId; - }); - } - getById(id) { - if (typeof id !== "string") { - return undefined; - } - return this.methods.find((m) => { - return m.repoId === id; - }); - } - getList() { - return this.methods.map((m) => m); - } - length() { - return this.methods.length; - } - reset() { - this.methods = []; - } - } - - const SUBSCRIPTION_REQUEST = "onSubscriptionRequest"; - const SUBSCRIPTION_ADDED = "onSubscriptionAdded"; - const SUBSCRIPTION_REMOVED = "onSubscriptionRemoved"; - class ServerStreaming { - session; - repository; - serverRepository; - logger; - ERR_URI_SUBSCRIPTION_FAILED = "com.tick42.agm.errors.subscription.failure"; - callbacks = CallbackRegistryFactory(); - nextStreamId = 0; - constructor(session, repository, serverRepository, logger) { - this.session = session; - this.repository = repository; - this.serverRepository = serverRepository; - this.logger = logger; - session.on("add-interest", (msg) => { - this.handleAddInterest(msg); - }); - session.on("remove-interest", (msg) => { - this.handleRemoveInterest(msg); - }); - } - acceptRequestOnBranch(requestContext, streamingMethod, branch) { - if (typeof branch !== "string") { - branch = ""; - } - if (typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - throw new TypeError("The streaming method is missing its subscriptions."); - } - if (!Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - throw new TypeError("The streaming method is missing its branches."); - } - const streamId = this.getStreamId(streamingMethod, branch); - const key = requestContext.msg.subscription_id; - const subscription = { - id: key, - arguments: requestContext.arguments, - instance: requestContext.instance, - branchKey: branch, - streamId, - subscribeMsg: requestContext.msg, - }; - streamingMethod.protocolState.subscriptionsMap[key] = subscription; - this.session.sendFireAndForget({ - type: "accepted", - subscription_id: key, - stream_id: streamId, - }).catch((err) => { - this.logger.warn(`Failed to send accepted message for subscription ${key}: ${JSON.stringify(err)}`); - }); - this.callbacks.execute(SUBSCRIPTION_ADDED, subscription, streamingMethod); - } - rejectRequest(requestContext, streamingMethod, reason) { - if (typeof reason !== "string") { - reason = ""; - } - this.sendSubscriptionFailed("Subscription rejected by user. " + reason, requestContext.msg.subscription_id); - } - pushData(streamingMethod, data, branches) { - if (typeof streamingMethod !== "object" || !Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - return; - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - if (typeof branches === "string") { - branches = [branches]; - } - else if (!Array.isArray(branches) || branches.length <= 0) { - branches = []; - } - const streamIdList = streamingMethod.protocolState.branchKeyToStreamIdMap - .filter((br) => { - if (!branches || branches.length === 0) { - return true; - } - return branches.indexOf(br.key) >= 0; - }).map((br) => { - return br.streamId; - }); - streamIdList.forEach((streamId) => { - const publishMessage = { - type: "publish", - stream_id: streamId, - data, - }; - this.session.sendFireAndForget(publishMessage) - .catch((err) => { - this.logger.warn(`Failed to send publish message for stream ${streamId}: ${JSON.stringify(err)}`); - }); - }); - } - pushDataToSingle(method, subscription, data) { - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - const postMessage = { - type: "post", - subscription_id: subscription.id, - data, - }; - this.session.sendFireAndForget(postMessage) - .catch((err) => { - this.logger.warn(`Failed to send post message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - } - closeSingleSubscription(streamingMethod, subscription) { - if (streamingMethod.protocolState.subscriptionsMap) { - delete streamingMethod.protocolState.subscriptionsMap[subscription.id]; - } - const dropSubscriptionMessage = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping a single subscription", - }; - this.session.sendFireAndForget(dropSubscriptionMessage) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - subscription.instance; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - closeMultipleSubscriptions(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object" || typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - let subscriptionsToClose = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey === "string") { - subscriptionsToClose = subscriptionsToClose.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - subscriptionsToClose.forEach((subscription) => { - delete subscriptionsMap[subscription.id]; - const drop = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping all subscriptions on stream_id: " + subscription.streamId, - }; - this.session.sendFireAndForget(drop) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - }); - } - getSubscriptionList(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object") { - return []; - } - let subscriptions = []; - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey !== "string") { - subscriptions = allSubscriptions; - } - else { - subscriptions = allSubscriptions.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - return subscriptions; - } - getBranchList(streamingMethod) { - if (typeof streamingMethod !== "object") { - return []; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - const result = []; - allSubscriptions.forEach((sub) => { - let branch = ""; - if (typeof sub === "object" && typeof sub.branchKey === "string") { - branch = sub.branchKey; - } - if (result.indexOf(branch) === -1) { - result.push(branch); - } - }); - return result; - } - onSubAdded(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED, callback); - } - onSubRequest(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST, callback); - } - onSubRemoved(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED, callback); - } - handleRemoveInterest(msg) { - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (typeof msg.subscription_id !== "string" || - typeof streamingMethod !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - if (typeof streamingMethod.protocolState.subscriptionsMap[msg.subscription_id] !== "object") { - return; - } - const subscription = streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - delete streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - onSubscriptionLifetimeEvent(eventName, handlerFunc) { - this.callbacks.add(eventName, handlerFunc); - } - getNextStreamId() { - return this.nextStreamId++ + ""; - } - handleAddInterest(msg) { - const caller = this.repository.getServerById(msg.caller_id); - const instance = caller?.instance ?? {}; - const requestContext = { - msg, - arguments: msg.arguments_kv || {}, - instance, - }; - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (streamingMethod === undefined) { - const errorMsg = "No method with id " + msg.method_id + " on this server."; - this.sendSubscriptionFailed(errorMsg, msg.subscription_id); - return; - } - if (streamingMethod.protocolState.subscriptionsMap && - streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]) { - this.sendSubscriptionFailed("A subscription with id " + msg.subscription_id + " already exists.", msg.subscription_id); - return; - } - this.callbacks.execute(SUBSCRIPTION_REQUEST, requestContext, streamingMethod); - } - sendSubscriptionFailed(reason, subscriptionId) { - const errorMessage = { - type: "error", - reason_uri: this.ERR_URI_SUBSCRIPTION_FAILED, - reason, - request_id: subscriptionId, - }; - this.session.sendFireAndForget(errorMessage) - .catch((err) => { - this.logger.warn(`Failed to send subscription failed message for subscription ${subscriptionId}: ${JSON.stringify(err)}`); - }); - } - getStreamId(streamingMethod, branchKey) { - if (typeof branchKey !== "string") { - branchKey = ""; - } - if (!streamingMethod.protocolState.branchKeyToStreamIdMap) { - throw new Error(`streaming ${streamingMethod.definition.name} method without protocol state`); - } - const needleBranch = streamingMethod.protocolState.branchKeyToStreamIdMap.filter((branch) => { - return branch.key === branchKey; - })[0]; - let streamId = (needleBranch ? needleBranch.streamId : undefined); - if (typeof streamId !== "string" || streamId === "") { - streamId = this.getNextStreamId(); - streamingMethod.protocolState.branchKeyToStreamIdMap.push({ key: branchKey, streamId }); - } - return streamId; - } - } - - class ServerProtocol { - session; - clientRepository; - serverRepository; - logger; - callbacks = CallbackRegistryFactory(); - streaming; - constructor(session, clientRepository, serverRepository, logger) { - this.session = session; - this.clientRepository = clientRepository; - this.serverRepository = serverRepository; - this.logger = logger; - this.streaming = new ServerStreaming(session, clientRepository, serverRepository, logger.subLogger("streaming")); - this.session.on("invoke", (msg) => this.handleInvokeMessage(msg)); - } - createStream(repoMethod) { - repoMethod.protocolState.subscriptionsMap = {}; - repoMethod.protocolState.branchKeyToStreamIdMap = []; - return this.register(repoMethod, true); - } - register(repoMethod, isStreaming) { - const methodDef = repoMethod.definition; - const flags = Object.assign({}, { metadata: methodDef.flags ?? {} }, { streaming: isStreaming || false }); - const registerMsg = { - type: "register", - methods: [{ - id: repoMethod.repoId, - name: methodDef.name, - display_name: methodDef.displayName, - description: methodDef.description, - version: methodDef.version, - flags, - object_types: methodDef.objectTypes || methodDef.object_types, - input_signature: methodDef.accepts, - result_signature: methodDef.returns, - restrictions: undefined, - }], - }; - return this.session.send(registerMsg, { methodId: repoMethod.repoId }) - .then(() => { - this.logger.debug("registered method " + repoMethod.definition.name + " with id " + repoMethod.repoId); - }) - .catch((msg) => { - this.logger.warn(`failed to register method ${repoMethod.definition.name} with id ${repoMethod.repoId} - ${JSON.stringify(msg)}`); - throw msg; - }); - } - onInvoked(callback) { - this.callbacks.add("onInvoked", callback); - } - methodInvocationResult(method, invocationId, err, result) { - let msg; - if (err || err === "") { - msg = { - type: "error", - request_id: invocationId, - reason_uri: "agm.errors.client_error", - reason: err, - context: result, - peer_id: undefined, - }; - } - else { - msg = { - type: "yield", - invocation_id: invocationId, - peer_id: this.session.peerId, - result, - request_id: undefined, - }; - } - this.session.sendFireAndForget(msg) - .catch((error => { - this.logger.warn(`Failed to send method invocation result for method ${method.definition.name} invocation ${invocationId} - ${JSON.stringify(error)}`); - })); - } - async unregister(method) { - const msg = { - type: "unregister", - methods: [method.repoId], - }; - await this.session.send(msg); - } - getBranchList(method) { - return this.streaming.getBranchList(method); - } - getSubscriptionList(method, branchKey) { - return this.streaming.getSubscriptionList(method, branchKey); - } - closeAllSubscriptions(method, branchKey) { - this.streaming.closeMultipleSubscriptions(method, branchKey); - } - pushData(method, data, branches) { - this.streaming.pushData(method, data, branches); - } - pushDataToSingle(method, subscription, data) { - this.streaming.pushDataToSingle(method, subscription, data); - } - closeSingleSubscription(method, subscription) { - this.streaming.closeSingleSubscription(method, subscription); - } - acceptRequestOnBranch(requestContext, method, branch) { - this.streaming.acceptRequestOnBranch(requestContext, method, branch); - } - rejectRequest(requestContext, method, reason) { - this.streaming.rejectRequest(requestContext, method, reason); - } - onSubRequest(callback) { - this.streaming.onSubRequest(callback); - } - onSubAdded(callback) { - this.streaming.onSubAdded(callback); - } - onSubRemoved(callback) { - this.streaming.onSubRemoved(callback); - } - handleInvokeMessage(msg) { - const invocationId = msg.invocation_id; - const callerId = msg.caller_id; - const methodId = msg.method_id; - const args = msg.arguments_kv; - const methodList = this.serverRepository.getList(); - const method = methodList.filter((m) => { - return m.repoId === methodId; - })[0]; - if (method === undefined) { - return; - } - const client = this.clientRepository.getServerById(callerId)?.instance; - const invocationArgs = { args, instance: client }; - this.callbacks.execute("onInvoked", method, invocationId, invocationArgs); - } - } - - class UserSubscription { - repository; - subscriptionData; - get requestArguments() { - return this.subscriptionData.params.arguments || {}; - } - get servers() { - return this.subscriptionData.trackedServers.reduce((servers, pair) => { - if (pair.subscriptionId) { - const server = this.repository.getServerById(pair.serverId)?.instance; - if (server) { - servers.push(server); - } - } - return servers; - }, []); - } - get serverInstance() { - return this.servers[0]; - } - get stream() { - return this.subscriptionData.method; - } - constructor(repository, subscriptionData) { - this.repository = repository; - this.subscriptionData = subscriptionData; - } - onData(dataCallback) { - if (typeof dataCallback !== "function") { - throw new TypeError("The data callback must be a function."); - } - this.subscriptionData.handlers.onData.push(dataCallback); - if (this.subscriptionData.handlers.onData.length === 1 && this.subscriptionData.queued.data.length > 0) { - this.subscriptionData.queued.data.forEach((dataItem) => { - dataCallback(dataItem); - }); - } - } - onClosed(closedCallback) { - if (typeof closedCallback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onClosed.push(closedCallback); - } - onFailed(callback) { - } - onConnected(callback) { - if (typeof callback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onConnected.push(callback); - } - close() { - this.subscriptionData.close(); - } - setNewSubscription(newSub) { - this.subscriptionData = newSub; - } - } - - class TimedCache { - config; - cache = []; - timeoutIds = []; - constructor(config) { - this.config = config; - } - add(element) { - const id = nanoid(10); - this.cache.push({ id, element }); - const timeoutId = setTimeout(() => { - const elementIdx = this.cache.findIndex((entry) => entry.id === id); - if (elementIdx < 0) { - return; - } - this.cache.splice(elementIdx, 1); - }, this.config.ELEMENT_TTL_MS); - this.timeoutIds.push(timeoutId); - } - flush() { - const elements = this.cache.map((entry) => entry.element); - this.timeoutIds.forEach((id) => clearInterval(id)); - this.cache = []; - this.timeoutIds = []; - return elements; - } - } - - const STATUS_AWAITING_ACCEPT = "awaitingAccept"; - const STATUS_SUBSCRIBED = "subscribed"; - const ERR_MSG_SUB_FAILED = "Subscription failed."; - const ERR_MSG_SUB_REJECTED = "Subscription rejected."; - const ON_CLOSE_MSG_SERVER_INIT = "ServerInitiated"; - const ON_CLOSE_MSG_CLIENT_INIT = "ClientInitiated"; - class ClientStreaming { - session; - repository; - logger; - subscriptionsList = {}; - timedCache = new TimedCache({ ELEMENT_TTL_MS: 10000 }); - subscriptionIdToLocalKeyMap = {}; - nextSubLocalKey = 0; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("subscribed", this.handleSubscribed); - session.on("event", this.handleEventData); - session.on("subscription-cancelled", this.handleSubscriptionCancelled); - } - subscribe(streamingMethod, params, targetServers, success, error, existingSub) { - if (targetServers.length === 0) { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " No available servers matched the target params.", - }); - return; - } - const subLocalKey = this.getNextSubscriptionLocalKey(); - const pendingSub = this.registerSubscription(subLocalKey, streamingMethod, params, success, error, params.methodResponseTimeout || 10000, existingSub); - if (typeof pendingSub !== "object") { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Unable to register the user callbacks.", - }); - return; - } - targetServers.forEach((target) => { - const serverId = target.server.id; - const method = target.methods.find((m) => m.name === streamingMethod.name); - if (!method) { - this.logger.error(`can not find method ${streamingMethod.name} for target ${target.server.id}`); - return; - } - pendingSub.trackedServers.push({ - serverId, - subscriptionId: undefined, - }); - const msg = { - type: "subscribe", - server_id: serverId, - method_id: method.gatewayId, - arguments_kv: params.arguments, - }; - this.session.send(msg, { serverId, subLocalKey }) - .then((m) => this.handleSubscribed(m)) - .catch((err) => this.handleErrorSubscribing(err)); - }); - } - drainSubscriptions() { - const existing = Object.values(this.subscriptionsList); - this.subscriptionsList = {}; - this.subscriptionIdToLocalKeyMap = {}; - return existing; - } - drainSubscriptionsCache() { - return this.timedCache.flush(); - } - getNextSubscriptionLocalKey() { - const current = this.nextSubLocalKey; - this.nextSubLocalKey += 1; - return current; - } - registerSubscription(subLocalKey, method, params, success, error, timeout, existingSub) { - const subsInfo = { - localKey: subLocalKey, - status: STATUS_AWAITING_ACCEPT, - method, - params, - success, - error, - trackedServers: [], - handlers: { - onData: existingSub?.handlers.onData || [], - onClosed: existingSub?.handlers.onClosed || [], - onConnected: existingSub?.handlers.onConnected || [], - }, - queued: { - data: [], - closers: [], - }, - timeoutId: undefined, - close: () => this.closeSubscription(subLocalKey), - subscription: existingSub?.subscription - }; - if (!existingSub) { - if (params.onData) { - subsInfo.handlers.onData.push(params.onData); - } - if (params.onClosed) { - subsInfo.handlers.onClosed.push(params.onClosed); - } - if (params.onConnected) { - subsInfo.handlers.onConnected.push(params.onConnected); - } - } - this.subscriptionsList[subLocalKey] = subsInfo; - subsInfo.timeoutId = setTimeout(() => { - if (this.subscriptionsList[subLocalKey] === undefined) { - return; - } - const pendingSub = this.subscriptionsList[subLocalKey]; - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - error({ - method, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Subscription attempt timed out after " + timeout + " ms.", - }); - delete this.subscriptionsList[subLocalKey]; - } - else if (pendingSub.status === STATUS_SUBSCRIBED && pendingSub.trackedServers.length > 0) { - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return (typeof server.subscriptionId !== "undefined"); - }); - delete pendingSub.timeoutId; - if (pendingSub.trackedServers.length <= 0) { - this.callOnClosedHandlers(pendingSub); - delete this.subscriptionsList[subLocalKey]; - } - } - }, timeout); - return subsInfo; - } - handleErrorSubscribing = (errorResponse) => { - const tag = errorResponse._tag; - const subLocalKey = tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return server.serverId !== tag.serverId; - }); - if (pendingSub.trackedServers.length <= 0) { - clearTimeout(pendingSub.timeoutId); - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - const reason = (typeof errorResponse.reason === "string" && errorResponse.reason !== "") ? - ' Publisher said "' + errorResponse.reason + '".' : - " No reason given."; - const callArgs = typeof pendingSub.params.arguments === "object" ? - JSON.stringify(pendingSub.params.arguments) : - "{}"; - pendingSub.error({ - message: ERR_MSG_SUB_REJECTED + reason + " Called with:" + callArgs, - called_with: pendingSub.params.arguments, - method: pendingSub.method, - }); - } - else if (pendingSub.status === STATUS_SUBSCRIBED) { - this.callOnClosedHandlers(pendingSub); - } - delete this.subscriptionsList[subLocalKey]; - } - }; - handleSubscribed = (msg) => { - const subLocalKey = msg._tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - const serverId = msg._tag.serverId; - const acceptingServer = pendingSub.trackedServers - .filter((server) => { - return server.serverId === serverId; - })[0]; - if (typeof acceptingServer !== "object") { - return; - } - acceptingServer.subscriptionId = msg.subscription_id; - this.subscriptionIdToLocalKeyMap[msg.subscription_id] = subLocalKey; - const isFirstResponse = (pendingSub.status === STATUS_AWAITING_ACCEPT); - pendingSub.status = STATUS_SUBSCRIBED; - if (isFirstResponse) { - let reconnect = false; - let sub = pendingSub.subscription; - if (sub) { - sub.setNewSubscription(pendingSub); - pendingSub.success(sub); - reconnect = true; - } - else { - sub = new UserSubscription(this.repository, pendingSub); - pendingSub.subscription = sub; - pendingSub.success(sub); - } - for (const handler of pendingSub.handlers.onConnected) { - try { - handler(sub.serverInstance, reconnect); - } - catch (e) { - } - } - } - }; - handleEventData = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const trackedServersFound = subscription.trackedServers.filter((s) => { - return s.subscriptionId === msg.subscription_id; - }); - if (trackedServersFound.length !== 1) { - return; - } - const isPrivateData = msg.oob; - const sendingServerId = trackedServersFound[0].serverId; - const server = this.repository.getServerById(sendingServerId); - const receivedStreamData = () => { - return { - data: msg.data, - server: server?.instance ?? {}, - requestArguments: subscription.params.arguments, - message: undefined, - private: isPrivateData, - }; - }; - const onDataHandlers = subscription.handlers.onData; - const queuedData = subscription.queued.data; - if (onDataHandlers.length > 0) { - onDataHandlers.forEach((callback) => { - if (typeof callback === "function") { - callback(receivedStreamData()); - } - }); - } - else { - queuedData.push(receivedStreamData()); - } - }; - handleSubscriptionCancelled = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const expectedNewLength = subscription.trackedServers.length - 1; - subscription.trackedServers = subscription.trackedServers.filter((server) => { - if (server.subscriptionId === msg.subscription_id) { - subscription.queued.closers.push(server.serverId); - return false; - } - else { - return true; - } - }); - if (subscription.trackedServers.length !== expectedNewLength) { - return; - } - if (subscription.trackedServers.length <= 0) { - this.timedCache.add(subscription); - clearTimeout(subscription.timeoutId); - this.callOnClosedHandlers(subscription); - delete this.subscriptionsList[subLocalKey]; - } - delete this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - }; - callOnClosedHandlers(subscription, reason) { - const closersCount = subscription.queued.closers.length; - const closingServerId = (closersCount > 0) ? subscription.queued.closers[closersCount - 1] : null; - let closingServer; - if (closingServerId !== undefined && typeof closingServerId === "string") { - closingServer = this.repository.getServerById(closingServerId)?.instance ?? {}; - } - subscription.handlers.onClosed.forEach((callback) => { - if (typeof callback !== "function") { - return; - } - callback({ - message: reason || ON_CLOSE_MSG_SERVER_INIT, - requestArguments: subscription.params.arguments || {}, - server: closingServer, - stream: subscription.method, - }); - }); - } - closeSubscription(subLocalKey) { - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - subscription.trackedServers.forEach((server) => { - if (typeof server.subscriptionId === "undefined") { - return; - } - subscription.queued.closers.push(server.serverId); - this.session.sendFireAndForget({ - type: "unsubscribe", - subscription_id: server.subscriptionId, - reason_uri: "", - reason: ON_CLOSE_MSG_CLIENT_INIT, - }).catch((err) => { - this.logger.warn(`Error sending unsubscribe for subscription id ${server.subscriptionId}: ${JSON.stringify(err)}`); - }); - delete this.subscriptionIdToLocalKeyMap[server.subscriptionId]; - }); - subscription.trackedServers = []; - this.callOnClosedHandlers(subscription, ON_CLOSE_MSG_CLIENT_INIT); - delete this.subscriptionsList[subLocalKey]; - } - } - - class ClientProtocol { - session; - repository; - logger; - streaming; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("peer-added", (msg) => this.handlePeerAdded(msg)); - session.on("peer-removed", (msg) => this.handlePeerRemoved(msg)); - session.on("methods-added", (msg) => this.handleMethodsAddedMessage(msg)); - session.on("methods-removed", (msg) => this.handleMethodsRemovedMessage(msg)); - this.streaming = new ClientStreaming(session, repository, logger); - } - subscribe(stream, options, targetServers, success, error, existingSub) { - this.streaming.subscribe(stream, options, targetServers, success, error, existingSub); - } - invoke(id, method, args, target) { - const serverId = target.id; - const methodId = method.gatewayId; - const msg = { - type: "call", - server_id: serverId, - method_id: methodId, - arguments_kv: args, - }; - return this.session.send(msg, { invocationId: id, serverId }) - .then((m) => this.handleResultMessage(m)) - .catch((err) => this.handleInvocationError(err)); - } - drainSubscriptions() { - return this.streaming.drainSubscriptions(); - } - drainSubscriptionsCache() { - return this.streaming.drainSubscriptionsCache(); - } - handlePeerAdded(msg) { - const newPeerId = msg.new_peer_id; - const remoteId = msg.identity; - const isLocal = msg.meta ? msg.meta.local : true; - const pid = Number(remoteId.process); - const serverInfo = { - machine: remoteId.machine, - pid: isNaN(pid) ? remoteId.process : pid, - instance: remoteId.instance, - application: remoteId.application, - applicationName: remoteId.applicationName, - environment: remoteId.environment, - region: remoteId.region, - user: remoteId.user, - windowId: remoteId.windowId, - peerId: newPeerId, - api: remoteId.api, - isLocal - }; - this.repository.addServer(serverInfo, newPeerId); - } - handlePeerRemoved(msg) { - const removedPeerId = msg.removed_id; - const reason = msg.reason; - this.repository.removeServerById(removedPeerId, reason); - } - handleMethodsAddedMessage(msg) { - const serverId = msg.server_id; - const methods = msg.methods; - methods.forEach((method) => { - this.repository.addServerMethod(serverId, method); - }); - } - handleMethodsRemovedMessage(msg) { - const serverId = msg.server_id; - const methodIdList = msg.methods; - const server = this.repository.getServerById(serverId); - if (server) { - const serverMethodKeys = Object.keys(server.methods); - serverMethodKeys.forEach((methodKey) => { - const method = server.methods[methodKey]; - if (methodIdList.indexOf(method.gatewayId) > -1) { - this.repository.removeServerMethod(serverId, methodKey); - } - }); - } - } - handleResultMessage(msg) { - const invocationId = msg._tag.invocationId; - const result = msg.result; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - return { - invocationId, - result, - instance: server?.instance, - status: InvokeStatus.Success, - message: "" - }; - } - handleInvocationError(msg) { - this.logger.debug(`handle invocation error ${JSON.stringify(msg)}`); - if ("_tag" in msg) { - const invocationId = msg._tag.invocationId; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - const message = msg.reason; - const context = msg.context; - return { - invocationId, - result: context, - instance: server?.instance, - status: InvokeStatus.Error, - message - }; - } - else { - return { - invocationId: "", - message: msg.message, - status: InvokeStatus.Error, - error: msg - }; - } - } - } - - function gW3ProtocolFactory (instance, connection, clientRepository, serverRepository, libConfig, interop) { - const logger = libConfig.logger.subLogger("gw3-protocol"); - let resolveReadyPromise; - const readyPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - const session = connection.domain("agm", ["subscribed"]); - const server = new ServerProtocol(session, clientRepository, serverRepository, logger.subLogger("server")); - const client = new ClientProtocol(session, clientRepository, logger.subLogger("client")); - async function handleReconnect() { - logger.info("reconnected - will replay registered methods and subscriptions"); - client.drainSubscriptionsCache().forEach((sub) => { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to soft-re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`soft-subscribing to method ${methodInfo.name} DONE`)).catch((error) => logger.warn(`subscribing to method ${methodInfo.name} failed: ${JSON.stringify(error)}}`)); - }); - const reconnectionPromises = []; - const existingSubscriptions = client.drainSubscriptions(); - for (const sub of existingSubscriptions) { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - reconnectionPromises.push(interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`subscribing to method ${methodInfo.name} DONE`))); - } - const registeredMethods = serverRepository.getList(); - serverRepository.reset(); - for (const method of registeredMethods) { - const def = method.definition; - if (method.stream) { - reconnectionPromises.push(interop.server.createStream(def, method.streamCallbacks, undefined, undefined, method.stream) - .then(() => logger.info(`subscribing to method ${def.name} DONE`)) - .catch(() => logger.warn(`subscribing to method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallback) { - reconnectionPromises.push(interop.register(def, method.theFunction.userCallback) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallbackAsync) { - reconnectionPromises.push(interop.registerAsync(def, method.theFunction.userCallbackAsync) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - } - await Promise.all(reconnectionPromises); - logger.info("Interop is re-announced"); - } - function handleInitialJoin() { - if (resolveReadyPromise) { - resolveReadyPromise({ - client, - server, - }); - resolveReadyPromise = undefined; - } - } - session.onJoined((reconnect) => { - clientRepository.addServer(instance, connection.peerId); - if (reconnect) { - handleReconnect().then(() => connection.setLibReAnnounced({ name: "interop" })).catch((error) => logger.warn(`Error while re-announcing interop: ${JSON.stringify(error)}`)); - } - else { - handleInitialJoin(); - } - }); - session.onLeft(() => { - clientRepository.reset(); - }); - session.join(); - return readyPromise; - } - - class Interop { - instance; - readyPromise; - client; - server; - unwrappedInstance; - protocol; - clientRepository; - serverRepository; - constructor(configuration) { - if (typeof configuration === "undefined") { - throw new Error("configuration is required"); - } - if (typeof configuration.connection === "undefined") { - throw new Error("configuration.connections is required"); - } - const connection = configuration.connection; - if (typeof configuration.methodResponseTimeout !== "number") { - configuration.methodResponseTimeout = 30 * 1000; - } - if (typeof configuration.waitTimeoutMs !== "number") { - configuration.waitTimeoutMs = 30 * 1000; - } - this.unwrappedInstance = new InstanceWrapper(this, undefined, connection); - this.instance = this.unwrappedInstance.unwrap(); - this.clientRepository = new ClientRepository(configuration.logger.subLogger("cRep"), this); - this.serverRepository = new ServerRepository(); - let protocolPromise; - if (connection.protocolVersion === 3) { - protocolPromise = gW3ProtocolFactory(this.instance, connection, this.clientRepository, this.serverRepository, configuration, this); - } - else { - throw new Error(`protocol ${connection.protocolVersion} not supported`); - } - this.readyPromise = protocolPromise.then((protocol) => { - this.protocol = protocol; - this.client = new Client(this.protocol, this.clientRepository, this.instance, configuration); - this.server = new Server(this.protocol, this.serverRepository); - return this; - }); - } - ready() { - return this.readyPromise; - } - serverRemoved(callback) { - return this.client.serverRemoved(callback); - } - serverAdded(callback) { - return this.client.serverAdded(callback); - } - serverMethodRemoved(callback) { - return this.client.serverMethodRemoved(callback); - } - serverMethodAdded(callback) { - return this.client.serverMethodAdded(callback); - } - methodRemoved(callback) { - return this.client.methodRemoved(callback); - } - methodAdded(callback) { - return this.client.methodAdded(callback); - } - methodsForInstance(instance) { - return this.client.methodsForInstance(instance); - } - methods(methodFilter) { - return this.client.methods(methodFilter); - } - servers(methodFilter) { - return this.client.servers(methodFilter); - } - subscribe(method, options, successCallback, errorCallback) { - return this.client.subscribe(method, options, successCallback, errorCallback); - } - createStream(streamDef, callbacks, successCallback, errorCallback) { - return this.server.createStream(streamDef, callbacks, successCallback, errorCallback); - } - unregister(methodFilter) { - return this.server.unregister(methodFilter); - } - registerAsync(methodDefinition, callback) { - return this.server.registerAsync(methodDefinition, callback); - } - register(methodDefinition, callback) { - return this.server.register(methodDefinition, callback); - } - invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - return this.client.invoke(methodFilter, argumentObj, target, additionalOptions, success, error); - } - waitForMethod(name) { - const pw = new PromiseWrapper(); - const unsubscribe = this.client.methodAdded((m) => { - if (m.name === name) { - unsubscribe(); - pw.resolve(m); - } - }); - return pw.promise; - } - } - - const successMessages = ["subscribed", "success"]; - class MessageBus { - connection; - logger; - peerId; - session; - subscriptions; - readyPromise; - constructor(connection, logger) { - this.connection = connection; - this.logger = logger; - this.peerId = connection.peerId; - this.subscriptions = []; - this.session = connection.domain("bus", successMessages); - this.readyPromise = this.session.join(); - this.readyPromise.then(() => { - this.watchOnEvent(); - }); - } - ready() { - return this.readyPromise; - } - publish = (topic, data, options) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "publish", - topic, - data, - peer_id: this.peerId, - routing_key: routingKey, - target_identity: target - }); - this.session.send(args) - .catch((err) => { - this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`); - }); - }; - subscribe = (topic, callback, options) => { - return new Promise((resolve, reject) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "subscribe", - topic, - peer_id: this.peerId, - routing_key: routingKey, - source: target - }); - this.session.send(args) - .then((response) => { - const { subscription_id } = response; - this.subscriptions.push({ subscription_id, topic, callback, source: target }); - resolve({ - unsubscribe: () => { - this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId }) - .then(() => { - this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id); - }).catch((err) => { - this.logger.warn(`Failed to send unsubscribe request for ${subscription_id}: ${JSON.stringify(err)}`); - }); - return Promise.resolve(); - } - }); - }) - .catch((error) => reject(error)); - }); - }; - watchOnEvent = () => { - this.session.on("event", (args) => { - const { data, subscription_id } = args; - const source = args["publisher-identity"]; - const subscription = this.subscriptions.find((s) => s.subscription_id === subscription_id); - if (subscription) { - if (!subscription.source) { - subscription.callback(data, subscription.topic, source); - } - else { - if (this.keysMatch(subscription.source, source)) { - subscription.callback(data, subscription.topic, source); - } - } - } - }); - }; - removeEmptyValues(obj) { - const cleaned = {}; - Object.keys(obj).forEach((key) => { - if (obj[key] !== undefined && obj[key] !== null) { - cleaned[key] = obj[key]; - } - }); - return cleaned; - } - keysMatch(obj1, obj2) { - const keysObj1 = Object.keys(obj1); - let allMatch = true; - keysObj1.forEach((key) => { - if (obj1[key] !== obj2[key]) { - allMatch = false; - } - }); - return allMatch; - } - } - - const IOConnectCoreFactory = (userConfig, ext) => { - const iodesktop = typeof window === "object" ? (window.iodesktop ?? window.glue42gd) : undefined; - const preloadPromise = typeof window === "object" ? (window.gdPreloadPromise ?? Promise.resolve()) : Promise.resolve(); - const glueInitTimer = timer("glue"); - userConfig = userConfig || {}; - ext = ext || {}; - const internalConfig = prepareConfig(userConfig, ext, iodesktop); - let _connection; - let _interop; - let _logger; - let _metrics; - let _contexts; - let _bus; - let _allowTrace; - const libs = {}; - function registerLib(name, inner, t) { - _allowTrace = _logger.canPublish("trace"); - if (_allowTrace) { - _logger.trace(`registering ${name} module`); - } - const done = (e) => { - inner.initTime = t.stop(); - inner.initEndTime = t.endTime; - inner.marks = t.marks; - if (!_allowTrace) { - return; - } - const traceMessage = e ? - `${name} failed - ${e.message}` : - `${name} is ready - ${t.endTime - t.startTime}`; - _logger.trace(traceMessage); - }; - inner.initStartTime = t.startTime; - if (inner.ready) { - inner.ready() - .then(() => { - done(); - }) - .catch((e) => { - const error = typeof e === "string" ? new Error(e) : e; - done(error); - }); - } - else { - done(); - } - if (!Array.isArray(name)) { - name = [name]; - } - name.forEach((n) => { - libs[n] = inner; - IOConnectCoreFactory[n] = inner; - }); - } - function setupConnection() { - const initTimer = timer("connection"); - _connection = new Connection(internalConfig.connection, _logger.subLogger("connection")); - let authPromise = Promise.resolve(internalConfig.auth); - if (internalConfig.connection && !internalConfig.auth) { - if (iodesktop) { - authPromise = iodesktop.getGWToken() - .then((token) => { - return { - gatewayToken: token - }; - }); - } - else if (typeof window !== "undefined" && window?.glue42electron) { - if (typeof window.glue42electron.gwToken === "string") { - authPromise = Promise.resolve({ - gatewayToken: window.glue42electron.gwToken - }); - } - } - else { - authPromise = Promise.reject("You need to provide auth information"); - } - } - return authPromise - .then((authConfig) => { - initTimer.mark("auth-promise-resolved"); - let authRequest; - if (Object.prototype.toString.call(authConfig) === "[object Object]") { - authRequest = authConfig; - } - else { - throw new Error("Invalid auth object - " + JSON.stringify(authConfig)); - } - return _connection.login(authRequest); - }) - .then(() => { - registerLib("connection", _connection, initTimer); - return internalConfig; - }) - .catch((e) => { - if (_connection) { - _connection.logout(); - } - throw e; - }); - } - function setupLogger() { - const initTimer = timer("logger"); - _logger = new Logger(`${internalConfig.connection.identity?.application}`, undefined, internalConfig.customLogger); - _logger.consoleLevel(internalConfig.logger.console); - _logger.publishLevel(internalConfig.logger.publish); - if (_logger.canPublish("debug")) { - _logger.debug("initializing glue..."); - } - registerLib("logger", _logger, initTimer); - return Promise.resolve(undefined); - } - function setupMetrics() { - const initTimer = timer("metrics"); - const config = internalConfig.metrics; - const metricsPublishingEnabledFunc = iodesktop?.getMetricsPublishingEnabled; - const identity = internalConfig.connection.identity; - const canUpdateMetric = metricsPublishingEnabledFunc ? metricsPublishingEnabledFunc : () => true; - const disableAutoAppSystem = (typeof config !== "boolean" && config.disableAutoAppSystem) ?? false; - _metrics = metrics({ - connection: config ? _connection : undefined, - logger: _logger.subLogger("metrics"), - canUpdateMetric, - system: "Glue42", - service: identity?.service ?? iodesktop?.applicationName ?? internalConfig.application, - instance: identity?.instance ?? identity?.windowId ?? nanoid(10), - disableAutoAppSystem, - pagePerformanceMetrics: typeof config !== "boolean" ? config?.pagePerformanceMetrics : undefined - }); - registerLib("metrics", _metrics, initTimer); - return Promise.resolve(); - } - function setupInterop() { - const initTimer = timer("interop"); - const agmConfig = { - connection: _connection, - logger: _logger.subLogger("interop"), - }; - _interop = new Interop(agmConfig); - Logger.Interop = _interop; - registerLib(["interop", "agm"], _interop, initTimer); - return Promise.resolve(); - } - function setupContexts() { - const hasActivities = (internalConfig.activities && _connection.protocolVersion === 3); - const needsContexts = internalConfig.contexts || hasActivities; - if (needsContexts) { - const initTimer = timer("contexts"); - _contexts = new ContextsModule({ - connection: _connection, - logger: _logger.subLogger("contexts"), - trackAllContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.trackAllContexts : false, - reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false, - subscribeOnGet: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnGet : true, - subscribeOnUpdate: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnUpdate : true, - onlyReAnnounceSubscribedContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.onlyReAnnounceSubscribedContexts : true - }); - registerLib("contexts", _contexts, initTimer); - } - else { - const replayer = _connection.replayer; - if (replayer) { - replayer.drain(ContextMessageReplaySpec.name); - } - } - return Promise.resolve(); - } - async function setupBus() { - if (!internalConfig.bus) { - return Promise.resolve(); - } - const initTimer = timer("bus"); - _bus = new MessageBus(_connection, _logger.subLogger("bus")); - registerLib("bus", _bus, initTimer); - return Promise.resolve(); - } - function setupExternalLibs(externalLibs) { - try { - externalLibs.forEach((lib) => { - setupExternalLib(lib.name, lib.create); - }); - return Promise.resolve(); - } - catch (e) { - return Promise.reject(e); - } - } - function setupExternalLib(name, createCallback) { - const initTimer = timer(name); - const lib = createCallback(libs); - if (lib) { - registerLib(name, lib, initTimer); - } - } - function waitForLibs() { - const libsReadyPromises = Object.keys(libs).map((key) => { - const lib = libs[key]; - return lib.ready ? - lib.ready() : Promise.resolve(); - }); - return Promise.all(libsReadyPromises); - } - function constructGlueObject() { - const feedbackFunc = (feedbackInfo) => { - if (!_interop) { - return; - } - _interop.invoke("T42.ACS.Feedback", feedbackInfo, "best"); - }; - const info = { - coreVersion: version, - version: internalConfig.version - }; - glueInitTimer.stop(); - const glue = { - feedback: feedbackFunc, - info, - logger: _logger, - interop: _interop, - agm: _interop, - connection: _connection, - metrics: _metrics, - contexts: _contexts, - bus: _bus, - version: internalConfig.version, - userConfig, - done: () => { - _logger?.info("done called by user..."); - return _connection.logout(); - } - }; - glue.performance = { - get glueVer() { - return internalConfig.version; - }, - get glueConfig() { - return JSON.stringify(userConfig); - }, - get browser() { - return window.performance.timing.toJSON(); - }, - get memory() { - return window.performance.memory; - }, - get initTimes() { - const all = getAllTimers(); - return Object.keys(all).map((key) => { - const t = all[key]; - return { - name: key, - duration: t.endTime - t.startTime, - marks: t.marks, - startTime: t.startTime, - endTime: t.endTime - }; - }); - } - }; - Object.keys(libs).forEach((key) => { - const lib = libs[key]; - glue[key] = lib; - }); - glue.config = {}; - Object.keys(internalConfig).forEach((k) => { - glue.config[k] = internalConfig[k]; - }); - if (ext && ext.extOptions) { - Object.keys(ext.extOptions).forEach((k) => { - glue.config[k] = ext?.extOptions[k]; - }); - } - if (ext?.enrichGlue) { - ext.enrichGlue(glue); - } - if (iodesktop && iodesktop.updatePerfData) { - iodesktop.updatePerfData(glue.performance); - } - if (glue.agm) { - const deprecatedDecorator = (fn, wrong, proper) => { - return function () { - glue.logger.warn(`glue.js - 'glue.agm.${wrong}' method is deprecated, use 'glue.interop.${proper}' instead.`); - return fn.apply(glue.agm, arguments); - }; - }; - const agmAny = glue.agm; - agmAny.method_added = deprecatedDecorator(glue.agm.methodAdded, "method_added", "methodAdded"); - agmAny.method_removed = deprecatedDecorator(glue.agm.methodRemoved, "method_removed", "methodRemoved"); - agmAny.server_added = deprecatedDecorator(glue.agm.serverAdded, "server_added", "serverAdded"); - agmAny.server_method_aded = deprecatedDecorator(glue.agm.serverMethodAdded, "server_method_aded", "serverMethodAdded"); - agmAny.server_method_removed = deprecatedDecorator(glue.agm.serverMethodRemoved, "server_method_removed", "serverMethodRemoved"); - } - return glue; - } - async function registerInstanceIfNeeded() { - const RegisterInstanceMethodName = "T42.ACS.RegisterInstance"; - if (Utils.isNode() && typeof process.env._GD_STARTING_CONTEXT_ === "undefined" && typeof userConfig?.application !== "undefined") { - const isMethodAvailable = _interop.methods({ name: RegisterInstanceMethodName }).length > 0; - if (isMethodAvailable) { - try { - await _interop.invoke(RegisterInstanceMethodName, { appName: userConfig?.application, pid: process.pid }); - } - catch (error) { - const typedError = error; - _logger.error(`Cannot register as an instance: ${JSON.stringify(typedError.message)}`); - } - } - } - } - return preloadPromise - .then(setupLogger) - .then(setupConnection) - .then(() => Promise.all([setupMetrics(), setupInterop(), setupContexts(), setupBus()])) - .then(() => _interop.readyPromise) - .then(() => registerInstanceIfNeeded()) - .then(() => { - return setupExternalLibs(internalConfig.libs || []); - }) - .then(waitForLibs) - .then(constructGlueObject) - .catch((err) => { - return Promise.reject({ - err, - libs - }); - }); - }; - if (typeof window !== "undefined") { - window.IOConnectCore = IOConnectCoreFactory; - } - IOConnectCoreFactory.version = version; - IOConnectCoreFactory.default = IOConnectCoreFactory; - - const iOConnectBrowserFactory = createFactoryFunction(IOConnectCoreFactory); - if (typeof window !== "undefined") { - const windowAny = window; - windowAny.IOBrowser = iOConnectBrowserFactory; - delete windowAny.GlueCore; - delete windowAny.IOConnectCore; - } - const legacyGlobal = window.glue42gd || window.glue42core; - const ioGlobal = window.iodesktop || window.iobrowser; - if (!legacyGlobal && !ioGlobal) { - window.iobrowser = { webStarted: false }; - } - if (!window.iodesktop && !window.iobrowser.system) { - window.iobrowser.system = setupGlobalSystem(); - } - iOConnectBrowserFactory.version = version$1; - - return iOConnectBrowserFactory; - -})); -//# sourceMappingURL=browser.umd.js.map diff --git a/javascript/start/portfolio-downloader/package-lock.json b/javascript/start/portfolio-downloader/package-lock.json new file mode 100644 index 0000000..bfbc981 --- /dev/null +++ b/javascript/start/portfolio-downloader/package-lock.json @@ -0,0 +1,1279 @@ +{ + "name": "portfolio-downloader", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "portfolio-downloader", + "version": "1.0.0", + "dependencies": { + "@interopio/browser": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@interopio/browser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser/-/browser-4.2.4.tgz", + "integrity": "sha512-BPgkwH6N8HyGf7st99ZJwQ7arijz9j1bGu7pUAXBrtbv6cu4zH5GR7JKPGANZmFl0uefNPQyAQ4hc7C/i1i++A==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0", + "@interopio/search-api": "^3.2.1", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.2" + } + }, + "node_modules/@interopio/core": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@interopio/core/-/core-6.8.1.tgz", + "integrity": "sha512-WFWIV8JilNuAcxXaB+81IjL9j82sU73ABMUUEOWpvWoyqxhPlneOS+rSYViFX5gdk5pLH3fM6T/MmRGn3UFLwQ==", + "license": "MIT", + "dependencies": { + "callback-registry": "^2.7.2", + "ws": "^8.18.0" + } + }, + "node_modules/@interopio/desktop": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/@interopio/desktop/-/desktop-6.18.0.tgz", + "integrity": "sha512-YqRHRiCymbY2fOCT2HHJnLY4780JSRI1fUtaWEoIa5Z3djZk/3xRgVxIjOVw9Y/TAFGCwyIeW142a7HYnSGD5Q==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/schemas": "^10.1.0", + "@interopio/utils": "^1.4.2", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.1" + } + }, + "node_modules/@interopio/schemas": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@interopio/schemas/-/schemas-10.1.0.tgz", + "integrity": "sha512-8uDEoOAZenTr4a3O8vLq6JyS/LutkT/gh9EjuOrS9fOmHEUfJaS2u+qPo5em9/8MtjKgblZEJStSsW1gr34CtQ==", + "license": "ISC", + "dependencies": { + "ajv": "^6.12.6", + "ajv-keywords": "^3.4.1" + }, + "peerDependencies": { + "log4js": "^6.4.2" + }, + "peerDependenciesMeta": { + "log4js": { + "optional": true + } + } + }, + "node_modules/@interopio/search-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@interopio/search-api/-/search-api-3.2.1.tgz", + "integrity": "sha512-raUZzqBQoidm/6Mvgao2wFWlTDu9D4jghiX1dqor1LdsIfUpelJkkuFGeDl0z/3DWneaxDF8Vc/uoBtLz7qJLw==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1" + } + }, + "node_modules/@interopio/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@interopio/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-14Bb2WI9Cwf9zjhTurP4qP9AVY4cxR1AOrwrOtHrTGAeeHp88mALFWfMEv1QnRhlQ06To2vQcRgebNrPlHDZ8Q==", + "license": "ISC", + "dependencies": { + "decoder-validate": "^0.0.2" + } + }, + "node_modules/@interopio/workspaces-api": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@interopio/workspaces-api/-/workspaces-api-4.2.3.tgz", + "integrity": "sha512-5wrR1yhETKuX4txVrmS5q3G+8KI6GW4yOxsrVdf5qErO2HxN938XUdiAHIesarwlQoncrgnVx7uTn6IeOWUoXg==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/callback-registry": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/callback-registry/-/callback-registry-2.7.2.tgz", + "integrity": "sha512-VVrtF21DaH0VHeNMkLDd4VGuxsYM3V3l3lwYneKVMU/6X3TRtcQszUwlAcqj2HrLcbP1NyS12LsanUwCykaz/Q==", + "license": "ISC" + }, + "node_modules/decoder-validate": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/decoder-validate/-/decoder-validate-0.0.2.tgz", + "integrity": "sha512-9BsqAH9Zq6CvlxKHkSrZrH2iYlhuhHcrh6uTnDvcsa9P5YEweEzt1ci+X/9STgSCE7b9BA7/QIiwhfUDDWmjxw==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/javascript/start/portfolio-downloader/package.json b/javascript/start/portfolio-downloader/package.json new file mode 100644 index 0000000..28168ef --- /dev/null +++ b/javascript/start/portfolio-downloader/package.json @@ -0,0 +1,13 @@ +{ + "name": "portfolio-downloader", + "version": "1.0.0", + "scripts": { + "start": "vite --port 9400" + }, + "dependencies": { + "@interopio/browser": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } +} diff --git a/javascript/start/stocks/index.html b/javascript/start/stocks/index.html index 9dd9c0e..26175c5 100644 --- a/javascript/start/stocks/index.html +++ b/javascript/start/stocks/index.html @@ -13,10 +13,7 @@ - - - - + diff --git a/javascript/start/stocks/index.js b/javascript/start/stocks/index.js index c076e0f..0495cc4 100644 --- a/javascript/start/stocks/index.js +++ b/javascript/start/stocks/index.js @@ -1,3 +1,8 @@ +// TODO: Chapter 2 +// import IOBrowser from '@interopio/browser'; +// TODO: Chapter 9.3 +// import IOWorkspaces from '@interopio/workspaces-api'; + let clientPortfolioStocks; let clientName; diff --git a/javascript/start/stocks/lib/browser.umd.js b/javascript/start/stocks/lib/browser.umd.js deleted file mode 100644 index a5e6fcb..0000000 --- a/javascript/start/stocks/lib/browser.umd.js +++ /dev/null @@ -1,17399 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.browser = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs$1 (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) - }; - - function isNonNullObject(value) { - return !!value && typeof value === 'object' - } - - function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); - - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) - } - - // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 - var canUseSymbol = typeof Symbol === 'function' && Symbol.for; - var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; - - function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE - } - - function emptyTarget(val) { - return Array.isArray(val) ? [] : {} - } - - function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value - } - - function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) - } - - function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge - } - - function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return Object.propertyIsEnumerable.call(target, symbol) - }) - : [] - } - - function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) - } - - function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } - } - - // Protects from prototype poisoning and unexpected merging up the prototype chain. - function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. - } - - function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } - - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination - } - - function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; - - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } - } - - deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } - - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) - }; - - var deepmerge_1 = deepmerge; - - var cjs = deepmerge_1; - - var deepmerge$1 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$2 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$2 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$2 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$2 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$2 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$2 = function (f, r) { - return r.ok === true ? ok$2(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$2(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$2 = function (f, r) { - return r.ok === true ? r : err$2(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$2 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$2 = function() { - __assign$2 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$2.apply(this, arguments); - }; - - function __rest$2(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$2(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$2(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$2(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$2 = function (json) { return Array.isArray(json); }; - var isJsonObject$2 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$2(json); - }; - var typeString$2 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$2 = function (expected, got) { - return "expected " + expected + ", got " + typeString$2(got); - }; - var printPath$2 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$2 = function (newAt, _a) { - var at = _a.at, rest = __rest$2(_a, ["at"]); - return (__assign$2({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$2 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$2(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$2(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$2(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$2(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$2(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$2(json) - : err$2({ message: expectedGot$2('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$2(json) - : err$2({ message: expectedGot$2('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$2(json) - : err$2({ message: expectedGot$2('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$2(json, value) - ? ok$2(value) - : err$2({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$2(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$2({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else if (isJsonObject$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$2(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$2(function (err$$1) { return prependAt$2("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$2([])); - } - else if (isJsonArray$2(json)) { - return ok$2(json); - } - else { - return err$2({ message: expectedGot$2('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$2(json)) { - if (json.length !== decoders.length) { - return err$2({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$2(prependAt$2("[" + i + "]", nth.error)); - } - } - return ok$2(result); - } - else { - return err$2({ message: expectedGot$2("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$2(Object.assign, acc, decoder.decode(json)); }, ok$2({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$2(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$2(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$2(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$2(prependAt$2("." + key, r.error)); - } - } - } - return ok$2(obj); - } - else { - return err$2({ message: expectedGot$2('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$2(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$2({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$2(withDefault$2(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$2(jsonAtPath)) { - return err$2({ - at: printPath$2(paths.slice(0, i + 1)), - message: expectedGot$2('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$2(function (error) { - return jsonAtPath === undefined - ? { at: printPath$2(paths), message: 'path does not exist' } - : prependAt$2(printPath$2(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$2(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$2({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$2 = Decoder$2.string; - /** See `Decoder.number` */ - var number$2 = Decoder$2.number; - /** See `Decoder.boolean` */ - var boolean$2 = Decoder$2.boolean; - /** See `Decoder.anyJson` */ - var anyJson$2 = Decoder$2.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$2.unknownJson; - /** See `Decoder.constant` */ - var constant$2 = Decoder$2.constant; - /** See `Decoder.object` */ - var object$2 = Decoder$2.object; - /** See `Decoder.array` */ - var array$2 = Decoder$2.array; - /** See `Decoder.tuple` */ - Decoder$2.tuple; - /** See `Decoder.dict` */ - Decoder$2.dict; - /** See `Decoder.optional` */ - var optional$2 = Decoder$2.optional; - /** See `Decoder.oneOf` */ - var oneOf$1 = Decoder$2.oneOf; - /** See `Decoder.union` */ - var union$1 = Decoder$2.union; - /** See `Decoder.intersection` */ - var intersection = Decoder$2.intersection; - /** See `Decoder.withDefault` */ - Decoder$2.withDefault; - /** See `Decoder.valueAt` */ - Decoder$2.valueAt; - /** See `Decoder.succeed` */ - Decoder$2.succeed; - /** See `Decoder.fail` */ - Decoder$2.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder$2.lazy; - - const defaultConfig = { - gateway: { webPlatform: {} }, - libraries: [], - exposeAPI: true, - }; - const defaultWidgetConfig = { - awaitFactory: true, - enable: false, - timeout: 5 * 1000, - restoreLastKnownPosition: true, - }; - const defaultModalsConfig = { - alerts: { - enabled: false - }, - dialogs: { - enabled: false - }, - awaitFactory: true, - timeout: 5 * 1000, - }; - const defaultIntentResolverConfig = { - enable: false, - timeout: 5 * 1000, - awaitFactory: true, - }; - - const Glue42CoreMessageTypes = { - platformUnload: { name: "platformUnload" }, - transportSwitchRequest: { name: "transportSwitchRequest" }, - transportSwitchResponse: { name: "transportSwitchResponse" }, - getCurrentTransport: { name: "getCurrentTransport" }, - getCurrentTransportResponse: { name: "getCurrentTransportResponse" }, - checkPreferredLogic: { name: "checkPreferredLogic" }, - checkPreferredConnection: { name: "checkPreferredConnection" }, - checkPreferredLogicResponse: { name: "checkPreferredLogicResponse" }, - checkPreferredConnectionResponse: { name: "checkPreferredConnectionResponse" } - }; - const webPlatformTransportName = "web-platform"; - const latestFDC3Type = "latest_fdc3_type"; - const errorChannel = new MessageChannel(); - const REQUEST_WIDGET_READY = "requestWidgetFactoryReady"; - const REQUEST_MODALS_UI_FACTORY_READY = "requestModalsUIFactoryReady"; - const MAX_SET_TIMEOUT_DELAY = 2147483647; - const REQUEST_INTENT_RESOLVER_UI_FACTORY_READY = "requestIntentResolverUIFactoryReady"; - const READONLY_PROPERTY_DESCRIPTOR = { - configurable: false, - enumerable: true, - writable: false, - }; - - const extractErrorMsg = (error) => { - if (typeof error === "string") { - return error; - } - if (error?.message) { - return typeof error.message === "string" ? error.message : JSON.stringify(error.message); - } - return JSON.stringify(error); - }; - const runDecoderWithIOError = (decoder, json) => { - try { - const result = decoder.runWithException(json); - return result; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const getSupportedOperationsNames = (operations) => { - return Object.keys(operations).filter((operation) => (operations)[operation].execute); - }; - const handleOperationCheck = (supportedOperations, operationName) => { - const isSupported = supportedOperations.some((operation) => operation.toLowerCase() === operationName.toLowerCase()); - return { isSupported }; - }; - const getSafeTimeoutDelay = (delay) => { - return Math.min(delay, MAX_SET_TIMEOUT_DELAY); - }; - const wrapPromise = () => { - let wrapperResolve; - let wrapperReject; - const promise = new Promise((resolve, reject) => { - wrapperResolve = resolve; - wrapperReject = reject; - }); - return { promise, resolve: wrapperResolve, reject: wrapperReject }; - }; - - class IOError { - raiseError(error, shouldThrowOriginalError) { - const errorMessage = extractErrorMsg(error); - errorChannel.port1.postMessage(errorMessage); - if (shouldThrowOriginalError) { - throw error; - } - throw new Error(errorMessage); - } - } - const ioError = new IOError(); - - const connectBrowserAppProps = ["name", "title", "version", "customProperties", "icon", "caption", "type"]; - const fdc3v2AppProps = ["appId", "name", "type", "details", "version", "title", "tooltip", "lang", "description", "categories", "icons", "screenshots", "contactEmail", "moreInfo", "publisher", "customConfig", "hostManifests", "interop", "localizedVersions"]; - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok$1 = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err$1 = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise$1 = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault$1 = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException$1 = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map$1 = function (f, r) { - return r.ok === true ? ok$1(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2$1 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok$1(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError$1 = function (f, r) { - return r.ok === true ? r : err$1(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen$1 = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign$1 = function() { - __assign$1 = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); - }; - - function __rest$1(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual$1(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual$1(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual$1(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray$1 = function (json) { return Array.isArray(json); }; - var isJsonObject$1 = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray$1(json); - }; - var typeString$1 = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot$1 = function (expected, got) { - return "expected " + expected + ", got " + typeString$1(got); - }; - var printPath$1 = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt$1 = function (newAt, _a) { - var at = _a.at, rest = __rest$1(_a, ["at"]); - return (__assign$1({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder$1 = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError$1(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise$1(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException$1(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map$1(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen$1(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok$1(json) - : err$1({ message: expectedGot$1('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok$1(json) - : err$1({ message: expectedGot$1('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok$1(json) - : err$1({ message: expectedGot$1('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual$1(json, value) - ? ok$1(value) - : err$1({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject$1(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err$1({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else if (isJsonObject$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray$1(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError$1(function (err$$1) { return prependAt$1("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2$1(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok$1([])); - } - else if (isJsonArray$1(json)) { - return ok$1(json); - } - else { - return err$1({ message: expectedGot$1('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray$1(json)) { - if (json.length !== decoders.length) { - return err$1({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err$1(prependAt$1("[" + i + "]", nth.error)); - } - } - return ok$1(result); - } - else { - return err$1({ message: expectedGot$1("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2$1(Object.assign, acc, decoder.decode(json)); }, ok$1({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok$1(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok$1(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject$1(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err$1(prependAt$1("." + key, r.error)); - } - } - } - return ok$1(obj); - } - else { - return err$1({ message: expectedGot$1('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok$1(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err$1({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok$1(withDefault$1(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray$1(jsonAtPath)) { - return err$1({ - at: printPath$1(paths.slice(0, i + 1)), - message: expectedGot$1('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError$1(function (error) { - return jsonAtPath === undefined - ? { at: printPath$1(paths), message: 'path does not exist' } - : prependAt$1(printPath$1(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok$1(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err$1({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string$1 = Decoder$1.string; - /** See `Decoder.number` */ - var number$1 = Decoder$1.number; - /** See `Decoder.boolean` */ - var boolean$1 = Decoder$1.boolean; - /** See `Decoder.anyJson` */ - var anyJson$1 = Decoder$1.anyJson; - /** See `Decoder.unknownJson` */ - Decoder$1.unknownJson; - /** See `Decoder.constant` */ - var constant$1 = Decoder$1.constant; - /** See `Decoder.object` */ - var object$1 = Decoder$1.object; - /** See `Decoder.array` */ - var array$1 = Decoder$1.array; - /** See `Decoder.tuple` */ - Decoder$1.tuple; - /** See `Decoder.dict` */ - var dict = Decoder$1.dict; - /** See `Decoder.optional` */ - var optional$1 = Decoder$1.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder$1.oneOf; - /** See `Decoder.union` */ - Decoder$1.union; - /** See `Decoder.intersection` */ - Decoder$1.intersection; - /** See `Decoder.withDefault` */ - Decoder$1.withDefault; - /** See `Decoder.valueAt` */ - Decoder$1.valueAt; - /** See `Decoder.succeed` */ - Decoder$1.succeed; - /** See `Decoder.fail` */ - Decoder$1.fail; - /** See `Decoder.lazy` */ - Decoder$1.lazy; - - const nonEmptyStringDecoder$3 = string$1().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$3 = number$1().where((num) => num >= 0, "Expected a non-negative number"); - const regexDecoder = anyJson$1().andThen((value) => { - return value instanceof RegExp ? anyJson$1() : fail(`expected a regex, got a ${typeof value}`); - }); - - const intentDefinitionDecoder$1 = object$1({ - name: nonEmptyStringDecoder$3, - displayName: optional$1(string$1()), - contexts: optional$1(array$1(string$1())), - customConfig: optional$1(object$1()) - }); - const v2TypeDecoder = oneOf(constant$1("web"), constant$1("native"), constant$1("citrix"), constant$1("onlineNative"), constant$1("other")); - const v2DetailsDecoder = object$1({ - url: nonEmptyStringDecoder$3 - }); - const v2IconDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3) - }); - const v2ScreenshotDecoder = object$1({ - src: nonEmptyStringDecoder$3, - size: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3), - label: optional$1(nonEmptyStringDecoder$3) - }); - const v2ListensForIntentDecoder = object$1({ - contexts: array$1(nonEmptyStringDecoder$3), - displayName: optional$1(nonEmptyStringDecoder$3), - resultType: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(anyJson$1()) - }); - const v2IntentsDecoder = object$1({ - listensFor: optional$1(dict(v2ListensForIntentDecoder)), - raises: optional$1(dict(array$1(nonEmptyStringDecoder$3))) - }); - const v2UserChannelDecoder = object$1({ - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2AppChannelDecoder = object$1({ - name: nonEmptyStringDecoder$3, - description: optional$1(nonEmptyStringDecoder$3), - broadcasts: optional$1(array$1(nonEmptyStringDecoder$3)), - listensFor: optional$1(array$1(nonEmptyStringDecoder$3)) - }); - const v2InteropDecoder = object$1({ - intents: optional$1(v2IntentsDecoder), - userChannels: optional$1(v2UserChannelDecoder), - appChannels: optional$1(array$1(v2AppChannelDecoder)) - }); - const glue42ApplicationDetailsDecoder = object$1({ - url: optional$1(nonEmptyStringDecoder$3), - top: optional$1(number$1()), - left: optional$1(number$1()), - width: optional$1(nonNegativeNumberDecoder$3), - height: optional$1(nonNegativeNumberDecoder$3) - }); - const glue42HostManifestsBrowserDecoder = object$1({ - name: optional$1(nonEmptyStringDecoder$3), - type: optional$1(nonEmptyStringDecoder$3.where((s) => s === "window", "Expected a value of window")), - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - customProperties: optional$1(anyJson$1()), - icon: optional$1(string$1()), - caption: optional$1(string$1()), - details: optional$1(glue42ApplicationDetailsDecoder), - intents: optional$1(array$1(intentDefinitionDecoder$1)), - hidden: optional$1(boolean$1()) - }); - const v1DefinitionDecoder = object$1({ - name: nonEmptyStringDecoder$3, - appId: nonEmptyStringDecoder$3, - title: optional$1(nonEmptyStringDecoder$3), - version: optional$1(nonEmptyStringDecoder$3), - manifest: nonEmptyStringDecoder$3, - manifestType: nonEmptyStringDecoder$3, - tooltip: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - images: optional$1(array$1(object$1({ url: optional$1(nonEmptyStringDecoder$3) }))), - icons: optional$1(array$1(object$1({ icon: optional$1(nonEmptyStringDecoder$3) }))), - customConfig: anyJson$1(), - intents: optional$1(array$1(intentDefinitionDecoder$1)) - }); - const v2LocalizedDefinitionDecoder = object$1({ - appId: optional$1(nonEmptyStringDecoder$3), - name: optional$1(nonEmptyStringDecoder$3), - details: optional$1(v2DetailsDecoder), - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder) - }); - const v2DefinitionDecoder = object$1({ - appId: nonEmptyStringDecoder$3, - name: optional$1(nonEmptyStringDecoder$3), - type: v2TypeDecoder, - details: v2DetailsDecoder, - version: optional$1(nonEmptyStringDecoder$3), - title: optional$1(nonEmptyStringDecoder$3), - tooltip: optional$1(nonEmptyStringDecoder$3), - lang: optional$1(nonEmptyStringDecoder$3), - description: optional$1(nonEmptyStringDecoder$3), - categories: optional$1(array$1(nonEmptyStringDecoder$3)), - icons: optional$1(array$1(v2IconDecoder)), - screenshots: optional$1(array$1(v2ScreenshotDecoder)), - contactEmail: optional$1(nonEmptyStringDecoder$3), - supportEmail: optional$1(nonEmptyStringDecoder$3), - moreInfo: optional$1(nonEmptyStringDecoder$3), - publisher: optional$1(nonEmptyStringDecoder$3), - customConfig: optional$1(array$1(anyJson$1())), - hostManifests: optional$1(anyJson$1()), - interop: optional$1(v2InteropDecoder), - localizedVersions: optional$1(dict(v2LocalizedDefinitionDecoder)) - }); - const allDefinitionsDecoder = oneOf(v1DefinitionDecoder, v2DefinitionDecoder); - - const parseDecoderErrorToStringMessage = (error) => { - return `${error.kind} at ${error.at}: ${JSON.stringify(error.input)}. Reason - ${error.message}`; - }; - - class FDC3Service { - fdc3ToDesktopDefinitionType = { - web: "window", - native: "exe", - citrix: "citrix", - onlineNative: "clickonce", - other: "window" - }; - toApi() { - return { - isFdc3Definition: this.isFdc3Definition.bind(this), - parseToBrowserBaseAppData: this.parseToBrowserBaseAppData.bind(this), - parseToDesktopAppConfig: this.parseToDesktopAppConfig.bind(this) - }; - } - isFdc3Definition(definition) { - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - return { isFdc3: false, reason: parseDecoderErrorToStringMessage(decodeRes.error) }; - } - if (definition.appId && definition.details) { - return { isFdc3: true, version: "2.0" }; - } - if (definition.manifest) { - return { isFdc3: true, version: "1.2" }; - } - return { isFdc3: false, reason: "The passed definition is not FDC3" }; - } - parseToBrowserBaseAppData(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - const userProperties = this.getUserPropertiesFromDefinition(definition, version); - const createOptions = { url: this.getUrl(definition, version) }; - const baseApplicationData = { - name: definition.appId, - type: "window", - createOptions, - userProperties: { - ...userProperties, - intents: version === "1.2" - ? userProperties.intents - : this.getIntentsFromV2AppDefinition(definition), - details: createOptions - }, - title: definition.title, - version: definition.version, - icon: this.getIconFromDefinition(definition, version), - caption: definition.description, - fdc3: version === "2.0" ? { ...definition, definitionVersion: "2.0" } : undefined, - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return baseApplicationData; - } - const ioDefinitionDecodeRes = glue42HostManifestsBrowserDecoder.run(ioConnectDefinition); - if (!ioDefinitionDecodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(ioDefinitionDecodeRes.error)}`); - } - if (!Object.keys(ioDefinitionDecodeRes.result).length) { - return baseApplicationData; - } - return this.mergeBaseAppDataWithGlueManifest(baseApplicationData, ioDefinitionDecodeRes.result); - } - parseToDesktopAppConfig(definition) { - const { isFdc3, version } = this.isFdc3Definition(definition); - if (!isFdc3) { - throw new Error("The passed definition is not FDC3"); - } - const decodeRes = allDefinitionsDecoder.run(definition); - if (!decodeRes.ok) { - throw new Error(`Invalid FDC3 ${version} definition. Error: ${parseDecoderErrorToStringMessage(decodeRes.error)}`); - } - if (version === "1.2") { - const fdc3v1Definition = definition; - return { - name: fdc3v1Definition.appId, - type: "window", - details: { - url: this.getUrl(definition, version) - }, - version: fdc3v1Definition.version, - title: fdc3v1Definition.title, - tooltip: fdc3v1Definition.tooltip, - caption: fdc3v1Definition.description, - icon: fdc3v1Definition.icons?.[0].icon, - intents: fdc3v1Definition.intents, - customProperties: { - manifestType: fdc3v1Definition.manifestType, - images: fdc3v1Definition.images, - contactEmail: fdc3v1Definition.contactEmail, - supportEmail: fdc3v1Definition.supportEmail, - publisher: fdc3v1Definition.publisher, - icons: fdc3v1Definition.icons, - customConfig: fdc3v1Definition.customConfig - } - }; - } - const fdc3v2Definition = definition; - const desktopDefinition = { - name: fdc3v2Definition.appId, - type: this.fdc3ToDesktopDefinitionType[fdc3v2Definition.type], - details: fdc3v2Definition.details, - version: fdc3v2Definition.version, - title: fdc3v2Definition.title, - tooltip: fdc3v2Definition.tooltip, - caption: fdc3v2Definition.description, - icon: this.getIconFromDefinition(fdc3v2Definition, "2.0"), - intents: this.getIntentsFromV2AppDefinition(fdc3v2Definition), - fdc3: { ...fdc3v2Definition, definitionVersion: "2.0" } - }; - const ioConnectDefinition = definition.hostManifests?.ioConnect || definition.hostManifests?.["Glue42"]; - if (!ioConnectDefinition) { - return desktopDefinition; - } - if (typeof ioConnectDefinition !== "object" || Array.isArray(ioConnectDefinition)) { - throw new Error(`Invalid '${definition.hostManifests.ioConnect ? "hostManifests.ioConnect" : "hostManifests['Glue42']"}' key`); - } - return this.mergeDesktopConfigWithGlueManifest(desktopDefinition, ioConnectDefinition); - } - getUserPropertiesFromDefinition(definition, version) { - if (version === "1.2") { - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key))); - } - return Object.fromEntries(Object.entries(definition).filter(([key]) => !connectBrowserAppProps.includes(key) && !fdc3v2AppProps.includes(key))); - } - getUrl(definition, version) { - let url; - if (version === "1.2") { - const parsedManifest = JSON.parse(definition.manifest); - url = parsedManifest.details?.url || parsedManifest.url; - } - else { - url = definition.details?.url; - } - if (!url || typeof url !== "string") { - throw new Error(`Invalid FDC3 ${version} definition. Provide valid 'url' under '${version === "1.2" ? "manifest" : "details"}' key`); - } - return url; - } - getIntentsFromV2AppDefinition(definition) { - const fdc3Intents = definition.interop?.intents?.listensFor; - if (!fdc3Intents) { - return; - } - const intents = Object.entries(fdc3Intents).map((fdc3Intent) => { - const [intentName, intentData] = fdc3Intent; - return { - name: intentName, - ...intentData - }; - }); - return intents; - } - getIconFromDefinition(definition, version) { - if (version === "1.2") { - return definition.icons?.find((iconDef) => iconDef.icon)?.icon || undefined; - } - return definition.icons?.find((iconDef) => iconDef.src)?.src || undefined; - } - mergeBaseAppDataWithGlueManifest(baseAppData, hostManifestDefinition) { - let baseApplicationDefinition = baseAppData; - if (hostManifestDefinition.customProperties) { - baseApplicationDefinition.userProperties = { ...baseAppData.userProperties, ...hostManifestDefinition.customProperties }; - } - if (hostManifestDefinition.details) { - const details = { ...baseAppData.createOptions, ...hostManifestDefinition.details }; - baseApplicationDefinition.createOptions = details; - baseApplicationDefinition.userProperties.details = details; - } - if (Array.isArray(hostManifestDefinition.intents)) { - baseApplicationDefinition.userProperties.intents = (baseApplicationDefinition.userProperties.intents || []).concat(hostManifestDefinition.intents); - } - baseApplicationDefinition = { ...baseApplicationDefinition, ...hostManifestDefinition }; - delete baseApplicationDefinition.details; - delete baseApplicationDefinition.intents; - return baseApplicationDefinition; - } - mergeDesktopConfigWithGlueManifest(config, desktopDefinition) { - const appConfig = Object.assign({}, config, desktopDefinition, { details: { ...config.details, ...desktopDefinition.details } }); - if (Array.isArray(desktopDefinition.intents)) { - appConfig.intents = (config.intents || []).concat(desktopDefinition.intents); - } - return appConfig; - } - } - - const decoders$1 = { - common: { - nonEmptyStringDecoder: nonEmptyStringDecoder$3, - nonNegativeNumberDecoder: nonNegativeNumberDecoder$3, - regexDecoder - }, - fdc3: { - allDefinitionsDecoder, - v1DefinitionDecoder, - v2DefinitionDecoder - } - }; - - var INTENTS_ERRORS; - (function (INTENTS_ERRORS) { - INTENTS_ERRORS["USER_CANCELLED"] = "User Closed Intents Resolver UI without choosing a handler"; - INTENTS_ERRORS["CALLER_NOT_DEFINED"] = "Caller Id is not defined"; - INTENTS_ERRORS["TIMEOUT_HIT"] = "Timeout hit"; - INTENTS_ERRORS["INTENT_NOT_FOUND"] = "Cannot find Intent"; - INTENTS_ERRORS["HANDLER_NOT_FOUND"] = "Cannot find Intent Handler"; - INTENTS_ERRORS["TARGET_INSTANCE_UNAVAILABLE"] = "Cannot start Target Instance"; - INTENTS_ERRORS["INTENT_DELIVERY_FAILED"] = "Target Instance did not add a listener"; - INTENTS_ERRORS["RESOLVER_UNAVAILABLE"] = "Intents Resolver UI unavailable"; - INTENTS_ERRORS["RESOLVER_TIMEOUT"] = "User did not choose a handler"; - INTENTS_ERRORS["INVALID_RESOLVER_RESPONSE"] = "Intents Resolver UI returned invalid response"; - INTENTS_ERRORS["INTENT_HANDLER_REJECTION"] = "Intent Handler function processing the raised intent threw an error or rejected the promise it returned"; - })(INTENTS_ERRORS || (INTENTS_ERRORS = {})); - - let IoC$1 = class IoC { - _fdc3; - _decoders = decoders$1; - _errors = { - intents: INTENTS_ERRORS - }; - get fdc3() { - if (!this._fdc3) { - this._fdc3 = new FDC3Service().toApi(); - } - return this._fdc3; - } - get decoders() { - return this._decoders; - } - get errors() { - return this._errors; - } - }; - - const ioc = new IoC$1(); - ioc.fdc3; - const decoders = ioc.decoders; - ioc.errors; - - const nonEmptyStringDecoder$2 = string$2().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder$2 = number$2().where((num) => num >= 0, "Expected a non-negative number"); - const optionalNonEmptyStringDecoder = optional$2(nonEmptyStringDecoder$2); - const libDomainDecoder = oneOf$1(constant$2("system"), constant$2("windows"), constant$2("appManager"), constant$2("layouts"), constant$2("intents"), constant$2("notifications"), constant$2("channels"), constant$2("extension"), constant$2("themes"), constant$2("prefs"), constant$2("ui")); - const windowOperationTypesDecoder = oneOf$1(constant$2("openWindow"), constant$2("windowHello"), constant$2("windowAdded"), constant$2("windowRemoved"), constant$2("getBounds"), constant$2("getFrameBounds"), constant$2("getUrl"), constant$2("moveResize"), constant$2("focus"), constant$2("close"), constant$2("getTitle"), constant$2("setTitle"), constant$2("focusChange"), constant$2("getChannel"), constant$2("notifyChannelsChanged"), constant$2("setZoomFactor"), constant$2("zoomFactorChange"), constant$2("refresh"), constant$2("operationCheck")); - const appManagerOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("appDirectoryStateChange"), constant$2("instanceStarted"), constant$2("instanceStopped"), constant$2("applicationStart"), constant$2("instanceStop"), constant$2("clear"), constant$2("operationCheck")); - const layoutsOperationTypesDecoder = oneOf$1(constant$2("layoutAdded"), constant$2("layoutChanged"), constant$2("layoutRemoved"), constant$2("layoutRenamed"), constant$2("get"), constant$2("getAll"), constant$2("export"), constant$2("import"), constant$2("remove"), constant$2("rename"), constant$2("clientSaveRequest"), constant$2("getGlobalPermissionState"), constant$2("checkGlobalActivated"), constant$2("requestGlobalPermission"), constant$2("getDefaultGlobal"), constant$2("setDefaultGlobal"), constant$2("clearDefaultGlobal"), constant$2("updateMetadata"), constant$2("operationCheck"), constant$2("getCurrent"), constant$2("defaultLayoutChanged"), constant$2("layoutRestored")); - const notificationsOperationTypesDecoder = oneOf$1(constant$2("raiseNotification"), constant$2("requestPermission"), constant$2("notificationShow"), constant$2("notificationClick"), constant$2("getPermission"), constant$2("list"), constant$2("notificationRaised"), constant$2("notificationClosed"), constant$2("click"), constant$2("clear"), constant$2("clearAll"), constant$2("configure"), constant$2("getConfiguration"), constant$2("configurationChanged"), constant$2("setState"), constant$2("clearOld"), constant$2("activeCountChange"), constant$2("stateChange"), constant$2("operationCheck"), constant$2("getActiveCount")); - const systemOperationTypesDecoder = oneOf$1(constant$2("getEnvironment"), constant$2("getBase"), constant$2("platformShutdown"), constant$2("isFdc3DataWrappingSupported"), constant$2("clientError"), constant$2("systemHello"), constant$2("operationCheck")); - const windowRelativeDirectionDecoder = oneOf$1(constant$2("top"), constant$2("left"), constant$2("right"), constant$2("bottom")); - const windowBoundsDecoder = object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }); - const windowOpenSettingsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - context: optional$2(anyJson$2()), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - windowId: optional$2(nonEmptyStringDecoder$2), - layoutComponentId: optional$2(nonEmptyStringDecoder$2) - })); - const openWindowConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2, - options: windowOpenSettingsDecoder - }); - const windowHelloDecoder = object$2({ - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const coreWindowDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleWindowDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const helloSuccessDecoder = object$2({ - windows: array$2(coreWindowDataDecoder), - isWorkspaceFrame: boolean$2() - }); - const windowTitleConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - title: string$2() - }); - const focusEventDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - hasFocus: boolean$2() - }); - const windowMoveResizeConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relative: optional$2(boolean$2()) - }); - const windowBoundsResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const frameWindowBoundsResultDecoder = object$2({ - bounds: object$2({ - top: number$2(), - left: number$2(), - width: nonNegativeNumberDecoder$2, - height: nonNegativeNumberDecoder$2 - }) - }); - const windowUrlResultDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - url: nonEmptyStringDecoder$2 - }); - const windowZoomFactorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - factorIndex: nonNegativeNumberDecoder$2 - }); - const anyDecoder = anyJson$2(); - const boundsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2) - }); - const instanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - applicationName: nonEmptyStringDecoder$2 - }); - const iframePermissionsPolicyConfigDecoder = object$2({ - flags: string$2() - }); - const workspacesSandboxDecoder = object$2({ - flags: string$2() - }); - const requestChannelSelectorConfigDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelsNames: array$2(nonEmptyStringDecoder$2) - }); - const channelSelectorDecoder$1 = object$2({ - enabled: boolean$2(), - }); - const applicationDetailsDecoder = object$2({ - url: nonEmptyStringDecoder$2, - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - workspacesSandbox: optional$2(workspacesSandboxDecoder), - channelSelector: optional$2(channelSelectorDecoder$1), - iframePermissionsPolicy: optional$2(iframePermissionsPolicyConfigDecoder) - }); - const intentDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - displayName: optional$2(string$2()), - contexts: optional$2(array$2(string$2())), - customConfig: optional$2(object$2()), - resultType: optional$2(string$2()) - }); - const applicationDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - customProperties: optional$2(anyJson$2()), - icon: optional$2(string$2()), - caption: optional$2(string$2()), - details: applicationDetailsDecoder, - intents: optional$2(array$2(intentDefinitionDecoder)), - hidden: optional$2(boolean$2()), - fdc3: optional$2(decoders.fdc3.v2DefinitionDecoder) - }); - const appRemoveConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const appsExportOperationDecoder = object$2({ - definitions: array$2(applicationDefinitionDecoder) - }); - const applicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - instances: array$2(instanceDataDecoder), - userProperties: optional$2(anyJson$2()), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const baseApplicationDataDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: nonEmptyStringDecoder$2.where((s) => s === "window", "Expected a value of window"), - userProperties: anyJson$2(), - title: optional$2(nonEmptyStringDecoder$2), - version: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(string$2()), - caption: optional$2(nonEmptyStringDecoder$2) - }); - const appDirectoryStateChangeDecoder = object$2({ - appsAdded: array$2(baseApplicationDataDecoder), - appsChanged: array$2(baseApplicationDataDecoder), - appsRemoved: array$2(baseApplicationDataDecoder) - }); - const appHelloSuccessDecoder = object$2({ - apps: array$2(applicationDataDecoder), - initialChannelId: optional$2(nonEmptyStringDecoder$2) - }); - const basicInstanceDataDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const layoutTypeDecoder = oneOf$1(constant$2("Global"), constant$2("Activity"), constant$2("ApplicationDefault"), constant$2("Swimlane"), constant$2("Workspace")); - const componentTypeDecoder = oneOf$1(constant$2("application"), constant$2("activity")); - const windowComponentStateDecoder = object$2({ - context: optional$2(anyJson$2()), - bounds: windowBoundsDecoder, - createArgs: object$2({ - name: optional$2(nonEmptyStringDecoder$2), - url: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - instanceId: nonEmptyStringDecoder$2, - isCollapsed: optional$2(boolean$2()), - isSticky: optional$2(boolean$2()), - restoreSettings: object$2({ - groupId: optional$2(nonEmptyStringDecoder$2), - groupZOrder: optional$2(number$2()) - }), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const windowLayoutComponentDecoder = object$2({ - type: constant$2("window"), - componentType: optional$2(componentTypeDecoder), - application: nonEmptyStringDecoder$2, - state: windowComponentStateDecoder - }); - const windowLayoutItemDecoder = object$2({ - type: constant$2("window"), - config: object$2({ - appName: nonEmptyStringDecoder$2, - url: optional$2(nonEmptyStringDecoder$2), - title: optional$2(string$2()), - allowExtract: optional$2(boolean$2()), - allowReorder: optional$2(boolean$2()), - showCloseButton: optional$2(boolean$2()), - isMaximized: optional$2(boolean$2()) - }) - }); - const groupLayoutItemDecoder = object$2({ - type: constant$2("group"), - config: anyJson$2(), - children: array$2(oneOf$1(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object$2({ - type: constant$2("column"), - config: anyJson$2(), - children: array$2(oneOf$1(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object$2({ - type: constant$2("row"), - config: anyJson$2(), - children: array$2(oneOf$1(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutComponentStateDecoder = object$2({ - config: anyJson$2(), - context: anyJson$2(), - children: array$2(oneOf$1(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }); - const workspaceLayoutComponentDecoder = object$2({ - type: constant$2("Workspace"), - application: optional$2(nonEmptyStringDecoder$2), - state: workspaceLayoutComponentStateDecoder - }); - const workspaceFrameComponentStateDecoder = object$2({ - bounds: windowBoundsDecoder, - instanceId: nonEmptyStringDecoder$2, - selectedWorkspace: nonNegativeNumberDecoder$2, - workspaces: array$2(workspaceLayoutComponentStateDecoder), - windowState: optional$2(nonEmptyStringDecoder$2), - restoreState: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()) - }); - const workspaceFrameComponentDecoder = object$2({ - type: constant$2("workspaceFrame"), - application: nonEmptyStringDecoder$2, - componentType: optional$2(componentTypeDecoder), - state: workspaceFrameComponentStateDecoder - }); - const glueLayoutDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()) - }); - const renamedLayoutNotificationDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - token: optional$2(nonEmptyStringDecoder$2), - components: array$2(oneOf$1(windowLayoutComponentDecoder, workspaceLayoutComponentDecoder, workspaceFrameComponentDecoder)), - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - version: optional$2(number$2()), - prevName: nonEmptyStringDecoder$2 - }); - const newLayoutOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()), - instances: optional$2(array$2(nonEmptyStringDecoder$2)), - ignoreInstances: optional$2(array$2(nonEmptyStringDecoder$2)), - setAsCurrent: optional$2(boolean$2()), - ignoreContexts: optional$2(boolean$2()) - }); - const restoreOptionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()), - closeRunningInstance: optional$2(boolean$2()), - closeMe: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2) - }); - const layoutSummaryDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder, - context: optional$2(anyJson$2()), - metadata: optional$2(anyJson$2()) - }); - const simpleLayoutConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - type: layoutTypeDecoder - }); - const saveLayoutConfigDecoder = object$2({ - layout: newLayoutOptionsDecoder - }); - const renameLayoutConfigDecoder = object$2({ - layout: glueLayoutDecoder, - newName: nonEmptyStringDecoder$2 - }); - const layoutResultDecoder = object$2({ - status: nonEmptyStringDecoder$2 - }); - const updateLayoutMetadataConfigDecoder = object$2({ - layout: glueLayoutDecoder, - }); - const restoreLayoutConfigDecoder = object$2({ - layout: restoreOptionsDecoder - }); - const getAllLayoutsConfigDecoder = object$2({ - type: layoutTypeDecoder - }); - const allLayoutsFullConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder) - }); - const defaultGlobalChangedDecoder = optional$2(object$2({ - name: nonEmptyStringDecoder$2 - })); - const importModeDecoder = oneOf$1(constant$2("replace"), constant$2("merge")); - const layoutsImportConfigDecoder = object$2({ - layouts: array$2(glueLayoutDecoder), - mode: importModeDecoder, - skipManagerRequest: optional$2(boolean$2()) - }); - const allLayoutsSummariesResultDecoder = object$2({ - summaries: array$2(layoutSummaryDecoder) - }); - const simpleLayoutResultDecoder = object$2({ - layout: glueLayoutDecoder - }); - const optionalSimpleLayoutResult = object$2({ - layout: optional$2(glueLayoutDecoder) - }); - const setDefaultGlobalConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const intentsOperationTypesDecoder = oneOf$1(constant$2("findIntent"), constant$2("getIntents"), constant$2("getIntentsByHandler"), constant$2("raise"), constant$2("filterHandlers")); - const intentHandlerDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2, - applicationTitle: optional$2(string$2()), - applicationDescription: optional$2(string$2()), - applicationIcon: optional$2(string$2()), - type: oneOf$1(constant$2("app"), constant$2("instance")), - displayName: optional$2(string$2()), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - instanceId: optional$2(string$2()), - instanceTitle: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - object$2({ - applicationName: string$2(), - applicationIcon: optional$2(string$2()), - instanceId: optional$2(string$2()), - }); - object$2({ - intent: nonEmptyStringDecoder$2, - handler: intentHandlerDecoder - }); - const intentDecoder = object$2({ - name: nonEmptyStringDecoder$2, - handlers: array$2(intentHandlerDecoder) - }); - const intentTargetDecoder = oneOf$1(constant$2("startNew"), constant$2("reuse"), object$2({ - app: optional$2(nonEmptyStringDecoder$2), - instance: optional$2(nonEmptyStringDecoder$2) - })); - const intentContextDecoder = object$2({ - type: optional$2(nonEmptyStringDecoder$2), - data: optional$2(anyJson$2()) - }); - const intentsDecoder = array$2(intentDecoder); - const wrappedIntentsDecoder = object$2({ - intents: intentsDecoder - }); - const intentFilterDecoder = object$2({ - name: optional$2(nonEmptyStringDecoder$2), - contextType: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const findFilterDecoder = oneOf$1(nonEmptyStringDecoder$2, intentFilterDecoder); - const wrappedIntentFilterDecoder = object$2({ - filter: optional$2(intentFilterDecoder) - }); - const applicationStartOptionsDecoder = object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - }); - const intentRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - target: optional$2(intentTargetDecoder), - context: optional$2(intentContextDecoder), - options: optional$2(applicationStartOptionsDecoder), - handlers: optional$2(array$2(intentHandlerDecoder)), - timeout: optional$2(nonNegativeNumberDecoder$2), - waitUserResponseIndefinitely: optional$2(boolean$2()), - clearSavedHandler: optional$2(boolean$2()) - }); - const originAppDecoder = object$2({ - interopInstance: nonEmptyStringDecoder$2, - name: optional$2(nonEmptyStringDecoder$2) - }); - const startReasonDecoder = object$2({ - originApp: originAppDecoder, - intentRequest: optional$2(intentRequestDecoder) - }); - const applicationStartConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2, - waitForAGMReady: boolean$2(), - id: optional$2(nonEmptyStringDecoder$2), - context: optional$2(anyJson$2()), - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - forceChromeTab: optional$2(boolean$2()), - layoutComponentId: optional$2(nonEmptyStringDecoder$2), - channelId: optional$2(nonEmptyStringDecoder$2), - startReason: startReasonDecoder - }); - const raiseRequestDecoder = oneOf$1(nonEmptyStringDecoder$2, intentRequestDecoder); - const resolverConfigDecoder = object$2({ - enabled: boolean$2(), - appName: nonEmptyStringDecoder$2, - waitResponseTimeout: number$2() - }); - const handlerExclusionCriteriaApplicationNameDecoder = object$2({ - applicationName: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaInstanceIdDecoder = object$2({ - instanceId: nonEmptyStringDecoder$2 - }); - const handlerExclusionCriteriaDecoder = oneOf$1(handlerExclusionCriteriaApplicationNameDecoder, handlerExclusionCriteriaInstanceIdDecoder); - const handlerFilterDecoder = object$2({ - title: optional$2(nonEmptyStringDecoder$2), - openResolver: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$2), - intent: optional$2(nonEmptyStringDecoder$2), - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - resultType: optional$2(nonEmptyStringDecoder$2), - applicationNames: optional$2(array$2(nonEmptyStringDecoder$2)), - excludeList: optional$2(array$2(handlerExclusionCriteriaDecoder)) - }); - const embeddedResolverConfigDecoder = object$2({ - enabled: boolean$2(), - initialCaller: object$2({ instanceId: nonEmptyStringDecoder$2 }), - }); - const raiseIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const intentResultDecoder = object$2({ - request: intentRequestDecoder, - handler: intentHandlerDecoder, - result: anyJson$2() - }); - const filterHandlersResultDecoder = object$2({ - handlers: array$2(intentHandlerDecoder) - }); - const filterHandlersWithResolverConfigDecoder = object$2({ - filterHandlersRequest: handlerFilterDecoder, - resolverConfig: resolverConfigDecoder, - embeddedResolverConfig: optional$2(embeddedResolverConfigDecoder) - }); - const AddIntentListenerRequestDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - displayName: optional$2(string$2()), - icon: optional$2(string$2()), - description: optional$2(string$2()), - resultType: optional$2(string$2()), - customConfig: optional$2(object$2()) - }); - const AddIntentListenerDecoder = oneOf$1(nonEmptyStringDecoder$2, AddIntentListenerRequestDecoder); - const intentInfoDecoder = object$2({ - intent: nonEmptyStringDecoder$2, - contextTypes: optional$2(array$2(nonEmptyStringDecoder$2)), - description: optional$2(nonEmptyStringDecoder$2), - displayName: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - resultType: optional$2(nonEmptyStringDecoder$2) - }); - const getIntentsResultDecoder = object$2({ - intents: array$2(intentInfoDecoder) - }); - const channelNameDecoder = (channelNames) => { - return nonEmptyStringDecoder$2.where(s => channelNames.includes(s), "Expected a valid channel name"); - }; - const fdc3OptionsDecoder = object$2({ - contextType: optional$2(nonEmptyStringDecoder$2) - }); - const publishOptionsDecoder = optional$2(oneOf$1(nonEmptyStringDecoder$2, object$2({ - name: optional$2(nonEmptyStringDecoder$2), - fdc3: optional$2(boolean$2()) - }))); - const leaveChannelsConfig = object$2({ - windowId: optionalNonEmptyStringDecoder, - channel: optionalNonEmptyStringDecoder - }); - const fdc3ContextDecoder = anyJson$2().where((value) => typeof value.type === "string", "Expected a valid FDC3 Context with compulsory 'type' field"); - const interopActionSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$2, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("all"), constant$2("best"))) - }); - const glue42NotificationActionDecoder = object$2({ - action: string$2(), - title: nonEmptyStringDecoder$2, - icon: optional$2(string$2()), - interop: optional$2(interopActionSettingsDecoder) - }); - const notificationStateDecoder = oneOf$1(constant$2("Active"), constant$2("Acknowledged"), constant$2("Seen"), constant$2("Closed"), constant$2("Stale"), constant$2("Snoozed"), constant$2("Processing")); - const activeNotificationsCountChangeDecoder = object$2({ - count: number$2() - }); - const notificationDefinitionDecoder = object$2({ - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())) - }); - const glue42NotificationOptionsDecoder = object$2({ - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const notificationSetStateRequestDecoder = object$2({ - id: nonEmptyStringDecoder$2, - state: notificationStateDecoder - }); - object$2().where((value) => value.fdc3 ? typeof value.fdc3.type === "string" : true, "Expected a valid FDC3 Context with compulsory 'type' field"); - const channelFDC3DisplayMetadataDecoder = object$2({ - color: optional$2(nonEmptyStringDecoder$2), - icon: optional$2(nonEmptyStringDecoder$2), - name: optional$2(nonEmptyStringDecoder$2), - glyph: optional$2(nonEmptyStringDecoder$2) - }); - const channelFdc3MetaDecoder = object$2({ - id: nonEmptyStringDecoder$2, - displayMetadata: optional$2(channelFDC3DisplayMetadataDecoder) - }); - const channelMetaDecoder = object$2({ - color: nonEmptyStringDecoder$2, - fdc3: optional$2(channelFdc3MetaDecoder) - }); - const channelDefinitionDecoder = object$2({ - name: nonEmptyStringDecoder$2, - meta: channelMetaDecoder, - data: optional$2(object$2()), - }); - const pathValueDecoder = object$2({ - path: nonEmptyStringDecoder$2, - value: anyJson$2() - }); - const pathsValueDecoder = array$2(pathValueDecoder); - const removeChannelDataDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const channelRestrictionsDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const channelRestrictionConfigWithWindowIdDecoder = object$2({ - name: nonEmptyStringDecoder$2, - read: boolean$2(), - write: boolean$2(), - windowId: nonEmptyStringDecoder$2 - }); - const restrictionConfigDataDecoder = object$2({ - config: channelRestrictionConfigWithWindowIdDecoder - }); - const restrictionsDecoder = object$2({ - channels: array$2(channelRestrictionsDecoder) - }); - const getRestrictionsDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const restrictionsConfigDecoder = object$2({ - read: boolean$2(), - write: boolean$2(), - windowId: optional$2(nonEmptyStringDecoder$2) - }); - const restrictAllDataDecoder = object$2({ - restrictions: restrictionsConfigDecoder - }); - const raiseNotificationDecoder = object$2({ - settings: glue42NotificationOptionsDecoder, - id: nonEmptyStringDecoder$2 - }); - const raiseNotificationResultDecoder = object$2({ - settings: glue42NotificationOptionsDecoder - }); - const permissionRequestResultDecoder = object$2({ - permissionGranted: boolean$2() - }); - const permissionQueryResultDecoder = object$2({ - permission: oneOf$1(constant$2("default"), constant$2("granted"), constant$2("denied")) - }); - const notificationEventPayloadDecoder = object$2({ - definition: notificationDefinitionDecoder, - action: optional$2(string$2()), - id: optional$2(nonEmptyStringDecoder$2) - }); - const notificationFilterDecoder = object$2({ - allowed: optional$2(array$2(nonEmptyStringDecoder$2)), - blocked: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const notificationsConfigurationDecoder = object$2({ - enable: optional$2(boolean$2()), - enableToasts: optional$2(boolean$2()), - sourceFilter: optional$2(notificationFilterDecoder), - showNotificationBadge: optional$2(boolean$2()) - }); - const notificationsConfigurationProtocolDecoder = object$2({ - configuration: notificationsConfigurationDecoder - }); - const strictNotificationsConfigurationProtocolDecoder = object$2({ - configuration: object$2({ - enable: boolean$2(), - enableToasts: boolean$2(), - sourceFilter: object$2({ - allowed: array$2(nonEmptyStringDecoder$2), - blocked: array$2(nonEmptyStringDecoder$2) - }) - }) - }); - const platformSaveRequestConfigDecoder = object$2({ - layoutType: oneOf$1(constant$2("Global"), constant$2("Workspace")), - layoutName: nonEmptyStringDecoder$2, - context: optional$2(anyJson$2()) - }); - const saveRequestClientResponseDecoder = object$2({ - windowContext: optional$2(anyJson$2()), - }); - const permissionStateResultDecoder = object$2({ - state: oneOf$1(constant$2("prompt"), constant$2("denied"), constant$2("granted")) - }); - const simpleAvailabilityResultDecoder = object$2({ - isAvailable: boolean$2() - }); - const simpleItemIdDecoder = object$2({ - itemId: nonEmptyStringDecoder$2 - }); - const operationCheckResultDecoder = object$2({ - isSupported: boolean$2() - }); - const operationCheckConfigDecoder = object$2({ - operation: nonEmptyStringDecoder$2 - }); - const workspaceFrameBoundsResultDecoder = object$2({ - bounds: windowBoundsDecoder - }); - const themeDecoder = object$2({ - displayName: nonEmptyStringDecoder$2, - name: nonEmptyStringDecoder$2 - }); - const simpleThemeResponseDecoder = object$2({ - theme: themeDecoder - }); - const allThemesResponseDecoder = object$2({ - themes: array$2(themeDecoder) - }); - const selectThemeConfigDecoder = object$2({ - name: nonEmptyStringDecoder$2 - }); - const notificationsDataDecoder = object$2({ - id: nonEmptyStringDecoder$2, - title: nonEmptyStringDecoder$2, - clickInterop: optional$2(interopActionSettingsDecoder), - actions: optional$2(array$2(glue42NotificationActionDecoder)), - focusPlatformOnDefaultClick: optional$2(boolean$2()), - badge: optional$2(string$2()), - body: optional$2(string$2()), - data: optional$2(anyJson$2()), - dir: optional$2(oneOf$1(constant$2("auto"), constant$2("ltr"), constant$2("rtl"))), - icon: optional$2(string$2()), - image: optional$2(string$2()), - lang: optional$2(string$2()), - renotify: optional$2(boolean$2()), - requireInteraction: optional$2(boolean$2()), - silent: optional$2(boolean$2()), - tag: optional$2(string$2()), - timestamp: optional$2(nonNegativeNumberDecoder$2), - vibrate: optional$2(array$2(number$2())), - severity: optional$2(oneOf$1(constant$2("Low"), constant$2("None"), constant$2("Medium"), constant$2("High"), constant$2("Critical"))), - showToast: optional$2(boolean$2()), - showInPanel: optional$2(boolean$2()), - state: optional$2(notificationStateDecoder) - }); - const simpleNotificationDataDecoder = object$2({ - notification: notificationsDataDecoder - }); - const allNotificationsDataDecoder = object$2({ - notifications: array$2(notificationsDataDecoder) - }); - const simpleNotificationSelectDecoder = object$2({ - id: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2 - }); - const getWindowIdsOnChannelResultDecoder = object$2({ - windowIds: array$2(nonEmptyStringDecoder$2) - }); - const channelsOperationTypesDecoder = oneOf$1(constant$2("appHello"), constant$2("addChannel"), constant$2("getMyChannel"), constant$2("getWindowIdsOnChannel"), constant$2("getWindowIdsWithChannels"), constant$2("joinChannel"), constant$2("restrict"), constant$2("getRestrictions"), constant$2("restrictAll"), constant$2("notifyChannelsChanged"), constant$2("leaveChannel"), constant$2("getMode"), constant$2("operationCheck")); - const modeDecoder = oneOf$1(constant$2("single"), constant$2("multi")); - const getChannelsModeDecoder = object$2({ - mode: modeDecoder - }); - const channelsAppHelloDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2 - }); - const channelsAppHelloSuccessDecoder = object$2({ - mode: modeDecoder, - channels: array$2(nonEmptyStringDecoder$2), - restrictions: array$2(channelRestrictionsDecoder) - }); - const getMyChanelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2) - }); - const windowWithChannelFilterDecoder = object$2({ - application: optional$2(nonEmptyStringDecoder$2), - channels: optional$2(array$2(nonEmptyStringDecoder$2)), - windowIds: optional$2(array$2(nonEmptyStringDecoder$2)) - }); - const wrappedWindowWithChannelFilterDecoder = object$2({ - filter: optional$2(windowWithChannelFilterDecoder) - }); - const getWindowIdsWithChannelsResultDecoder = object$2({ - windowIdsWithChannels: array$2(object$2({ - application: nonEmptyStringDecoder$2, - channel: optional$2(nonEmptyStringDecoder$2), - windowId: nonEmptyStringDecoder$2 - })) - }); - const startApplicationContextDecoder = optional$2(anyJson$2()); - const startApplicationOptionsDecoder = optional$2(object$2({ - top: optional$2(number$2()), - left: optional$2(number$2()), - width: optional$2(nonNegativeNumberDecoder$2), - height: optional$2(nonNegativeNumberDecoder$2), - relativeTo: optional$2(nonEmptyStringDecoder$2), - relativeDirection: optional$2(windowRelativeDirectionDecoder), - waitForAGMReady: optional$2(boolean$2()), - channelId: optional$2(nonEmptyStringDecoder$2), - reuseId: optional$2(nonEmptyStringDecoder$2), - originIntentRequest: optional$2(intentRequestDecoder) - })); - const joinChannelDataDecoder = object$2({ - channel: nonEmptyStringDecoder$2, - windowId: nonEmptyStringDecoder$2 - }); - const leaveChannelDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelName: optional$2(nonEmptyStringDecoder$2) - }); - const channelsChangedDataDecoder = object$2({ - windowId: nonEmptyStringDecoder$2, - channelNames: array$2(nonEmptyStringDecoder$2) - }); - const windowChannelResultDecoder = object$2({ - channel: optional$2(nonEmptyStringDecoder$2), - }); - const prefsOperationTypesDecoder = oneOf$1(constant$2("clear"), constant$2("clearAll"), constant$2("get"), constant$2("getAll"), constant$2("set"), constant$2("update"), constant$2("prefsChanged"), constant$2("prefsHello"), constant$2("operationCheck"), constant$2("registerSubscriber")); - const appPreferencesDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - lastUpdate: optional$2(nonEmptyStringDecoder$2), - }); - const basePrefsConfigDecoder = object$2({ - app: nonEmptyStringDecoder$2, - }); - const getPrefsResultDecoder = object$2({ - prefs: appPreferencesDecoder, - }); - const getAllPrefsResultDecoder = object$2({ - all: array$2(appPreferencesDecoder), - }); - const subscriberRegisterConfigDecoder = object$2({ - interopId: nonEmptyStringDecoder$2, - appName: optional$2(nonEmptyStringDecoder$2) - }); - const changePrefsDataDecoder = object$2({ - app: nonEmptyStringDecoder$2, - data: object$2(), - }); - const prefsHelloSuccessDecoder = object$2({ - platform: object$2({ - app: nonEmptyStringDecoder$2, - }), - validNonExistentApps: optional$2(array$2(nonEmptyStringDecoder$2)), - }); - const clientErrorDataDecoder = object$2({ - message: nonEmptyStringDecoder$2 - }); - const systemHelloSuccessDecoder = object$2({ - isClientErrorOperationSupported: boolean$2() - }); - - const nonEmptyStringDecoder$1 = decoders.common.nonEmptyStringDecoder; - const nonNegativeNumberDecoder$1 = decoders.common.nonNegativeNumberDecoder; - const widgetSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const modalsSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const intentResolverSourcesDecoder = object$2({ - bundle: nonEmptyStringDecoder$1, - styles: array$2(nonEmptyStringDecoder$1), - fonts: optional$2(array$2(nonEmptyStringDecoder$1)) - }); - const channelSelectorTypeDecoder = oneOf$1(constant$2("directional"), constant$2("default")); - const channelSelectorDecoder = object$2({ - type: optional$2(channelSelectorTypeDecoder), - enable: optional$2(boolean$2()) - }); - const positionDecoder = oneOf$1(constant$2("top-left"), constant$2("top-center"), constant$2("top-right"), constant$2("center-left"), constant$2("center-right"), constant$2("bottom-left"), constant$2("bottom-center"), constant$2("bottom-right")); - const displayModeDecoder = oneOf$1(constant$2("all"), constant$2("fdc3")); - const widgetChannelsDecoder = object$2({ - selector: optional$2(channelSelectorDecoder), - displayMode: optional$2(displayModeDecoder) - }); - const platformWidgetDefaultConfigDecoder = object$2({ - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const widgetConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - channels: optional$2(widgetChannelsDecoder), - position: optional$2(positionDecoder), - displayInWorkspace: optional$2(boolean$2()), - restoreLastKnownPosition: optional$2(boolean$2()), - }); - const modalsConfigDecoder = object$2({ - alerts: optional$2(object$2({ - enabled: boolean$2() - })), - dialogs: optional$2(object$2({ - enabled: boolean$2() - })), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1), - }); - const uiOperationTypesDecoder = oneOf$1(constant$2("getResources"), constant$2("operationCheck"), constant$2("showAlert"), constant$2("showDialog"), constant$2("alertInteropAction"), constant$2("showResolver")); - const getResourcesDataDecoder = object$2({ - origin: nonEmptyStringDecoder$1 - }); - const blockedResourcesDecoder = object$2({ - blockedOrigin: constant$2(true) - }); - const availableWidgetResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - config: platformWidgetDefaultConfigDecoder, - sources: widgetSourcesDecoder - }); - const widgetResourcesDecoder = union$1(blockedResourcesDecoder, availableWidgetResourcesDecoder); - const availableModalsResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: modalsSourcesDecoder - }); - const modalsResourcesDecoder = union$1(blockedResourcesDecoder, availableModalsResourcesDecoder); - const availableIntentResolverResourcesDecoder = object$2({ - blockedOrigin: constant$2(false), - sources: intentResolverSourcesDecoder - }); - const intentResolverResourcesDecoder = union$1(blockedResourcesDecoder, availableIntentResolverResourcesDecoder); - const resourcesDecoder = object$2({ - widget: optional$2(widgetResourcesDecoder), - modals: optional$2(modalsResourcesDecoder), - intentResolver: optional$2(intentResolverResourcesDecoder) - }); - const getResourcesResultDecoder = object$2({ - resources: resourcesDecoder, - }); - const alertsInteropSettingsDecoder = object$2({ - method: nonEmptyStringDecoder$1, - arguments: optional$2(anyJson$2()), - target: optional$2(oneOf$1(constant$2("best"), constant$2("all"), nonEmptyStringDecoder$1)) - }); - const modalRequestTargetDecoder = oneOf$1(constant$2("Global"), constant$2("WindowContainer"), nonEmptyStringDecoder$1); - const modalRequestMessageTargetDecoder = object$2({ - instance: nonEmptyStringDecoder$1, - container: optional$2(oneOf$1(constant$2("Global"), constant$2("WindowContainer"))) - }); - const alertRequestConfigDecoder = object$2({ - variant: oneOf$1(constant$2("default"), constant$2("success"), constant$2("critical"), constant$2("info"), constant$2("warning")), - text: nonEmptyStringDecoder$1, - showCloseButton: optional$2(boolean$2()), - clickInterop: optional$2(alertsInteropSettingsDecoder), - onCloseInterop: optional$2(alertsInteropSettingsDecoder), - actions: optional$2(array$2(object$2({ - id: nonEmptyStringDecoder$1, - title: nonEmptyStringDecoder$1, - clickInterop: alertsInteropSettingsDecoder - }))), - data: optional$2(anyJson$2()), - ttl: optional$2(nonNegativeNumberDecoder$1), - target: optional$2(modalRequestTargetDecoder) - }); - const uiAlertRequestMessageDecoder = object$2({ - config: alertRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const dialogRequestConfigDecoder = object$2({ - templateName: nonEmptyStringDecoder$1, - variables: anyJson$2(), - target: optional$2(modalRequestTargetDecoder), - timer: optional$2(object$2({ - duration: nonNegativeNumberDecoder$1 - })), - size: optional$2(object$2({ - width: nonNegativeNumberDecoder$1, - height: nonNegativeNumberDecoder$1 - })), - movable: optional$2(boolean$2()), - transparent: optional$2(boolean$2()) - }); - const dialogResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - isEnterPressed: optional$2(boolean$2()), - responseButtonClicked: optional$2(object$2({ - id: nonEmptyStringDecoder$1, - text: nonEmptyStringDecoder$1 - })), - inputs: optional$2(array$2(object$2({ - type: oneOf$1(constant$2("checkbox"), constant$2("email"), constant$2("number"), constant$2("password"), constant$2("text")), - id: nonEmptyStringDecoder$1, - checked: optional$2(boolean$2()), - value: optional$2(string$2()) - }))) - }); - object$2({ - result: dialogResponseDecoder - }); - const uiDialogRequestMessageDecoder = object$2({ - config: dialogRequestConfigDecoder, - target: modalRequestMessageTargetDecoder - }); - const openAlertResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const openDialogResultDecoder = object$2({ - id: nonEmptyStringDecoder$1, - responsePromise: anyJson$2() - }); - const dialogOnCompletionConfigDecoder = object$2({ - response: dialogResponseDecoder - }); - const alertInteropActionDecoder = object$2({ - name: nonEmptyStringDecoder$1, - settings: alertsInteropSettingsDecoder - }); - const alertOnClickConfigDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const alertInteropActionDataDecoder = object$2({ - interopAction: alertInteropActionDecoder - }); - const intentResolverConfigDecoder = object$2({ - enable: boolean$2(), - awaitFactory: optional$2(boolean$2()), - timeout: optional$2(nonNegativeNumberDecoder$1) - }); - const openResolverResultDecoder = object$2({ - id: nonEmptyStringDecoder$1 - }); - const userSettingsDecoder = object$2({ - preserveChoice: boolean$2() - }); - const userChoiceResponseDecoder = object$2({ - intent: nonEmptyStringDecoder$1, - handler: intentHandlerDecoder, - userSettings: userSettingsDecoder - }); - const intentResolverResponseDecoder = object$2({ - isExpired: optional$2(boolean$2()), - isClosed: optional$2(boolean$2()), - userChoice: optional$2(userChoiceResponseDecoder) - }); - const onUserResponseResponseDecoder = object$2({ - response: intentResolverResponseDecoder - }); - const openConfigWithIntentRequestDecoder = object$2({ - intentRequest: intentRequestDecoder - }); - const openConfigWithHandlerFilterDecoder = object$2({ - handlerFilter: handlerFilterDecoder - }); - const intentResolverOpenConfigDecoder = union$1(openConfigWithIntentRequestDecoder, openConfigWithHandlerFilterDecoder); - const uiResolverRequestMessageConfigDecoder = intersection(intentResolverOpenConfigDecoder, object$2({ timeout: nonNegativeNumberDecoder$1 })); - const uiResolverRequestMessageDecoder = object$2({ - config: uiResolverRequestMessageConfigDecoder - }); - const uiResolverResponseMessageDecoder = object$2({ - result: intentResolverResponseDecoder - }); - - const parseConfig = (config = {}) => { - const isPlatformInternal = !!config?.gateway?.webPlatform?.port; - const decodedWidgetConfigResult = optional$2(widgetConfigDecoder).run(config.widget); - if (!decodedWidgetConfigResult.ok) { - throw ioError.raiseError(`The provided widget config is invalid. Error: ${JSON.stringify(decodedWidgetConfigResult.error)}`); - } - const decodedModalsConfigResult = optional$2(modalsConfigDecoder).run(config.modals); - if (!decodedModalsConfigResult.ok) { - throw ioError.raiseError(`The provided modals config is invalid. Error: ${JSON.stringify(decodedModalsConfigResult.error)}`); - } - const decodedIntentResolverConfigResult = optional$2(intentResolverConfigDecoder).run(config.intentResolver); - if (!decodedIntentResolverConfigResult.ok) { - throw ioError.raiseError(`The provided 'intentResolver' config is invalid. Error: ${JSON.stringify(decodedIntentResolverConfigResult.error)}`); - } - const combined = { - ...defaultConfig, - ...config, - isPlatformInternal, - logger: config.systemLogger?.level ?? "info", - customLogger: config.systemLogger?.customLogger, - widget: deepmerge$1(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}), - modals: deepmerge$1(defaultModalsConfig, decodedModalsConfigResult.result ?? {}), - intentResolver: deepmerge$1(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}), - }; - return combined; - }; - - const checkSingleton = () => { - const ioConnectBrowserNamespace = window.glue42core || window.iobrowser; - if (ioConnectBrowserNamespace && ioConnectBrowserNamespace.webStarted) { - return ioError.raiseError("IoConnect Browser has already been started for this application."); - } - if (!ioConnectBrowserNamespace) { - window.iobrowser = { webStarted: true }; - return; - } - ioConnectBrowserNamespace.webStarted = true; - }; - - const enterprise = (config) => { - const enterpriseConfig = { - windows: true, - layouts: "full", - appManager: "full", - channels: true, - libraries: config?.libraries ?? [], - logger: config?.systemLogger?.level ?? "warn" - }; - const injectedFactory = window.IODesktop || window.Glue; - return injectedFactory(enterpriseConfig); - }; - - const operations$a = { - openWindow: { name: "openWindow", dataDecoder: openWindowConfigDecoder, resultDecoder: coreWindowDataDecoder }, - windowHello: { name: "windowHello", dataDecoder: windowHelloDecoder, resultDecoder: helloSuccessDecoder }, - windowAdded: { name: "windowAdded", dataDecoder: coreWindowDataDecoder }, - windowRemoved: { name: "windowRemoved", dataDecoder: simpleWindowDecoder }, - getBounds: { name: "getBounds", dataDecoder: simpleWindowDecoder, resultDecoder: windowBoundsResultDecoder }, - getFrameBounds: { name: "getFrameBounds", dataDecoder: simpleWindowDecoder, resultDecoder: frameWindowBoundsResultDecoder }, - getUrl: { name: "getUrl", dataDecoder: simpleWindowDecoder, resultDecoder: windowUrlResultDecoder }, - moveResize: { name: "moveResize", dataDecoder: windowMoveResizeConfigDecoder }, - focus: { name: "focus", dataDecoder: simpleWindowDecoder }, - close: { name: "close", dataDecoder: simpleWindowDecoder }, - getTitle: { name: "getTitle", dataDecoder: simpleWindowDecoder, resultDecoder: windowTitleConfigDecoder }, - setTitle: { name: "setTitle", dataDecoder: windowTitleConfigDecoder }, - focusChange: { name: "focusChange", dataDecoder: focusEventDataDecoder }, - getChannel: { name: "getChannel", dataDecoder: simpleWindowDecoder, resultDecoder: windowChannelResultDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - setZoomFactor: { name: "setZoomFactor", dataDecoder: windowZoomFactorConfigDecoder }, - zoomFactorChange: { name: "zoomFactorChange", dataDecoder: windowZoomFactorConfigDecoder }, - refresh: { name: "refresh", dataDecoder: simpleWindowDecoder }, - operationCheck: { name: "operationCheck" } - }; - - function createRegistry$1(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry$1.default = createRegistry$1; - var lib$1 = createRegistry$1; - - - var CallbackRegistryFactory$1 = /*@__PURE__*/getDefaultExportFromCjs$1(lib$1); - - const ZOOM_FACTORS = Object.freeze({ - 0: 24, - 1: 33, - 2: 50, - 3: 67, - 4: 75, - 5: 80, - 6: 90, - 7: 100, - 8: 110, - 9: 125, - 10: 150, - 11: 175, - 12: 200, - 13: 250, - 14: 300, - 15: 400, - 16: 500 - }); - - class WebWindowModel { - _id; - _name; - _bridge; - _logger; - registry = CallbackRegistryFactory$1(); - myCtxKey; - ctxUnsubscribe; - zoomFactorIndex = 7; - me; - constructor(_id, _name, _bridge, _logger) { - this._id = _id; - this._name = _name; - this._bridge = _bridge; - this._logger = _logger; - this.myCtxKey = `___window___${this.id}`; - } - get id() { - return this._id.slice(); - } - get name() { - return this._name.slice(); - } - get zoomFactor() { - return ZOOM_FACTORS[this.zoomFactorIndex]; - } - clean() { - if (this.ctxUnsubscribe) { - this.ctxUnsubscribe(); - } - } - processSelfFocusEvent(hasFocus) { - this.me.isFocused = hasFocus; - this.registry.execute("focus-change", this.me); - } - processChannelsChangedEvent(channelNames) { - this.registry.execute("channels-changed", channelNames); - } - processSelfZoomFactorChangedEvent(factorIndex) { - this.zoomFactorIndex = factorIndex; - this.registry.execute("zoom-factor-changed", this.me); - } - async toApi() { - this.ctxUnsubscribe = await this._bridge.contextLib.subscribe(this.myCtxKey, (data) => this.registry.execute("context-updated", data)); - this.me = { - id: this.id, - name: this.name, - isFocused: false, - zoomFactor: this.zoomFactor, - getURL: this.getURL.bind(this), - moveResize: this.moveResize.bind(this), - resizeTo: this.resizeTo.bind(this), - moveTo: this.moveTo.bind(this), - focus: this.focus.bind(this), - close: this.close.bind(this), - getTitle: this.getTitle.bind(this), - setTitle: this.setTitle.bind(this), - getBounds: this.getBounds.bind(this), - getContext: this.getContext.bind(this), - updateContext: this.updateContext.bind(this), - setContext: this.setContext.bind(this), - refresh: this.refresh.bind(this), - onContextUpdated: this.onContextUpdated.bind(this), - onFocusChanged: this.onFocusChanged.bind(this), - getChannel: this.getChannel.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - zoomIn: this.zoomIn.bind(this), - zoomOut: this.zoomOut.bind(this), - setZoomFactor: this.setZoomFactor.bind(this), - onZoomFactorChanged: this.onZoomFactorChanged.bind(this), - }; - Object.defineProperties(this.me, { - id: READONLY_PROPERTY_DESCRIPTOR, - name: READONLY_PROPERTY_DESCRIPTOR, - zoomFactor: { - get: () => { - return this.zoomFactor; - }, - enumerable: true, - }, - }); - return this.me; - } - async getURL() { - const result = await this._bridge.send("windows", operations$a.getUrl, { windowId: this.id }); - return result.url; - } - onFocusChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - return this.registry.add("focus-change", callback); - } - async moveResize(dimension) { - const targetBounds = runDecoderWithIOError(boundsDecoder, dimension); - const commandArgs = Object.assign({}, targetBounds, { windowId: this.id, relative: false }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async resizeTo(width, height) { - if (typeof width === "undefined" && typeof height === "undefined") { - return this.me; - } - if (typeof width !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, width); - } - if (typeof height !== "undefined") { - runDecoderWithIOError(nonNegativeNumberDecoder$2, height); - } - const commandArgs = Object.assign({}, { width, height }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async moveTo(top, left) { - if (typeof top === "undefined" && typeof left === "undefined") { - return this.me; - } - if (typeof top !== "undefined") { - runDecoderWithIOError(number$2(), top); - } - if (typeof left !== "undefined") { - runDecoderWithIOError(number$2(), left); - } - const commandArgs = Object.assign({}, { top, left }, { windowId: this.id, relative: true }); - await this._bridge.send("windows", operations$a.moveResize, commandArgs); - return this.me; - } - async focus() { - if (this.name === "Platform") { - window.open(undefined, this.id); - } - else { - await this._bridge.send("windows", operations$a.focus, { windowId: this.id }); - } - return this.me; - } - async close() { - await this._bridge.send("windows", operations$a.close, { windowId: this.id }); - return this.me; - } - async getTitle() { - const result = await this._bridge.send("windows", operations$a.getTitle, { windowId: this.id }); - return result.title; - } - async setTitle(title) { - const ttl = runDecoderWithIOError(nonEmptyStringDecoder$2, title); - await this._bridge.send("windows", operations$a.setTitle, { windowId: this.id, title: ttl }); - return this.me; - } - async getBounds() { - const result = await this._bridge.send("windows", operations$a.getBounds, { windowId: this.id }); - return result.bounds; - } - async getContext() { - const ctx = await this._bridge.contextLib.get(this.myCtxKey); - const { ___io___, ...rest } = ctx; - return rest; - } - async updateContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - await this._bridge.contextLib.update(this.myCtxKey, ctx); - return this.me; - } - async setContext(context) { - const ctx = runDecoderWithIOError(anyDecoder, context); - const current = await this._bridge.contextLib.get(this.myCtxKey); - const newCtx = current.___io___ ? { ...ctx, ___io___: current.___io___ } : ctx; - await this._bridge.contextLib.set(this.myCtxKey, newCtx); - return this.me; - } - onContextUpdated(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to context changes, because the provided callback is not a function!"); - } - const wrappedCallback = (data) => { - const { ___io___, ...rest } = data; - callback(rest, this.me); - }; - return this.registry.add("context-updated", wrappedCallback); - } - async getChannel() { - const result = await this._bridge.send("windows", operations$a.getChannel, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return result.channel; - } - onChannelsChanged(callback) { - return this.registry.add("channels-changed", callback); - } - getClosestZoomFactorIndex(factor) { - const closestIndex = Object.entries(ZOOM_FACTORS).reduce((closestIndex, [currentIndex, currentValue]) => { - return (Math.abs(currentValue - factor) <= Math.abs(ZOOM_FACTORS[closestIndex] - factor) ? parseInt(currentIndex) : closestIndex); - }, 0); - const closestFactor = ZOOM_FACTORS[closestIndex]; - if (closestFactor !== factor) { - this._logger.warn(`Zoom factor ${factor} is not available, using closest value ${closestFactor} instead.`); - } - return closestIndex; - } - async zoom(factorIndex) { - if (factorIndex === this.zoomFactorIndex || !(factorIndex in ZOOM_FACTORS)) { - return; - } - await this._bridge.send("windows", operations$a.setZoomFactor, { windowId: this.id, factorIndex }, undefined, { includeOperationCheck: true }); - this.zoomFactorIndex = factorIndex; - } - async zoomIn() { - await this.zoom(this.zoomFactorIndex + 1); - return this.me; - } - async zoomOut() { - await this.zoom(this.zoomFactorIndex - 1); - return this.me; - } - async setZoomFactor(factor) { - const targetZoomFactor = runDecoderWithIOError(number$2(), factor); - const closestZoomFactorIndex = this.getClosestZoomFactorIndex(targetZoomFactor); - await this.zoom(closestZoomFactorIndex); - return this.me; - } - onZoomFactorChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to zoom factor changes, because the provided callback is not a function!"); - } - return this.registry.add("zoom-factor-changed", callback); - } - async refresh() { - await this._bridge.send("windows", operations$a.refresh, { windowId: this.id }, undefined, { includeOperationCheck: true }); - return this.me; - } - } - - const commonOperations = { - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - getWorkspaceWindowFrameBounds: { name: "getWorkspaceWindowFrameBounds", resultDecoder: workspaceFrameBoundsResultDecoder, dataDecoder: simpleItemIdDecoder } - }; - - const PromiseWrap = (callback, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - callback() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - const PromisePlus$1 = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WindowsController { - supportedOperationsNames = []; - focusEventHandler; - registry = CallbackRegistryFactory$1(); - platformRegistration; - ioc; - bridge; - publicWindowId; - allWindowProjections = []; - me; - logger; - isWorkspaceFrame; - instanceId; - channelsController; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("windows.controller.web"); - this.logger.trace("starting the web windows controller"); - this.publicWindowId = ioc.publicWindowId; - this.addWindowOperationExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.instanceId = coreGlue.interop.instance.instance; - this.channelsController = ioc.channelsController; - this.logger.trace(`set the public window id: ${this.publicWindowId}, set the bridge operations and ioc, registering with the platform now`); - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - await this.initializeFocusTracking(); - this.logger.trace("registration with the platform successful, attaching the windows property to glue and returning"); - const api = this.toApi(); - coreGlue.windows = api; - } - handlePlatformShutdown() { - this.registry.clear(); - this.allWindowProjections = []; - if (!this.focusEventHandler) { - return; - } - document.removeEventListener("visibilityChange", this.focusEventHandler); - window.removeEventListener("focus", this.focusEventHandler); - window.removeEventListener("blur", this.focusEventHandler); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(windowOperationTypesDecoder, args.operation); - const operation = operations$a[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async open(name, url, options) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(nonEmptyStringDecoder$2, url); - const settings = runDecoderWithIOError(windowOpenSettingsDecoder, options); - const windowSuccess = await this.bridge.send("windows", operations$a.openWindow, { name, url, options: settings }); - return this.waitForWindowAdded(windowSuccess.windowId); - } - list() { - return this.allWindowProjections.map((projection) => projection.api); - } - findById(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - return this.allWindowProjections.find((projection) => projection.id === id)?.api; - } - toApi() { - return { - open: this.open.bind(this), - my: this.my.bind(this), - list: this.list.bind(this), - findById: this.findById.bind(this), - onWindowAdded: this.onWindowAdded.bind(this), - onWindowRemoved: this.onWindowRemoved.bind(this), - onWindowGotFocus: this.onWindowGotFocus.bind(this), - onWindowLostFocus: this.onWindowLostFocus.bind(this) - }; - } - addWindowOperationExecutors() { - operations$a.focusChange.execute = this.handleFocusChangeEvent.bind(this); - operations$a.windowAdded.execute = this.handleWindowAdded.bind(this); - operations$a.windowRemoved.execute = this.handleWindowRemoved.bind(this); - operations$a.getBounds.execute = this.handleGetBounds.bind(this); - operations$a.getFrameBounds.execute = this.handleGetBounds.bind(this); - operations$a.getTitle.execute = this.handleGetTitle.bind(this); - operations$a.getUrl.execute = this.handleGetUrl.bind(this); - operations$a.moveResize.execute = this.handleMoveResize.bind(this); - operations$a.setTitle.execute = this.handleSetTitle.bind(this); - operations$a.getChannel.execute = this.handleGetChannel.bind(this); - operations$a.notifyChannelsChanged.execute = this.handleChannelsChanged.bind(this); - operations$a.setZoomFactor.execute = this.handleSetZoomFactor.bind(this); - operations$a.zoomFactorChange.execute = this.handleZoomFactorChanged.bind(this); - operations$a.refresh.execute = this.handleRefresh.bind(this); - operations$a.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$a); - } - my() { - return Object.assign({}, this.me); - } - onWindowAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window added, because the provided callback is not a function!"); - } - return this.registry.add("window-added", callback); - } - onWindowRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to window removed, because the provided callback is not a function!"); - } - return this.registry.add("window-removed", callback); - } - onWindowGotFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowGotFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-got-focus", callback); - } - onWindowLostFocus(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onWindowLostFocus, because the provided callback is not a function!"); - } - return this.registry.add("window-lost-focus", callback); - } - async sayHello() { - const helloSuccess = await this.bridge.send("windows", operations$a.windowHello, { windowId: this.publicWindowId }); - return helloSuccess; - } - async registerWithPlatform() { - const { windows, isWorkspaceFrame } = await this.sayHello(); - this.isWorkspaceFrame = isWorkspaceFrame; - this.logger.trace("the platform responded to the hello message"); - if (!this.isWorkspaceFrame && this.publicWindowId) { - this.logger.trace("i am not treated as a workspace frame, setting my window"); - const myWindow = windows.find((w) => w.windowId === this.publicWindowId); - if (!myWindow) { - const windowsInfo = windows.map(w => `${w.windowId}:${w.name}`).join(", "); - return ioError.raiseError(`Cannot initialize the window library, because I received no information about me -> id: ${this.publicWindowId} name: ${window.name} from the platform: known windows: ${windowsInfo}`); - } - const myProjection = await this.ioc.buildWebWindow(this.publicWindowId, myWindow.name, this.logger); - this.me = myProjection.api; - this.allWindowProjections.push(myProjection); - } - const currentWindows = await Promise.all(windows - .filter((w) => w.windowId !== this.publicWindowId) - .map((w) => this.ioc.buildWebWindow(w.windowId, w.name, this.logger))); - this.logger.trace("all windows projections are completed, building the list collection"); - this.allWindowProjections.push(...currentWindows); - } - async handleFocusChangeEvent(focusData) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === focusData.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfFocusEvent(focusData.hasFocus); - const keyToExecute = focusData.hasFocus ? "window-got-focus" : "window-lost-focus"; - this.registry.execute(keyToExecute, foundProjection.api); - } - async handleWindowAdded(data) { - if (this.allWindowProjections.some((projection) => projection.id === data.windowId)) { - return; - } - const webWindowProjection = await this.ioc.buildWebWindow(data.windowId, data.name, this.logger); - this.allWindowProjections.push(webWindowProjection); - this.registry.execute("window-added", webWindowProjection.api); - } - async handleWindowRemoved(data) { - const removed = this.allWindowProjections.find((w) => w.id === data.windowId); - if (!removed) { - return; - } - this.allWindowProjections = this.allWindowProjections.filter((w) => w.id !== data.windowId); - removed.model.clean(); - this.registry.execute("window-removed", removed.api); - } - async handleGetBounds() { - if (!this.me && !this.isWorkspaceFrame) { - return ioError.raiseError("This window cannot report it's bounds, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.isWorkspaceFrame ? "noop" : this.me.id, - bounds: { - top: window.screenTop, - left: window.screenLeft, - width: window.innerWidth, - height: window.innerHeight - } - }; - } - async handleGetTitle() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's title, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - title: document.title - }; - } - async handleGetUrl() { - if (!this.me) { - return ioError.raiseError("This window cannot report it's url, because it is not a Glue Window, most likely because it is an iframe"); - } - return { - windowId: this.me.id, - url: window.location.href - }; - } - async handleMoveResize(config) { - const targetTop = typeof config.top === "number" ? config.top : - config.relative ? 0 : window.screenTop; - const targetLeft = typeof config.left === "number" ? config.left : - config.relative ? 0 : window.screenLeft; - const targetHeight = typeof config.height === "number" ? config.height : - config.relative ? 0 : window.innerHeight; - const targetWidth = typeof config.width === "number" ? config.width : - config.relative ? 0 : window.innerWidth; - const moveMethod = config.relative ? window.moveBy : window.moveTo; - const resizeMethod = config.relative ? window.resizeBy : window.resizeTo; - moveMethod(targetLeft, targetTop); - resizeMethod(targetWidth, targetHeight); - } - async handleSetTitle(config) { - document.title = config.title; - } - async initializeFocusTracking() { - if (this.isWorkspaceFrame) { - this.logger.trace("Ignoring the focus tracking, because this client is a workspace frame"); - return; - } - try { - await this.bridge.send("windows", commonOperations.operationCheck, { operation: "focusChange" }); - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support focus tracking, disabling focus events for this client."); - return; - } - const hasFocus = document.hasFocus(); - await this.transmitFocusChange(true); - if (!hasFocus) { - await this.transmitFocusChange(false); - } - this.defineEventListeners(); - } - processFocusEvent() { - const hasFocus = document.hasFocus(); - this.transmitFocusChange(hasFocus); - } - waitForWindowAdded(windowId) { - const foundWindow = this.allWindowProjections.find((projection) => projection.id === windowId); - if (foundWindow) { - return Promise.resolve(foundWindow.api); - } - return PromisePlus$1((resolve) => { - const unsubscribe = this.onWindowAdded((addedWindow) => { - if (addedWindow.id === windowId) { - unsubscribe(); - resolve(addedWindow); - } - }); - }, 30000, `Timed out waiting for ${windowId} to be announced`); - } - async transmitFocusChange(hasFocus) { - const eventData = { - windowId: this.me?.id || `iframe-${this.instanceId}`, - hasFocus - }; - if (this.me) { - this.me.isFocused = hasFocus; - } - await this.bridge.send("windows", operations$a.focusChange, eventData); - } - defineEventListeners() { - this.focusEventHandler = this.processFocusEvent.bind(this); - document.addEventListener("visibilityChange", this.focusEventHandler); - window.addEventListener("focus", this.focusEventHandler); - window.addEventListener("blur", this.focusEventHandler); - } - async handleGetChannel() { - if (!this.me) { - return ioError.raiseError("This window cannot report its channel, because it is not a ioConnect Window, most likely because it is an iframe"); - } - const channel = this.channelsController.my(); - return { - ...(channel ? { channel } : {}), - }; - } - async handleRefresh() { - if (!this.me) { - return ioError.raiseError("This window cannot refresh, because it is not an ioConnect Window, most likely because it is an iframe"); - } - setTimeout(() => { - window.location.reload(); - }, 0); - } - async handleChannelsChanged(data) { - const windowProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - windowProjection?.model.processChannelsChangedEvent(data.channelNames); - } - async handleSetZoomFactor(config) { - if (!this.me) { - return ioError.raiseError("This window cannot change its zoom factor, because it is not an ioConnect Window, most likely because it is an iframe"); - } - document.body.style.zoom = `${ZOOM_FACTORS[config.factorIndex]}%`; - } - async handleZoomFactorChanged(data) { - const foundProjection = this.allWindowProjections.find((projection) => projection.id === data.windowId); - if (!foundProjection) { - return; - } - foundProjection.model.processSelfZoomFactorChangedEvent(data.factorIndex); - } - } - - const GlueWebPlatformControlName = "T42.Web.Platform.Control"; - const GlueWebPlatformStreamName = "T42.Web.Platform.Stream"; - const GlueClientControlName = "T42.Web.Client.Control"; - const GlueCorePlusThemesStream = "T42.Core.Plus.Themes.Stream"; - - class GlueBridge { - coreGlue; - communicationId; - platformMethodTimeoutMs = 10000; - controllers; - sub; - running; - constructor(coreGlue, communicationId) { - this.coreGlue = coreGlue; - this.communicationId = communicationId; - } - get contextLib() { - return this.coreGlue.contexts; - } - get interopInstance() { - return this.coreGlue.interop.instance.instance; - } - async stop() { - this.running = false; - this.sub.close(); - await this.coreGlue.interop.unregister(GlueClientControlName); - } - async start(controllers) { - this.running = true; - this.controllers = controllers; - await Promise.all([ - this.checkWaitMethod(GlueWebPlatformControlName), - this.checkWaitMethod(GlueWebPlatformStreamName) - ]); - const systemId = this.communicationId; - const [sub] = await Promise.all([ - this.coreGlue.interop.subscribe(GlueWebPlatformStreamName, systemId ? { target: { instance: this.communicationId } } : undefined), - this.coreGlue.interop.registerAsync(GlueClientControlName, (args, _, success, error) => this.passMessageController(args, success, error)) - ]); - this.sub = sub; - this.sub.onData((pkg) => this.passMessageController(pkg.data)); - } - getInteropInstance(windowId) { - const result = this.coreGlue.interop.servers().find((s) => s.windowId && s.windowId === windowId); - return { - application: result?.application, - applicationName: result?.applicationName, - peerId: result?.peerId, - instance: result?.instance, - windowId: result?.windowId - }; - } - async send(domain, operation, operationData, options, webOptions) { - if (operation.dataDecoder) { - try { - operation.dataDecoder.runWithException(operationData); - } - catch (error) { - return ioError.raiseError(`Unexpected Web->Platform outgoing validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - } - const operationSupported = webOptions?.includeOperationCheck ? - (await this.checkOperationSupported(domain, operation)).isSupported : - true; - if (!operationSupported) { - return ioError.raiseError(`Cannot complete operation: ${operation.name} for domain: ${domain} because this client is connected to a platform which does not support it`); - } - try { - const operationResult = await this.transmitMessage(domain, operation, operationData, options); - if (operation.resultDecoder) { - operation.resultDecoder.runWithException(operationResult); - } - return operationResult; - } - catch (error) { - if (error?.kind) { - return ioError.raiseError(`Unexpected Web<-Platform incoming validation error: ${error.message}, for operation: ${operation.name} and input: ${JSON.stringify(error.input)}`); - } - return ioError.raiseError(error); - } - } - async createNotificationsSteam() { - const streamExists = this.coreGlue.interop.methods().some((method) => method.name === GlueCorePlusThemesStream); - if (!streamExists) { - return ioError.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus."); - } - return this.coreGlue.interop.subscribe(GlueCorePlusThemesStream, this.communicationId ? { target: { instance: this.communicationId } } : undefined); - } - async checkOperationSupported(domain, operation) { - try { - const result = await this.send(domain, commonOperations.operationCheck, { operation: operation.name }); - return result; - } - catch (error) { - return { isSupported: false }; - } - } - checkWaitMethod(name) { - return PromisePlus$1((resolve) => { - const hasMethod = this.coreGlue.interop.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = this.communicationId ? - method.getServers().some((server) => server.instance === this.communicationId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - return resolve(); - } - const unSub = this.coreGlue.interop.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = this.communicationId ? - server.instance === this.communicationId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }, this.platformMethodTimeoutMs, `Cannot initiate Glue Web, because a system method's discovery timed out: ${name}`); - } - passMessageController(args, success, error) { - const decodeResult = libDomainDecoder.run(args.domain); - if (!decodeResult.ok) { - if (error) { - error(`Cannot execute this client control, because of domain validation error: ${JSON.stringify(decodeResult.error)}`); - } - return; - } - const domain = decodeResult.result; - this.controllers[domain] - .handleBridgeMessage(args) - .then((resolutionData) => { - if (success) { - success(resolutionData); - } - }) - .catch((err) => { - if (error) { - error(err); - } - console.warn(err); - }); - } - async transmitMessage(domain, operation, data, options) { - const messageData = { domain, data, operation: operation.name }; - let invocationResult; - const baseErrorMessage = `Internal Platform Communication Error. Attempted operation: ${JSON.stringify(operation.name)} with data: ${JSON.stringify(data)}. `; - const systemId = this.communicationId; - try { - if (!this.running) { - throw new Error("Cannot send a control message, because the platform shut down"); - } - invocationResult = await this.coreGlue.interop.invoke(GlueWebPlatformControlName, messageData, systemId ? { instance: this.communicationId } : undefined, options); - if (!invocationResult) { - throw new Error("Received unsupported result from the platform - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from the platform - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - } - - const operations$9 = { - appHello: { name: "appHello", dataDecoder: windowHelloDecoder, resultDecoder: appHelloSuccessDecoder }, - appDirectoryStateChange: { name: "appDirectoryStateChange", dataDecoder: appDirectoryStateChangeDecoder }, - instanceStarted: { name: "instanceStarted", dataDecoder: instanceDataDecoder }, - instanceStopped: { name: "instanceStopped", dataDecoder: instanceDataDecoder }, - applicationStart: { name: "applicationStart", dataDecoder: applicationStartConfigDecoder, resultDecoder: instanceDataDecoder }, - instanceStop: { name: "instanceStop", dataDecoder: basicInstanceDataDecoder }, - import: { name: "import" }, - remove: { name: "remove", dataDecoder: appRemoveConfigDecoder }, - export: { name: "export", resultDecoder: appsExportOperationDecoder }, - clear: { name: "clear" }, - operationCheck: { name: "operationCheck" } - }; - - class AppManagerController { - me; - supportedOperationsNames = []; - baseApplicationsTimeoutMS = 60000; - appImportTimeoutMS = 20; - registry = CallbackRegistryFactory$1(); - ioc; - bridge; - publicWindowId; - applications = []; - instances = []; - platformRegistration; - logger; - channelsController; - interop; - initialChannelId; - handlePlatformShutdown() { - this.registry.clear(); - this.applications = []; - this.instances = []; - delete this.me; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("appManger.controller.web"); - this.logger.trace("starting the web appManager controller"); - this.publicWindowId = ioc.publicWindowId; - this.addOperationsExecutors(); - this.ioc = ioc; - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.interop = coreGlue.interop; - this.platformRegistration = this.registerWithPlatform(); - await this.platformRegistration; - this.logger.trace("registration with the platform successful, attaching the appManager property to glue and returning"); - const api = this.toApi(); - coreGlue.appManager = api; - } - async postStart() { - if (!this.initialChannelId) { - return; - } - await this.channelsController.handleAppManagerInitialChannelId(this.initialChannelId); - } - async handleBridgeMessage(args) { - await this.platformRegistration; - const operationName = runDecoderWithIOError(appManagerOperationTypesDecoder, args.operation); - const operation = operations$9[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStarted requires a single argument of type function"); - } - return this.registry.add("instance-started", callback, this.instances); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onInstanceStopped requires a single argument of type function"); - } - return this.registry.add("instance-stopped", callback); - } - async startApplication(appName, context, options) { - const channels = await this.channelsController.all(); - if (options?.channelId && !channels.includes(options.channelId)) { - return ioError.raiseError(`The channel with name "${options.channelId}" doesn't exist!`); - } - const startOptions = { - name: appName, - waitForAGMReady: options?.waitForAGMReady ?? true, - context, - top: options?.top, - left: options?.left, - width: options?.width, - height: options?.height, - relativeTo: options?.relativeTo, - relativeDirection: options?.relativeDirection, - id: options?.reuseId, - forceChromeTab: options?.forceTab, - layoutComponentId: options?.layoutComponentId, - channelId: options?.channelId, - startReason: { - originApp: { - name: this.me?.application.name, - interopInstance: this.interop.instance.instance - } - } - }; - if (options?.originIntentRequest) { - startOptions.startReason.intentRequest = options.originIntentRequest; - } - const openResult = await this.bridge.send("appManager", operations$9.applicationStart, startOptions); - const app = this.applications.find((a) => a.name === openResult.applicationName); - return this.ioc.buildInstance(openResult, app); - } - getApplication(name) { - const verifiedName = runDecoderWithIOError(nonEmptyStringDecoder$2, name); - return this.applications.find((app) => app.name === verifiedName); - } - getInstances() { - return this.instances.slice(); - } - onAppAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppAdded requires a single argument of type function"); - } - return this.registry.add("application-added", callback, this.applications); - } - onAppRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppRemoved requires a single argument of type function"); - } - return this.registry.add("application-removed", callback); - } - toApi() { - const api = { - myInstance: this.me, - inMemory: { - import: this.importApps.bind(this), - remove: this.remove.bind(this), - export: this.exportApps.bind(this), - clear: this.clear.bind(this) - }, - application: this.getApplication.bind(this), - applications: this.getApplications.bind(this), - instances: this.getInstances.bind(this), - onAppAdded: this.onAppAdded.bind(this), - onAppChanged: this.onAppChanged.bind(this), - onAppRemoved: this.onAppRemoved.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - return api; - } - addOperationsExecutors() { - operations$9.appDirectoryStateChange.execute = this.handleAppDirectoryStateChange.bind(this); - operations$9.instanceStarted.execute = this.handleInstanceStartedMessage.bind(this); - operations$9.instanceStopped.execute = this.handleInstanceStoppedMessage.bind(this); - operations$9.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$9); - } - async handleAppDirectoryStateChange(data) { - data.appsAdded.forEach(this.handleApplicationAddedMessage.bind(this)); - data.appsChanged.forEach(this.handleApplicationChangedMessage.bind(this)); - data.appsRemoved.forEach(this.handleApplicationRemovedMessage.bind(this)); - } - onAppChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onAppChanged requires a single argument of type function"); - } - return this.registry.add("application-changed", callback); - } - async handleApplicationAddedMessage(appData) { - if (this.applications.some((app) => app.name === appData.name)) { - return; - } - const app = await this.ioc.buildApplication(appData, []); - const instances = this.instances.filter((instance) => instance.application.name === app.name); - app.instances.push(...instances); - this.applications.push(app); - this.registry.execute("application-added", app); - } - async handleApplicationRemovedMessage(appData) { - const appIndex = this.applications.findIndex((app) => app.name === appData.name); - if (appIndex < 0) { - return; - } - const app = this.applications[appIndex]; - this.applications.splice(appIndex, 1); - this.registry.execute("application-removed", app); - } - async handleApplicationChangedMessage(appData) { - const app = this.applications.find((app) => app.name === appData.name); - if (!app) { - return this.handleApplicationAddedMessage(appData); - } - app.title = appData.title; - app.version = appData.version; - app.icon = appData.icon; - app.caption = appData.caption; - app.userProperties = appData.userProperties; - this.registry.execute("application-changed", app); - } - async handleInstanceStartedMessage(instanceData) { - if (this.instances.some((instance) => instance.id === instanceData.id)) { - return; - } - const application = this.applications.find((app) => app.name === instanceData.applicationName); - if (!application) { - return ioError.raiseError(`Cannot add instance: ${instanceData.id}, because there is no application definition associated with it`); - } - const instance = this.ioc.buildInstance(instanceData, application); - this.instances.push(instance); - application.instances.push(instance); - this.registry.execute("instance-started", instance); - } - async handleInstanceStoppedMessage(instanceData) { - const instance = this.instances.find((i) => i.id === instanceData.id); - if (instance) { - const instIdx = this.instances.findIndex((inst) => inst.id === instanceData.id); - this.instances.splice(instIdx, 1); - } - const application = this.applications.find((app) => app.instances.some((inst) => inst.id === instanceData.id)); - if (application) { - const instIdxApps = application.instances.findIndex((inst) => inst.id === instanceData.id); - application.instances.splice(instIdxApps, 1); - } - if (!instance) { - return; - } - this.registry.execute("instance-stopped", instance); - } - async importApps(definitions, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(definitions)) { - return ioError.raiseError("Import must be called with an array of definitions"); - } - if (definitions.length > 10000) { - return ioError.raiseError("Cannot import more than 10000 app definitions in Glue42 Core."); - } - const parseResult = definitions.reduce((soFar, definition) => { - const { isValid, error } = this.isValidDefinition(definition); - if (!isValid) { - soFar.invalid.push({ app: definition?.name, error: error ?? `Provided definition is invalid ${JSON.stringify(definition)}` }); - } - else { - soFar.valid.push(definition); - } - return soFar; - }, { valid: [], invalid: [] }); - const responseTimeout = this.baseApplicationsTimeoutMS + this.appImportTimeoutMS * parseResult.valid.length; - await this.bridge.send("appManager", operations$9.import, { definitions: parseResult.valid, mode }, { methodResponseTimeoutMs: responseTimeout }); - return { - imported: parseResult.valid.map((valid) => valid.name), - errors: parseResult.invalid - }; - } - isValidDefinition(definition) { - const isFdc3V2Definition = definition?.appId && definition?.details; - if (isFdc3V2Definition) { - const decodeResult = decoders.fdc3.v2DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v2 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const isFdc3V1Definition = definition?.appId && definition?.manifest; - if (isFdc3V1Definition) { - const decodeResult = decoders.fdc3.v1DefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid FDC3 v1 definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - const decodeResult = applicationDefinitionDecoder.run(definition); - return { isValid: decodeResult.ok, error: decodeResult.ok ? undefined : `Received invalid definition. Error: ${JSON.stringify(decodeResult.error)}` }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("appManager", operations$9.remove, { name }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async clear() { - await this.bridge.send("appManager", operations$9.clear, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - } - async exportApps() { - const response = await this.bridge.send("appManager", operations$9.export, undefined, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - return response.definitions; - } - getApplications() { - return this.applications.slice(); - } - async registerWithPlatform() { - const result = await this.bridge.send("appManager", operations$9.appHello, { windowId: this.publicWindowId }, { methodResponseTimeoutMs: this.baseApplicationsTimeoutMS }); - this.logger.trace("the platform responded to the hello message with a full list of apps"); - this.applications = await Promise.all(result.apps.map((app) => this.ioc.buildApplication(app, app.instances))); - this.instances = this.applications.reduce((instancesSoFar, app) => { - instancesSoFar.push(...app.instances); - return instancesSoFar; - }, []); - this.me = this.findMyInstance(); - this.logger.trace(`all applications were parsed and saved. I am ${this.me ? "NOT a" : "a"} valid instance`); - this.initialChannelId = result.initialChannelId; - } - findMyInstance() { - for (const app of this.applications) { - const foundInstance = app.instances.find((instance) => instance.id === this.publicWindowId); - if (foundInstance) { - return foundInstance; - } - } - return undefined; - } - } - - class InstanceModel { - data; - bridge; - application; - me; - myCtxKey; - constructor(data, bridge, application) { - this.data = data; - this.bridge = bridge; - this.application = application; - this.myCtxKey = `___instance___${this.data.id}`; - } - toApi() { - const agm = this.bridge.getInteropInstance(this.data.id); - const api = { - id: this.data.id, - agm, - application: this.application, - stop: this.stop.bind(this), - getContext: this.getContext.bind(this) - }; - this.me = Object.freeze(api); - return this.me; - } - async getContext() { - return this.bridge.contextLib.get(this.myCtxKey); - } - async stop() { - await this.bridge.send("appManager", operations$9.instanceStop, { id: this.data.id }); - } - } - - class ApplicationModel { - data; - instances; - controller; - me; - constructor(data, instances, controller) { - this.data = data; - this.instances = instances; - this.controller = controller; - } - toApi() { - const api = { - name: this.data.name, - title: this.data.title, - version: this.data.version, - icon: this.data.icon, - caption: this.data.caption, - userProperties: this.data.userProperties, - instances: this.instances, - start: this.start.bind(this), - onInstanceStarted: this.onInstanceStarted.bind(this), - onInstanceStopped: this.onInstanceStopped.bind(this) - }; - this.me = api; - return this.me; - } - onInstanceStarted(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStarted((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - onInstanceStopped(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("OnInstanceStarted requires a single argument of type function"); - } - return this.controller.onInstanceStopped((instance) => { - if (instance.application.name === this.data.name) { - callback(instance); - } - }); - } - async start(context, options) { - const verifiedContext = runDecoderWithIOError(startApplicationContextDecoder, context); - const verifiedOptions = runDecoderWithIOError(startApplicationOptionsDecoder, options); - return this.controller.startApplication(this.data.name, verifiedContext, verifiedOptions); - } - } - - const operations$8 = { - layoutAdded: { name: "layoutAdded", dataDecoder: glueLayoutDecoder }, - layoutChanged: { name: "layoutChanged", dataDecoder: glueLayoutDecoder }, - layoutRemoved: { name: "layoutRemoved", dataDecoder: glueLayoutDecoder }, - layoutRestored: { name: "layoutRestored", dataDecoder: glueLayoutDecoder }, - defaultLayoutChanged: { name: "defaultLayoutChanged", dataDecoder: defaultGlobalChangedDecoder }, - layoutRenamed: { name: "layoutRenamed", dataDecoder: renamedLayoutNotificationDecoder }, - get: { name: "get", dataDecoder: simpleLayoutConfigDecoder, resultDecoder: optionalSimpleLayoutResult }, - getAll: { name: "getAll", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsSummariesResultDecoder }, - export: { name: "export", dataDecoder: getAllLayoutsConfigDecoder, resultDecoder: allLayoutsFullConfigDecoder }, - import: { name: "import", dataDecoder: layoutsImportConfigDecoder }, - remove: { name: "remove", dataDecoder: simpleLayoutConfigDecoder }, - rename: { name: "rename", dataDecoder: renameLayoutConfigDecoder, resultDecoder: layoutResultDecoder }, - save: { name: "save", dataDecoder: saveLayoutConfigDecoder, resultDecoder: simpleLayoutResultDecoder }, - restore: { name: "restore", dataDecoder: restoreLayoutConfigDecoder }, - clientSaveRequest: { name: "clientSaveRequest", dataDecoder: platformSaveRequestConfigDecoder, resultDecoder: saveRequestClientResponseDecoder }, - getGlobalPermissionState: { name: "getGlobalPermissionState", resultDecoder: permissionStateResultDecoder }, - requestGlobalPermission: { name: "requestGlobalPermission", resultDecoder: simpleAvailabilityResultDecoder }, - checkGlobalActivated: { name: "checkGlobalActivated", resultDecoder: simpleAvailabilityResultDecoder }, - getDefaultGlobal: { name: "getDefaultGlobal", resultDecoder: optionalSimpleLayoutResult }, - setDefaultGlobal: { name: "setDefaultGlobal", dataDecoder: setDefaultGlobalConfigDecoder }, - clearDefaultGlobal: { name: "clearDefaultGlobal" }, - getCurrent: { name: "getCurrent", resultDecoder: optionalSimpleLayoutResult }, - updateMetadata: { name: "updateMetadata", dataDecoder: updateLayoutMetadataConfigDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class LayoutsController { - supportedOperationsNames = []; - defaultLayoutRestoreTimeoutMS = 120000; - registry = CallbackRegistryFactory$1(); - bridge; - logger; - windowsController; - saveRequestSubscription; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("layouts.controller.web"); - this.logger.trace("starting the web layouts controller"); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.addOperationsExecutors(); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the layouts property to glue and returning"); - coreGlue.layouts = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(layoutsOperationTypesDecoder, args.operation); - const operation = operations$8[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - get: this.get.bind(this), - getAll: this.getAll.bind(this), - getCurrentLayout: this.getCurrentLayout.bind(this), - export: this.exportLayouts.bind(this), - import: this.importLayouts.bind(this), - save: this.save.bind(this), - restore: this.restore.bind(this), - remove: this.remove.bind(this), - onAdded: this.onAdded.bind(this), - onChanged: this.onChanged.bind(this), - onRemoved: this.onRemoved.bind(this), - onDefaultGlobalChanged: this.onDefaultGlobalChanged.bind(this), - onSaveRequested: this.subscribeOnSaveRequested.bind(this), - getMultiScreenPermissionState: this.getGlobalPermissionState.bind(this), - requestMultiScreenPermission: this.requestGlobalPermission.bind(this), - getGlobalTypeState: this.checkGlobalActivated.bind(this), - getDefaultGlobal: this.getDefaultGlobal.bind(this), - setDefaultGlobal: this.setDefaultGlobal.bind(this), - clearDefaultGlobal: this.clearDefaultGlobal.bind(this), - rename: this.rename.bind(this), - onRenamed: this.onRenamed.bind(this), - onRestored: this.onRestored.bind(this), - updateMetadata: this.updateMetadata.bind(this) - }; - return Object.freeze(api); - } - addOperationsExecutors() { - operations$8.layoutAdded.execute = this.handleOnAdded.bind(this); - operations$8.layoutChanged.execute = this.handleOnChanged.bind(this); - operations$8.layoutRemoved.execute = this.handleOnRemoved.bind(this); - operations$8.layoutRenamed.execute = this.handleOnRenamed.bind(this); - operations$8.layoutRestored.execute = this.handleOnRestored.bind(this); - operations$8.defaultLayoutChanged.execute = this.handleOnDefaultChanged.bind(this); - operations$8.clientSaveRequest.execute = this.handleSaveRequest.bind(this); - operations$8.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$8); - } - async get(name, type) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.get, { name, type }); - return result.layout; - } - async getCurrentLayout() { - const result = await this.bridge.send("layouts", operations$8.getCurrent, undefined); - return result.layout; - } - async getAll(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.getAll, { type }); - return result.summaries; - } - async exportLayouts(type) { - runDecoderWithIOError(layoutTypeDecoder, type); - const result = await this.bridge.send("layouts", operations$8.export, { type }); - return result.layouts; - } - async importLayouts(layouts, mode = "replace") { - runDecoderWithIOError(importModeDecoder, mode); - if (!Array.isArray(layouts)) { - return ioError.raiseError("Import must be called with an array of layouts"); - } - if (layouts.length > 1000) { - return ioError.raiseError("Cannot import more than 1000 layouts at once in Glue42 Core."); - } - const parseResult = layouts.reduce((soFar, layout) => { - const decodeResult = glueLayoutDecoder.run(layout); - if (decodeResult.ok) { - soFar.valid.push(layout); - } - else { - this.logger.warn(`A layout with name: ${layout.name} was not imported, because of error: ${JSON.stringify(decodeResult.error)}`); - } - return soFar; - }, { valid: [] }); - const layoutsToImport = layouts.filter((layout) => parseResult.valid.some((validLayout) => validLayout.name === layout.name)); - await this.bridge.send("layouts", operations$8.import, { layouts: layoutsToImport, mode }); - } - async save(layout) { - runDecoderWithIOError(newLayoutOptionsDecoder, layout); - const saveResult = await this.bridge.send("layouts", operations$8.save, { layout }); - return saveResult.layout; - } - async restore(options) { - runDecoderWithIOError(restoreOptionsDecoder, options); - const invocationTimeout = options.timeout ? options.timeout * 2 : this.defaultLayoutRestoreTimeoutMS; - await this.bridge.send("layouts", operations$8.restore, { layout: options }, { methodResponseTimeoutMs: invocationTimeout }); - } - async remove(type, name) { - runDecoderWithIOError(layoutTypeDecoder, type); - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.remove, { type, name }); - } - async handleSaveRequest(config) { - const response = {}; - if (this.saveRequestSubscription) { - try { - const onSaveRequestResponse = this.saveRequestSubscription(config); - response.windowContext = onSaveRequestResponse?.windowContext; - } - catch (error) { - this.logger.warn(`An error was thrown by the onSaveRequested callback, ignoring the callback: ${JSON.stringify(error)}`); - } - } - return response; - } - async getGlobalPermissionState() { - const requestResult = await this.bridge.send("layouts", operations$8.getGlobalPermissionState, undefined); - return requestResult; - } - async requestGlobalPermission() { - const currentState = (await this.getGlobalPermissionState()).state; - if (currentState === "denied") { - return { permissionGranted: false }; - } - if (currentState === "granted") { - return { permissionGranted: true }; - } - const myWindow = this.windowsController.my(); - const globalNamespace = window.glue42core || window.iobrowser; - const amIWorkspaceFrame = globalNamespace.isPlatformFrame; - if (myWindow.name !== "Platform" && !amIWorkspaceFrame) { - return ioError.raiseError("Cannot request permission for multi-window placement from any app other than the Platform."); - } - const requestResult = await this.bridge.send("layouts", operations$8.requestGlobalPermission, undefined, { methodResponseTimeoutMs: 180000 }); - return { permissionGranted: requestResult.isAvailable }; - } - async checkGlobalActivated() { - const requestResult = await this.bridge.send("layouts", operations$8.checkGlobalActivated, undefined); - return { activated: requestResult.isAvailable }; - } - async getDefaultGlobal() { - const requestResult = await this.bridge.send("layouts", operations$8.getDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - return requestResult.layout; - } - async setDefaultGlobal(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("layouts", operations$8.setDefaultGlobal, { name }, undefined, { includeOperationCheck: true }); - } - async clearDefaultGlobal() { - await this.bridge.send("layouts", operations$8.clearDefaultGlobal, undefined, undefined, { includeOperationCheck: true }); - } - async rename(layout, newName) { - runDecoderWithIOError(glueLayoutDecoder, layout); - runDecoderWithIOError(nonEmptyStringDecoder$2, newName); - const result = await this.bridge.send("layouts", operations$8.rename, { layout, newName }, undefined, { includeOperationCheck: true }); - return result; - } - async updateMetadata(layout) { - runDecoderWithIOError(glueLayoutDecoder, layout); - await this.bridge.send("layouts", operations$8.updateMetadata, { layout }, undefined, { includeOperationCheck: true }); - } - onAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onAdded, because the provided callback is not a function!"); - } - this.exportLayouts("Global").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - this.exportLayouts("Workspace").then((layouts) => layouts.forEach((layout) => callback(layout))).catch(() => { }); - return this.registry.add(operations$8.layoutAdded.name, callback); - } - onChanged(callback) { - return this.registry.add(operations$8.layoutChanged.name, callback); - } - onDefaultGlobalChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onDefaultGlobalChanged, because the provided callback is not a function!"); - } - this.getDefaultGlobal().then((layout) => callback(layout ? { name: layout.name } : undefined)).catch(() => { }); - return this.registry.add(operations$8.defaultLayoutChanged.name, callback); - } - onRemoved(callback) { - return this.registry.add(operations$8.layoutRemoved.name, callback); - } - onRenamed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRenamed, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRenamed.name, callback); - } - onRestored(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onRestored, because the provided callback is not a function!"); - } - return this.registry.add(operations$8.layoutRestored.name, callback); - } - subscribeOnSaveRequested(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because the provided argument is not a valid callback function."); - } - if (this.saveRequestSubscription) { - return ioError.raiseError("Cannot subscribe to onSaveRequested, because this client has already subscribed and only one subscription is supported. Consider unsubscribing from the initial one."); - } - this.saveRequestSubscription = callback; - return () => { - delete this.saveRequestSubscription; - }; - } - async handleOnAdded(layout) { - this.registry.execute(operations$8.layoutAdded.name, layout); - } - async handleOnChanged(layout) { - this.registry.execute(operations$8.layoutChanged.name, layout); - } - async handleOnDefaultChanged(layout) { - this.registry.execute(operations$8.defaultLayoutChanged.name, layout); - } - async handleOnRemoved(layout) { - this.registry.execute(operations$8.layoutRemoved.name, layout); - } - async handleOnRestored(layout) { - this.registry.execute(operations$8.layoutRestored.name, layout); - } - async handleOnRenamed(renamedData) { - const { prevName, ...layout } = renamedData; - this.registry.execute(operations$8.layoutRenamed.name, layout, { name: prevName }); - } - } - - const operations$7 = { - raiseNotification: { name: "raiseNotification", dataDecoder: raiseNotificationDecoder, resultDecoder: raiseNotificationResultDecoder }, - requestPermission: { name: "requestPermission", resultDecoder: permissionRequestResultDecoder }, - notificationShow: { name: "notificationShow", dataDecoder: notificationEventPayloadDecoder }, - notificationClick: { name: "notificationClick", dataDecoder: notificationEventPayloadDecoder }, - getPermission: { name: "getPermission", resultDecoder: permissionQueryResultDecoder }, - list: { name: "list", resultDecoder: allNotificationsDataDecoder }, - notificationRaised: { name: "notificationRaised", dataDecoder: simpleNotificationDataDecoder }, - notificationClosed: { name: "notificationClosed", dataDecoder: simpleNotificationSelectDecoder }, - click: { name: "click" }, - clear: { name: "clear" }, - clearAll: { name: "clearAll" }, - clearOld: { name: "clearOld" }, - configure: { name: "configure", dataDecoder: notificationsConfigurationProtocolDecoder }, - getConfiguration: { name: "getConfiguration", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - getActiveCount: { name: "getActiveCount", resultDecoder: activeNotificationsCountChangeDecoder }, - configurationChanged: { name: "configurationChanged", resultDecoder: strictNotificationsConfigurationProtocolDecoder }, - setState: { name: "setState", dataDecoder: notificationSetStateRequestDecoder }, - activeCountChange: { name: "activeCountChange", resultDecoder: activeNotificationsCountChangeDecoder }, - stateChange: { name: "stateChange", resultDecoder: notificationSetStateRequestDecoder }, - operationCheck: { name: "operationCheck" } - }; - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet$1 = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid$1 = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet$1[(Math.random() * 64) | 0]; - } - return id - }; - - class NotificationsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - bridge; - notificationsSettings; - notifications = {}; - coreGlue; - buildNotificationFunc; - notificationsConfiguration; - notificationsActiveCount = 0; - handlePlatformShutdown() { - this.notifications = {}; - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("notifications.controller.web"); - this.logger.trace("starting the web notifications controller"); - this.bridge = ioc.bridge; - this.coreGlue = coreGlue; - this.notificationsSettings = ioc.config.notifications; - this.buildNotificationFunc = ioc.buildNotification; - this.notificationsConfiguration = await this.getConfiguration(); - this.notificationsActiveCount = await this.getActiveCount(); - const api = this.toApi(); - this.addOperationExecutors(); - coreGlue.notifications = api; - this.logger.trace("notifications are ready"); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(notificationsOperationTypesDecoder, args.operation); - const operation = operations$7[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - requestPermission: this.requestPermission.bind(this), - getPermission: this.getPermission.bind(this), - list: this.list.bind(this), - onRaised: this.onRaised.bind(this), - onClosed: this.onClosed.bind(this), - click: this.click.bind(this), - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearOld: this.clearOld.bind(this), - configure: this.configure.bind(this), - getConfiguration: this.getConfiguration.bind(this), - getFilter: this.getFilter.bind(this), - setFilter: this.setFilter.bind(this), - setState: this.setState.bind(this), - onConfigurationChanged: this.onConfigurationChanged.bind(this), - onActiveCountChanged: this.onActiveCountChanged.bind(this), - onCounterChanged: this.onActiveCountChanged.bind(this), - onStateChanged: this.onStateChanged.bind(this) - }; - return Object.freeze(api); - } - async getPermission() { - const queryResult = await this.bridge.send("notifications", operations$7.getPermission, undefined); - return queryResult.permission; - } - async requestPermission() { - const permissionResult = await this.bridge.send("notifications", operations$7.requestPermission, undefined); - return permissionResult.permissionGranted; - } - async raise(options) { - const settings = runDecoderWithIOError(glue42NotificationOptionsDecoder, options); - settings.showToast = typeof settings.showToast === "boolean" ? settings.showToast : true; - settings.showInPanel = typeof settings.showInPanel === "boolean" ? settings.showInPanel : true; - const permissionGranted = await this.requestPermission(); - if (!permissionGranted) { - return ioError.raiseError("Cannot raise the notification, because the user has declined the permission request"); - } - const id = nanoid$1(10); - const raiseResult = await this.bridge.send("notifications", operations$7.raiseNotification, { settings, id }); - const notification = this.buildNotificationFunc(raiseResult.settings, id); - this.notifications[id] = notification; - return notification; - } - async list() { - const bridgeResponse = await this.bridge.send("notifications", operations$7.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.notifications; - } - onRaised(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onRaised expects a callback of type function"); - } - return this.registry.add("notification-raised", callback); - } - onClosed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onClosed expects a callback of type function"); - } - return this.registry.add("notification-closed", callback); - } - async click(id, action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - if (action) { - runDecoderWithIOError(nonEmptyStringDecoder$2, action); - } - await this.bridge.send("notifications", operations$7.click, { id, action }, undefined, { includeOperationCheck: true }); - } - async clear(id) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - await this.bridge.send("notifications", operations$7.clear, { id }, undefined, { includeOperationCheck: true }); - } - async clearAll() { - await this.bridge.send("notifications", operations$7.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearOld() { - await this.bridge.send("notifications", operations$7.clearOld, undefined, undefined, { includeOperationCheck: true }); - } - async configure(config) { - const verifiedConfig = runDecoderWithIOError(notificationsConfigurationDecoder, config); - await this.bridge.send("notifications", operations$7.configure, { configuration: verifiedConfig }, undefined, { includeOperationCheck: true }); - } - async getConfiguration() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration; - } - async getActiveCount() { - try { - const response = await this.bridge.send("notifications", operations$7.getActiveCount, undefined, undefined, { includeOperationCheck: true }); - return response.count; - } - catch (error) { - console.warn("Failed to get accurate active notifications count", error); - return 0; - } - } - async getFilter() { - const response = await this.bridge.send("notifications", operations$7.getConfiguration, undefined, undefined, { includeOperationCheck: true }); - return response.configuration.sourceFilter; - } - async setFilter(filter) { - const verifiedFilter = runDecoderWithIOError(notificationFilterDecoder, filter); - await this.bridge.send("notifications", operations$7.configure, { configuration: { sourceFilter: verifiedFilter } }, undefined, { includeOperationCheck: true }); - return verifiedFilter; - } - async setState(id, state) { - runDecoderWithIOError(nonEmptyStringDecoder$2, id); - runDecoderWithIOError(notificationStateDecoder, state); - await this.bridge.send("notifications", operations$7.setState, { id, state }, undefined, { includeOperationCheck: true }); - } - onConfigurationChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to configuration changed, because the provided callback is not a function!"); - } - setTimeout(() => callback(this.notificationsConfiguration), 0); - return this.registry.add("notifications-config-changed", callback); - } - onActiveCountChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onActiveCountChanged changed, because the provided callback is not a function!"); - } - setTimeout(() => callback({ count: this.notificationsActiveCount }), 0); - return this.registry.add("notifications-active-count-changed", callback); - } - onStateChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to onStateChanged changed, because the provided callback is not a function!"); - } - return this.registry.add("notification-state-changed", callback); - } - addOperationExecutors() { - operations$7.notificationShow.execute = this.handleNotificationShow.bind(this); - operations$7.notificationClick.execute = this.handleNotificationClick.bind(this); - operations$7.notificationRaised.execute = this.handleNotificationRaised.bind(this); - operations$7.notificationClosed.execute = this.handleNotificationClosed.bind(this); - operations$7.configurationChanged.execute = this.handleConfigurationChanged.bind(this); - operations$7.activeCountChange.execute = this.handleActiveCountChanged.bind(this); - operations$7.stateChange.execute = this.handleNotificationStateChanged.bind(this); - operations$7.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$7); - } - async handleConfigurationChanged(data) { - this.notificationsConfiguration = data.configuration; - this.registry.execute("notifications-config-changed", data.configuration); - } - async handleActiveCountChanged(data) { - this.notificationsActiveCount = data.count; - this.registry.execute("notifications-active-count-changed", data); - } - async handleNotificationStateChanged(data) { - this.registry.execute("notification-state-changed", { id: data.id }, data.state); - } - async handleNotificationShow(data) { - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onshow) { - notification.onshow(); - } - } - async handleNotificationClick(data) { - if (!data.action && this.notificationsSettings?.defaultClick) { - this.notificationsSettings.defaultClick(this.coreGlue, data.definition); - } - if (data.action && this.notificationsSettings?.actionClicks?.some((actionDef) => actionDef.action === data.action)) { - const foundHandler = this.notificationsSettings?.actionClicks?.find((actionDef) => actionDef.action === data.action); - foundHandler.handler(this.coreGlue, data.definition); - } - if (!data.id) { - return; - } - const notification = this.notifications[data.id]; - if (notification && notification.onclick) { - notification.onclick(); - delete this.notifications[data.id]; - } - } - async handleNotificationRaised(data) { - this.registry.execute("notification-raised", data.notification); - } - async handleNotificationClosed(data) { - this.registry.execute("notification-closed", data); - } - } - - const operations$6 = { - getIntents: { name: "getIntents", resultDecoder: wrappedIntentsDecoder }, - findIntent: { name: "findIntent", dataDecoder: wrappedIntentFilterDecoder, resultDecoder: wrappedIntentsDecoder }, - raise: { name: "raise", dataDecoder: raiseIntentRequestDecoder, resultDecoder: intentResultDecoder }, - filterHandlers: { name: "filterHandlers", dataDecoder: filterHandlersWithResolverConfigDecoder, resultDecoder: filterHandlersResultDecoder }, - getIntentsByHandler: { name: "getIntentsByHandler", dataDecoder: intentHandlerDecoder, resultDecoder: getIntentsResultDecoder } - }; - - const GLUE42_FDC3_INTENTS_METHOD_PREFIX = "Tick42.FDC3.Intents."; - const INTENTS_RESOLVER_APP_NAME = "intentsResolver"; - const DEFAULT_RESOLVER_RESPONSE_TIMEOUT = 60 * 1000; - const ADDITIONAL_BRIDGE_OPERATION_TIMEOUT = 30 * 1000; - const DEFAULT_PICK_HANDLER_BY_TIMEOUT = 90 * 1000; - - class IntentsController { - bridge; - logger; - interop; - appManagerController; - windowsController; - myIntents = new Set(); - prefsController; - uiController; - useIntentsResolverUI = true; - intentsResolverAppName; - intentResolverResponseTimeout = DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - unregisterIntentPromises = []; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("intents.controller.web"); - this.logger.trace("starting the web intents controller"); - this.bridge = ioc.bridge; - this.interop = coreGlue.interop; - this.appManagerController = ioc.appManagerController; - this.windowsController = ioc.windowsController; - this.prefsController = ioc.prefsController; - this.uiController = ioc.uiController; - this.checkIfIntentsResolverIsEnabled(ioc.config); - const api = this.toApi(); - this.logger.trace("no need for platform registration, attaching the intents property to glue and returning"); - coreGlue.intents = api; - } - handlePlatformShutdown() { - this.myIntents = new Set(); - this.unregisterIntentPromises = []; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(intentsOperationTypesDecoder, args.operation); - const operation = operations$6[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - toApi() { - const api = { - raise: this.raise.bind(this), - all: this.all.bind(this), - addIntentListener: this.addIntentListener.bind(this), - register: this.register.bind(this), - find: this.find.bind(this), - filterHandlers: this.filterHandlers.bind(this), - getIntents: this.getIntentsByHandler.bind(this), - clearSavedHandlers: this.clearSavedHandlers.bind(this), - onHandlerAdded: this.onHandlerAdded.bind(this), - onHandlerRemoved: this.onHandlerRemoved.bind(this) - }; - return api; - } - async raise(request) { - const validatedIntentRequest = runDecoderWithIOError(raiseRequestDecoder, request); - const intentRequest = typeof validatedIntentRequest === "string" - ? { intent: validatedIntentRequest } - : validatedIntentRequest; - await Promise.all(this.unregisterIntentPromises); - if (intentRequest.clearSavedHandler) { - this.logger.trace(`User removes saved handler for intent ${intentRequest.intent}`); - await this.removeRememberedHandler(intentRequest.intent); - } - const resultFromRememberedHandler = await this.checkHandleRaiseWithRememberedHandler(intentRequest); - if (resultFromRememberedHandler) { - return resultFromRememberedHandler; - } - const requestWithResolverInfo = { - intentRequest, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - const methodResponseTimeoutMs = intentRequest.waitUserResponseIndefinitely - ? MAX_SET_TIMEOUT_DELAY - : (intentRequest.timeout || this.intentResolverResponseTimeout) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - this.logger.trace(`Sending raise request to the platform: ${JSON.stringify(request)} and method response timeout of ${methodResponseTimeoutMs}ms`); - const response = await this.bridge.send("intents", operations$6.raise, requestWithResolverInfo, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }); - this.logger.trace(`Raise operation completed with response: ${JSON.stringify(response)}`); - return response; - } - getLegacyResolverConfigByRequest(filter) { - if (filter.handlerFilter) { - return { - enabled: typeof filter.handlerFilter?.openResolver === "boolean" ? filter.handlerFilter?.openResolver : this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout: filter.handlerFilter?.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT - }; - } - const waitResponseTimeout = filter.intentRequest?.waitUserResponseIndefinitely ? MAX_SET_TIMEOUT_DELAY : this.intentResolverResponseTimeout; - return { - enabled: this.useIntentsResolverUI, - appName: this.intentsResolverAppName, - waitResponseTimeout - }; - } - getEmbeddedResolverConfig() { - return { - enabled: this.uiController.isIntentResolverEnabled(), - initialCaller: { instanceId: this.interop.instance.instance } - }; - } - async all() { - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.getIntents, undefined); - return result.intents; - } - addIntentListener(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - let registerPromise; - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - const result = { - unsubscribe: () => { - this.myIntents.delete(intentName); - registerPromise - .then(() => this.interop.unregister(methodName)) - .catch((err) => this.logger.trace(`Unregistration of a method with name ${methodName} failed with reason: ${err}`)); - } - }; - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - registerPromise = this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - return handler(rest); - } - }); - registerPromise.catch(err => { - this.myIntents.delete(intentName); - this.logger.warn(`Registration of a method with name ${methodName} failed with reason: ${err}`); - }); - return result; - } - async register(intent, handler) { - runDecoderWithIOError(AddIntentListenerDecoder, intent); - if (typeof handler !== "function") { - return ioError.raiseError("Cannot add intent listener, because the provided handler is not a function!"); - } - await Promise.all(this.unregisterIntentPromises); - const intentName = typeof intent === "string" ? intent : intent.intent; - const methodName = this.buildInteropMethodName(intentName); - const alreadyRegistered = this.myIntents.has(intentName); - if (alreadyRegistered) { - return ioError.raiseError(`Intent listener for intent ${intentName} already registered!`); - } - this.myIntents.add(intentName); - let intentFlag = {}; - if (typeof intent === "object") { - const { intent: removed, ...rest } = intent; - intentFlag = rest; - } - try { - await this.interop.register({ name: methodName, flags: { intent: intentFlag } }, (args) => { - if (this.myIntents.has(intentName)) { - const { _initialCallerId, ...rest } = args; - const caller = this.interop.servers().find((server) => server.instance === _initialCallerId); - return handler(rest, caller); - } - }); - } - catch (err) { - this.myIntents.delete(intentName); - return ioError.raiseError(`Registration of a method with name ${methodName} failed with reason: ${JSON.stringify(err)}`); - } - return { - unsubscribe: () => this.unsubscribeIntent(intentName) - }; - } - async find(intentFilter) { - let data = undefined; - if (typeof intentFilter !== "undefined") { - const intentFilterObj = runDecoderWithIOError(findFilterDecoder, intentFilter); - if (typeof intentFilterObj === "string") { - data = { - filter: { - name: intentFilterObj - } - }; - } - else if (typeof intentFilterObj === "object") { - data = { - filter: intentFilterObj - }; - } - } - await Promise.all(this.unregisterIntentPromises); - const result = await this.bridge.send("intents", operations$6.findIntent, data); - return result.intents; - } - onHandlerAdded(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerAdded' event - callback is not a function!"); - } - const unOnAppAdded = this.subscribeForAppEvent("onAppAdded", callback); - const unOnServerMethodAdded = this.subscribeForServerMethodEvent("serverMethodAdded", callback); - return () => { - unOnAppAdded(); - unOnServerMethodAdded(); - }; - } - onHandlerRemoved(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe for 'onHandlerRemoved' event - callback is not a function!"); - } - const unOnAppRemoved = this.subscribeForAppEvent("onAppRemoved", callback); - const unOnServerMethodRemoved = this.subscribeForServerMethodEvent("serverMethodRemoved", callback); - return () => { - unOnAppRemoved(); - unOnServerMethodRemoved(); - }; - } - subscribeForAppEvent(method, callback) { - return this.appManagerController[method]((app) => { - const appIntents = app.userProperties.intents; - if (!appIntents?.length) { - return; - } - appIntents.forEach((intent) => { - const handler = this.buildIntentHandlerFromApp(app, intent); - callback(handler, intent.name); - }); - }); - } - subscribeForServerMethodEvent(eventMethod, callback) { - return this.interop[eventMethod](async ({ server, method }) => { - if (!method.name.startsWith(GLUE42_FDC3_INTENTS_METHOD_PREFIX)) { - return; - } - const intentName = method.name.replace(GLUE42_FDC3_INTENTS_METHOD_PREFIX, ""); - const handler = await this.buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName); - callback(handler, intentName); - }); - } - buildIntentHandlerFromApp(app, intent) { - const handler = { - applicationName: app.name, - type: "app", - applicationDescription: app.caption, - applicationIcon: app.icon, - applicationTitle: app.title, - contextTypes: intent.contexts, - displayName: intent.displayName, - resultType: intent.resultType, - customConfig: intent.customConfig - }; - return handler; - } - async buildIntentHandlerFromServerMethod(eventMethod, server, method, intentName) { - const info = method.flags.intent; - const app = this.appManagerController.getApplication(server.application || server.applicationName); - let title; - if (eventMethod === "serverMethodAdded" && server.windowId) { - title = await (this.windowsController.findById(server.windowId))?.getTitle(); - } - const appIntent = app?.userProperties?.intents?.find((intent) => intent.name === intentName); - const handler = { - applicationName: server.application || server.applicationName || "", - instanceId: server.windowId || server.instance, - type: "instance", - applicationIcon: info?.icon || app?.icon, - applicationTitle: app?.title, - applicationDescription: info?.description || app?.caption, - contextTypes: info?.contextTypes || appIntent?.contexts, - instanceTitle: title, - displayName: info?.displayName || appIntent?.displayName, - resultType: info?.resultType || appIntent?.resultType, - customConfig: info?.customConfig - }; - return handler; - } - async clearSavedHandlers() { - this.logger.trace("Removing all saved handlers from prefs storage for current app"); - await this.prefsController.update({ intents: undefined }); - } - checkIfIntentsResolverIsEnabled(options) { - this.useIntentsResolverUI = typeof options.intents?.enableIntentsResolverUI === "boolean" - ? options.intents.enableIntentsResolverUI - : true; - this.intentsResolverAppName = options.intents?.intentsResolverAppName ?? INTENTS_RESOLVER_APP_NAME; - this.intentResolverResponseTimeout = options.intents?.methodResponseTimeoutMs ?? DEFAULT_RESOLVER_RESPONSE_TIMEOUT; - } - clearUnregistrationPromise(promiseToRemove) { - this.unregisterIntentPromises = this.unregisterIntentPromises.filter(promise => promise !== promiseToRemove); - } - buildInteropMethodName(intentName) { - return `${GLUE42_FDC3_INTENTS_METHOD_PREFIX}${intentName}`; - } - unsubscribeIntent(intentName) { - this.myIntents.delete(intentName); - const methodName = this.buildInteropMethodName(intentName); - const unregisterPromise = this.interop.unregister(methodName); - this.unregisterIntentPromises.push(unregisterPromise); - unregisterPromise - .then(() => { - this.clearUnregistrationPromise(unregisterPromise); - }) - .catch((err) => { - this.logger.error(`Unregistration of a method with name ${methodName} failed with reason: ${err}`); - this.clearUnregistrationPromise(unregisterPromise); - }); - } - async filterHandlers(handlerFilter) { - runDecoderWithIOError(handlerFilterDecoder, handlerFilter); - this.checkIfAtLeastOneFilterIsPresent(handlerFilter); - const embeddedResolverConfig = this.getEmbeddedResolverConfig(); - if (handlerFilter.openResolver && !this.useIntentsResolverUI && !embeddedResolverConfig.enabled) { - return ioError.raiseError("Cannot resolve 'filterHandlers' request using Intents Resolver UI because it's globally disabled"); - } - const methodResponseTimeoutMs = (handlerFilter.timeout || DEFAULT_PICK_HANDLER_BY_TIMEOUT) + ADDITIONAL_BRIDGE_OPERATION_TIMEOUT; - const filterHandlersRequestWithResolverConfig = { - filterHandlersRequest: handlerFilter, - resolverConfig: this.getLegacyResolverConfigByRequest({ handlerFilter }), - embeddedResolverConfig - }; - const result = await this.bridge.send("intents", operations$6.filterHandlers, filterHandlersRequestWithResolverConfig, { methodResponseTimeoutMs, waitTimeoutMs: methodResponseTimeoutMs }, { includeOperationCheck: true }); - return result; - } - checkIfAtLeastOneFilterIsPresent(filter) { - const errorMsg = "Provide at least one filter criteria of the following: 'intent' | 'contextTypes' | 'resultType' | 'applicationNames'"; - if (!Object.keys(filter).length) { - return ioError.raiseError(errorMsg); - } - const { intent, resultType, contextTypes, applicationNames } = filter; - const existingValidContextTypes = contextTypes?.length; - const existingValidApplicationNames = applicationNames?.length; - if (!intent && !resultType && !existingValidContextTypes && !existingValidApplicationNames) { - return ioError.raiseError(errorMsg); - } - } - async getIntentsByHandler(handler) { - runDecoderWithIOError(intentHandlerDecoder, handler); - const result = await this.bridge.send("intents", operations$6.getIntentsByHandler, handler, undefined, { includeOperationCheck: true }); - return result; - } - async removeRememberedHandler(intentName) { - this.logger.trace(`Removing saved handler from prefs storage for intent ${intentName}`); - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const intentPrefs = prefs.data?.intents; - if (!intentPrefs) { - this.logger.trace("No app prefs found for current app"); - return; - } - delete intentPrefs[intentName]; - const updatedPrefs = { - ...prefs.data, - intents: intentPrefs - }; - try { - await this.prefsController.update(updatedPrefs); - } - catch (error) { - this.logger.warn(`prefs.update() threw the following error: ${error}`); - return; - } - this.logger.trace(`Handler saved choice for intent ${intentName} removed successfully`); - } - async checkForRememberedHandler(intentRequest) { - let prefs; - try { - prefs = await this.prefsController.get(); - } - catch (error) { - this.logger.warn(`prefs.get() threw the following error: ${error}`); - return; - } - const prefsForIntent = prefs.data?.intents?.[intentRequest.intent]; - return prefsForIntent?.handler; - } - async checkHandleRaiseWithRememberedHandler(intentRequest) { - if (intentRequest.target) { - return; - } - const rememberedHandler = await this.checkForRememberedHandler(intentRequest); - if (!rememberedHandler) { - return; - } - const operationData = { - intentRequest: { - ...intentRequest, - target: { - app: rememberedHandler.applicationName, - instance: rememberedHandler.instanceId - } - }, - resolverConfig: this.getLegacyResolverConfigByRequest({ intentRequest }), - embeddedResolverConfig: this.getEmbeddedResolverConfig() - }; - try { - const response = await this.bridge.send("intents", operations$6.raise, operationData); - return response; - } - catch (error) { - this.logger.trace(`Could not raise intent to remembered handler. Reason: ${error}. Removing it from Prefs store`); - await this.removeRememberedHandler(intentRequest.intent); - } - } - } - - const operations$5 = { - appHello: { name: "appHello", dataDecoder: channelsAppHelloDataDecoder, resultDecoder: channelsAppHelloSuccessDecoder }, - addChannel: { name: "addChannel", dataDecoder: channelDefinitionDecoder }, - removeChannel: { name: "removeChannel", dataDecoder: removeChannelDataDecoder }, - getMyChannel: { name: "getMyChannel", resultDecoder: getMyChanelResultDecoder }, - getWindowIdsOnChannel: { name: "getWindowIdsOnChannel", dataDecoder: getWindowIdsOnChannelDataDecoder, resultDecoder: getWindowIdsOnChannelResultDecoder }, - getWindowIdsWithChannels: { name: "getWindowIdsWithChannels", dataDecoder: wrappedWindowWithChannelFilterDecoder, resultDecoder: getWindowIdsWithChannelsResultDecoder }, - joinChannel: { name: "joinChannel", dataDecoder: joinChannelDataDecoder }, - restrict: { name: "restrict", dataDecoder: restrictionConfigDataDecoder }, - getRestrictions: { name: "getRestrictions", dataDecoder: getRestrictionsDataDecoder, resultDecoder: restrictionsDecoder }, - restrictAll: { name: "restrictAll", dataDecoder: restrictAllDataDecoder }, - notifyChannelsChanged: { name: "notifyChannelsChanged", dataDecoder: channelsChangedDataDecoder }, - leaveChannel: { name: "leaveChannel", dataDecoder: leaveChannelDataDecoder }, - requestChannelSelector: { name: "requestChannelSelector", dataDecoder: requestChannelSelectorConfigDecoder }, - getMode: { name: "getMode", resultDecoder: getChannelsModeDecoder }, - operationCheck: { name: "operationCheck" }, - }; - - const DEFAULT_MODE = "single"; - const CHANNELS_PREFIX = "___channel___"; - const SUBS_KEY = "subs"; - const CHANGED_KEY = "changed"; - const CHANNELS_CHANGED = "channels_changed"; - const STORAGE_NAMESPACE = "io_connect_channels"; - const DEFAULT_STORAGE_MODE = "inMemory"; - - class ChannelsController { - supportedOperationsNames = []; - registry = CallbackRegistryFactory$1(); - logger; - contexts; - interop; - bridge; - windowsController; - _mode; - myWindowId; - storage; - handlePlatformShutdown() { - this.registry.clear(); - this.storage.clear(); - } - addOperationsExecutors() { - operations$5.getMyChannel.execute = this.handleGetMyChannel.bind(this); - operations$5.joinChannel.execute = this.handleJoinChannel.bind(this); - operations$5.leaveChannel.execute = this.handleLeaveChannel.bind(this); - operations$5.restrict.execute = this.handleRestrict.bind(this); - operations$5.getRestrictions.execute = ({ windowId }) => this.getRestrictions(windowId); - operations$5.restrictAll.execute = this.handleRestrictAll.bind(this); - operations$5.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$5); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("channels.controller.web"); - this.logger.trace("starting the web channels controller"); - this.contexts = coreGlue.contexts; - this.interop = coreGlue.interop; - this.addOperationsExecutors(); - this.bridge = ioc.bridge; - this.windowsController = ioc.windowsController; - this.storage = ioc.channelsStorage; - this.logger.trace("no need for platform registration, attaching the channels property to glue and returning"); - this.myWindowId = this.windowsController.my().id ?? this.interop.instance.instance; - await this.initialize(); - const api = this.toApi(); - coreGlue.channels = api; - } - async postStart(io, ioc) { - try { - await this.requestChannelSelector(io.appManager.myInstance); - } - catch (error) { - this.logger.warn(`Failed to display channel selector: ${extractErrorMsg(error)}`); - } - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(channelsOperationTypesDecoder, args.operation); - const operation = operations$5[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async list() { - const channelNames = this.getAllChannelNames(); - const channelContexts = await Promise.all(channelNames.map((channelName) => this.get(channelName))); - return channelContexts; - } - my() { - return this.current(); - } - async handleGetMyChannel() { - const channel = this.my(); - return channel ? { channel } : {}; - } - async join(name, windowId) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const joinData = { channel: name, windowId: windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.joinChannel, joinData, undefined, { includeOperationCheck: true }); - } - handleJoinChannel({ channel }) { - if (this._mode === "single") { - return this.switchToChannel(channel); - } - return this.joinAdditionalChannel(channel); - } - onChanged(callback) { - return this.changed(callback); - } - async leave(config = {}) { - runDecoderWithIOError(leaveChannelsConfig, config); - if (config.channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.channel); - } - const leaveData = { channelName: config.channel, windowId: config.windowId ?? this.myWindowId }; - await this.bridge.send("channels", operations$5.leaveChannel, leaveData, undefined, { includeOperationCheck: true }); - } - async handleAppManagerInitialChannelId(channel) { - if (this.storage.mode === "inMemory") { - return; - } - if (this.storage.getSessionStorageData()) { - return; - } - return this.handleJoinChannel({ channel, windowId: this.myWindowId }); - } - async handleLeaveChannel({ channelName }) { - const channelNamesToLeave = channelName ? [channelName] : this.storage.channels; - channelNamesToLeave.forEach((name) => this.storage.invokeUnsubscribes(name)); - this.storage.channels = this.storage.channels.filter((channelName) => !channelNamesToLeave.includes(channelName)); - this.executeChangedEvents(); - await this.notifyChannelsChanged(); - } - toApi() { - const api = { - mode: this._mode, - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - publish: this.publish.bind(this), - all: this.all.bind(this), - list: this.list.bind(this), - get: this.get.bind(this), - getMyChannels: this.getMyChannels.bind(this), - myChannels: this.myChannels.bind(this), - onChannelsChanged: this.onChannelsChanged.bind(this), - join: this.join.bind(this), - leave: this.leave.bind(this), - current: this.current.bind(this), - my: this.my.bind(this), - changed: this.changed.bind(this), - onChanged: this.onChanged.bind(this), - add: this.add.bind(this), - remove: this.remove.bind(this), - getMy: this.getMy.bind(this), - getWindowsOnChannel: this.getWindowsOnChannel.bind(this), - getWindowsWithChannels: this.getWindowsWithChannels.bind(this), - restrict: this.restrict.bind(this), - getRestrictions: this.getRestrictions.bind(this), - restrictAll: this.restrictAll.bind(this), - clearChannelData: this.clearChannelData.bind(this), - setPath: this.setPath.bind(this), - setPaths: this.setPaths.bind(this) - }; - return Object.freeze(api); - } - createContextName(channelName) { - return `${CHANNELS_PREFIX}${channelName}`; - } - getAllChannelNames() { - const contextNames = this.contexts.all(); - const channelContextNames = contextNames.filter((contextName) => contextName.startsWith(CHANNELS_PREFIX)); - const channelNames = channelContextNames.map((channelContextName) => channelContextName.replace(CHANNELS_PREFIX, "")); - return channelNames; - } - async joinAdditionalChannel(name) { - if (this.storage.channels.includes(name)) { - return; - } - this.storage.channels = [...this.storage.channels, name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - async switchToChannel(name) { - const currentChannel = this.storage.channels[0]; - if (name === currentChannel) { - return; - } - this.storage.invokeUnsubscribes(currentChannel); - this.storage.channels = [name]; - const contextName = this.createContextName(name); - const unsub = await this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }); - this.storage.addUnsubscribe(name, unsub); - this.executeChangedEvents(name); - await this.notifyChannelsChanged(); - } - executeChangedEvents(name) { - this.registry.execute(CHANGED_KEY, name); - this.registry.execute(CHANNELS_CHANGED, this.storage.channels); - } - async notifyChannelsChanged() { - const windowId = this.windowsController.my().id; - if (!windowId) { - return; - } - try { - await this.bridge.send("channels", operations$5.notifyChannelsChanged, { channelNames: this.storage.channels, windowId }, undefined, { includeOperationCheck: true }); - } - catch (error) { - this.logger.warn(`Failed to notify channel changed: ${extractErrorMsg(error)}`); - } - } - async updateData(name, data) { - const contextName = this.createContextName(name); - const fdc3Type = this.getFDC3Type(data); - if (this.contexts.setPathSupported) { - const pathValues = Object.keys(data).map((key) => { - return { - path: `data.${key}`, - value: data[key] - }; - }); - if (fdc3Type) { - pathValues.push({ path: latestFDC3Type, value: fdc3Type }); - } - await this.contexts.setPaths(contextName, pathValues); - } - else { - if (fdc3Type) { - data[latestFDC3Type] = fdc3Type; - } - await this.contexts.update(contextName, { data }); - } - } - getFDC3Type(data) { - const fdc3PropsArr = Object.keys(data).filter((key) => key.indexOf("fdc3_") === 0); - if (fdc3PropsArr.length === 0) { - return; - } - if (fdc3PropsArr.length > 1) { - return ioError.raiseError("FDC3 does not support updating of multiple context keys"); - } - return fdc3PropsArr[0].split("_").slice(1).join("_"); - } - subscribe(callback, options) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels, because the provided callback is not a function!"); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const currentChannel = this.current(); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - if (currentChannel) { - this.replaySubscribe(wrappedCallback, currentChannel); - } - return this.registry.add(SUBS_KEY, wrappedCallback); - } - async subscribeFor(name, callback, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (typeof callback !== "function") { - return ioError.raiseError(`Cannot subscribe to channel ${name}, because the provided callback is not a function!`); - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const wrappedCallback = options?.contextType - ? this.getWrappedSubscribeCallbackWithFdc3Type(callback, options.contextType) - : this.getWrappedSubscribeCallback(callback); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - wrappedCallback(context.data, context, delta, extraData?.updaterId); - }); - } - async publish(data, options) { - if (typeof data !== "object") { - return ioError.raiseError("Cannot publish to channel, because the provided data is not an object!"); - } - runDecoderWithIOError(publishOptionsDecoder, options); - if (typeof options === "object") { - return this.publishWithOptions(data, options); - } - if (typeof options === "string") { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options); - } - if (!options && this.storage.channels.length > 1) { - return this.publishOnMultipleChannels(data); - } - const channelName = typeof options === "string" ? options : this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - return this.updateData(channelName, data); - } - async all() { - const channelNames = this.getAllChannelNames(); - return channelNames; - } - async get(name, options) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), name); - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - const contextName = this.createContextName(name); - const channelContext = await this.contexts.get(contextName); - if (options?.contextType) { - return this.getContextForFdc3Type(channelContext, options.contextType); - } - if (channelContext.latest_fdc3_type) { - return this.getContextWithFdc3Data(channelContext); - } - return channelContext; - } - async getMyChannels() { - return Promise.all(this.storage.channels.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.get(contextName); - })); - } - myChannels() { - return this.storage.channels; - } - getContextForFdc3Type(channelContext, searchedType) { - const encodedType = `fdc3_${searchedType.split(".").join("&")}`; - if (!channelContext.data[encodedType]) { - return { - name: channelContext.name, - meta: channelContext.meta, - data: {} - }; - } - const fdc3Context = { type: searchedType, ...channelContext.data[encodedType] }; - return { - name: channelContext.name, - meta: channelContext.meta, - data: { fdc3: fdc3Context } - }; - } - getContextWithFdc3Data(channelContext) { - const { latest_fdc3_type, ...rest } = channelContext; - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Context = { type: parsedType, ...rest.data[`fdc3_${latest_fdc3_type}`] }; - delete rest.data[`fdc3_${latest_fdc3_type}`]; - const context = { - name: channelContext.name, - meta: channelContext.meta, - data: { - ...rest.data, - fdc3: fdc3Context - } - }; - return context; - } - current() { - return this.storage.channels[0]; - } - changed(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channel changed, because the provided callback is not a function!"); - } - return this.registry.add(CHANGED_KEY, callback); - } - async add(info) { - const channelContext = runDecoderWithIOError(channelDefinitionDecoder, info); - const channelWithSuchNameExists = this.getAllChannelNames().includes(channelContext.name); - if (channelWithSuchNameExists) { - return ioError.raiseError("There's an already existing channel with such name"); - } - await this.bridge.send("channels", operations$5.addChannel, channelContext); - return { - name: channelContext.name, - meta: channelContext.meta, - data: channelContext.data || {} - }; - } - async remove(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - const channelWithSuchNameExists = this.getAllChannelNames().includes(name); - if (!channelWithSuchNameExists) { - return ioError.raiseError("There's no channel with such name"); - } - await this.bridge.send("channels", operations$5.removeChannel, { name }, undefined, { includeOperationCheck: true }); - } - replaySubscribe = (callback, channelId) => { - this.get(channelId) - .then((channelContext) => { - if (!channelContext) { - return undefined; - } - const contextName = this.createContextName(channelContext.name); - return this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - callback(context.data, context, delta, extraData?.updaterId); - }); - }) - .then((un) => un?.()) - .catch(err => this.logger.trace(err)); - }; - async getMy(options) { - if (!this.storage.channels.length) { - return; - } - if (options) { - runDecoderWithIOError(fdc3OptionsDecoder, options); - } - return this.get(this.storage.channels[this.storage.channels.length - 1], options); - } - async getWindowsOnChannel(channel) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), channel); - const { windowIds } = await this.bridge.send("channels", operations$5.getWindowIdsOnChannel, { channel }, undefined, { includeOperationCheck: true }); - const result = windowIds.reduce((windows, windowId) => { - const window = this.windowsController.findById(windowId); - return window ? [...windows, window] : windows; - }, []); - return result; - } - async getWindowsWithChannels(filter) { - const operationData = filter !== undefined - ? { filter: runDecoderWithIOError(windowWithChannelFilterDecoder, filter) } - : {}; - const { windowIdsWithChannels } = await this.bridge.send("channels", operations$5.getWindowIdsWithChannels, operationData, undefined, { includeOperationCheck: true }); - const result = windowIdsWithChannels.reduce((windowsWithChannels, { application, channel, windowId }) => { - const window = this.windowsController.findById(windowId); - return window ? [...windowsWithChannels, { application, channel, window }] : windowsWithChannels; - }, []); - return result; - } - async clearChannelData(name) { - const paths = [ - { path: "data", value: {} }, - { path: "latest_fdc3_type", value: null }, - ]; - await this.handleSetPaths("clearChannelData", paths, name); - } - async restrict(config) { - runDecoderWithIOError(channelRestrictionsDecoder, config); - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), config.name); - const configData = { - config: { - ...config, - windowId: config.windowId ?? this.myWindowId - } - }; - await this.bridge.send("channels", operations$5.restrict, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrict({ config }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateRestriction(config); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateRestriction(config); - const isForCurrentChannel = config.name === currentChannel.name; - if (!isForCurrentChannel || prevReadAllowed || !config.read) { - return; - } - this.replaySubscribeCallback(config.name); - } - updateRestriction(config) { - const exists = this.storage.restrictions.some((r) => r.name === config.name); - this.storage.restrictions = exists - ? this.storage.restrictions.map((restriction) => restriction.name === config.name ? config : restriction) - : this.storage.restrictions.concat(config); - } - updateAllRestrictions(config) { - const allChannelNames = this.getAllChannelNames(); - this.storage.restrictions = allChannelNames.map((name) => ({ name, ...config })); - } - async getRestrictions(windowId) { - runDecoderWithIOError(optionalNonEmptyStringDecoder, windowId); - const forAnotherClient = windowId && windowId !== this.interop.instance.instance; - if (windowId && forAnotherClient) { - return this.bridge.send("channels", operations$5.getRestrictions, { windowId }, undefined, { includeOperationCheck: true }); - } - return { channels: this.storage.restrictions }; - } - async restrictAll(restrictions) { - runDecoderWithIOError(restrictionsConfigDecoder, restrictions); - const configData = { - restrictions: { - ...restrictions, - windowId: restrictions.windowId ?? this.myWindowId - } - }; - return this.bridge.send("channels", operations$5.restrictAll, configData, undefined, { includeOperationCheck: true }); - } - async handleRestrictAll({ restrictions }) { - const currentChannel = await this.getMy(); - if (!currentChannel) { - return this.updateAllRestrictions(restrictions); - } - const prevReadAllowed = this.isAllowedByRestrictions(currentChannel.name, "read"); - this.updateAllRestrictions(restrictions); - if (prevReadAllowed || !restrictions.read) { - return; - } - this.replaySubscribeCallback(currentChannel.name); - } - async setPath(path, name) { - const validatedPath = runDecoderWithIOError(pathValueDecoder, path); - const paths = [{ path: `data.${validatedPath.path}`, value: validatedPath.value }]; - await this.handleSetPaths("setPath", paths, name); - } - async setPaths(paths, name) { - const validatedPaths = runDecoderWithIOError(pathsValueDecoder, paths); - const dataPaths = validatedPaths.map(({ path, value }) => ({ path: `data.${path}`, value })); - await this.handleSetPaths("setPaths", dataPaths, name); - } - async handleSetPaths(operation, paths, name) { - const channelNamesToUpdate = name ? [name] : this.storage.channels; - if (!channelNamesToUpdate.length) { - return ioError.raiseError(`Cannot complete ${operation} operation, because channel is not specified. Either join one or pass a channel name as second argument!`); - } - this.validateChannelNames(channelNamesToUpdate); - const { allowed, forbidden } = this.groupChannelsByPermission("write", channelNamesToUpdate); - if (channelNamesToUpdate.length === forbidden.length) { - return ioError.raiseError(`Cannot complete ${operation} operation due to write restrictions to the following channels: ${channelNamesToUpdate.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Cannot set paths on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} due to write restrictions`); - } - await Promise.all(allowed.map((channelName) => { - const contextName = this.createContextName(channelName); - return this.contexts.setPaths(contextName, paths); - })); - } - validateChannelNames(names) { - const allChannelNames = this.getAllChannelNames(); - names.forEach((name) => runDecoderWithIOError(channelNameDecoder(allChannelNames), name)); - } - groupChannelsByPermission(action, channelNames) { - return channelNames.reduce((byFar, channelName) => { - const isAllowed = this.isAllowedByRestrictions(channelName, action); - if (isAllowed) { - byFar.allowed.push(channelName); - } - else { - byFar.forbidden.push(channelName); - } - return byFar; - }, { allowed: [], forbidden: [] }); - } - isAllowedByRestrictions(channelName, action) { - const restriction = this.storage.restrictions.find((restriction) => restriction.name === channelName); - return restriction ? restriction[action] : true; - } - replaySubscribeCallback(channelName) { - const contextName = this.createContextName(channelName); - this.contexts.subscribe(contextName, (context, delta, _, __, extraData) => { - this.registry.execute(SUBS_KEY, context.data, context, delta, extraData?.updaterId); - }).then((unsub) => { - if (unsub && typeof unsub === "function") { - unsub(); - } - }).catch(err => this.logger.error(err)); - } - async publishWithOptions(data, options) { - if (options.name) { - const channelNames = this.getAllChannelNames(); - runDecoderWithIOError(channelNameDecoder(channelNames), options.name); - } - const publishOnMultipleChannels = options.name ? false : this.storage.channels.length > 1; - if (publishOnMultipleChannels) { - return this.publishOnMultipleChannels(data, options.fdc3); - } - const channelName = options.name || this.storage.channels[0]; - if (!channelName) { - return ioError.raiseError("Cannot publish to channel, because not joined to a channel!"); - } - const canPublish = this.isAllowedByRestrictions(channelName, "write"); - if (!canPublish) { - return ioError.raiseError(`Cannot publish on channel ${channelName} due to restrictions`); - } - if (!options.fdc3) { - return this.updateData(channelName, data); - } - return this.publishFdc3Data(channelName, data); - } - async publishOnMultipleChannels(data, isFdc3) { - const { allowed, forbidden } = this.groupChannelsByPermission("write", this.storage.channels); - if (this.storage.channels.length === forbidden.length) { - return ioError.raiseError(`Cannot complete 'publish' operation due to write restrictions to all joined channels: ${this.storage.channels.join(", ")}`); - } - if (forbidden.length) { - this.logger.warn(`Data on channel${forbidden.length > 1 ? "s" : ""}: ${forbidden.join(", ")} won't be published due to write restrictions`); - } - const publishMethod = isFdc3 ? this.publishFdc3Data.bind(this) : this.updateData.bind(this); - await Promise.all(allowed.map((channelName) => publishMethod(channelName, data))); - } - async publishFdc3Data(channelName, data) { - runDecoderWithIOError(fdc3ContextDecoder, data); - const { type, ...rest } = data; - const parsedType = type.split(".").join("&"); - const fdc3DataToPublish = { [`fdc3_${parsedType}`]: rest }; - return this.updateData(channelName, fdc3DataToPublish); - } - getWrappedSubscribeCallback(callback) { - const wrappedCallback = (channelData, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const latestTypePropName = `fdc3_${latest_fdc3_type}`; - if (!latest_fdc3_type || (delta.data && !delta.data[latestTypePropName])) { - callback(channelData, context, updaterId); - return; - } - const parsedType = latest_fdc3_type.split("&").join("."); - const fdc3Data = { type: parsedType, ...data[latestTypePropName] }; - const { [latestTypePropName]: latestFDC3Type, ...rest } = channelData; - callback({ ...rest, fdc3: fdc3Data }, context, updaterId); - }; - return wrappedCallback; - } - getWrappedSubscribeCallbackWithFdc3Type(callback, fdc3Type) { - const didReplay = { replayed: false }; - const wrappedCallback = (_, context, delta, updaterId) => { - const canRead = this.isAllowedByRestrictions(context.name, "read"); - if (!canRead) { - return; - } - const { data, latest_fdc3_type } = context; - const searchedType = `fdc3_${fdc3Type.split(".").join("&")}`; - if (!data[searchedType] || (delta.data && !delta.data[searchedType])) { - return; - } - if (didReplay.replayed) { - return this.parseDataAndInvokeSubscribeCallback({ latestFdc3TypeEncoded: latest_fdc3_type, searchedType: fdc3Type, callback, context, updaterId }); - } - const fdc3Data = { type: fdc3Type, ...data[searchedType] }; - callback({ fdc3: fdc3Data }, context, updaterId); - didReplay.replayed = true; - }; - return wrappedCallback; - } - parseDataAndInvokeSubscribeCallback(args) { - const { latestFdc3TypeEncoded, searchedType, callback, context, updaterId } = args; - const latestPublishedType = latestFdc3TypeEncoded.split("&").join("."); - if (latestPublishedType !== searchedType) { - return; - } - const fdc3Data = { type: searchedType, ...context.data[`fdc3_${latestFdc3TypeEncoded}`] }; - callback({ fdc3: fdc3Data }, context, updaterId); - } - async requestChannelSelector(myInstance) { - if (!myInstance) { - return; - } - const myApplicationData = myInstance.application; - const myAppDetails = myApplicationData.userProperties?.details; - if (!myAppDetails) { - return; - } - if (!myAppDetails?.channelSelector?.enabled) { - return; - } - const windowId = myInstance.id; - const requestChannelSelectorConfig = { windowId, channelsNames: this.storage.channels }; - await this.bridge.send("channels", operations$5.requestChannelSelector, requestChannelSelectorConfig, undefined, { includeOperationCheck: true }); - } - async getPlatformChannelsMode() { - try { - const result = await this.bridge.send("channels", operations$5.getMode, {}, undefined, { includeOperationCheck: true }); - return result.mode; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - return DEFAULT_MODE; - } - } - onChannelsChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to channels changed, because the provided callback is not a function"); - } - return this.registry.add(CHANNELS_CHANGED, callback); - } - async initialize() { - const isAppHelloSupported = await this.checkIfAppHelloSupported(); - if (!isAppHelloSupported) { - return this.handleAppHelloFailure("Platform does not support 'appHello' operation and channel state persistence by windowId. Setting 'sessionStorage' mode for tracking channels and restrictions"); - } - const { success, error } = await this.sendAppHello(); - if (error) { - return this.handleAppHelloFailure(error); - } - this.logger.trace(`Received 'appHelloSuccess' message. Setting initial channels state to: ${JSON.stringify(success)}`); - const { mode, channels, restrictions } = success; - this.storage.mode = "inMemory"; - this._mode = mode; - this.storage.channels = channels; - this.storage.restrictions = restrictions; - } - async handleAppHelloFailure(errorMsg) { - this.logger.trace(errorMsg); - this.storage.mode = "sessionStorage"; - this._mode = await this.getPlatformChannelsMode(); - } - async sendAppHello() { - try { - const result = await this.bridge.send("channels", operations$5.appHello, { windowId: this.myWindowId }, undefined, { includeOperationCheck: true }); - return { success: result, error: undefined }; - } - catch (error) { - return { error: `Failed to get initial state from platform. Error: ${extractErrorMsg(error)}`, success: undefined }; - } - } - async checkIfAppHelloSupported() { - try { - const { isSupported } = await this.bridge.send("channels", operations$5.operationCheck, { operation: operations$5.appHello.name }, undefined, { includeOperationCheck: true }); - return isSupported; - } - catch (error) { - this.logger.trace(`Platform does not support 'appHello' operation and channel state persistence by windowId. Error: ${extractErrorMsg(error)}`); - return false; - } - } - } - - const operations$4 = { - getEnvironment: { name: "getEnvironment", resultDecoder: anyDecoder }, - getBase: { name: "getBase", resultDecoder: anyDecoder }, - platformShutdown: { name: "platformShutdown" }, - isFdc3DataWrappingSupported: { name: "isFdc3DataWrappingSupported" }, - clientError: { name: "clientError", dataDecoder: clientErrorDataDecoder }, - systemHello: { name: "systemHello", resultDecoder: systemHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" } - }; - - class SystemController { - supportedOperationsNames = []; - bridge; - ioc; - logger; - errorPort = errorChannel.port2; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("system.controller.web"); - this.logger.trace("starting the web system controller"); - this.bridge = ioc.bridge; - this.ioc = ioc; - this.addOperationsExecutors(); - let isClientErrorOperationSupported = false; - try { - const systemHelloSuccess = await this.bridge.send("system", operations$4.systemHello, undefined, undefined, { includeOperationCheck: true }); - isClientErrorOperationSupported = systemHelloSuccess.isClientErrorOperationSupported; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support some system operations."); - } - this.errorPort.onmessage = async (event) => { - if (!isClientErrorOperationSupported) { - return; - } - await this.bridge.send("system", operations$4.clientError, { message: event.data }, undefined, { includeOperationCheck: true }); - }; - await this.setEnvironment(); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(systemOperationTypesDecoder, args.operation); - const operation = operations$4[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async processPlatformShutdown() { - Object.values(this.ioc.controllers).forEach((controller) => controller.handlePlatformShutdown ? controller.handlePlatformShutdown() : null); - this.ioc.preferredConnectionController.stop(); - this.ioc.eventsDispatcher.stop(); - await this.bridge.stop(); - } - async setEnvironment() { - const environment = await this.bridge.send("system", operations$4.getEnvironment, undefined); - const base = await this.bridge.send("system", operations$4.getBase, undefined); - const globalNamespace = window.glue42core || window.iobrowser; - const globalNamespaceName = window.glue42core ? "glue42core" : "iobrowser"; - const globalObj = Object.assign({}, globalNamespace, base, { environment }); - window[globalNamespaceName] = globalObj; - } - addOperationsExecutors() { - operations$4.platformShutdown.execute = this.processPlatformShutdown.bind(this); - operations$4.isFdc3DataWrappingSupported.execute = this.handleIsFdc3DataWrappingSupported.bind(this); - operations$4.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$4); - } - async handleIsFdc3DataWrappingSupported() { - return { isSupported: true }; - } - } - - class Notification { - onclick = () => { }; - onshow = () => { }; - id; - title; - badge; - body; - data; - dir; - icon; - image; - lang; - renotify; - requireInteraction; - silent; - tag; - timestamp; - vibrate; - clickInterop; - actions; - focusPlatformOnDefaultClick; - severity; - showToast; - showInPanel; - state; - constructor(config, id) { - this.id = id; - this.badge = config.badge; - this.body = config.body; - this.data = config.data; - this.dir = config.dir; - this.icon = config.icon; - this.image = config.image; - this.lang = config.lang; - this.renotify = config.renotify; - this.requireInteraction = config.requireInteraction; - this.silent = config.silent; - this.tag = config.tag; - this.timestamp = config.timestamp; - this.vibrate = config.vibrate; - this.title = config.title; - this.clickInterop = config.clickInterop; - this.actions = config.actions; - this.focusPlatformOnDefaultClick = config.focusPlatformOnDefaultClick; - this.severity = config.severity; - this.showToast = config.showToast; - this.showInPanel = config.showInPanel; - this.state = config.state; - } - } - - oneOf$1(constant$2("clientHello")); - const extensionConfigDecoder = object$2({ - widget: object$2({ - inject: boolean$2() - }) - }); - - const operations$3 = { - clientHello: { name: "clientHello", resultDecoder: extensionConfigDecoder } - }; - - class ExtController { - windowId; - logger; - bridge; - eventsDispatcher; - channelsController; - config; - channels = []; - unsubFuncs = []; - contentCommands = { - widgetVisualizationPermission: { name: "widgetVisualizationPermission", handle: this.handleWidgetVisualizationPermission.bind(this) }, - changeChannel: { name: "changeChannel", handle: this.handleChangeChannel.bind(this) } - }; - handlePlatformShutdown() { - this.unsubFuncs.forEach((unsub) => unsub()); - this.channels = []; - this.unsubFuncs = []; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("extension.controller.web"); - this.windowId = ioc.publicWindowId; - this.logger.trace("starting the extension web controller"); - this.bridge = ioc.bridge; - this.channelsController = ioc.channelsController; - this.eventsDispatcher = ioc.eventsDispatcher; - try { - await this.registerWithPlatform(); - } - catch (error) { - return; - } - this.channels = await this.channelsController.list(); - const unsubDispatcher = this.eventsDispatcher.onContentMessage(this.handleContentMessage.bind(this)); - const unsubChannels = this.channelsController.onChanged((channel) => { - this.eventsDispatcher.sendContentMessage({ command: "channelChange", newChannel: channel }); - }); - this.unsubFuncs.push(unsubDispatcher); - this.unsubFuncs.push(unsubChannels); - } - async handleBridgeMessage(_) { - } - handleContentMessage(message) { - if (!message || typeof message.command !== "string") { - return; - } - const foundHandler = this.contentCommands[message.command]; - if (!foundHandler) { - return; - } - foundHandler.handle(message); - } - async registerWithPlatform() { - this.logger.trace("registering with the platform"); - this.config = await this.bridge.send("extension", operations$3.clientHello, { windowId: this.windowId }); - this.logger.trace("the platform responded to the hello message with a valid extension config"); - } - async handleWidgetVisualizationPermission() { - if (!this.config?.widget.inject) { - return this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: false }); - } - const currentChannel = this.channels.find((channel) => channel.name === this.channelsController.my()); - this.eventsDispatcher.sendContentMessage({ command: "permissionResponse", allowed: true, channels: this.channels, currentChannel }); - } - async handleChangeChannel(message) { - if (message.name === "no-channel") { - await this.channelsController.leave(); - return; - } - await this.channelsController.join(message.name); - } - } - - class EventsDispatcher { - config; - glue; - registry = CallbackRegistryFactory$1(); - glue42EventName = "Glue42"; - _handleMessage; - _resolveWidgetReadyPromise; - _resolveModalsUIFactoryReadyPromise; - _resolveIntentResolverUIFactoryReadyPromise; - constructor(config) { - this.config = config; - } - events = { - notifyStarted: { name: "notifyStarted", handle: this.handleNotifyStarted.bind(this) }, - contentInc: { name: "contentInc", handle: this.handleContentInc.bind(this) }, - requestGlue: { name: "requestGlue", handle: this.handleRequestGlue.bind(this) }, - widgetFactoryReady: { name: "widgetFactoryReady", handle: this.handleWidgetReady.bind(this) }, - modalsUIFactoryReady: { name: "modalsUIFactoryReady", handle: this.handleModalsUIFactoryReady.bind(this) }, - intentResolverUIFactoryReady: { name: "intentResolverUIFactoryReady", handle: this.handleIntentResolverUIFactoryReady.bind(this) }, - }; - stop() { - window.removeEventListener(this.glue42EventName, this._handleMessage); - } - start(glue) { - this.glue = glue; - this.wireCustomEventListener(); - this.announceStarted(); - } - sendContentMessage(message) { - this.send("contentOut", "glue42core", message); - } - onContentMessage(callback) { - return this.registry.add("content-inc", callback); - } - async widgetReady() { - const widgetReadyPromise = new Promise((resolve) => { - this._resolveWidgetReadyPromise = resolve; - }); - this.requestWidgetReady(); - return widgetReadyPromise; - } - async modalsUIFactoryReady() { - const modalsUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveModalsUIFactoryReadyPromise = resolve; - }); - this.requestModalsUIFactoryReady(); - return modalsUIFactoryReadyPromise; - } - async intentResolverUIFactoryReady() { - const intentResolverUIFactoryReadyPromise = new Promise((resolve) => { - this._resolveIntentResolverUIFactoryReadyPromise = resolve; - }); - this.requestIntentResolverUIFactoryReady(); - return intentResolverUIFactoryReadyPromise; - } - wireCustomEventListener() { - this._handleMessage = this.handleMessage.bind(this); - window.addEventListener(this.glue42EventName, this._handleMessage); - } - handleMessage(event) { - const data = event.detail; - const namespace = data?.glue42 ?? data?.glue42core; - if (!namespace) { - return; - } - const glue42Event = namespace.event; - const foundHandler = this.events[glue42Event]; - if (!foundHandler) { - return; - } - foundHandler.handle(namespace.message); - } - announceStarted() { - this.send("start", "glue42"); - } - handleRequestGlue() { - if (!this.config.exposeAPI) { - this.send("requestGlueResponse", "glue42", { error: "Will not give access to the underlying Glue API, because it was explicitly denied upon initialization." }); - return; - } - this.send("requestGlueResponse", "glue42", { glue: this.glue }); - } - handleNotifyStarted() { - this.announceStarted(); - } - handleContentInc(message) { - this.registry.execute("content-inc", message); - } - requestWidgetReady() { - this.send(REQUEST_WIDGET_READY, "glue42"); - } - handleWidgetReady() { - this._resolveWidgetReadyPromise?.(); - } - requestModalsUIFactoryReady() { - this.send(REQUEST_MODALS_UI_FACTORY_READY, "glue42"); - } - handleModalsUIFactoryReady() { - this._resolveModalsUIFactoryReadyPromise?.(); - } - requestIntentResolverUIFactoryReady() { - this.send(REQUEST_INTENT_RESOLVER_UI_FACTORY_READY, "glue42"); - } - handleIntentResolverUIFactoryReady() { - this._resolveIntentResolverUIFactoryReadyPromise?.(); - } - send(eventName, namespace, message) { - const payload = {}; - payload[namespace] = { event: eventName, message }; - const event = new CustomEvent(this.glue42EventName, { detail: payload }); - window.dispatchEvent(event); - } - } - - class PreferredConnectionController { - coreGlue; - transactionTimeout = 15000; - transactionLocks = {}; - webPlatformTransport; - webPlatformMessagesUnsubscribe; - reconnectCounter = 0; - logger; - constructor(coreGlue) { - this.coreGlue = coreGlue; - this.logger = this.coreGlue.logger.subLogger("web.preferred.connection.controller"); - } - stop() { - if (!this.webPlatformMessagesUnsubscribe) { - return; - } - this.webPlatformMessagesUnsubscribe(); - } - async start(coreConfig) { - if (coreConfig.isPlatformInternal) { - this.logger.trace("This is an internal client to the platform, skipping all client preferred communication logic."); - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - if (!isConnectedToPlatform) { - return ioError.raiseError("Cannot initiate the Glue Web Bridge, because the initial connection was not handled by a Web Platform transport."); - } - if (!this.coreGlue.connection.transport.isPreferredActivated) { - this.logger.trace("The platform of this client was configured without a preferred connection, skipping the rest of the initialization."); - return; - } - this.webPlatformTransport = this.coreGlue.connection.transport; - this.webPlatformMessagesUnsubscribe = this.webPlatformTransport.onMessage(this.handleWebPlatformMessage.bind(this)); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - handleWebPlatformMessage(msg) { - if (typeof msg === "string") { - return; - } - const isConnectedToPlatform = this.coreGlue.connection.transport.name() === webPlatformTransportName; - const type = msg.type; - const args = msg.args; - const transactionId = msg.transactionId; - if (type === Glue42CoreMessageTypes.transportSwitchRequest.name) { - return this.handleTransportSwitchRequest(args, transactionId); - } - if (type === Glue42CoreMessageTypes.platformUnload.name && !isConnectedToPlatform) { - return this.handlePlatformUnload(); - } - if (type === Glue42CoreMessageTypes.getCurrentTransportResponse.name) { - return this.handleGetCurrentTransportResponse(args, transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredLogic.name) { - return this.handleCheckPreferredLogic(transactionId); - } - if (type === Glue42CoreMessageTypes.checkPreferredConnection.name) { - return this.handleCheckPreferredConnection(args, transactionId); - } - } - async reEstablishPlatformPort() { - try { - await this.webPlatformTransport.connect(); - } - catch (error) { - this.logger.trace(`Error when re-establishing port connection to the platform: ${JSON.stringify(error)}`); - --this.reconnectCounter; - if (this.reconnectCounter > 0) { - return this.reEstablishPlatformPort(); - } - this.logger.warn("This client lost connection to the platform while connected to a preferred GW and was not able to re-connect to the platform."); - } - this.logger.trace("The connection to the platform was re-established, closing the connection to the web gateway."); - this.reconnectCounter = 0; - this.webPlatformTransport.close(); - const transportState = await this.getCurrentPlatformTransportState(); - await this.checkSwitchTransport(transportState); - } - async checkSwitchTransport(config) { - const myCurrentTransportName = this.coreGlue.connection.transport.name(); - if (myCurrentTransportName === config.transportName) { - this.logger.trace("A check switch was requested, but the platform transport and my transport are identical, no switch is necessary"); - return; - } - this.logger.trace(`A check switch was requested and a transport switch is necessary, because this client is now on ${myCurrentTransportName}, but it should reconnect to ${JSON.stringify(config)}`); - const result = await this.coreGlue.connection.switchTransport(config); - this.setConnected(); - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - } - async getCurrentPlatformTransportState() { - this.logger.trace("Requesting the current transport state of the platform."); - const transaction = this.setTransaction(Glue42CoreMessageTypes.getCurrentTransport.name); - this.sendPlatformMessage(Glue42CoreMessageTypes.getCurrentTransport.name, transaction.id); - const transportState = await transaction.lock; - this.logger.trace(`The platform responded with transport state: ${JSON.stringify(transportState)}`); - return transportState; - } - setTransaction(operation) { - const transaction = {}; - const transactionId = nanoid$1(10); - const transactionLock = new Promise((resolve, reject) => { - let transactionLive = true; - transaction.lift = (args) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - resolve(args); - }; - transaction.fail = (reason) => { - transactionLive = false; - delete this.transactionLocks[transactionId]; - reject(reason); - }; - setTimeout(() => { - if (!transactionLive) { - return; - } - transactionLive = false; - this.logger.warn(`Transaction for operation: ${operation} timed out.`); - delete this.transactionLocks[transactionId]; - reject(`Transaction for operation: ${operation} timed out.`); - }, this.transactionTimeout); - }); - transaction.lock = transactionLock; - transaction.id = transactionId; - this.transactionLocks[transactionId] = transaction; - return transaction; - } - sendPlatformMessage(type, transactionId, args) { - this.logger.trace(`Sending a platform message of type: ${type}, id: ${transactionId} and args: ${JSON.stringify(args)}`); - this.webPlatformTransport.sendObject({ - glue42core: { type, args, transactionId } - }); - } - handleTransportSwitchRequest(args, transactionId) { - this.logger.trace(`Received a transport switch request with id: ${transactionId} and data: ${JSON.stringify(args)}`); - this.coreGlue.connection.switchTransport(args.switchSettings) - .then((result) => { - this.logger.trace(`The transport switch was completed with result: ${JSON.stringify(result)}`); - this.setConnected(); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: result.success }); - }) - .catch((error) => { - this.logger.error(error); - this.sendPlatformMessage(Glue42CoreMessageTypes.transportSwitchResponse.name, transactionId, { success: false }); - }); - } - handlePlatformUnload() { - this.reconnectCounter = 5; - this.logger.trace("The platform was unloaded while I am connected to a preferred connection, re-establishing the port connection."); - this.reEstablishPlatformPort(); - } - handleGetCurrentTransportResponse(args, transactionId) { - this.logger.trace(`Got a current transport response from the platform with id: ${transactionId} and data: ${JSON.stringify(args)}`); - const transportState = args.transportState; - const transaction = this.transactionLocks[transactionId]; - transaction?.lift(transportState); - } - handleCheckPreferredLogic(transactionId) { - setTimeout(() => this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredLogicResponse.name, transactionId), 0); - } - handleCheckPreferredConnection(args, transactionId) { - const url = args.url; - this.logger.trace(`Testing the possible connection to: ${url}`); - this.checkPreferredConnection(url) - .then((result) => { - this.logger.trace(`The connection to ${url} is possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, result); - }) - .catch((error) => { - this.logger.trace(`The connection to ${url} is not possible`); - this.sendPlatformMessage(Glue42CoreMessageTypes.checkPreferredConnectionResponse.name, transactionId, { error }); - }); - } - checkPreferredConnection(url) { - return new Promise((resolve) => { - const ws = new WebSocket(url); - ws.onerror = () => resolve({ live: false }); - ws.onopen = () => { - ws.close(); - resolve({ live: true }); - }; - }); - } - setConnected() { - this.webPlatformTransport.manualSetReadyState(); - } - } - - const operations$2 = { - getCurrent: { name: "getCurrent", resultDecoder: simpleThemeResponseDecoder }, - list: { name: "list", resultDecoder: allThemesResponseDecoder }, - select: { name: "select", dataDecoder: selectThemeConfigDecoder } - }; - - class ThemesController { - logger; - bridge; - registry = CallbackRegistryFactory$1(); - themesSubscription; - activeThemeSubs = 0; - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("themes.controller.web"); - this.logger.trace("starting the web themes controller"); - this.bridge = ioc.bridge; - const api = this.toApi(); - coreGlue.themes = api; - this.logger.trace("themes are ready"); - } - handlePlatformShutdown() { - this.registry.clear(); - this.activeThemeSubs = 0; - this.themesSubscription?.close(); - delete this.themesSubscription; - } - async handleBridgeMessage() { - } - toApi() { - const api = { - getCurrent: this.getCurrent.bind(this), - list: this.list.bind(this), - select: this.select.bind(this), - onChanged: this.onChanged.bind(this) - }; - return Object.freeze(api); - } - async getCurrent() { - const bridgeResponse = await this.bridge.send("themes", operations$2.getCurrent, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.theme; - } - async list() { - const bridgeResponse = await this.bridge.send("themes", operations$2.list, undefined, undefined, { includeOperationCheck: true }); - return bridgeResponse.themes; - } - async select(name) { - runDecoderWithIOError(nonEmptyStringDecoder$2, name); - await this.bridge.send("themes", operations$2.select, { name }, undefined, { includeOperationCheck: true }); - } - async onChanged(callback) { - if (typeof callback !== "function") { - return ioError.raiseError("onChanged requires a callback of type function"); - } - const subReady = this.themesSubscription ? - Promise.resolve() : - this.configureThemeSubscription(); - await subReady; - ++this.activeThemeSubs; - const unsubFunc = this.registry.add("on-theme-change", callback); - return () => this.themeUnsub(unsubFunc); - } - async configureThemeSubscription() { - if (this.themesSubscription) { - return; - } - this.themesSubscription = await this.bridge.createNotificationsSteam(); - this.themesSubscription.onData((data) => { - const eventData = data.data; - const validation = simpleThemeResponseDecoder.run(eventData); - if (!validation.ok) { - this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`); - return; - } - const themeChanged = validation.result; - this.registry.execute("on-theme-change", themeChanged.theme); - }); - this.themesSubscription.onClosed(() => { - this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received"); - this.registry.clear(); - this.activeThemeSubs = 0; - delete this.themesSubscription; - }); - } - themeUnsub(registryUnsub) { - registryUnsub(); - --this.activeThemeSubs; - if (this.activeThemeSubs) { - return; - } - this.themesSubscription?.close(); - delete this.themesSubscription; - } - } - - class ChannelsStorage { - sessionStorage = window.sessionStorage; - _mode = DEFAULT_STORAGE_MODE; - inMemoryChannels = []; - inMemoryRestrictions = []; - _unsubscribeDict = {}; - clear() { - this._mode = DEFAULT_STORAGE_MODE; - this.inMemoryChannels = []; - this.inMemoryRestrictions = []; - this._unsubscribeDict = {}; - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify([])); - } - get mode() { - return this._mode; - } - set mode(mode) { - this._mode = mode; - } - get channels() { - if (this.mode === "inMemory") { - return this.inMemoryChannels.slice(); - } - return this.getSessionStorageData()?.channels ?? []; - } - set channels(channels) { - if (this.mode === "inMemory") { - this.inMemoryChannels = channels; - } - this.setSessionStorageChannels(channels); - } - get restrictions() { - if (this.mode === "inMemory") { - return this.inMemoryRestrictions.slice(); - } - return this.getSessionStorageData()?.restrictions ?? []; - } - set restrictions(restrictions) { - if (this.mode === "inMemory") { - this.inMemoryRestrictions = restrictions; - } - this.setSessionStorageRestrictions(restrictions); - } - getSessionStorageData() { - return JSON.parse(this.sessionStorage.getItem(STORAGE_NAMESPACE) || "null"); - } - addUnsubscribe(channel, unsubscribe) { - this._unsubscribeDict[channel] = unsubscribe; - } - invokeUnsubscribes(channel) { - if (channel) { - this._unsubscribeDict[channel]?.(); - delete this._unsubscribeDict[channel]; - return; - } - Object.values(this._unsubscribeDict).forEach((unsub) => unsub()); - this._unsubscribeDict = {}; - } - setSessionStorageChannels(channels) { - const data = this.getSessionStorageData(); - if (data?.channels) { - data.channels = channels; - return this.setSessionStorageData(data); - } - const newData = { channels, restrictions: data?.restrictions ?? [] }; - return this.setSessionStorageData(newData); - } - setSessionStorageRestrictions(restrictions) { - const data = this.getSessionStorageData(); - if (data?.restrictions) { - data.restrictions = restrictions; - return this.setSessionStorageData(data); - } - const newData = { channels: data?.channels ?? [], restrictions }; - return this.setSessionStorageData(newData); - } - setSessionStorageData(data) { - this.sessionStorage.setItem(STORAGE_NAMESPACE, JSON.stringify(data)); - } - } - - const operations$1 = { - clear: { name: "clear", dataDecoder: basePrefsConfigDecoder }, - clearAll: { name: "clearAll" }, - get: { name: "get", dataDecoder: basePrefsConfigDecoder, resultDecoder: getPrefsResultDecoder }, - getAll: { name: "getAll", resultDecoder: getAllPrefsResultDecoder }, - set: { name: "set", dataDecoder: changePrefsDataDecoder }, - update: { name: "update", dataDecoder: changePrefsDataDecoder }, - prefsChanged: { name: "prefsChanged", dataDecoder: getPrefsResultDecoder }, - prefsHello: { name: "prefsHello", resultDecoder: prefsHelloSuccessDecoder }, - operationCheck: { name: "operationCheck" }, - registerSubscriber: { name: "registerSubscriber", dataDecoder: subscriberRegisterConfigDecoder }, - }; - - class PrefsController { - supportedOperationsNames = []; - bridge; - config; - logger; - appManagerController; - platformAppName; - registry = CallbackRegistryFactory$1(); - validNonExistentApps; - signaledSubscription = false; - interopId; - handlePlatformShutdown() { - this.registry.clear(); - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("prefs.controller.web"); - this.logger.trace("starting the web prefs controller"); - this.addOperationsExecutors(); - this.interopId = coreGlue.interop.instance.instance; - this.bridge = ioc.bridge; - this.config = ioc.config; - this.appManagerController = ioc.appManagerController; - try { - const prefsHelloSuccess = await this.bridge.send("prefs", operations$1.prefsHello, undefined, undefined, { includeOperationCheck: true }); - this.platformAppName = prefsHelloSuccess.platform.app; - this.validNonExistentApps = prefsHelloSuccess.validNonExistentApps ?? []; - } - catch (error) { - this.logger.warn("The platform of this client is outdated and does not support Prefs API."); - return; - } - this.logger.trace("no need for platform registration, attaching the prefs property to glue and returning"); - const api = this.toApi(); - coreGlue.prefs = api; - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(prefsOperationTypesDecoder, args.operation); - const operation = operations$1[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async get(app) { - const verifiedApp = app === undefined || app === null ? this.getMyAppName() : runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const { prefs } = await this.bridge.send("prefs", operations$1.get, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - return prefs; - } - async update(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.updateFor(app, data); - } - addOperationsExecutors() { - operations$1.prefsChanged.execute = this.handleOnChanged.bind(this); - operations$1.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - this.supportedOperationsNames = getSupportedOperationsNames(operations$1); - } - toApi() { - const api = { - clear: this.clear.bind(this), - clearAll: this.clearAll.bind(this), - clearFor: this.clearFor.bind(this), - get: this.get.bind(this), - getAll: this.getAll.bind(this), - set: this.set.bind(this), - setFor: this.setFor.bind(this), - subscribe: this.subscribe.bind(this), - subscribeFor: this.subscribeFor.bind(this), - update: this.update.bind(this), - updateFor: this.updateFor.bind(this), - }; - return api; - } - async clear() { - const app = this.getMyAppName(); - await this.clearFor(app); - } - async clearAll() { - await this.bridge.send("prefs", operations$1.clearAll, undefined, undefined, { includeOperationCheck: true }); - } - async clearFor(app) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - await this.bridge.send("prefs", operations$1.clear, { app: verifiedApp }, undefined, { includeOperationCheck: true }); - } - async getAll() { - const result = await this.bridge.send("prefs", operations$1.getAll, undefined, undefined, { includeOperationCheck: true }); - return result; - } - async set(data, options) { - const verifiedOptions = runDecoderWithIOError(optional$2(basePrefsConfigDecoder), options); - const app = verifiedOptions?.app ?? this.getMyAppName(); - await this.setFor(app, data); - } - async setFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.set, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - subscribe(callback) { - const app = this.getMyAppName(); - return this.subscribeFor(app, callback); - } - subscribeFor(app, callback) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const applications = this.appManagerController.getApplications(); - const isValidApp = verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp); - if (!isValidApp) { - return ioError.raiseError(`The provided app name "${app}" is not valid.`); - } - if (typeof callback !== "function") { - return ioError.raiseError("Cannot subscribe to prefs, because the provided callback is not a function!"); - } - if (!this.signaledSubscription) { - this.bridge.send("prefs", operations$1.registerSubscriber, { interopId: this.interopId, appName: verifiedApp }, undefined, { includeOperationCheck: true }) - .catch((error) => { - this.logger.warn("Failed to register subscriber for prefs"); - this.logger.error(error); - }); - this.signaledSubscription = true; - } - const subscriptionKey = this.getSubscriptionKey(verifiedApp); - this.get(verifiedApp).then(callback); - return this.registry.add(subscriptionKey, callback); - } - async updateFor(app, data) { - const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app); - const verifiedData = runDecoderWithIOError(object$2(), data); - await this.bridge.send("prefs", operations$1.update, { app: verifiedApp, data: verifiedData }, undefined, { includeOperationCheck: true }); - } - getMyAppName() { - const myAppName = this.config.isPlatformInternal ? this.platformAppName : this.appManagerController.me?.application.name; - if (!myAppName) { - return ioError.raiseError("App Preferences operations can not be executed for windows that do not have app!"); - } - return myAppName; - } - getSubscriptionKey(app) { - return `prefs-changed-${app}`; - } - async handleOnChanged({ prefs }) { - const subscriptionKey = this.getSubscriptionKey(prefs.app); - this.registry.execute(subscriptionKey, prefs); - } - } - - const operations = { - getResources: { name: "getResources", dataDecoder: getResourcesDataDecoder, resultDecoder: getResourcesResultDecoder }, - operationCheck: { name: "operationCheck", dataDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - showAlert: { name: "showAlert", dataDecoder: uiAlertRequestMessageDecoder }, - showDialog: { name: "showDialog", dataDecoder: uiDialogRequestMessageDecoder }, - alertInteropAction: { name: "alertInteropAction", dataDecoder: alertInteropActionDataDecoder }, - showResolver: { name: "showResolver", dataDecoder: uiResolverRequestMessageDecoder, resultDecoder: uiResolverResponseMessageDecoder }, - }; - - const DEFAULT_ALERT_TTL = 5 * 1000; - const MODALS_SHADOW_HOST_ID = "io-modals-shadow-host"; - const MODALS_ROOT_ELEMENT_ID = "io-modals-root"; - const WIDGET_SHADOW_HOST_ID = "io-widget-shadow-host"; - const WIDGET_ROOT_ELEMENT_ID = "io-widget-root"; - const INTENT_RESOLVER_SHADOW_HOST_ID = "io-intent-resolver-shadow-host"; - const INTENT_RESOLVER_ROOT_ELEMENT_ID = "io-intent-resolver-root"; - const SHADOW_ROOT_ELEMENT_CLASSNAME = "io-body io-variables"; - - class UIController { - ioc; - supportedOperationsNames = []; - logger; - bridge; - config; - zIndexDictionary = { - [WIDGET_SHADOW_HOST_ID]: "100", - [MODALS_SHADOW_HOST_ID]: "101", - [INTENT_RESOLVER_SHADOW_HOST_ID]: "100" - }; - widgetResources; - modalsResources; - intentResolverResources; - modalsUiApi; - isDialogOpen = false; - intentResolverUiApi; - isIntentResolverOpen = false; - constructor(ioc) { - this.ioc = ioc; - } - async start(coreGlue, ioc) { - this.logger = coreGlue.logger.subLogger("ui.controller.web"); - this.logger.trace("starting the ui controller"); - this.bridge = ioc.bridge; - this.config = ioc.config; - this.addOperationsExecutors(); - const resources = await this.getResources(); - if (!resources) { - this.logger.trace("No UI elements to display - platform is not initialized with any UI resources"); - return; - } - this.logger.trace(`Received UI resources from platform: ${JSON.stringify(resources)}`); - this.setResources(resources); - } - async handleBridgeMessage(args) { - const operationName = runDecoderWithIOError(uiOperationTypesDecoder, args.operation); - const operation = operations[operationName]; - if (!operation.execute) { - return; - } - let operationData = args.data; - if (operation.dataDecoder) { - operationData = runDecoderWithIOError(operation.dataDecoder, args.data); - } - return await operation.execute(operationData); - } - async showComponents(io) { - const initializeWidgetPromise = this.widgetResources ? this.initializeWidget(io, this.widgetResources) : Promise.resolve(); - const initializeModalsPromise = this.modalsResources ? this.initializeModalsUi(io, this.modalsResources) : Promise.resolve(); - const initializeIntentResolverPromise = this.intentResolverResources ? this.initializeIntentResolverUI(io, this.intentResolverResources) : Promise.resolve(); - await Promise.all([ - this.config.widget.awaitFactory ? initializeWidgetPromise : Promise.resolve(), - this.config.modals.awaitFactory ? initializeModalsPromise : Promise.resolve(), - this.config.intentResolver.awaitFactory ? initializeIntentResolverPromise : Promise.resolve(), - ]); - } - isIntentResolverEnabled() { - return !!this.intentResolverResources && this.config.intentResolver.enable; - } - addOperationsExecutors() { - operations.operationCheck.execute = async (config) => handleOperationCheck(this.supportedOperationsNames, config.operation); - operations.showAlert.execute = this.handleShowAlert.bind(this); - operations.showDialog.execute = this.handleShowDialog.bind(this); - operations.showResolver.execute = this.handleShowResolver.bind(this); - this.supportedOperationsNames = getSupportedOperationsNames(operations); - } - async handleShowAlert({ config }) { - if (!this.config.modals.alerts.enabled) { - return ioError.raiseError("Unable to perform showAlert operation because the client was initialized with 'modals: { alerts: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showAlert operation because modalsUiApi is missing."); - } - const { promise: closePromise, resolve: resolveClosePromise } = wrapPromise(); - const onClick = (config) => { - const decodedConfig = alertOnClickConfigDecoder.run(config); - if (!decodedConfig.ok) { - this.logger.error(`alert.onClick() was invoked with an invalid config. Error: ${JSON.stringify(decodedConfig.error)}.`); - return; - } - const { interopAction } = decodedConfig.result; - this.bridge.send("ui", operations.alertInteropAction, { interopAction }, undefined, { includeOperationCheck: true }) - .catch((error) => this.logger.warn(extractErrorMsg(error))); - }; - let result; - try { - this.logger.trace(`Open alert with config: ${JSON.stringify(config)}`); - result = modalsUiApi.alerts.open({ ...config, onClick, onClose: resolveClosePromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.alerts.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openAlertResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.alerts.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - const timeoutId = setTimeout(() => { - resolveClosePromise(); - }, getSafeTimeoutDelay(config.ttl ?? DEFAULT_ALERT_TTL)); - closePromise.then(() => { - clearTimeout(timeoutId); - try { - modalsUiApi.alerts.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close alert with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - }); - } - async handleShowDialog({ config }) { - if (!this.config.modals.dialogs.enabled) { - return ioError.raiseError("Unable to perform showDialog operation because the client was initialized with 'modals: { dialogs: { enabled: false } }' config."); - } - const modalsUiApi = this.modalsUiApi; - if (!modalsUiApi) { - return ioError.raiseError("Unable to perform showDialog operation because modalsUiApi is missing."); - } - if (this.isDialogOpen) { - return ioError.raiseError("Cannot open a dialog because another one is already open."); - } - const { promise: completionPromise, resolve: resolveCompletionPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open dialog with config: ${JSON.stringify(config)}`); - result = modalsUiApi.dialogs.open({ ...config, onCompletion: resolveCompletionPromise }); - } - catch (error) { - return ioError.raiseError(`modalsUiApi.dialogs.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodeResult = openDialogResultDecoder.run(result); - if (!decodeResult.ok) { - return ioError.raiseError(`modalsUiApi.dialogs.open() returned an invalid result. Error: ${JSON.stringify(decodeResult.error)}.`); - } - this.isDialogOpen = true; - let timeoutId; - if (config.timer) { - timeoutId = setTimeout(() => { - resolveCompletionPromise({ response: { isExpired: true } }); - }, getSafeTimeoutDelay(config.timer.duration)); - } - const response = await completionPromise; - clearTimeout(timeoutId); - this.isDialogOpen = false; - try { - modalsUiApi.dialogs.close({ id: decodeResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close dialog with id ${decodeResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodeResponse = dialogOnCompletionConfigDecoder.run(response); - if (!decodeResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodeResponse.error)}.`); - } - return { result: decodeResponse.result.response }; - } - async handleShowResolver({ config }) { - this.logger.trace(`Received open intent resolver request with config: ${JSON.stringify(config)}`); - if (!this.config.intentResolver.enable) { - return ioError.raiseError("Unable to perform showResolver operation because the client was initialized with 'intentResolver: { enable: false }' config."); - } - const intentResolverApi = this.intentResolverUiApi; - if (!intentResolverApi) { - return ioError.raiseError("Unable to perform showResolver operation because intentResolverApi is missing."); - } - if (this.isIntentResolverOpen) { - return ioError.raiseError("Cannot open the intent resolver because another one is already open."); - } - const { promise: completionPromise, resolve: resolveIntentResolverPromise } = wrapPromise(); - let result; - try { - this.logger.trace(`Open intent resolver with config: ${JSON.stringify(config)}`); - result = intentResolverApi.open({ ...config, onUserResponse: resolveIntentResolverPromise }); - } - catch (error) { - return ioError.raiseError(`intentResolverUI.open() failed. Reason: ${extractErrorMsg(error)}.`); - } - const decodedOpenResult = openResolverResultDecoder.run(result); - if (!decodedOpenResult.ok) { - return ioError.raiseError(`intentResolverUI.open() returned an invalid result. Error: ${JSON.stringify(decodedOpenResult.error)}.`); - } - const timer = setTimeout(() => resolveIntentResolverPromise({ response: { isExpired: true } }), getSafeTimeoutDelay(config.timeout)); - const response = await completionPromise; - clearTimeout(timer); - this.isIntentResolverOpen = false; - try { - intentResolverApi.close({ id: decodedOpenResult.result.id }); - } - catch (error) { - this.logger.warn(`Failed to close intent resolver with id ${decodedOpenResult.result.id}. Reason: ${extractErrorMsg(error)}`); - } - const decodedResponse = onUserResponseResponseDecoder.run(response); - if (!decodedResponse.ok) { - return ioError.raiseError(`completionPromise was resolved with an invalid result. Error: ${JSON.stringify(decodedResponse.error)}.`); - } - return { result: decodedResponse.result.response }; - } - async getResources() { - const data = { - origin: window.origin - }; - try { - const result = await this.bridge.send("ui", operations.getResources, data, undefined, { includeOperationCheck: true }); - return result.resources; - } - catch (error) { - this.logger.warn(error?.message || JSON.stringify(error)); - } - } - appendModalsResources(resources) { - this.logger.trace("Appending modals resources"); - return this.appendResources(MODALS_SHADOW_HOST_ID, MODALS_ROOT_ELEMENT_ID, resources.sources); - } - appendWidgetResources(resources) { - this.logger.trace("Appending widget resources"); - return this.appendResources(WIDGET_SHADOW_HOST_ID, WIDGET_ROOT_ELEMENT_ID, resources.sources); - } - appendIntentResolverResources(resources) { - this.logger.trace("Appending intent resolver resources"); - return this.appendResources(INTENT_RESOLVER_SHADOW_HOST_ID, INTENT_RESOLVER_ROOT_ELEMENT_ID, resources.sources); - } - appendResources(shadowHostId, rootElementId, sources) { - const { bundle, fonts = [], styles } = sources; - const shadowHost = document.createElement("div"); - shadowHost.id = shadowHostId; - shadowHost.style.position = "fixed"; - shadowHost.style.zIndex = this.zIndexDictionary[shadowHostId]; - const shadowRoot = shadowHost.attachShadow({ mode: "open" }); - const script = document.createElement("script"); - script.src = bundle; - script.type = "module"; - shadowRoot.appendChild(script); - const rootElement = document.createElement("div"); - rootElement.id = rootElementId; - rootElement.className = SHADOW_ROOT_ELEMENT_CLASSNAME; - shadowRoot.appendChild(rootElement); - styles.forEach((style) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = style; - shadowRoot.appendChild(link); - }); - fonts.forEach((font) => { - const link = document.createElement("link"); - link.rel = "stylesheet"; - link.href = font; - document.head.insertBefore(link, document.head.firstChild); - }); - document.body.appendChild(shadowHost); - return { rootElement }; - } - async initializeWidget(io, resources) { - this.logger.trace("Initializing IOBrowserWidget."); - const { rootElement } = this.appendWidgetResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...deepmerge$1(resources.config, this.config.widget), - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.widgetReady(); - this.logger.trace(`IOBrowserWidget factory is available. Invoking it with config: ${JSON.stringify(config)}`); - await window.IOBrowserWidget(io, config); - this.logger.trace("IOBrowserWidget was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserWidget to initialize.`); - } - async initializeModalsUi(io, resources) { - this.logger.trace("Initializing IOBrowserModalsUI."); - const { rootElement } = this.appendModalsResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.modals, - rootElement - }; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.modalsUIFactoryReady(); - this.logger.trace(`IOBrowserModalsUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.modalsUiApi = await window.IOBrowserModalsUI(io, config); - this.logger.trace("IOBrowserModalsUI was initialized successfully."); - }, config.timeout, `Timeout of ${config.timeout}ms hit waiting for IOBrowserModalsUI to initialize.`); - } - async initializeIntentResolverUI(io, resources) { - this.logger.trace("Initializing IOBrowserIntentResolverUI."); - const { rootElement } = this.appendIntentResolverResources(resources); - this.subscribeForThemeChanges(io, rootElement); - const config = { - ...this.config.intentResolver, - rootElement - }; - const timeout = config.timeout; - return PromiseWrap(async () => { - await this.ioc.eventsDispatcher.intentResolverUIFactoryReady(); - this.logger.trace(`IOBrowserIntentResolverUI factory is available. Invoking it with config: ${JSON.stringify(config)}`); - this.intentResolverUiApi = await window.IOBrowserIntentResolverUI(io, config); - this.logger.trace("IOBrowserIntentResolverUI initialized successfully."); - }, timeout, `Timeout of ${timeout}ms hit waiting for IOBrowserIntentResolverUI to initialize.`); - } - setResources(resources) { - this.setWidgetResources(resources.widget); - this.setModalsUiResources(resources.modals); - this.setIntentResolverResources(resources.intentResolver); - } - setWidgetResources(resources) { - const baseMsg = "Widget won't be displayed. Reason: "; - const decodedConfig = widgetConfigDecoder.run(this.config.widget); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid widget config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.widget.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'widget: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving widget resources`); - return; - } - this.widgetResources = resources; - } - setModalsUiResources(resources) { - const baseMsg = "Modals won't be displayed. Reason: "; - const decodedConfig = modalsConfigDecoder.run(this.config.modals); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid modals config. Error: ${decodedConfig.error}`); - return; - } - if (!this.config.modals.alerts.enabled && !this.config.modals.dialogs.enabled) { - this.logger.trace(`${baseMsg} Client initialized with 'modals: { alerts: { enabled: false }, dialogs: { enabled: false } }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving modals resources`); - return; - } - this.modalsResources = resources; - } - setIntentResolverResources(resources) { - const baseMsg = "Intent Resolver UI won't be displayed. Reason: "; - const decodedConfig = intentResolverConfigDecoder.run(this.config.intentResolver); - if (!decodedConfig.ok) { - this.logger.warn(`${baseMsg} invalid intent resolver config. Error: ${JSON.stringify(decodedConfig.error)}`); - return; - } - if (!this.config.intentResolver.enable) { - this.logger.trace(`${baseMsg} Client initialized with 'intentResolver: { enable: false }' config`); - return; - } - if (!resources) { - this.logger.trace(`${baseMsg} Platform did not provide resources`); - return; - } - if (resources.blockedOrigin) { - this.logger.warn(`${baseMsg} Platform has blocked client's origin ('${window.location.toString()}') from retrieving intent resolver resources`); - return; - } - this.intentResolverResources = resources; - } - subscribeForThemeChanges(io, element) { - const themesApi = io.themes; - if (!themesApi) { - return; - } - const changeTheme = async (theme) => { - if (element.classList.contains(theme.name)) { - return; - } - const allThemes = await themesApi.list(); - element.classList.remove(...allThemes.map(({ name }) => name)); - element.classList.add(theme.name); - }; - themesApi.onChanged(changeTheme); - themesApi.getCurrent().then(changeTheme); - } - } - - class IoC { - _coreGlue; - _communicationId; - _publicWindowId; - _webConfig; - _windowsControllerInstance; - _appManagerControllerInstance; - _layoutsControllerInstance; - _notificationsControllerInstance; - _intentsControllerInstance; - _channelsControllerInstance; - _themesControllerInstance; - _extensionController; - _systemControllerInstance; - _bridgeInstance; - _eventsDispatcher; - _preferredConnectionController; - _channelsStorage; - _prefsControllerInstance; - _uiController; - controllers = { - windows: this.windowsController, - appManager: this.appManagerController, - layouts: this.layoutsController, - notifications: this.notificationsController, - intents: this.intentsController, - channels: this.channelsController, - system: this.systemController, - extension: this.extensionController, - themes: this.themesController, - prefs: this.prefsController, - ui: this.uiController - }; - get communicationId() { - return this._communicationId; - } - get publicWindowId() { - return this._publicWindowId; - } - get windowsController() { - if (!this._windowsControllerInstance) { - this._windowsControllerInstance = new WindowsController(); - } - return this._windowsControllerInstance; - } - get uiController() { - if (!this._uiController) { - this._uiController = new UIController(this); - } - return this._uiController; - } - get appManagerController() { - if (!this._appManagerControllerInstance) { - this._appManagerControllerInstance = new AppManagerController(); - } - return this._appManagerControllerInstance; - } - get layoutsController() { - if (!this._layoutsControllerInstance) { - this._layoutsControllerInstance = new LayoutsController(); - } - return this._layoutsControllerInstance; - } - get themesController() { - if (!this._themesControllerInstance) { - this._themesControllerInstance = new ThemesController(); - } - return this._themesControllerInstance; - } - get notificationsController() { - if (!this._notificationsControllerInstance) { - this._notificationsControllerInstance = new NotificationsController(); - } - return this._notificationsControllerInstance; - } - get intentsController() { - if (!this._intentsControllerInstance) { - this._intentsControllerInstance = new IntentsController(); - } - return this._intentsControllerInstance; - } - get systemController() { - if (!this._systemControllerInstance) { - this._systemControllerInstance = new SystemController(); - } - return this._systemControllerInstance; - } - get channelsController() { - if (!this._channelsControllerInstance) { - this._channelsControllerInstance = new ChannelsController(); - } - return this._channelsControllerInstance; - } - get prefsController() { - if (!this._prefsControllerInstance) { - this._prefsControllerInstance = new PrefsController(); - } - return this._prefsControllerInstance; - } - get extensionController() { - if (!this._extensionController) { - this._extensionController = new ExtController(); - } - return this._extensionController; - } - get eventsDispatcher() { - if (!this._eventsDispatcher) { - this._eventsDispatcher = new EventsDispatcher(this.config); - } - return this._eventsDispatcher; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new GlueBridge(this._coreGlue, this.communicationId); - } - return this._bridgeInstance; - } - get preferredConnectionController() { - if (!this._preferredConnectionController) { - this._preferredConnectionController = new PreferredConnectionController(this._coreGlue); - } - return this._preferredConnectionController; - } - get channelsStorage() { - if (!this._channelsStorage) { - this._channelsStorage = new ChannelsStorage(); - } - return this._channelsStorage; - } - get config() { - return this._webConfig; - } - defineGlue(coreGlue) { - this._coreGlue = coreGlue; - this._publicWindowId = coreGlue.connection.transport.publicWindowId; - const globalNamespace = window.glue42core || window.iobrowser; - this._communicationId = coreGlue.connection.transport.communicationId || globalNamespace.communicationId; - } - defineConfig(config) { - this._webConfig = config; - } - async buildWebWindow(id, name, logger) { - const model = new WebWindowModel(id, name, this.bridge, logger); - const api = await model.toApi(); - return { id, model, api }; - } - buildNotification(config, id) { - return new Notification(config, id); - } - async buildApplication(app, applicationInstances) { - const application = (new ApplicationModel(app, [], this.appManagerController)).toApi(); - const instances = applicationInstances.map((instanceData) => this.buildInstance(instanceData, application)); - application.instances.push(...instances); - return application; - } - buildInstance(instanceData, app) { - return (new InstanceModel(instanceData, this.bridge, app)).toApi(); - } - } - - var version$1 = "4.2.4"; - - const setupGlobalSystem = (io, bridge) => { - return { - getContainerInfo: async () => { - if (window === window.parent) { - return; - } - if (window.name.includes("#wsp")) { - return { - workspaceFrame: { - id: "N/A" - } - }; - } - return window.parent === window.top ? - { top: {} } : - { parent: {} }; - }, - getProfileData: async () => { - if (!bridge) { - throw new Error("Bridge is not available and cannot fetch the profile data"); - } - const data = await bridge.send("system", { name: "getProfileData" }, undefined); - return data; - } - }; - }; - - const createFactoryFunction = (coreFactoryFunction) => { - let cachedApiPromise; - const initAPI = async (config) => { - const ioc = new IoC(); - const glue = await PromiseWrap(() => coreFactoryFunction(config, { version: version$1 }), 30000, "Glue Web initialization timed out, because core didn't resolve"); - const logger = glue.logger.subLogger("web.main.controller"); - ioc.defineGlue(glue); - await ioc.preferredConnectionController.start(config); - await ioc.bridge.start(ioc.controllers); - ioc.defineConfig(config); - logger.trace("the bridge has been started, initializing all controllers"); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.start(glue, ioc))); - logger.trace("all controllers reported started, starting all additional libraries"); - try { - await Promise.all(config.libraries.map((lib) => lib(glue, config))); - logger.trace("all libraries were started"); - ioc.eventsDispatcher.start(glue); - logger.trace("start event dispatched, glue is ready, returning it"); - await ioc.uiController.showComponents(glue).catch((err) => logger.warn(err?.message ? err.message : JSON.stringify(err))); - await Promise.all(Object.values(ioc.controllers).map((controller) => controller.postStart ? controller.postStart(glue, ioc) : Promise.resolve())); - window.iobrowser.system = setupGlobalSystem(glue, ioc.bridge); - window.iobrowser = Object.freeze({ ...window.iobrowser }); - return glue; - } - catch (error) { - return ioError.raiseError(error, true); - } - }; - const factory = (userConfig) => { - if (window.glue42gd || window.iodesktop) { - return enterprise(userConfig); - } - const config = parseConfig(userConfig); - try { - checkSingleton(); - } - catch (error) { - return typeof cachedApiPromise === "undefined" ? Promise.reject(new Error(error)) : cachedApiPromise; - } - const apiPromise = initAPI(config); - cachedApiPromise = userConfig?.memoizeAPI ? apiPromise : undefined; - return apiPromise; - }; - return factory; - }; - - var MetricTypes = { - STRING: 1, - NUMBER: 2, - TIMESTAMP: 3, - OBJECT: 4 - }; - - function getMetricTypeByValue(metric) { - if (metric.type === MetricTypes.TIMESTAMP) { - return "timestamp"; - } - else if (metric.type === MetricTypes.NUMBER) { - return "number"; - } - else if (metric.type === MetricTypes.STRING) { - return "string"; - } - else if (metric.type === MetricTypes.OBJECT) { - return "object"; - } - return "unknown"; - } - function getTypeByValue(value) { - if (value.constructor === Date) { - return "timestamp"; - } - else if (typeof value === "number") { - return "number"; - } - else if (typeof value === "string") { - return "string"; - } - else if (typeof value === "object") { - return "object"; - } - else { - return "string"; - } - } - function serializeMetric(metric) { - const serializedMetrics = {}; - const type = getMetricTypeByValue(metric); - if (type === "object") { - const values = Object.keys(metric.value).reduce((memo, key) => { - const innerType = getTypeByValue(metric.value[key]); - if (innerType === "object") { - const composite = defineNestedComposite(metric.value[key]); - memo[key] = { - type: "object", - description: "", - context: {}, - composite, - }; - } - else { - memo[key] = { - type: innerType, - description: "", - context: {}, - }; - } - return memo; - }, {}); - serializedMetrics.composite = values; - } - serializedMetrics.name = normalizeMetricName(metric.path.join("/") + "/" + metric.name); - serializedMetrics.type = type; - serializedMetrics.description = metric.description; - serializedMetrics.context = {}; - return serializedMetrics; - } - function defineNestedComposite(values) { - return Object.keys(values).reduce((memo, key) => { - const type = getTypeByValue(values[key]); - if (type === "object") { - memo[key] = { - type: "object", - description: "", - context: {}, - composite: defineNestedComposite(values[key]), - }; - } - else { - memo[key] = { - type, - description: "", - context: {}, - }; - } - return memo; - }, {}); - } - function normalizeMetricName(name) { - if (typeof name !== "undefined" && name.length > 0 && name[0] !== "/") { - return "/" + name; - } - else { - return name; - } - } - function getMetricValueByType(metric) { - const type = getMetricTypeByValue(metric); - if (type === "timestamp") { - return Date.now(); - } - else { - return publishNestedComposite(metric.value); - } - } - function publishNestedComposite(values) { - if (typeof values !== "object") { - return values; - } - return Object.keys(values).reduce((memo, key) => { - const value = values[key]; - if (typeof value === "object" && value.constructor !== Date) { - memo[key] = publishNestedComposite(value); - } - else if (value.constructor === Date) { - memo[key] = new Date(value).getTime(); - } - else if (value.constructor === Boolean) { - memo[key] = value.toString(); - } - else { - memo[key] = value; - } - return memo; - }, {}); - } - function flatten(arr) { - return arr.reduce((flat, toFlatten) => { - return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); - }, []); - } - function getHighestState(arr) { - return arr.sort((a, b) => { - if (!a.state) { - return 1; - } - if (!b.state) { - return -1; - } - return b.state - a.state; - })[0]; - } - function aggregateDescription(arr) { - let msg = ""; - arr.forEach((m, idx, a) => { - const path = m.path.join("."); - if (idx === a.length - 1) { - msg += path + "." + m.name + ": " + m.description; - } - else { - msg += path + "." + m.name + ": " + m.description + ","; - } - }); - if (msg.length > 100) { - return msg.slice(0, 100) + "..."; - } - else { - return msg; - } - } - function composeMsgForRootStateMetric(system) { - const aggregatedState = system.root.getAggregateState(); - const merged = flatten(aggregatedState); - const highestState = getHighestState(merged); - const aggregateDesc = aggregateDescription(merged); - return { - description: aggregateDesc, - value: highestState.state, - }; - } - - function gw3 (connection, config) { - if (!connection || typeof connection !== "object") { - throw new Error("Connection is required parameter"); - } - let joinPromise; - let session; - const init = (repo) => { - let resolveReadyPromise; - joinPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - session = connection.domain("metrics"); - session.onJoined((reconnect) => { - if (!reconnect && resolveReadyPromise) { - resolveReadyPromise(); - resolveReadyPromise = undefined; - } - const rootStateMetric = { - name: "/State", - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const defineRootMetricsMsg = { - type: "define", - metrics: [rootStateMetric], - }; - session.sendFireAndForget(defineRootMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for root state metric: ${JSON.stringify(err)}`); - }); - if (reconnect) { - replayRepo(repo); - } - }); - session.join({ - system: config.system, - service: config.service, - instance: config.instance - }); - }; - const replayRepo = (repo) => { - replaySystem(repo.root); - }; - const replaySystem = (system) => { - createSystem(system); - system.metrics.forEach((m) => { - createMetric(m); - }); - system.subSystems.forEach((ss) => { - replaySystem(ss); - }); - }; - const createSystem = async (system) => { - if (system.parent === undefined) { - return; - } - await joinPromise; - const metric = { - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - type: "object", - composite: { - Description: { - type: "string", - description: "", - }, - Value: { - type: "number", - description: "", - }, - }, - description: "System state", - context: {}, - }; - const createMetricsMsg = { - type: "define", - metrics: [metric], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const updateSystem = async (system, state) => { - await joinPromise; - const shadowedUpdateMetric = { - type: "publish", - values: [{ - name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), - value: { - Description: state.description, - Value: state.state, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(shadowedUpdateMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for system state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - const stateObj = composeMsgForRootStateMetric(system); - const rootMetric = { - type: "publish", - peer_id: connection.peerId, - values: [{ - name: "/State", - value: { - Description: stateObj.description, - Value: stateObj.value, - }, - timestamp: Date.now(), - }], - }; - session.sendFireAndForget(rootMetric) - .catch((err) => { - config.logger.warn(`Failed to send update for root state metric of ${system.name}: ${JSON.stringify(err)}`); - }); - }; - const createMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - const m = serializeMetric(metricClone); - const createMetricsMsg = { - type: "define", - metrics: [m], - }; - session.sendFireAndForget(createMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to send define for metric ${metric.name}: ${JSON.stringify(err)}`); - }); - if (typeof metricClone.value !== "undefined") { - updateMetricCore(metricClone); - } - }; - const updateMetric = async (metric) => { - const metricClone = cloneMetric(metric); - await joinPromise; - updateMetricCore(metricClone); - }; - const updateMetricCore = (metric) => { - if (canUpdate()) { - const value = getMetricValueByType(metric); - const publishMetricsMsg = { - type: "publish", - values: [{ - name: normalizeMetricName(metric.path.join("/") + "/" + metric.name), - value, - timestamp: Date.now(), - }], - }; - return session.sendFireAndForget(publishMetricsMsg) - .catch((err) => { - config.logger.warn(`Failed to publish metric ${metric.name}: ${JSON.stringify(err)}`); - }); - } - return Promise.resolve(); - }; - const cloneMetric = (metric) => { - const metricClone = { ...metric }; - if (typeof metric.value === "object" && metric.value !== null) { - metricClone.value = { ...metric.value }; - } - return metricClone; - }; - const canUpdate = () => { - try { - const func = config.canUpdateMetric ?? (() => true); - return func(); - } - catch { - return true; - } - }; - return { - init, - createSystem, - updateSystem, - createMetric, - updateMetric, - }; - } - - var Helpers = { - validate: (definition, parent, transport) => { - if (definition === null || typeof definition !== "object") { - throw new Error("Missing definition"); - } - if (parent === null || typeof parent !== "object") { - throw new Error("Missing parent"); - } - if (transport === null || typeof transport !== "object") { - throw new Error("Missing transport"); - } - }, - }; - - class BaseMetric { - definition; - system; - transport; - value; - type; - path = []; - name; - description; - get repo() { - return this.system?.repo; - } - get id() { return `${this.system.path}/${name}`; } - constructor(definition, system, transport, value, type) { - this.definition = definition; - this.system = system; - this.transport = transport; - this.value = value; - this.type = type; - Helpers.validate(definition, system, transport); - this.path = system.path.slice(0); - this.path.push(system.name); - this.name = definition.name; - this.description = definition.description; - transport.createMetric(this); - } - update(newValue) { - this.value = newValue; - return this.transport.updateMetric(this); - } - } - - class NumberMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.NUMBER); - } - incrementBy(num) { - this.update(this.value + num); - } - increment() { - this.incrementBy(1); - } - decrement() { - this.incrementBy(-1); - } - decrementBy(num) { - this.incrementBy(num * -1); - } - } - - class ObjectMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.OBJECT); - } - update(newValue) { - this.mergeValues(newValue); - return this.transport.updateMetric(this); - } - mergeValues(values) { - return Object.keys(this.value).forEach((k) => { - if (typeof values[k] !== "undefined") { - this.value[k] = values[k]; - } - }); - } - } - - class StringMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.STRING); - } - } - - class TimestampMetric extends BaseMetric { - constructor(definition, system, transport, value) { - super(definition, system, transport, value, MetricTypes.TIMESTAMP); - } - now() { - this.update(new Date()); - } - } - - function system(name, repo, protocol, parent, description) { - if (!repo) { - throw new Error("Repository is required"); - } - if (!protocol) { - throw new Error("Transport is required"); - } - const _transport = protocol; - const _name = name; - const _description = description || ""; - const _repo = repo; - const _parent = parent; - const _path = _buildPath(parent); - let _state = {}; - const id = _arrayToString(_path, "/") + name; - const root = repo.root; - const _subSystems = []; - const _metrics = []; - function subSystem(nameSystem, descriptionSystem) { - if (!nameSystem || nameSystem.length === 0) { - throw new Error("name is required"); - } - const match = _subSystems.filter((s) => s.name === nameSystem); - if (match.length > 0) { - return match[0]; - } - const _system = system(nameSystem, _repo, _transport, me, descriptionSystem); - _subSystems.push(_system); - return _system; - } - function setState(state, stateDescription) { - _state = { state, description: stateDescription }; - _transport.updateSystem(me, _state); - } - function stringMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.STRING, value, (metricDef) => new StringMetric(metricDef, me, _transport, value)); - } - function numberMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.NUMBER, value, (metricDef) => new NumberMetric(metricDef, me, _transport, value)); - } - function objectMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.OBJECT, value, (metricDef) => new ObjectMetric(metricDef, me, _transport, value)); - } - function timestampMetric(definition, value) { - return _getOrCreateMetric(definition, MetricTypes.TIMESTAMP, value, (metricDef) => new TimestampMetric(metricDef, me, _transport, value)); - } - function _getOrCreateMetric(metricObject, expectedType, value, createMetric) { - let metricDef = { name: "" }; - if (typeof metricObject === "string") { - metricDef = { name: metricObject }; - } - else { - metricDef = metricObject; - } - const matching = _metrics.filter((shadowedMetric) => shadowedMetric.name === metricDef.name); - if (matching.length > 0) { - const existing = matching[0]; - if (existing.type !== expectedType) { - throw new Error(`A metric named ${metricDef.name} is already defined with different type.`); - } - if (typeof value !== "undefined") { - existing - .update(value) - .catch(() => { }); - } - return existing; - } - const metric = createMetric(metricDef); - _metrics.push(metric); - return metric; - } - function _buildPath(shadowedSystem) { - if (!shadowedSystem || !shadowedSystem.parent) { - return []; - } - const path = _buildPath(shadowedSystem.parent); - path.push(shadowedSystem.name); - return path; - } - function _arrayToString(path, separator) { - return ((path && path.length > 0) ? path.join(separator) : ""); - } - function getAggregateState() { - const aggState = []; - if (Object.keys(_state).length > 0) { - aggState.push({ - name: _name, - path: _path, - state: _state.state, - description: _state.description, - }); - } - _subSystems.forEach((shadowedSubSystem) => { - const result = shadowedSubSystem.getAggregateState(); - if (result.length > 0) { - aggState.push(...result); - } - }); - return aggState; - } - const me = { - get name() { - return _name; - }, - get description() { - return _description; - }, - get repo() { - return _repo; - }, - get parent() { - return _parent; - }, - path: _path, - id, - root, - get subSystems() { - return _subSystems; - }, - get metrics() { - return _metrics; - }, - subSystem, - getState: () => { - return _state; - }, - setState, - stringMetric, - timestampMetric, - objectMetric, - numberMetric, - getAggregateState, - }; - _transport.createSystem(me); - return me; - } - - class Repository { - root; - constructor(options, protocol) { - protocol.init(this); - this.root = system("", this, protocol); - this.addSystemMetrics(this.root, options.clickStream || options.clickStream === undefined); - } - addSystemMetrics(rootSystem, useClickStream) { - if (typeof navigator !== "undefined") { - rootSystem.stringMetric("UserAgent", navigator.userAgent); - } - if (useClickStream && typeof document !== "undefined") { - const clickStream = rootSystem.subSystem("ClickStream"); - const documentClickHandler = (e) => { - if (!e.target) { - return; - } - const target = e.target; - const className = target ? target.getAttribute("class") ?? "" : ""; - clickStream.objectMetric("LastBrowserEvent", { - type: "click", - timestamp: new Date(), - target: { - className, - id: target.id, - type: "<" + target.tagName.toLowerCase() + ">", - href: target.href || "", - }, - }); - }; - clickStream.objectMetric("Page", { - title: document.title, - page: window.location.href, - }); - if (document.addEventListener) { - document.addEventListener("click", documentClickHandler); - } - else { - document.attachEvent("onclick", documentClickHandler); - } - } - rootSystem.stringMetric("StartTime", (new Date()).toString()); - const urlMetric = rootSystem.stringMetric("StartURL", ""); - const appNameMetric = rootSystem.stringMetric("AppName", ""); - if (typeof window !== "undefined") { - if (typeof window.location !== "undefined") { - const startUrl = window.location.href; - urlMetric.update(startUrl); - } - if (typeof window.glue42gd !== "undefined") { - appNameMetric.update(window.glue42gd.appName); - } - } - } - } - - class NullProtocol { - init(repo) { - } - createSystem(system) { - return Promise.resolve(); - } - updateSystem(metric, state) { - return Promise.resolve(); - } - createMetric(metric) { - return Promise.resolve(); - } - updateMetric(metric) { - return Promise.resolve(); - } - } - - class PerfTracker { - api; - lastCount = 0; - initialPublishTimeout = 10 * 1000; - publishInterval = 60 * 1000; - system; - constructor(api, initialPublishTimeout, publishInterval) { - this.api = api; - this.initialPublishTimeout = initialPublishTimeout ?? this.initialPublishTimeout; - this.publishInterval = publishInterval ?? this.publishInterval; - this.scheduleCollection(); - this.system = this.api.subSystem("performance", "Performance data published by the web application"); - } - scheduleCollection() { - setTimeout(() => { - this.collect(); - setInterval(() => { - this.collect(); - }, this.publishInterval); - }, this.initialPublishTimeout); - } - collect() { - try { - this.collectMemory(); - this.collectEntries(); - } - catch { - } - } - collectMemory() { - const memory = window.performance.memory; - this.system.stringMetric("memory", JSON.stringify({ - totalJSHeapSize: memory.totalJSHeapSize, - usedJSHeapSize: memory.usedJSHeapSize - })); - } - collectEntries() { - const allEntries = window.performance.getEntries(); - if (allEntries.length <= this.lastCount) { - return; - } - this.lastCount = allEntries.length; - const jsonfiedEntries = allEntries.map((i) => i.toJSON()); - this.system.stringMetric("entries", JSON.stringify(jsonfiedEntries)); - } - } - - var metrics = (options) => { - let protocol; - if (!options.connection || typeof options.connection !== "object") { - protocol = new NullProtocol(); - } - else { - protocol = gw3(options.connection, options); - } - const repo = new Repository(options, protocol); - let rootSystem = repo.root; - if (!options.disableAutoAppSystem) { - rootSystem = rootSystem.subSystem("App"); - } - const api = addFAVSupport(rootSystem); - initPerf(api, options.pagePerformanceMetrics); - return api; - }; - function initPerf(api, config) { - if (typeof window === "undefined") { - return; - } - const perfConfig = window?.glue42gd?.metrics?.pagePerformanceMetrics; - if (perfConfig) { - config = perfConfig; - } - if (config?.enabled) { - new PerfTracker(api, config.initialPublishTimeout, config.publishInterval); - } - } - function addFAVSupport(system) { - const reportingSystem = system.subSystem("reporting"); - const def = { - name: "features" - }; - let featureMetric; - const featureMetricFunc = (name, action, payload) => { - if (typeof name === "undefined" || name === "") { - throw new Error("name is mandatory"); - } - else if (typeof action === "undefined" || action === "") { - throw new Error("action is mandatory"); - } - else if (typeof payload === "undefined" || payload === "") { - throw new Error("payload is mandatory"); - } - if (!featureMetric) { - featureMetric = reportingSystem.objectMetric(def, { name, action, payload }); - } - else { - featureMetric.update({ - name, - action, - payload - }); - } - }; - system.featureMetric = featureMetricFunc; - return system; - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackRegistryFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - class InProcTransport { - gw; - registry = CallbackRegistryFactory(); - client; - constructor(settings, logger) { - this.gw = settings.facade; - this.gw.connect((_client, message) => { - this.messageHandler(message); - }).then((client) => { - this.client = client; - }); - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - if (this.client) { - this.client.send(msg); - return Promise.resolve(undefined); - } - else { - return Promise.reject(`not connected`); - } - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "in-memory"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class SharedWorkerTransport { - logger; - worker; - registry = CallbackRegistryFactory(); - constructor(workerFile, logger) { - this.logger = logger; - this.worker = new SharedWorker(workerFile); - this.worker.port.onmessage = (e) => { - this.messageHandler(e.data); - }; - } - get isObjectBasedTransport() { - return true; - } - sendObject(msg) { - this.worker.port.postMessage(msg); - return Promise.resolve(); - } - send(_msg) { - return Promise.reject("not supported"); - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - onConnectedChanged(callback) { - callback(true); - return () => { }; - } - close() { - return Promise.resolve(); - } - open() { - return Promise.resolve(); - } - name() { - return "shared-worker"; - } - reconnect() { - return Promise.resolve(); - } - messageHandler(msg) { - this.registry.execute("onMessage", msg); - } - } - - class Utils { - static isNode() { - if (typeof Utils._isNode !== "undefined") { - return Utils._isNode; - } - if (typeof window !== "undefined") { - Utils._isNode = false; - return false; - } - try { - Utils._isNode = Object.prototype.toString.call(global.process) === "[object process]"; - } - catch (e) { - Utils._isNode = false; - } - return Utils._isNode; - } - static _isNode; - } - - class PromiseWrapper { - static delay(time) { - return new Promise((resolve) => setTimeout(resolve, time)); - } - resolve; - reject; - promise; - rejected = false; - resolved = false; - get ended() { - return this.rejected || this.resolved; - } - constructor() { - this.promise = new Promise((resolve, reject) => { - this.resolve = (t) => { - this.resolved = true; - resolve(t); - }; - this.reject = (err) => { - this.rejected = true; - reject(err); - }; - }); - } - } - - const timers = {}; - function getAllTimers() { - return timers; - } - function timer (timerName) { - const existing = timers[timerName]; - if (existing) { - return existing; - } - const marks = []; - function now() { - return new Date().getTime(); - } - const startTime = now(); - mark("start", startTime); - let endTime; - let period; - function stop() { - endTime = now(); - mark("end", endTime); - period = endTime - startTime; - return period; - } - function mark(name, time) { - const currentTime = time ?? now(); - let diff = 0; - if (marks.length > 0) { - diff = currentTime - marks[marks.length - 1].time; - } - marks.push({ name, time: currentTime, diff }); - } - const timerObj = { - get startTime() { - return startTime; - }, - get endTime() { - return endTime; - }, - get period() { - return period; - }, - stop, - mark, - marks - }; - timers[timerName] = timerObj; - return timerObj; - } - - const WebSocketConstructor = Utils.isNode() ? null : window.WebSocket; - class WS { - ws; - logger; - settings; - startupTimer = timer("connection"); - _running = true; - _registry = CallbackRegistryFactory(); - wsRequests = []; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - if (!this.settings.ws) { - throw new Error("ws is missing"); - } - } - onMessage(callback) { - return this._registry.add("onMessage", callback); - } - send(msg, options) { - return new Promise((resolve, reject) => { - this.waitForSocketConnection(() => { - try { - this.ws?.send(msg); - resolve(); - } - catch (e) { - reject(e); - } - }, reject); - }); - } - open() { - this.logger.info("opening ws..."); - this._running = true; - return new Promise((resolve, reject) => { - this.waitForSocketConnection(resolve, reject); - }); - } - close() { - this._running = false; - if (this.ws) { - this.ws.close(); - } - return Promise.resolve(); - } - onConnectedChanged(callback) { - return this._registry.add("onConnectedChanged", callback); - } - name() { - return this.settings.ws; - } - reconnect() { - this.ws?.close(); - const pw = new PromiseWrapper(); - this.waitForSocketConnection(() => { - pw.resolve(); - }); - return pw.promise; - } - waitForSocketConnection(callback, failed) { - failed = failed ?? (() => { }); - if (!this._running) { - failed(`wait for socket on ${this.settings.ws} failed - socket closed by user`); - return; - } - if (this.ws?.readyState === 1) { - callback(); - return; - } - this.wsRequests.push({ callback, failed }); - if (this.wsRequests.length > 1) { - return; - } - this.openSocket(); - } - async openSocket(retryInterval, retriesLeft) { - this.logger.info(`opening ws to ${this.settings.ws}, retryInterval: ${retryInterval}, retriesLeft: ${retriesLeft}...`); - this.startupTimer.mark("opening-socket"); - if (retryInterval === undefined) { - retryInterval = this.settings.reconnectInterval; - } - if (typeof retriesLeft === "undefined") { - retriesLeft = this.settings.reconnectAttempts; - } - if (retriesLeft !== undefined) { - if (retriesLeft === 0) { - this.notifyForSocketState(`wait for socket on ${this.settings.ws} failed - no more retries left`); - return; - } - this.logger.debug(`will retry ${retriesLeft} more times (every ${retryInterval} ms)`); - } - try { - await this.initiateSocket(); - this.startupTimer.mark("socket-initiated"); - this.notifyForSocketState(); - } - catch { - setTimeout(() => { - const retries = retriesLeft === undefined ? undefined : retriesLeft - 1; - this.openSocket(retryInterval, retries); - }, retryInterval); - } - } - initiateSocket() { - const pw = new PromiseWrapper(); - this.logger.debug(`initiating ws to ${this.settings.ws}...`); - this.ws = new WebSocketConstructor(this.settings.ws ?? ""); - let wasOpen = false; - this.ws.onerror = (err) => { - let reason; - try { - reason = JSON.stringify(err); - } - catch (error) { - const seen = new WeakSet(); - const replacer = (key, value) => { - if (typeof value === "object" && value !== null) { - if (seen.has(value)) { - return; - } - seen.add(value); - } - if (value instanceof Error) { - return { - message: value.message, - name: value.name, - stack: value.stack - }; - } - return value; - }; - reason = JSON.stringify(err, replacer); - } - this.logger.info(`ws error - reason: ${reason}`); - pw.reject("error"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("error"); - } - this.notifyStatusChanged(false, reason); - }; - this.ws.onclose = (err) => { - this.logger.info(`ws closed - code: ${err?.code} reason: ${err?.reason}`); - pw.reject("closed"); - if (wasOpen) { - wasOpen = false; - this.notifyForSocketState("closed"); - } - this.notifyStatusChanged(false); - }; - this.ws.onopen = () => { - this.startupTimer.mark("ws-opened"); - this.logger.info(`ws opened ${this.settings.identity?.application}`); - pw.resolve(); - wasOpen = true; - this.notifyStatusChanged(true); - }; - this.ws.onmessage = (message) => { - this._registry.execute("onMessage", message.data); - }; - return pw.promise; - } - notifyForSocketState(error) { - this.wsRequests.forEach((wsRequest) => { - if (error) { - if (wsRequest.failed) { - wsRequest.failed(error); - } - } - else { - wsRequest.callback(); - } - }); - this.wsRequests = []; - } - notifyStatusChanged(status, reason) { - this._registry.execute("onConnectedChanged", status, reason); - } - } - - class MessageReplayerImpl { - specs; - specsNames = []; - messages = {}; - isDone; - subs = {}; - subsRefCount = {}; - connection; - constructor(specs) { - this.specs = {}; - for (const spec of specs) { - this.specs[spec.name] = spec; - this.specsNames.push(spec.name); - } - } - init(connection) { - this.connection = connection; - for (const name of this.specsNames) { - for (const type of this.specs[name].types) { - let refCount = this.subsRefCount[type]; - if (!refCount) { - refCount = 0; - } - refCount += 1; - this.subsRefCount[type] = refCount; - if (refCount > 1) { - continue; - } - const sub = connection.on(type, (msg) => this.processMessage(type, msg)); - this.subs[type] = sub; - } - } - } - processMessage(type, msg) { - if (this.isDone || !msg) { - return; - } - for (const name of this.specsNames) { - if (this.specs[name].types.indexOf(type) !== -1) { - const messages = this.messages[name] || []; - this.messages[name] = messages; - messages.push(msg); - } - } - } - drain(name, callback) { - if (callback) { - (this.messages[name] || []).forEach(callback); - } - delete this.messages[name]; - for (const type of this.specs[name].types) { - this.subsRefCount[type] -= 1; - if (this.subsRefCount[type] <= 0) { - this.connection?.off(this.subs[type]); - delete this.subs[type]; - delete this.subsRefCount[type]; - } - } - delete this.specs[name]; - if (!this.specs.length) { - this.isDone = true; - } - } - } - - /* @ts-self-types="./index.d.ts" */ - let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; - let nanoid = (size = 21) => { - let id = ''; - let i = size | 0; - while (i--) { - id += urlAlphabet[(Math.random() * 64) | 0]; - } - return id - }; - - const PromisePlus = (executor, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`; - reject(message); - }, timeoutMilliseconds); - const providedPromise = new Promise(executor); - providedPromise - .then((result) => { - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - clearTimeout(timeout); - reject(error); - }); - }); - }; - - class WebPlatformTransport { - settings; - logger; - identity; - isPreferredActivated; - _connectionProtocolVersion; - _communicationId; - publicWindowId; - selfAssignedWindowId; - iAmConnected = false; - parentReady = false; - rejected = false; - parentPingResolve; - parentPingInterval; - connectionResolve; - extConnectionResolve; - extConnectionReject; - connectionReject; - port; - myClientId; - extContentAvailable = false; - extContentConnecting = false; - extContentConnected = false; - parentWindowId; - parentInExtMode = false; - webNamespace = "g42_core_web"; - parent; - parentType; - parentPingTimeout = 5000; - connectionRequestTimeout = 7000; - defaultTargetString = "*"; - registry = CallbackRegistryFactory(); - messages = { - connectionAccepted: { name: "connectionAccepted", handle: this.handleConnectionAccepted.bind(this) }, - connectionRejected: { name: "connectionRejected", handle: this.handleConnectionRejected.bind(this) }, - connectionRequest: { name: "connectionRequest", handle: this.handleConnectionRequest.bind(this) }, - parentReady: { - name: "parentReady", handle: () => { - } - }, - parentPing: { name: "parentPing", handle: this.handleParentPing.bind(this) }, - platformPing: { name: "platformPing", handle: this.handlePlatformPing.bind(this) }, - platformReady: { name: "platformReady", handle: this.handlePlatformReady.bind(this) }, - clientUnload: { name: "clientUnload", handle: () => { } }, - manualUnload: { name: "manualUnload", handle: this.handleManualUnload.bind(this) }, - extConnectionResponse: { name: "extConnectionResponse", handle: this.handleExtConnectionResponse.bind(this) }, - extSetupRequest: { name: "extSetupRequest", handle: this.handleExtSetupRequest.bind(this) }, - gatewayDisconnect: { name: "gatewayDisconnect", handle: this.handleGatewayDisconnect.bind(this) }, - gatewayInternalConnect: { name: "gatewayInternalConnect", handle: this.handleGatewayInternalConnect.bind(this) } - }; - constructor(settings, logger, identity) { - this.settings = settings; - this.logger = logger; - this.identity = identity; - this.extContentAvailable = !!window.glue42ext; - this.setUpMessageListener(); - this.setUpUnload(); - this.setupPlatformUnloadListener(); - this.parentType = window.name.includes("#wsp") ? "workspace" : undefined; - } - manualSetReadyState() { - this.iAmConnected = true; - this.parentReady = true; - } - get transportWindowId() { - return this.publicWindowId; - } - get communicationId() { - return this._communicationId; - } - async sendObject(msg) { - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: msg }, window.origin); - } - if (!this.port) { - throw new Error("Cannot send message, because the port was not opened yet"); - } - this.port.postMessage(msg); - } - get isObjectBasedTransport() { - return true; - } - onMessage(callback) { - return this.registry.add("onMessage", callback); - } - send() { - return Promise.reject("not supported"); - } - onConnectedChanged(callback) { - return this.registry.add("onConnectedChanged", callback); - } - async open() { - this.logger.debug("opening a connection to the web platform gateway."); - await this.connect(); - this.notifyStatusChanged(true); - } - close() { - this.logger.debug(`closing connection - clientId: ${this.myClientId}, windowId: ${this.identity?.windowId || "unknown"}, client connected: ${this.iAmConnected}`); - const message = { - glue42core: { - type: this.messages.gatewayDisconnect.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.port?.postMessage(message); - this.parentReady = false; - this.notifyStatusChanged(false, "manual reconnection"); - return Promise.resolve(); - } - name() { - return "web-platform"; - } - async reconnect() { - await this.close(); - return Promise.resolve(); - } - initiateInternalConnection() { - return new Promise((resolve, reject) => { - this.logger.debug("opening an internal web platform connection"); - this.port = this.settings.port; - if (this.iAmConnected) { - this.logger.warn("cannot open a new connection, because this client is currently connected"); - return; - } - this.port.onmessage = (event) => { - if (this.iAmConnected && !event.data?.glue42core) { - this.registry.execute("onMessage", event.data); - return; - } - const data = event.data?.glue42core; - if (!data) { - return; - } - if (data.type === this.messages.gatewayInternalConnect.name && data.success) { - this.publicWindowId = this.settings.windowId; - if (this.identity && this.publicWindowId) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.publicWindowId; - } - resolve(); - } - if (data.type === this.messages.gatewayInternalConnect.name && data.error) { - reject(data.error); - } - }; - this.port.postMessage({ - glue42core: { - type: this.messages.gatewayInternalConnect.name - } - }); - }); - } - initiateRemoteConnection(target) { - return PromisePlus((resolve, reject) => { - this.connectionResolve = resolve; - this.connectionReject = reject; - this.myClientId = this.myClientId ?? nanoid(10); - const bridgeInstanceId = this.getMyWindowId() || nanoid(10); - const request = { - glue42core: { - type: this.messages.connectionRequest.name, - clientId: this.myClientId, - clientType: "child", - bridgeInstanceId, - selfAssignedWindowId: this.selfAssignedWindowId - } - }; - this.logger.debug(`sending connection request - clientId: ${this.myClientId}`); - if (this.extContentConnecting) { - request.glue42core.clientType = "child"; - request.glue42core.bridgeInstanceId = this.myClientId; - request.glue42core.parentWindowId = this.parentWindowId; - return window.postMessage(request, window.origin); - } - if (!target) { - throw new Error("Cannot send a connection request, because no glue target was specified!"); - } - target.postMessage(request, this.defaultTargetString); - }, this.connectionRequestTimeout, "The connection to the target glue window timed out"); - } - async isParentCheckSuccess(parentCheck) { - try { - await parentCheck; - return { success: true }; - } - catch (error) { - return { success: false }; - } - } - setUpMessageListener() { - if (this.settings.port) { - this.logger.debug("skipping generic message listener, because this is an internal client"); - return; - } - this.logger.debug("setting up window message listener"); - window.addEventListener("message", (event) => { - const data = event.data?.glue42core; - if (!data || this.rejected) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - if (!this.checkMessageTypeValid(data.type)) { - this.logger.error(`cannot handle the incoming glue42 core message, because the type is invalid: ${data.type}`); - return; - } - const messageType = data.type; - this.logger.debug(`received valid glue42core message of type: ${messageType}`); - this.messages[messageType].handle(event); - }); - } - setUpUnload() { - if (this.settings.port) { - this.logger.debug("skipping unload event listener, because this is an internal client"); - return; - } - this.logger.debug("setting up unload event listeners"); - window.addEventListener("beforeunload", () => { - if (this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - window.addEventListener("pagehide", () => { - if (!this._connectionProtocolVersion) { - return; - } - this.signalClientDisappearing(); - }); - } - signalClientDisappearing() { - if (this.extContentConnected) { - return; - } - this.logger.debug(`signaling client disappearing for clientId: ${this.myClientId}`); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - this.parent?.postMessage(message, this.defaultTargetString); - this.port?.postMessage(message); - } - handlePlatformReady(event) { - this.logger.debug("the web platform gave the ready signal"); - this.parentReady = true; - if (this.parentPingResolve) { - this.parentPingResolve(); - delete this.parentPingResolve; - } - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - this.parent = event.source; - this.parentType = window.name.includes("#wsp") ? "workspace" : "window"; - } - handleConnectionAccepted(event) { - const data = event.data?.glue42core; - if (this.myClientId !== data.clientId) { - return this.logger?.debug(`ignoring a connection accepted signal, because it is not targeted at me. My id: ${this.myClientId}, the id in the message: ${data.clientId}`); - } - return this.handleAcceptanceOfMyRequest(data); - } - handleAcceptanceOfMyRequest(data) { - this.logger.debug("handling a connection accepted signal targeted at me."); - this.isPreferredActivated = data.isPreferredActivated; - if (this.extContentConnecting) { - return this.processExtContentConnection(data); - } - if (!data.port) { - this.logger.error("cannot set up my connection, because I was not provided with a port"); - return; - } - this._connectionProtocolVersion = data.connectionProtocolVersion; - this.publicWindowId = this.getMyWindowId(); - if (this.identity) { - this.identity.windowId = this.publicWindowId; - this.identity.instance = this.identity.instance ? this.identity.instance : this.publicWindowId || nanoid(10); - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - this._communicationId = data.communicationId; - this.port = data.port; - this.port.onmessage = (e) => this.registry.execute("onMessage", e.data); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - this.logger.error("unable to call the connection resolve, because no connection promise was found"); - } - processExtContentConnection(data) { - this.logger.debug("handling a connection accepted signal targeted at me for extension content connection."); - this.extContentConnecting = false; - this.extContentConnected = true; - this.publicWindowId = this.parentWindowId || this.myClientId; - if (this.extContentConnecting && this.identity) { - this.identity.windowId = this.publicWindowId; - } - if (this.identity && data.appName) { - this.identity.application = data.appName; - this.identity.applicationName = data.appName; - } - window.addEventListener("message", (event) => { - const extData = event.data?.glue42ExtInc; - if (!extData) { - return; - } - const allowedOrigins = this.settings.allowedOrigins || []; - if (allowedOrigins.length && !allowedOrigins.includes(event.origin)) { - this.logger.warn(`received a message from an origin which is not in the allowed list: ${event.origin}`); - return; - } - this.registry.execute("onMessage", extData); - }); - if (this.connectionResolve) { - this.logger.debug("my connection is set up, calling the connection resolve."); - this.connectionResolve(); - delete this.connectionResolve; - return; - } - } - handleConnectionRejected(event) { - this.logger.debug("handling a connection rejection. Most likely the reason is that this window was not created by a glue API call"); - if (!this.connectionReject) { - return; - } - const errorMsg = typeof event.data.glue42core?.error === "string" - ? `Connection was rejected. ${event.data.glue42core?.error}` - : "The platform connection was rejected. Most likely because this window was not created by a glue API call"; - this.connectionReject(errorMsg); - delete this.connectionReject; - } - handleConnectionRequest() { - if (this.extContentConnecting) { - this.logger.debug("This connection request event is targeted at the extension content"); - return; - } - } - handleParentPing(event) { - if (!this.parentReady) { - this.logger.debug("my parent is not ready, I am ignoring the parent ping"); - return; - } - if (!this.iAmConnected) { - this.logger.debug("i am not fully connected yet, I am ignoring the parent ping"); - return; - } - const message = { - glue42core: { - type: this.messages.parentReady.name - } - }; - if (this.extContentConnected) { - message.glue42core.extMode = { windowId: this.myClientId }; - } - const source = event.source; - this.logger.debug("responding to a parent ping with a ready message"); - source.postMessage(message, event.origin); - } - setupPlatformUnloadListener() { - this.logger.debug("setting up platform unload listener"); - this.onMessage((msg) => { - if (msg.type === "platformUnload") { - this.logger.debug("detected a web platform unload"); - this.parentReady = false; - this.notifyStatusChanged(false, "Gateway unloaded"); - } - }); - } - handleManualUnload() { - this.logger.debug("handling manual unload"); - const message = { - glue42core: { - type: this.messages.clientUnload.name, - data: { - clientId: this.myClientId, - ownWindowId: this.identity?.windowId - } - } - }; - if (this.extContentConnected) { - return window.postMessage({ glue42ExtOut: message }, window.origin); - } - this.port?.postMessage(message); - } - handlePlatformPing() { - return; - } - notifyStatusChanged(status, reason) { - this.logger.debug(`status changed - connected: ${status}, reason: ${reason || "none"}`); - this.iAmConnected = status; - this.registry.execute("onConnectedChanged", status, reason); - } - checkMessageTypeValid(typeToValidate) { - return typeof typeToValidate === "string" && !!this.messages[typeToValidate]; - } - requestConnectionPermissionFromExt() { - return this.waitForContentScript() - .then(() => PromisePlus((resolve, reject) => { - this.extConnectionResolve = resolve; - this.extConnectionReject = reject; - const message = { - glue42core: { - type: "extSetupRequest" - } - }; - this.logger.debug("permission request to the extension content script was sent"); - window.postMessage(message, window.origin); - }, this.parentPingTimeout, "Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection timed out")); - } - handleExtConnectionResponse(event) { - const data = event.data?.glue42core; - if (!data.approved) { - return this.extConnectionReject ? this.extConnectionReject("Cannot initialize glue, because this app was not opened or created by a Glue Client and the request for extension connection was rejected") : undefined; - } - if (this.extConnectionResolve) { - this.extConnectionResolve(); - delete this.extConnectionResolve; - } - this.extContentConnecting = true; - this.parentType = "extension"; - this.logger.debug("The extension connection was approved, proceeding."); - } - handleExtSetupRequest() { - return; - } - handleGatewayDisconnect() { - return; - } - handleGatewayInternalConnect() { - return; - } - waitForContentScript() { - const contentReady = !!window.glue42ext?.content; - if (contentReady) { - return Promise.resolve(); - } - return PromisePlus((resolve) => { - window.addEventListener("Glue42EXTReady", () => { - resolve(); - }); - }, this.connectionRequestTimeout, "The content script was available, but was never heard to be ready"); - } - async connect() { - if (this.settings.port) { - await this.initiateInternalConnection(); - this.logger.debug("internal web platform connection completed"); - return; - } - this.logger.debug("opening a client web platform connection"); - await this.findParent(); - await this.initiateRemoteConnection(this.parent); - this.logger.debug("the client is connected"); - } - async findParent() { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const myInsideParents = this.getPossibleParentsInWindow(window); - const myOutsideParents = this.getPossibleParentsOutsideWindow(window.top?.opener, window.top); - const uniqueParents = new Set([...myInsideParents, ...myOutsideParents]); - if (!uniqueParents.size && !this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - if (!uniqueParents.size && this.extContentAvailable) { - await this.requestConnectionPermissionFromExt(); - return; - } - const defaultParentCheck = await this.isParentCheckSuccess(this.confirmParent(Array.from(uniqueParents))); - if (defaultParentCheck.success) { - this.logger.debug("The default parent was found!"); - return; - } - if (!this.extContentAvailable) { - throw new Error(connectionNotPossibleMsg); - } - await this.requestConnectionPermissionFromExt(); - } - getPossibleParentsInWindow(currentWindow) { - return (!currentWindow?.parent || currentWindow === currentWindow.parent) ? [] : [currentWindow.parent, ...this.getPossibleParentsInWindow(currentWindow.parent)]; - } - getPossibleParentsOutsideWindow(opener, current) { - return (!opener || !current || opener === current) ? [] : [opener, ...this.getPossibleParentsInWindow(opener), ...this.getPossibleParentsOutsideWindow(opener.opener, opener)]; - } - confirmParent(targets) { - const connectionNotPossibleMsg = "Cannot initiate glue, because this window was not opened or created by a glue client"; - const parentCheck = PromisePlus((resolve) => { - this.parentPingResolve = resolve; - const message = { - glue42core: { - type: this.messages.platformPing.name - } - }; - this.parentPingInterval = setInterval(() => { - targets.forEach((target) => { - target.postMessage(message, this.defaultTargetString); - }); - }, 1000); - }, this.parentPingTimeout, connectionNotPossibleMsg); - parentCheck.catch(() => { - if (this.parentPingInterval) { - clearInterval(this.parentPingInterval); - delete this.parentPingInterval; - } - }); - return parentCheck; - } - getMyWindowId() { - if (this.parentType === "workspace") { - return window.name.substring(0, window.name.indexOf("#wsp")); - } - if (window !== window.top) { - return; - } - if (window.name?.includes("g42")) { - return window.name; - } - this.selfAssignedWindowId = this.selfAssignedWindowId || `g42-${nanoid(10)}`; - return this.selfAssignedWindowId; - } - } - - const waitForInvocations = (invocations, callback) => { - let left = invocations; - return () => { - left--; - if (left === 0) { - callback(); - } - }; - }; - - class AsyncSequelizer { - minSequenceInterval; - queue = []; - isExecutingQueue = false; - constructor(minSequenceInterval = 0) { - this.minSequenceInterval = minSequenceInterval; - } - enqueue(action) { - return new Promise((resolve, reject) => { - this.queue.push({ action, resolve, reject }); - this.executeQueue(); - }); - } - async executeQueue() { - if (this.isExecutingQueue) { - return; - } - this.isExecutingQueue = true; - while (this.queue.length) { - const operation = this.queue.shift(); - if (!operation) { - this.isExecutingQueue = false; - return; - } - try { - const actionResult = await operation.action(); - operation.resolve(actionResult); - } - catch (error) { - operation.reject(error); - } - await this.intervalBreak(); - } - this.isExecutingQueue = false; - } - intervalBreak() { - return new Promise((res) => setTimeout(res, this.minSequenceInterval)); - } - } - - function domainSession (domain, connection, logger, successMessages, errorMessages) { - if (domain == null) { - domain = "global"; - } - successMessages = successMessages ?? ["success"]; - errorMessages = errorMessages ?? ["error"]; - let isJoined = domain === "global"; - let tryReconnecting = false; - let _latestOptions; - let _connectionOn = false; - const callbacks = CallbackRegistryFactory(); - connection.disconnected(handleConnectionDisconnected); - connection.loggedIn(handleConnectionLoggedIn); - connection.on("success", (msg) => handleSuccessMessage(msg)); - connection.on("error", (msg) => handleErrorMessage(msg)); - connection.on("result", (msg) => handleSuccessMessage(msg)); - if (successMessages) { - successMessages.forEach((sm) => { - connection.on(sm, (msg) => handleSuccessMessage(msg)); - }); - } - if (errorMessages) { - errorMessages.forEach((sm) => { - connection.on(sm, (msg) => handleErrorMessage(msg)); - }); - } - const requestsMap = {}; - function join(options) { - _latestOptions = options; - return new Promise((resolve, reject) => { - if (isJoined) { - resolve({}); - return; - } - let joinPromise; - if (domain === "global") { - joinPromise = _connectionOn ? Promise.resolve({}) : Promise.reject("not connected to gateway"); - } - else { - logger.debug(`joining domain ${domain}`); - const joinMsg = { - type: "join", - destination: domain, - domain: "global", - options, - }; - joinPromise = send(joinMsg); - } - joinPromise - .then(() => { - handleJoined(); - resolve({}); - }) - .catch((err) => { - logger.debug("error joining " + domain + " domain: " + JSON.stringify(err)); - reject(err); - }); - }); - } - function leave() { - if (domain === "global") { - return Promise.resolve(); - } - logger.debug("stopping session " + domain + "..."); - const leaveMsg = { - type: "leave", - destination: domain, - domain: "global", - }; - tryReconnecting = false; - return send(leaveMsg) - .then(() => { - isJoined = false; - callbacks.execute("onLeft"); - }) - .catch(() => { - isJoined = false; - callbacks.execute("onLeft"); - }); - } - function handleJoined() { - logger.debug("did join " + domain); - isJoined = true; - const wasReconnect = tryReconnecting; - tryReconnecting = false; - callbacks.execute("onJoined", wasReconnect); - } - function handleConnectionDisconnected() { - logger.debug("connection is down"); - _connectionOn = false; - isJoined = false; - tryReconnecting = true; - Object.keys(requestsMap).forEach(requestId => { - const request = requestsMap[requestId]; - if (request) { - logger.trace(`failing pending request ${requestId} due to connection lost`); - request.error({ - err: "Connection lost - gateway connection was disconnected" - }); - } - }); - callbacks.execute("onLeft", { disconnected: true }); - } - async function handleConnectionLoggedIn() { - _connectionOn = true; - if (tryReconnecting) { - logger.debug("connection is now up - trying to reconnect..."); - try { - await join(_latestOptions); - } - catch { - logger.trace(`failed to reconnect`); - } - } - } - function onJoined(callback) { - if (isJoined) { - callback(false); - } - return callbacks.add("onJoined", callback); - } - function onLeft(callback) { - if (!isJoined) { - callback(); - } - return callbacks.add("onLeft", callback); - } - function handleErrorMessage(msg) { - if (domain !== msg.domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.error(msg); - } - function handleSuccessMessage(msg) { - if (msg.domain !== domain) { - return; - } - const requestId = msg.request_id; - if (!requestId) { - return; - } - const entry = requestsMap[requestId]; - if (!entry) { - return; - } - entry.success(msg); - } - function getNextRequestId() { - return nanoid(10); - } - let queuedCalls = []; - function send(msg, tag, options) { - const ignore = ["hello", "join"]; - if (msg.type && ignore.indexOf(msg.type) === -1) { - if (!isJoined) { - console.warn(`trying to send a message (${msg.domain} ${msg.type}) but not connected, will queue`); - const pw = new PromiseWrapper(); - queuedCalls.push({ msg, tag, options, pw }); - if (queuedCalls.length === 1) { - const unsubscribe = onJoined(() => { - logger.info(`joined - will now send queued messages (${queuedCalls.length} -> [${queuedCalls.map((m) => m.msg.type)}])`); - queuedCalls.forEach((qm) => { - send(qm.msg, qm.tag, qm.options) - .then((t) => qm.pw.resolve(t)) - .catch((e) => qm.pw.reject(e)); - }); - queuedCalls = []; - unsubscribe(); - }); - } - return pw.promise; - } - } - options = options ?? {}; - msg.request_id = msg.request_id ?? getNextRequestId(); - msg.domain = msg.domain ?? domain; - if (!options.skipPeerId) { - msg.peer_id = connection.peerId; - } - const requestId = msg.request_id; - return new Promise((resolve, reject) => { - requestsMap[requestId] = { - success: (successMsg) => { - delete requestsMap[requestId]; - successMsg._tag = tag; - resolve(successMsg); - }, - error: (errorMsg) => { - console.warn(`Gateway error - ${JSON.stringify(errorMsg)}`); - delete requestsMap[requestId]; - errorMsg._tag = tag; - reject(errorMsg); - }, - }; - connection - .send(msg, options) - .catch((err) => { - requestsMap[requestId]?.error({ err }); - }); - }); - } - function sendFireAndForget(msg) { - msg.request_id = msg.request_id ? msg.request_id : getNextRequestId(); - msg.domain = msg.domain ?? domain; - msg.peer_id = connection.peerId; - return connection.send(msg); - } - return { - join, - leave, - onJoined, - onLeft, - send, - sendFireAndForget, - on: (type, callback) => { - connection.on(type, (msg) => { - if (msg.domain !== domain) { - return; - } - try { - callback(msg); - } - catch (e) { - logger.error(`Callback failed: ${e} \n ${e.stack} \n msg was: ${JSON.stringify(msg)}`, e); - } - }); - }, - loggedIn: (callback) => connection.loggedIn(callback), - connected: (callback) => connection.connected(callback), - disconnected: (callback) => connection.disconnected(callback), - get peerId() { - return connection.peerId; - }, - get domain() { - return domain; - }, - }; - } - - class Connection { - settings; - logger; - protocolVersion = 3; - peerId; - token; - info; - resolvedIdentity; - availableDomains; - gatewayToken; - replayer; - messageHandlers = {}; - ids = 1; - registry = CallbackRegistryFactory(); - _connected = false; - isTrace = false; - transport; - _defaultTransport; - _defaultAuth; - _targetTransport; - _targetAuth; - _swapTransport = false; - _switchInProgress = false; - _transportSubscriptions = []; - datePrefix = "#T42_DATE#"; - datePrefixLen = this.datePrefix.length; - dateMinLen = this.datePrefixLen + 1; - datePrefixFirstChar = this.datePrefix[0]; - _sequelizer = new AsyncSequelizer(); - _isLoggedIn = false; - shouldTryLogin = true; - pingTimer; - sessions = []; - globalDomain; - initialLogin = true; - initialLoginAttempts = 3; - loginConfig; - loginRetryInProgress = false; - constructor(settings, logger) { - this.settings = settings; - this.logger = logger; - settings = settings || {}; - settings.reconnectAttempts = settings.reconnectAttempts ?? 10; - settings.reconnectInterval = settings.reconnectInterval ?? 1000; - if (settings.inproc) { - this.transport = new InProcTransport(settings.inproc, logger.subLogger("inMemory")); - } - else if (settings.sharedWorker) { - this.transport = new SharedWorkerTransport(settings.sharedWorker, logger.subLogger("shared-worker")); - } - else if (settings.webPlatform) { - this.transport = new WebPlatformTransport(settings.webPlatform, logger.subLogger("web-platform"), settings.identity); - } - else if (settings.ws !== undefined) { - this.transport = new WS(settings, logger.subLogger("ws")); - } - else { - throw new Error("No connection information specified"); - } - this.isTrace = logger.canPublish("trace"); - logger.debug(`starting with ${this.transport.name()} transport`); - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - this._defaultTransport = this.transport; - this.ping(); - } - async switchTransport(settings) { - return this._sequelizer.enqueue(async () => { - if (!settings || typeof settings !== "object") { - throw new Error("Cannot switch transports, because the settings are missing or invalid."); - } - if (typeof settings.type === "undefined") { - throw new Error("Cannot switch the transport, because the type is not defined"); - } - this.logger.trace(`Starting transport switch with settings: ${JSON.stringify(settings)}`); - const switchTargetTransport = settings.type === "secondary" ? this.getNewSecondaryTransport(settings) : this._defaultTransport; - this._targetTransport = switchTargetTransport; - this._targetAuth = settings.type === "secondary" ? this.getNewSecondaryAuth(settings) : this._defaultAuth; - const verifyPromise = this.verifyConnection(); - this._swapTransport = true; - this._switchInProgress = true; - this.logger.trace("The new transport has been set, closing the current transport"); - await this.transport.close(); - try { - await verifyPromise; - const isSwitchSuccess = this.transport === switchTargetTransport; - this.logger.info(`The reconnection after the switch was completed. Was the switch a success: ${isSwitchSuccess}`); - this._switchInProgress = false; - return { success: isSwitchSuccess }; - } - catch (error) { - this.logger.info("The reconnection after the switch timed out, reverting back to the default transport."); - this.switchTransport({ type: "default" }); - this._switchInProgress = false; - return { success: false }; - } - }); - } - onLibReAnnounced(callback) { - return this.registry.add("libReAnnounced", callback); - } - setLibReAnnounced(lib) { - this.registry.execute("libReAnnounced", lib); - } - send(message, options) { - if (this.transport.sendObject && - this.transport.isObjectBasedTransport) { - const msg = this.createObjectMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${JSON.stringify(msg)}`); - } - return this.transport.sendObject(msg, options); - } - else { - const strMessage = this.createStringMessage(message); - if (this.isTrace) { - this.logger.trace(`>> ${strMessage}`); - } - return this.transport.send(strMessage, options); - } - } - on(type, messageHandler) { - type = type.toLowerCase(); - if (this.messageHandlers[type] === undefined) { - this.messageHandlers[type] = {}; - } - const id = this.ids++; - this.messageHandlers[type][id] = messageHandler; - return { - type, - id, - }; - } - off(info) { - delete this.messageHandlers[info.type.toLowerCase()][info.id]; - } - get isConnected() { - return this._isLoggedIn; - } - connected(callback) { - return this.loggedIn(() => { - const currentServer = this.transport.name(); - callback(currentServer); - }); - } - disconnected(callback) { - return this.registry.add("disconnected", callback); - } - async login(authRequest, reconnect) { - this.logger.debug(`Login initiated - reconnect: ${reconnect}, transport: ${this.transport.name()}`); - if (!this._defaultAuth) { - this._defaultAuth = authRequest; - } - if (this._swapTransport) { - this.logger.trace("Detected a transport swap, swapping transports"); - const newAuth = this.transportSwap(); - authRequest = newAuth ?? authRequest; - } - try { - await this.transport.open(); - this.logger.debug(`Transport: ${this.transport.name()} opened, logging in`); - timer("connection").mark("transport-opened"); - const identity = await this.loginCore(authRequest, reconnect); - this.logger.debug(`Logged in with identity: ${JSON.stringify(identity)}`); - timer("connection").mark("protocol-logged-in"); - return identity; - } - catch (error) { - if (this._switchInProgress) { - this.logger.debug("An error while logging in after a transport swap, preparing a default swap."); - this.prepareDefaultSwap(); - } - throw new Error(error); - } - } - async logout() { - await this.logoutCore(); - await this.transport.close(); - } - loggedIn(callback) { - if (this._isLoggedIn) { - callback(); - } - return this.registry.add("onLoggedIn", callback); - } - domain(domain, successMessages, errorMessages) { - let session = this.sessions.find((s) => s.domain === domain); - if (!session) { - session = domainSession(domain, this, this.logger.subLogger(`domain=${domain}`), successMessages, errorMessages); - this.sessions.push(session); - } - return session; - } - authToken() { - const createTokenReq = { - domain: "global", - type: "create-token" - }; - if (!this.globalDomain) { - return Promise.reject(new Error("no global domain session")); - } - return this.globalDomain.send(createTokenReq) - .then((res) => { - return res.token; - }); - } - reconnect() { - return this.transport.reconnect(); - } - setLoggedIn(value) { - this._isLoggedIn = value; - if (this._isLoggedIn) { - this.initialLogin = false; - this.registry.execute("onLoggedIn"); - } - } - distributeMessage(message, type) { - const handlers = this.messageHandlers[type.toLowerCase()]; - if (handlers !== undefined) { - Object.keys(handlers).forEach((handlerId) => { - const handler = handlers[handlerId]; - if (handler !== undefined) { - try { - handler(message); - } - catch (error) { - try { - this.logger.error(`Message handler failed with ${error.stack}`, error); - } - catch (loggerError) { - console.log("Message handler failed", error); - } - } - } - }); - } - } - handleConnectionChanged(connected) { - if (this._connected === connected) { - this.logger.trace("connection state unchanged, skipping"); - return; - } - this.logger.info(`connection state changed to ${connected ? "connected" : "disconnected"}`); - this._connected = connected; - if (connected) { - if (this.settings?.replaySpecs?.length) { - this.replayer = new MessageReplayerImpl(this.settings.replaySpecs); - this.replayer.init(this); - } - this.registry.execute("connected"); - } - else { - this.setLoggedIn(false); - if (this.shouldTryLogin) { - this.attemptLoginWithRetry(); - } - this.registry.execute("disconnected"); - } - } - async attemptLoginWithRetry() { - if (!this.loginConfig) { - throw new Error("no login info"); - } - if (this.loginRetryInProgress) { - this.logger.debug("login attempt already in progress, ignoring request..."); - return; - } - if (this._isLoggedIn) { - this.logger.debug("already logged in, ignoring request..."); - return; - } - if (this.initialLogin) { - this.logger.debug(`initial login attempt failed, ${this.initialLoginAttempts} attempts remaining...`); - if (this.initialLoginAttempts <= 0) { - this.logger.info("maximum initial login attempts reached, will not try to login again"); - return; - } - this.initialLoginAttempts--; - } - try { - this.logger.debug(`will try a new login... ${this.loginRetryInProgress}`); - this.loginRetryInProgress = true; - await this.login(this.loginConfig, true); - } - catch (e) { - this.logger.error(`error trying to login: ${e?.message}`, e); - setTimeout(this.attemptLoginWithRetry.bind(this), this.settings.reconnectInterval ?? 1000); - } - finally { - this.loginRetryInProgress = false; - } - } - handleTransportMessage(msg) { - let msgObj; - if (typeof msg === "string") { - msgObj = this.processStringMessage(msg); - } - else { - msgObj = this.processObjectMessage(msg); - } - if (this.isTrace) { - this.logger.trace(`<< ${JSON.stringify(msgObj)}`); - } - this.distributeMessage(msgObj.msg, msgObj.msgType); - } - verifyConnection() { - return PromisePlus((resolve) => { - let unsub; - const ready = waitForInvocations(2, () => { - if (unsub) { - unsub(); - } - resolve(); - }); - unsub = this.onLibReAnnounced((lib) => { - if (lib.name === "interop") { - return ready(); - } - if (lib.name === "contexts") { - return ready(); - } - }); - }, 10000, "Transport switch timed out waiting for all libraries to be re-announced"); - } - getNewSecondaryTransport(settings) { - if (!settings.transportConfig?.url) { - throw new Error("Missing secondary transport URL."); - } - return new WS(Object.assign({}, this.settings, { ws: settings.transportConfig.url, reconnectAttempts: 1 }), this.logger.subLogger("ws-secondary")); - } - getNewSecondaryAuth(settings) { - if (!settings.transportConfig?.auth) { - throw new Error("Missing secondary transport auth information."); - } - return settings.transportConfig.auth; - } - transportSwap() { - this._swapTransport = false; - if (!this._targetTransport || !this._targetAuth) { - this.logger.warn(`Error while switching transports - either the target transport or auth is not defined: transport defined -> ${!!this._defaultTransport}, auth defined -> ${!!this._targetAuth}. Staying on the current one.`); - return; - } - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport = this._targetTransport; - const unsubConnectionChanged = this.transport.onConnectedChanged(this.handleConnectionChanged.bind(this)); - const unsubOnMessage = this.transport.onMessage(this.handleTransportMessage.bind(this)); - this._transportSubscriptions.push(unsubConnectionChanged); - this._transportSubscriptions.push(unsubOnMessage); - return this._targetAuth; - } - prepareDefaultSwap() { - this._transportSubscriptions.forEach((unsub) => unsub()); - this._transportSubscriptions = []; - this.transport.close().catch((error) => this.logger.warn(`Error closing the ${this.transport.name()} transport after a failed connection attempt: ${JSON.stringify(error)}`)); - this._targetTransport = this._defaultTransport; - this._targetAuth = this._defaultAuth; - this._swapTransport = true; - } - processStringMessage(message) { - const msg = JSON.parse(message, (key, value) => { - if (typeof value !== "string") { - return value; - } - if (value.length < this.dateMinLen) { - return value; - } - if (!value.startsWith(this.datePrefixFirstChar)) { - return value; - } - if (value.substring(0, this.datePrefixLen) !== this.datePrefix) { - return value; - } - try { - const milliseconds = parseInt(value.substring(this.datePrefixLen, value.length), 10); - if (isNaN(milliseconds)) { - return value; - } - return new Date(milliseconds); - } - catch (ex) { - return value; - } - }); - return { - msg, - msgType: msg.type, - }; - } - createStringMessage(message) { - const oldToJson = Date.prototype.toJSON; - try { - const datePrefix = this.datePrefix; - Date.prototype.toJSON = function () { - return datePrefix + this.getTime(); - }; - const result = JSON.stringify(message); - return result; - } - finally { - Date.prototype.toJSON = oldToJson; - } - } - processObjectMessage(message) { - if (!message.type) { - throw new Error("Object should have type property"); - } - return { - msg: message, - msgType: message.type, - }; - } - createObjectMessage(message) { - return message; - } - async loginCore(config, reconnect) { - this.loginConfig = config; - if (!this.loginConfig) { - this.loginConfig = { username: "", password: "" }; - } - this.shouldTryLogin = true; - const authentication = await this.setupAuthConfig(config, reconnect); - const helloMsg = { - type: "hello", - identity: this.settings.identity, - authentication - }; - if (config.sessionId) { - helloMsg.request_id = config.sessionId; - } - if (!this.globalDomain) { - this.globalDomain = domainSession("global", this, this.logger.subLogger("global-domain"), [ - "welcome", - "token", - "authentication-request" - ]); - } - const sendOptions = { skipPeerId: true }; - if (this.initialLogin) { - sendOptions.retryInterval = this.settings.reconnectInterval; - sendOptions.maxRetries = this.settings.reconnectAttempts; - } - try { - const welcomeMsg = await this.tryAuthenticate(this.globalDomain, helloMsg, sendOptions, config); - this.logger.info("login successful with peerId " + welcomeMsg.peer_id); - this.peerId = welcomeMsg.peer_id; - this.resolvedIdentity = welcomeMsg.resolved_identity; - this.availableDomains = welcomeMsg.available_domains; - if (welcomeMsg.options) { - this.token = welcomeMsg.options.access_token; - this.info = welcomeMsg.options.info; - } - this.setLoggedIn(true); - return welcomeMsg.resolved_identity; - } - catch (err) { - this.logger.error("error sending hello message - " + (err.message || err.msg || err.reason || err), err); - throw err; - } - finally { - if (config?.flowCallback && config.sessionId) { - config.flowCallback(config.sessionId, null); - } - } - } - async tryAuthenticate(globalDomain, helloMsg, sendOptions, config) { - let welcomeMsg; - while (true) { - const msg = await globalDomain.send(helloMsg, undefined, sendOptions); - if (msg.type === "authentication-request") { - const token = Buffer.from(msg.authentication.token, "base64"); - if (config.flowCallback && config.sessionId) { - helloMsg.authentication.token = - (await config.flowCallback(config.sessionId, token)) - .data - .toString("base64"); - } - helloMsg.request_id = config.sessionId; - } - else if (msg.type === "welcome") { - welcomeMsg = msg; - break; - } - else if (msg.type === "error") { - throw new Error("Authentication failed: " + msg.reason); - } - else { - throw new Error("Unexpected message type during authentication: " + msg.type); - } - } - return welcomeMsg; - } - async setupAuthConfig(config, reconnect) { - const authentication = {}; - this.gatewayToken = config.gatewayToken; - if (config.gatewayToken) { - if (reconnect) { - try { - config.gatewayToken = await this.getNewGWToken(); - } - catch (e) { - this.logger.warn(`failed to get GW token when reconnecting ${e?.message || e}`); - } - } - authentication.method = "gateway-token"; - authentication.token = config.gatewayToken; - this.gatewayToken = config.gatewayToken; - } - else if (config.flowName === "sspi") { - authentication.provider = "win"; - authentication.method = "access-token"; - if (config.flowCallback && config.sessionId) { - authentication.token = - (await config.flowCallback(config.sessionId, null)) - .data - .toString("base64"); - } - else { - throw new Error("Invalid SSPI config"); - } - } - else if (config.token) { - authentication.method = "access-token"; - authentication.token = config.token; - } - else if (config.username) { - authentication.method = "secret"; - authentication.login = config.username; - authentication.secret = config.password; - } - else if (config.provider) { - authentication.provider = config.provider; - authentication.providerContext = config.providerContext; - } - else { - throw new Error("invalid auth message" + JSON.stringify(config)); - } - return authentication; - } - async logoutCore() { - this.logger.debug("core logging out..."); - this.shouldTryLogin = false; - if (this.pingTimer) { - clearTimeout(this.pingTimer); - } - const promises = this.sessions.map((session) => { - return session.leave(); - }); - await Promise.all(promises); - } - getNewGWToken() { - if (typeof window !== "undefined") { - const glue42gd = window.glue42gd; - if (glue42gd) { - return glue42gd.getGWToken(); - } - } - return Promise.reject(new Error("not running in GD")); - } - ping() { - if (!this.shouldTryLogin) { - return; - } - if (this._isLoggedIn) { - this.send({ type: "ping" }); - } - this.pingTimer = setTimeout(() => { - this.ping(); - }, 30 * 1000); - } - } - - const order = ["trace", "debug", "info", "warn", "error", "off"]; - class Logger { - name; - parent; - static Interop; - static InteropMethodName = "T42.AppLogger.Log"; - static Instance; - path; - subLoggers = []; - _consoleLevel; - _publishLevel; - loggerFullName; - includeTimeAndLevel; - logFn = console; - customLogFn = false; - constructor(name, parent, logFn) { - this.name = name; - this.parent = parent; - this.name = name; - if (parent) { - this.path = `${parent.path}.${name}`; - } - else { - this.path = name; - } - this.loggerFullName = `[${this.path}]`; - this.includeTimeAndLevel = !logFn; - if (logFn) { - this.logFn = logFn; - this.customLogFn = true; - } - } - subLogger(name) { - const existingSub = this.subLoggers.filter((subLogger) => { - return subLogger.name === name; - })[0]; - if (existingSub !== undefined) { - return existingSub; - } - Object.keys(this).forEach((key) => { - if (key === name) { - throw new Error("This sub logger name is not allowed."); - } - }); - const sub = new Logger(name, this, this.customLogFn ? this.logFn : undefined); - this.subLoggers.push(sub); - return sub; - } - publishLevel(level) { - if (level) { - this._publishLevel = level; - } - return this._publishLevel || this.parent?.publishLevel(); - } - consoleLevel(level) { - if (level) { - this._consoleLevel = level; - } - return this._consoleLevel || this.parent?.consoleLevel(); - } - log(message, level, error) { - this.publishMessage(level || "info", message, error); - } - trace(message) { - this.log(message, "trace"); - } - debug(message) { - this.log(message, "debug"); - } - info(message) { - this.log(message, "info"); - } - warn(message) { - this.log(message, "warn"); - } - error(message, err) { - this.log(message, "error", err); - } - canPublish(level, compareWith) { - const levelIdx = order.indexOf(level); - const restrictionIdx = order.indexOf(compareWith || this.consoleLevel() || "trace"); - return levelIdx >= restrictionIdx; - } - publishMessage(level, message, error) { - const loggerName = this.loggerFullName; - if (level === "error" && !error) { - const e = new Error(); - if (e.stack) { - message = - message + - "\n" + - e.stack - .split("\n") - .slice(4) - .join("\n"); - } - } - if (this.canPublish(level, this.publishLevel())) { - const interop = Logger.Interop; - if (interop) { - try { - if (interop.methods({ name: Logger.InteropMethodName }).length > 0) { - const args = { - msg: message, - logger: loggerName, - level - }; - if (error && error instanceof Error) { - args.error = { - message: error.message, - stack: error.stack ?? "" - }; - } - interop.invoke(Logger.InteropMethodName, args) - .catch((e) => { - this.logFn.error(`Unable to send log message to the platform: ${e.message}`, e); - }); - } - } - catch { - } - } - } - if (this.canPublish(level)) { - let prefix = ""; - if (this.includeTimeAndLevel) { - const date = new Date(); - const time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`; - prefix = `[${time}] [${level}] `; - } - const toPrint = `${prefix}${loggerName}: ${message}`; - switch (level) { - case "trace": - this.logFn.debug(toPrint); - break; - case "debug": - if (this.logFn.debug) { - this.logFn.debug(toPrint); - } - else { - this.logFn.log(toPrint); - } - break; - case "info": - this.logFn.info(toPrint); - break; - case "warn": - this.logFn.warn(toPrint); - break; - case "error": - if (error) { - this.logFn.error(toPrint, error); - } - else { - this.logFn.error(toPrint); - } - break; - } - } - } - } - - const GW_MESSAGE_CREATE_CONTEXT = "create-context"; - const GW_MESSAGE_ACTIVITY_CREATED = "created"; - const GW_MESSAGE_ACTIVITY_DESTROYED = "destroyed"; - const GW_MESSAGE_CONTEXT_CREATED = "context-created"; - const GW_MESSAGE_CONTEXT_ADDED = "context-added"; - const GW_MESSAGE_SUBSCRIBE_CONTEXT = "subscribe-context"; - const GW_MESSAGE_SUBSCRIBED_CONTEXT = "subscribed-context"; - const GW_MESSAGE_UNSUBSCRIBE_CONTEXT = "unsubscribe-context"; - const GW_MESSAGE_DESTROY_CONTEXT = "destroy-context"; - const GW_MESSAGE_CONTEXT_DESTROYED = "context-destroyed"; - const GW_MESSAGE_UPDATE_CONTEXT = "update-context"; - const GW_MESSAGE_CONTEXT_UPDATED = "context-updated"; - const GW_MESSAGE_JOINED_ACTIVITY = "joined"; - - const ContextMessageReplaySpec = { - get name() { - return "context"; - }, - get types() { - return [ - GW_MESSAGE_CREATE_CONTEXT, - GW_MESSAGE_ACTIVITY_CREATED, - GW_MESSAGE_ACTIVITY_DESTROYED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_SUBSCRIBE_CONTEXT, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - GW_MESSAGE_DESTROY_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_UPDATE_CONTEXT, - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_JOINED_ACTIVITY - ]; - } - }; - - var version = "6.8.1"; - - function prepareConfig (configuration, ext, glue42gd) { - let nodeStartingContext; - if (Utils.isNode()) { - const startingContextString = process.env._GD_STARTING_CONTEXT_; - if (startingContextString) { - try { - nodeStartingContext = JSON.parse(startingContextString); - } - catch { - } - } - } - function getConnection() { - const gwConfig = configuration.gateway; - const protocolVersion = gwConfig?.protocolVersion ?? 3; - const reconnectInterval = gwConfig?.reconnectInterval; - const reconnectAttempts = gwConfig?.reconnectAttempts; - const defaultWs = "ws://localhost:8385"; - let ws = gwConfig?.ws; - const sharedWorker = gwConfig?.sharedWorker; - const inproc = gwConfig?.inproc; - const webPlatform = gwConfig?.webPlatform ?? undefined; - if (glue42gd) { - ws = glue42gd.gwURL; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) { - ws = nodeStartingContext.gwURL; - } - if (!ws && !sharedWorker && !inproc) { - ws = defaultWs; - } - let instanceId; - let windowId; - let pid; - let environment; - let region; - const appName = getApplication(); - let uniqueAppName = appName; - if (typeof glue42gd !== "undefined") { - windowId = glue42gd.windowId; - pid = glue42gd.pid; - if (glue42gd.env) { - environment = glue42gd.env.env; - region = glue42gd.env.region; - } - uniqueAppName = glue42gd.application ?? "glue-app"; - instanceId = glue42gd.appInstanceId; - } - else if (Utils.isNode()) { - pid = process.pid; - if (nodeStartingContext) { - environment = nodeStartingContext.env; - region = nodeStartingContext.region; - instanceId = nodeStartingContext.instanceId; - } - } - else if (typeof window?.glue42electron !== "undefined") { - windowId = window?.glue42electron.instanceId; - pid = window?.glue42electron.pid; - environment = window?.glue42electron.env; - region = window?.glue42electron.region; - uniqueAppName = window?.glue42electron.application ?? "glue-app"; - instanceId = window?.glue42electron.instanceId; - } - else ; - const replaySpecs = configuration.gateway?.replaySpecs ?? []; - replaySpecs.push(ContextMessageReplaySpec); - let identity = { - application: uniqueAppName, - applicationName: appName, - windowId, - instance: instanceId, - process: pid, - region, - environment, - api: ext.version || version - }; - if (configuration.identity) { - identity = Object.assign(identity, configuration.identity); - } - return { - identity, - reconnectInterval, - ws, - sharedWorker, - webPlatform, - inproc, - protocolVersion, - reconnectAttempts, - replaySpecs, - }; - } - function getContexts() { - const defaultConfig = { - reAnnounceKnownContexts: true, - subscribeOnUpdate: true, - subscribeOnGet: true, - onlyReAnnounceSubscribedContexts: true - }; - if (typeof configuration.contexts === "undefined") { - return defaultConfig; - } - if (typeof configuration.contexts === "boolean" && configuration.contexts) { - return defaultConfig; - } - if (typeof configuration.contexts === "object") { - return { ...defaultConfig, ...configuration.contexts }; - } - return false; - } - function getApplication() { - if (configuration.application) { - return configuration.application; - } - if (glue42gd) { - return glue42gd.applicationName; - } - if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") { - return window.glue42electron.application; - } - const uid = nanoid(10); - if (Utils.isNode()) { - if (nodeStartingContext) { - return nodeStartingContext.applicationConfig.name; - } - return "NodeJS" + uid; - } - if (typeof window !== "undefined" && typeof document !== "undefined") { - return document.title + ` (${uid})`; - } - return uid; - } - function getAuth() { - if (typeof configuration.auth === "string") { - return { - token: configuration.auth - }; - } - if (configuration.auth) { - return configuration.auth; - } - if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) { - return { - gatewayToken: nodeStartingContext.gwToken - }; - } - if (configuration.gateway?.webPlatform) { - return { - username: "glue42", - password: "" - }; - } - } - function getLogger() { - let config = configuration.logger; - const defaultLevel = "warn"; - if (!config) { - config = defaultLevel; - } - let gdConsoleLevel; - if (glue42gd) { - gdConsoleLevel = glue42gd.consoleLogLevel; - } - if (typeof config === "string") { - return { console: gdConsoleLevel ?? config, publish: defaultLevel }; - } - return { - console: gdConsoleLevel ?? config.console ?? defaultLevel, - publish: config.publish ?? defaultLevel - }; - } - const connection = getConnection(); - let application = getApplication(); - if (typeof window !== "undefined") { - const windowAsAny = window; - const containerApplication = windowAsAny.htmlContainer ? - `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` : - windowAsAny?.glue42gd?.application; - if (containerApplication) { - application = containerApplication; - } - } - return { - bus: configuration.bus ?? false, - application, - auth: getAuth(), - logger: getLogger(), - connection, - metrics: configuration.metrics ?? true, - contexts: getContexts(), - version: ext.version || version, - libs: ext.libs ?? [], - customLogger: configuration.customLogger - }; - } - - class GW3ContextData { - name; - contextId; - context; - isAnnounced; - createdByUs; - joinedActivity; - updateCallbacks = {}; - activityId; - sentExplicitSubscription; - get hasReceivedSnapshot() { - return this.snapshotPromiseWrapper.resolved; - } - set hasReceivedSnapshot(has) { - if (has) { - this.snapshotPromiseWrapper.resolve(); - } - else { - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - } - get snapshotPromise() { - return this.snapshotPromiseWrapper.promise; - } - snapshotPromiseWrapper; - constructor(contextId, name, isAnnounced, activityId) { - this.contextId = contextId; - this.name = name; - this.isAnnounced = isAnnounced; - this.activityId = activityId; - this.context = {}; - this.snapshotPromiseWrapper = new PromiseWrapper(); - } - hasCallbacks() { - return Object.keys(this.updateCallbacks).length > 0; - } - getState() { - if (this.isAnnounced && this.hasCallbacks()) { - return 3; - } - if (this.isAnnounced) { - return 2; - } - if (this.hasCallbacks()) { - return 1; - } - return 0; - } - } - - var lodash_clonedeep = {exports: {}}; - - /** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - lodash_clonedeep.exports; - - (function (module, exports) { - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as references for various `Number` constants. */ - var MAX_SAFE_INTEGER = 9007199254740991; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - weakMapTag = '[object WeakMap]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** - * Adds the key-value `pair` to `map`. - * - * @private - * @param {Object} map The map to modify. - * @param {Array} pair The key-value pair to add. - * @returns {Object} Returns `map`. - */ - function addMapEntry(map, pair) { - // Don't return `map.set` because it's not chainable in IE 11. - map.set(pair[0], pair[1]); - return map; - } - - /** - * Adds `value` to `set`. - * - * @private - * @param {Object} set The set to modify. - * @param {*} value The value to add. - * @returns {Object} Returns `set`. - */ - function addSetEntry(set, value) { - // Don't return `set.add` because it's not chainable in IE 11. - set.add(value); - return set; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array ? array.length : 0; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array ? array.length : 0; - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ - function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = root['__core-js_shared__']; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var objectToString = objectProto.toString; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? root.Buffer : undefined, - Symbol = root.Symbol, - Uint8Array = root.Uint8Array, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeKeys = overArg(Object.keys, Object); - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(root, 'DataView'), - Map = getNative(root, 'Map'), - Promise = getNative(root, 'Promise'), - Set = getNative(root, 'Set'), - WeakMap = getNative(root, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - this.__data__ = new ListCache(entries); - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - return this.__data__['delete'](key); - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var cache = this.__data__; - if (cache instanceof ListCache) { - var pairs = cache.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - return this; - } - cache = this.__data__ = new MapCache(pairs); - } - cache.set(key, value); - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - - var length = result.length, - skipIndexes = !!length; - - for (var key in value) { - if ((hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {boolean} [isFull] Specify a clone including symbols. - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, isFull, customizer, key, object, stack) { - var result; - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - if (isHostObject(value)) { - return object ? value : {}; - } - result = initCloneObject(isFunc ? {} : value); - if (!isDeep) { - return copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, baseClone, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (!isArr) { - var props = isFull ? getAllKeys(value) : keys(value); - } - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(proto) { - return isObject(proto) ? objectCreate(proto) : {}; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - return objectToString.call(value); - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var result = new buffer.constructor(buffer.length); - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `map`. - * - * @private - * @param {Object} map The map to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned map. - */ - function cloneMap(map, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); - return arrayReduce(array, addMapEntry, new map.constructor); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of `set`. - * - * @private - * @param {Object} set The set to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned set. - */ - function cloneSet(set, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); - return arrayReduce(array, addSetEntry, new set.constructor); - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = undefined; - - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; - } - - /** - * Copies own symbol properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * Creates an array of the own enumerable symbol properties of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11, - // for data views in Edge < 14, and promises in Node.js. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = objectToString.call(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : undefined; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ - function initCloneArray(array) { - var length = array.length, - result = array.constructor(length); - - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, cloneFunc, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return cloneMap(object, isDeep, cloneFunc); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return cloneSet(object, isDeep, cloneFunc); - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ - function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, true, true); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); - } - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return !!value && typeof value == 'object'; - } - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ - function stubArray() { - return []; - } - - /** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ - function stubFalse() { - return false; - } - - module.exports = cloneDeep; - } (lodash_clonedeep, lodash_clonedeep.exports)); - - var lodash_clonedeepExports = lodash_clonedeep.exports; - var cloneDeep = /*@__PURE__*/getDefaultExportFromCjs(lodash_clonedeepExports); - - function applyContextDelta(context, delta, logger) { - try { - if (logger?.canPublish("trace")) { - logger?.trace(`applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`); - } - if (!delta) { - return context; - } - if (delta.reset) { - context = { ...delta.reset }; - return context; - } - context = deepClone(context, undefined); - if (delta.commands) { - for (const command of delta.commands) { - if (command.type === "remove") { - deletePath(context, command.path); - } - else if (command.type === "set") { - setValueToPath(context, command.value, command.path); - } - } - return context; - } - const added = delta.added; - const updated = delta.updated; - const removed = delta.removed; - if (added) { - Object.keys(added).forEach((key) => { - context[key] = added[key]; - }); - } - if (updated) { - Object.keys(updated).forEach((key) => { - mergeObjectsProperties(key, context, updated); - }); - } - if (removed) { - removed.forEach((key) => { - delete context[key]; - }); - } - return context; - } - catch (e) { - logger?.error(`error applying context delta ${JSON.stringify(delta)} on context ${JSON.stringify(context)}`, e); - return context; - } - } - function deepClone(obj, hash) { - return cloneDeep(obj); - } - const mergeObjectsProperties = (key, what, withWhat) => { - const right = withWhat[key]; - if (right === undefined) { - return what; - } - const left = what[key]; - if (!left || !right) { - what[key] = right; - return what; - } - if (typeof left === "string" || - typeof left === "number" || - typeof left === "boolean" || - typeof right === "string" || - typeof right === "number" || - typeof right === "boolean" || - Array.isArray(left) || - Array.isArray(right)) { - what[key] = right; - return what; - } - what[key] = Object.assign({}, left, right); - return what; - }; - function deepEqual(x, y) { - if (x === y) { - return true; - } - if (!(x instanceof Object) || !(y instanceof Object)) { - return false; - } - if (x.constructor !== y.constructor) { - return false; - } - for (const p in x) { - if (!x.hasOwnProperty(p)) { - continue; - } - if (!y.hasOwnProperty(p)) { - return false; - } - if (x[p] === y[p]) { - continue; - } - if (typeof (x[p]) !== "object") { - return false; - } - if (!deepEqual(x[p], y[p])) { - return false; - } - } - for (const p in y) { - if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) { - return false; - } - } - return true; - } - function setValueToPath(obj, value, path) { - const pathArr = path.split("."); - const forbiddenKeys = ["__proto__", "constructor", "prototype"]; - let i; - for (i = 0; i < pathArr.length - 1; i++) { - const key = pathArr[i]; - if (forbiddenKeys.includes(key)) { - throw new Error(`The provided path ${path} is invalid. It cannot contain segment/key that is equal to one of the following values: ${forbiddenKeys}.`); - } - if (!obj[key]) { - obj[key] = {}; - } - if (typeof obj[key] !== "object") { - obj[key] = {}; - } - obj = obj[key]; - } - obj[pathArr[i]] = value; - } - function isSubset(superObj, subObj) { - return Object.keys(subObj).every((ele) => { - if (typeof subObj[ele] === "object") { - return isSubset(superObj?.[ele] || {}, subObj[ele] || {}); - } - return subObj[ele] === superObj?.[ele]; - }); - } - function deletePath(obj, path) { - const pathArr = path.split("."); - let i; - for (i = 0; i < pathArr.length - 1; i++) { - if (!obj[pathArr[i]]) { - return; - } - obj = obj[pathArr[i]]; - } - delete obj[pathArr[i]]; - } - - class GW3Bridge { - ERROR_URI_FAILURE = "global.errors.failure"; - ERROR_URI_INVALID_CONTEXT = "global.errors.invalid_context"; - _logger; - _connection; - _trackAllContexts; - _reAnnounceKnownContexts; - _subscribeOnUpdate; - _subscribeOnGet; - _onlyReAnnounceSubscribedContexts; - _gw3Session; - _contextNameToData = {}; - _gw3Subscriptions = []; - _nextCallbackSubscriptionNumber = 0; - _creationPromises = {}; - _contextNameToId = {}; - _contextIdToName = {}; - _protocolVersion = undefined; - _contextsTempCache = {}; - _contextsSubscriptionsCache = []; - _systemContextsSubKey; - get protocolVersion() { - if (!this._protocolVersion) { - const contextsDomainInfo = this._connection.availableDomains.find((d) => d.uri === "context"); - this._protocolVersion = contextsDomainInfo?.version ?? 1; - } - return this._protocolVersion; - } - get setPathSupported() { - return this.protocolVersion >= 2; - } - constructor(config) { - this._connection = config.connection; - this._logger = config.logger; - this._trackAllContexts = config.trackAllContexts; - this._reAnnounceKnownContexts = config.reAnnounceKnownContexts; - this._subscribeOnUpdate = config.subscribeOnUpdate ?? true; - this._subscribeOnGet = config.subscribeOnGet ?? true; - this._onlyReAnnounceSubscribedContexts = config.onlyReAnnounceSubscribedContexts ?? true; - this._gw3Session = this._connection.domain("global", [ - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_CONTEXT_UPDATED, - ]); - this._gw3Session.disconnected(this.resetState.bind(this)); - this._gw3Session.onJoined((wasReconnect) => { - if (!wasReconnect) { - return; - } - if (!this._reAnnounceKnownContexts) { - this._contextsTempCache = {}; - return this._connection.setLibReAnnounced({ name: "contexts" }); - } - this.reInitiateState() - .then(() => this._connection.setLibReAnnounced({ name: "contexts" })) - .catch((err) => { - this._logger.warn(`Error while re-announcing contexts: ${JSON.stringify(err)}`); - }); - }); - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - } - dispose() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - this._gw3Subscriptions.length = 0; - for (const contextName in this._contextNameToData) { - if (this._contextNameToId.hasOwnProperty(contextName)) { - delete this._contextNameToData[contextName]; - } - } - } - createContext(name, data) { - if (name in this._creationPromises) { - return this._creationPromises[name]; - } - this._creationPromises[name] = - this._gw3Session - .send({ - type: GW_MESSAGE_CREATE_CONTEXT, - domain: "global", - name, - data, - lifetime: "retained", - }) - .then((createContextMsg) => { - this._contextNameToId[name] = createContextMsg.context_id; - this._contextIdToName[createContextMsg.context_id] = name; - const contextData = this._contextNameToData[name] || new GW3ContextData(createContextMsg.context_id, name, true, undefined); - contextData.isAnnounced = true; - contextData.name = name; - contextData.contextId = createContextMsg.context_id; - contextData.context = createContextMsg.data || deepClone(data); - contextData.hasReceivedSnapshot = true; - this._contextNameToData[name] = contextData; - delete this._creationPromises[name]; - contextData.sentExplicitSubscription = true; - contextData.createdByUs = true; - this.subscribe(name, () => { }); - return createContextMsg.context_id; - }); - return this._creationPromises[name]; - } - all() { - return Object.keys(this._contextNameToData) - .filter((name) => this._contextNameToData[name].isAnnounced); - } - async update(name, delta) { - if (delta) { - delta = deepClone(delta); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - await this.createContext(name, delta); - return; - } - const currentContext = await this.get(contextData.name); - const calculatedDelta = this.setPathSupported ? - this.calculateContextDeltaV2(currentContext, delta) : - this.calculateContextDeltaV1(currentContext, delta); - if (!Object.keys(calculatedDelta.added).length - && !Object.keys(calculatedDelta.updated).length - && !calculatedDelta.removed.length - && !calculatedDelta.commands?.length) { - return Promise.resolve(); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: calculatedDelta, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, calculatedDelta, { - updaterId: gwResponse.peer_id - }); - } - } - async set(name, data) { - if (data) { - data = deepClone(data); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - return this.createContext(name, data); - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { reset: data }, - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - this.handleUpdated(contextData, { - reset: data, - added: {}, - removed: [], - updated: {} - }, { - updaterId: gwResponse.peer_id - }); - } - } - setPath(name, path, value) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later"); - } - return this.setPaths(name, [{ path, value }]); - } - async setPaths(name, pathValues) { - if (!this.setPathSupported) { - return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later"); - } - if (pathValues) { - pathValues = deepClone(pathValues); - } - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - const obj = {}; - for (const pathValue of pathValues) { - setValueToPath(obj, pathValue.value, pathValue.path); - } - return this.createContext(name, obj); - } - const commands = []; - for (const pathValue of pathValues) { - if (pathValue.value === null) { - commands.push({ type: "remove", path: pathValue.path }); - } - else { - commands.push({ type: "set", path: pathValue.path, value: pathValue.value }); - } - } - const gwResponse = await this._gw3Session - .send({ - type: GW_MESSAGE_UPDATE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - delta: { commands } - }, {}, { skipPeerId: false }); - if (this._subscribeOnUpdate && - !contextData.sentExplicitSubscription && - !contextData.activityId) { - this.subscribe(name, () => { }); - } - if (this._subscribeOnUpdate || - contextData.sentExplicitSubscription || - contextData.activityId) { - await contextData.snapshotPromise; - this.handleUpdated(contextData, { - added: {}, - removed: [], - updated: {}, - commands - }, { - updaterId: gwResponse.peer_id - }); - } - } - async get(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - if (!contextData && this._subscribeOnGet) { - this.subscribe(name, () => { }); - } - return Promise.resolve({}); - } - if (contextData && !contextData.sentExplicitSubscription) { - return new Promise((resolve, reject) => { - this.subscribe(name, (data, _d, _r, un) => { - if (!this._subscribeOnGet) { - this.unsubscribe(un); - } - resolve(data); - }).catch((e) => { - if (this.isInvalidContextError(e)) { - resolve({}); - return; - } - reject(e); - }); - }); - } - await contextData.snapshotPromise; - const context = contextData?.context ?? {}; - return Promise.resolve(deepClone(context)); - } - isInvalidContextError(e) { - return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT - || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id")); - } - async subscribe(name, callback, subscriptionKey) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const thisCallbackSubscriptionNumber = typeof subscriptionKey === "undefined" ? this._nextCallbackSubscriptionNumber : subscriptionKey; - if (typeof subscriptionKey === "undefined") { - this._nextCallbackSubscriptionNumber += 1; - this._contextsSubscriptionsCache.push({ contextName: name, subKey: thisCallbackSubscriptionNumber, callback }); - } - let contextData = this._contextNameToData[name]; - if (!contextData || - !contextData.isAnnounced) { - contextData = contextData || new GW3ContextData(undefined, name, false, undefined); - this._contextNameToData[name] = contextData; - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - return Promise.resolve(thisCallbackSubscriptionNumber); - } - const hadCallbacks = contextData.hasCallbacks(); - contextData.updateCallbacks[thisCallbackSubscriptionNumber] = callback; - if (!hadCallbacks) { - if (!contextData.joinedActivity && !contextData.createdByUs) { - if (contextData.context && contextData.sentExplicitSubscription) { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - return this.sendSubscribe(contextData) - .then(() => thisCallbackSubscriptionNumber, () => { - this.unsubscribe(thisCallbackSubscriptionNumber, true); - return thisCallbackSubscriptionNumber; - }); - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - else { - if (contextData.hasReceivedSnapshot && !subscriptionKey) { - const clone = deepClone(contextData.context); - callback(clone, clone, [], thisCallbackSubscriptionNumber); - } - return Promise.resolve(thisCallbackSubscriptionNumber); - } - } - unsubscribe(subscriptionKey, keepInSubscriptionsCache) { - if (!keepInSubscriptionsCache) { - this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter(x => x.subKey !== subscriptionKey); - } - for (const name of Object.keys(this._contextNameToData)) { - const contextData = this._contextNameToData[name]; - if (!contextData) { - continue; - } - const hadCallbacks = contextData.hasCallbacks(); - delete contextData.updateCallbacks[subscriptionKey]; - if (contextData.isAnnounced && - hadCallbacks && - !contextData.hasCallbacks() && - contextData.sentExplicitSubscription) { - contextData.hasReceivedSnapshot = false; - contextData.context = {}; - this.sendUnsubscribe(contextData).catch(() => { }); - } - if (!contextData.isAnnounced && - !contextData.hasCallbacks()) { - delete this._contextNameToData[name]; - delete this._contextNameToId[name]; - if (contextData.contextId) { - delete this._contextIdToName[contextData.contextId]; - } - } - } - } - async destroy(name) { - if (name in this._creationPromises) { - await this._creationPromises[name]; - } - const contextData = this._contextNameToData[name]; - const contextId = contextData?.contextId; - if (!contextData || !contextId) { - return Promise.reject(`context with ${name} does not exist`); - } - return this._gw3Session - .send({ - type: GW_MESSAGE_DESTROY_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }).then(() => undefined); - } - handleUpdated(contextData, delta, extraData) { - const oldContext = contextData.context; - contextData.context = applyContextDelta(contextData.context, delta, this._logger); - if (this._contextNameToData[contextData.name] === contextData && - !deepEqual(oldContext, contextData.context)) { - this.invokeUpdateCallbacks(contextData, delta, extraData); - } - } - subscribeToContextCreatedMessages() { - const createdMessageTypes = [ - GW_MESSAGE_CONTEXT_ADDED, - GW_MESSAGE_CONTEXT_CREATED, - GW_MESSAGE_ACTIVITY_CREATED, - ]; - for (const createdMessageType of createdMessageTypes) { - const sub = this._connection.on(createdMessageType, this.handleContextCreatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextCreatedMessage(contextCreatedMsg) { - const createdMessageType = contextCreatedMsg.type; - if (createdMessageType === GW_MESSAGE_ACTIVITY_CREATED) { - this._contextNameToId[contextCreatedMsg.activity_id] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.activity_id; - } - else if (createdMessageType === GW_MESSAGE_CONTEXT_ADDED) { - this._contextNameToId[contextCreatedMsg.name] = contextCreatedMsg.context_id; - this._contextIdToName[contextCreatedMsg.context_id] = contextCreatedMsg.name; - } - else ; - const name = this._contextIdToName[contextCreatedMsg.context_id]; - if (!name) { - throw new Error("Received created event for context with unknown name: " + contextCreatedMsg.context_id); - } - if (!this._contextNameToId[name]) { - throw new Error("Received created event for context with unknown id: " + contextCreatedMsg.context_id); - } - let contextData = this._contextNameToData[name]; - if (contextData) { - if (contextData.isAnnounced) { - return; - } - else { - if (!contextData.hasCallbacks()) { - throw new Error("Assertion failure: contextData.hasCallbacks()"); - } - contextData.isAnnounced = true; - contextData.contextId = contextCreatedMsg.context_id; - contextData.activityId = contextCreatedMsg.activity_id; - if (!contextData.sentExplicitSubscription) { - this.sendSubscribe(contextData).catch(() => { }); - } - } - } - else { - this._contextNameToData[name] = contextData = - new GW3ContextData(contextCreatedMsg.context_id, name, true, contextCreatedMsg.activity_id); - if (this._trackAllContexts) { - this.subscribe(name, () => { }).then((subKey) => this._systemContextsSubKey = subKey); - } - } - } - subscribeToContextUpdatedMessages() { - const updatedMessageTypes = [ - GW_MESSAGE_CONTEXT_UPDATED, - GW_MESSAGE_SUBSCRIBED_CONTEXT, - GW_MESSAGE_JOINED_ACTIVITY, - ]; - for (const updatedMessageType of updatedMessageTypes) { - const sub = this._connection.on(updatedMessageType, this.handleContextUpdatedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextUpdatedMessage(contextUpdatedMsg) { - const updatedMessageType = contextUpdatedMsg.type; - const contextId = contextUpdatedMsg.context_id; - let contextData = this._contextNameToData[this._contextIdToName[contextId]]; - const justSeen = !contextData || !contextData.isAnnounced; - if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - if (!contextData) { - contextData = - this._contextNameToData[contextUpdatedMsg.activity_id] || - new GW3ContextData(contextId, contextUpdatedMsg.activity_id, true, contextUpdatedMsg.activity_id); - } - this._contextNameToData[contextUpdatedMsg.activity_id] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.activity_id; - this._contextNameToId[contextUpdatedMsg.activity_id] = contextId; - contextData.contextId = contextId; - contextData.isAnnounced = true; - contextData.activityId = contextUpdatedMsg.activity_id; - contextData.joinedActivity = true; - } - else { - if (!contextData || !contextData.isAnnounced) { - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData = contextData || new GW3ContextData(contextId, contextUpdatedMsg.name, true, undefined); - contextData.sentExplicitSubscription = true; - this._contextNameToData[contextUpdatedMsg.name] = contextData; - this._contextIdToName[contextId] = contextUpdatedMsg.name; - this._contextNameToId[contextUpdatedMsg.name] = contextId; - } - else { - this._logger.error(`Received 'update' for unknown context: ${contextId}`); - } - return; - } - } - const oldContext = contextData.context; - contextData.hasReceivedSnapshot = true; - if (updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - contextData.context = contextUpdatedMsg.data ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_JOINED_ACTIVITY) { - contextData.context = contextUpdatedMsg.context_snapshot ?? {}; - } - else if (updatedMessageType === GW_MESSAGE_CONTEXT_UPDATED) { - contextData.context = applyContextDelta(contextData.context, contextUpdatedMsg.delta, this._logger); - } - else { - throw new Error("Unrecognized context update message " + updatedMessageType); - } - if (justSeen || - !deepEqual(contextData.context, oldContext) || - updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) { - this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta, { updaterId: contextUpdatedMsg.updater_id }); - } - } - invokeUpdateCallbacks(contextData, delta, extraData) { - delta = delta || { added: {}, updated: {}, reset: {}, removed: [] }; - if (delta.commands) { - delta.added = delta.updated = delta.reset = {}; - delta.removed = []; - for (const command of delta.commands) { - if (command.type === "remove") { - if (command.path.indexOf(".") === -1) { - delta.removed.push(command.path); - } - setValueToPath(delta.updated, null, command.path); - } - else if (command.type === "set") { - setValueToPath(delta.updated, command.value, command.path); - } - } - } - for (const updateCallbackIndex in contextData.updateCallbacks) { - if (contextData.updateCallbacks.hasOwnProperty(updateCallbackIndex)) { - try { - const updateCallback = contextData.updateCallbacks[updateCallbackIndex]; - updateCallback(deepClone(contextData.context), deepClone(Object.assign({}, delta.added || {}, delta.updated || {}, delta.reset || {})), delta.removed, parseInt(updateCallbackIndex, 10), extraData); - } - catch (err) { - this._logger.debug("callback error: " + JSON.stringify(err)); - } - } - } - } - subscribeToContextDestroyedMessages() { - const destroyedMessageTypes = [ - GW_MESSAGE_CONTEXT_DESTROYED, - GW_MESSAGE_ACTIVITY_DESTROYED, - ]; - for (const destroyedMessageType of destroyedMessageTypes) { - const sub = this._connection.on(destroyedMessageType, this.handleContextDestroyedMessage.bind(this)); - this._gw3Subscriptions.push(sub); - } - } - handleContextDestroyedMessage(destroyedMsg) { - const destroyedMessageType = destroyedMsg.type; - let contextId; - let name; - if (destroyedMessageType === GW_MESSAGE_ACTIVITY_DESTROYED) { - name = destroyedMsg.activity_id; - contextId = this._contextNameToId[name]; - if (!contextId) { - this._logger.error(`Received 'destroyed' for unknown activity: ${destroyedMsg.activity_id}`); - return; - } - } - else { - contextId = destroyedMsg.context_id; - name = this._contextIdToName[contextId]; - if (!name) { - this._logger.error(`Received 'destroyed' for unknown context: ${destroyedMsg.context_id}`); - return; - } - } - delete this._contextIdToName[contextId]; - delete this._contextNameToId[name]; - const contextData = this._contextNameToData[name]; - delete this._contextNameToData[name]; - if (!contextData || !contextData.isAnnounced) { - this._logger.error(`Received 'destroyed' for unknown context: ${contextId}`); - return; - } - } - async sendSubscribe(contextData) { - contextData.sentExplicitSubscription = true; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_SUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = false; - throw error; - } - } - async sendUnsubscribe(contextData) { - const prev = contextData.sentExplicitSubscription; - contextData.sentExplicitSubscription = false; - try { - await this._gw3Session.send({ - type: GW_MESSAGE_UNSUBSCRIBE_CONTEXT, - domain: "global", - context_id: contextData.contextId, - }); - return; - } - catch (error) { - contextData.sentExplicitSubscription = prev; - throw error; - } - } - calculateContextDeltaV1(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined }; - if (from) { - for (const x of Object.keys(from)) { - if (Object.keys(to).indexOf(x) !== -1 - && to[x] !== null - && !deepEqual(from[x], to[x])) { - delta.updated[x] = to[x]; - } - } - } - for (const x of Object.keys(to)) { - if (!from || (Object.keys(from).indexOf(x) === -1)) { - if (to[x] !== null) { - delta.added[x] = to[x]; - } - } - else if (to[x] === null) { - delta.removed.push(x); - } - } - return delta; - } - calculateContextDeltaV2(from, to) { - const delta = { added: {}, updated: {}, removed: [], reset: undefined, commands: [] }; - for (const x of Object.keys(to)) { - if (to[x] !== null) { - const fromX = from ? from[x] : null; - if (!deepEqual(fromX, to[x])) { - delta.commands?.push({ type: "set", path: x, value: to[x] }); - } - } - else { - delta.commands?.push({ type: "remove", path: x }); - } - } - return delta; - } - resetState() { - for (const sub of this._gw3Subscriptions) { - this._connection.off(sub); - } - if (this._systemContextsSubKey) { - this.unsubscribe(this._systemContextsSubKey, true); - delete this._systemContextsSubKey; - } - this._gw3Subscriptions = []; - this._contextNameToId = {}; - this._contextIdToName = {}; - delete this._protocolVersion; - this._contextsTempCache = Object.keys(this._contextNameToData).reduce((cacheSoFar, ctxName) => { - const contextData = this._contextNameToData[ctxName]; - const addToCache = !this._onlyReAnnounceSubscribedContexts || contextData.hasReceivedSnapshot; - if (addToCache) { - cacheSoFar[ctxName] = this._contextNameToData[ctxName].context; - } - return cacheSoFar; - }, {}); - this._contextNameToData = {}; - } - async reInitiateState() { - this.subscribeToContextCreatedMessages(); - this.subscribeToContextUpdatedMessages(); - this.subscribeToContextDestroyedMessages(); - this._connection.replayer?.drain(ContextMessageReplaySpec.name, (message) => { - const type = message.type; - if (!type) { - return; - } - if (type === GW_MESSAGE_CONTEXT_CREATED || - type === GW_MESSAGE_CONTEXT_ADDED || - type === GW_MESSAGE_ACTIVITY_CREATED) { - this.handleContextCreatedMessage(message); - } - else if (type === GW_MESSAGE_SUBSCRIBED_CONTEXT || - type === GW_MESSAGE_CONTEXT_UPDATED || - type === GW_MESSAGE_JOINED_ACTIVITY) { - this.handleContextUpdatedMessage(message); - } - else if (type === GW_MESSAGE_CONTEXT_DESTROYED || - type === GW_MESSAGE_ACTIVITY_DESTROYED) { - this.handleContextDestroyedMessage(message); - } - }); - await Promise.all(this._contextsSubscriptionsCache.map((subscription) => this.subscribe(subscription.contextName, subscription.callback, subscription.subKey))); - await this.flushQueue(); - for (const ctxName in this._contextsTempCache) { - if (typeof this._contextsTempCache[ctxName] !== "object" || Object.keys(this._contextsTempCache[ctxName]).length === 0) { - continue; - } - const lastKnownData = this._contextsTempCache[ctxName]; - this._logger.info(`Re-announcing known context: ${ctxName}`); - await this.flushQueue(); - await this.update(ctxName, lastKnownData); - } - this._contextsTempCache = {}; - this._logger.info("Contexts are re-announced"); - } - flushQueue() { - return new Promise((resolve) => setTimeout(() => resolve(), 0)); - } - } - - class ContextsModule { - initTime; - initStartTime; - initEndTime; - _bridge; - constructor(config) { - this._bridge = new GW3Bridge(config); - } - all() { - return this._bridge.all(); - } - update(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.update(name, data); - } - set(name, data) { - this.checkName(name); - this.checkData(data); - return this._bridge.set(name, data); - } - setPath(name, path, data) { - this.checkName(name); - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(data); - return this.set(name, data); - } - return this._bridge.setPath(name, path, data); - } - setPaths(name, paths) { - this.checkName(name); - if (!Array.isArray(paths)) { - throw new Error("Please provide the paths as an array of PathValues!"); - } - for (const { path, value } of paths) { - this.checkPath(path); - const isTopLevelPath = path === ""; - if (isTopLevelPath) { - this.checkData(value); - } - } - return this._bridge.setPaths(name, paths); - } - subscribe(name, callback) { - this.checkName(name); - if (typeof callback !== "function") { - throw new Error("Please provide the callback as a function!"); - } - return this._bridge - .subscribe(name, (data, delta, removed, key, extraData) => callback(data, delta, removed, () => this._bridge.unsubscribe(key), extraData)) - .then((key) => () => { - this._bridge.unsubscribe(key); - }); - } - get(name) { - this.checkName(name); - return this._bridge.get(name); - } - ready() { - return Promise.resolve(this); - } - destroy(name) { - this.checkName(name); - return this._bridge.destroy(name); - } - get setPathSupported() { - return this._bridge.setPathSupported; - } - checkName(name) { - if (typeof name !== "string" || name === "") { - throw new Error("Please provide the name as a non-empty string!"); - } - } - checkPath(path) { - if (typeof path !== "string") { - throw new Error("Please provide the path as a dot delimited string!"); - } - } - checkData(data) { - if (typeof data !== "object") { - throw new Error("Please provide the data as an object!"); - } - } - } - - function promisify (promise, successCallback, errorCallback) { - if (typeof successCallback !== "function" && typeof errorCallback !== "function") { - return promise; - } - if (typeof successCallback !== "function") { - successCallback = () => { }; - } - else if (typeof errorCallback !== "function") { - errorCallback = () => { }; - } - return promise.then(successCallback, errorCallback); - } - - function rejectAfter(ms = 0, promise, error) { - let timeout; - const clearTimeoutIfThere = () => { - if (timeout) { - clearTimeout(timeout); - } - }; - promise - .then(() => { - clearTimeoutIfThere(); - }) - .catch(() => { - clearTimeoutIfThere(); - }); - return new Promise((resolve, reject) => { - timeout = setTimeout(() => reject(error), ms); - }); - } - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - Decoder.oneOf; - /** See `Decoder.union` */ - var union = Decoder.union; - /** See `Decoder.intersection` */ - Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - var fail$1 = Decoder.fail; - /** See `Decoder.lazy` */ - Decoder.lazy; - - const functionCheck = (input, propDescription) => { - const providedType = typeof input; - return providedType === "function" ? - anyJson() : - fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${typeof providedType}`); - }; - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number or 0"); - const methodDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - objectTypes: optional(array(nonEmptyStringDecoder)), - displayName: optional(nonEmptyStringDecoder), - accepts: optional(nonEmptyStringDecoder), - returns: optional(nonEmptyStringDecoder), - description: optional(nonEmptyStringDecoder), - version: optional(nonNegativeNumberDecoder), - supportsStreaming: optional(boolean()), - flags: optional(object()), - getServers: optional(anyJson().andThen((result) => functionCheck(result, "method definition getServers"))) - }); - const methodFilterDecoder = union(nonEmptyStringDecoder, methodDefinitionDecoder); - const instanceDecoder = object({ - application: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - pid: optional(nonNegativeNumberDecoder), - machine: optional(nonEmptyStringDecoder), - user: optional(nonEmptyStringDecoder), - environment: optional(nonEmptyStringDecoder), - region: optional(nonEmptyStringDecoder), - service: optional(nonEmptyStringDecoder), - instance: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - peerId: optional(nonEmptyStringDecoder), - isLocal: optional(boolean()), - api: optional(nonEmptyStringDecoder), - getMethods: optional(anyJson().andThen((result) => functionCheck(result, "instance getMethods"))), - getStreams: optional(anyJson().andThen((result) => functionCheck(result, "instance getStreams"))) - }); - const targetDecoder = union(constant("best"), constant("all"), constant("skipMine"), instanceDecoder, array(instanceDecoder)); - const invokeOptionsDecoder = object({ - waitTimeoutMs: optional(nonNegativeNumberDecoder), - methodResponseTimeoutMs: optional(nonNegativeNumberDecoder) - }); - - var InvokeStatus; - (function (InvokeStatus) { - InvokeStatus[InvokeStatus["Success"] = 0] = "Success"; - InvokeStatus[InvokeStatus["Error"] = 1] = "Error"; - })(InvokeStatus || (InvokeStatus = {})); - class Client { - protocol; - repo; - instance; - configuration; - constructor(protocol, repo, instance, configuration) { - this.protocol = protocol; - this.repo = repo; - this.instance = instance; - this.configuration = configuration; - } - subscribe(method, options, successCallback, errorCallback, existingSub) { - const callProtocolSubscribe = (targetServers, stream, successProxy, errorProxy) => { - options.methodResponseTimeout = options.methodResponseTimeout ?? options.waitTimeoutMs; - this.protocol.client.subscribe(stream, options, targetServers, successProxy, errorProxy, existingSub); - }; - const promise = new Promise((resolve, reject) => { - const successProxy = (sub) => { - resolve(sub); - }; - const errorProxy = (err) => { - reject(err); - }; - if (!method) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - let methodDef; - if (typeof method === "string") { - methodDef = { name: method }; - } - else { - methodDef = method; - } - if (!methodDef.name) { - reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - return; - } - if (options === undefined) { - options = {}; - } - let target = options.target; - if (target === undefined) { - target = "best"; - } - if (typeof target === "string" && target !== "all" && target !== "best") { - reject(new Error(`"${target}" is not a valid target. Valid targets are "all", "best", or an instance.`)); - return; - } - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = options.method_response_timeout; - if (options.methodResponseTimeout === undefined) { - options.methodResponseTimeout = this.configuration.methodResponseTimeout; - } - } - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = options.wait_for_method_timeout; - if (options.waitTimeoutMs === undefined) { - options.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - const delayStep = 500; - let delayTillNow = 0; - let currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - callProtocolSubscribe(currentServers, currentServers[0].methods[0], successProxy, errorProxy); - } - else { - const retry = () => { - if (!target || !(options.waitTimeoutMs)) { - return; - } - delayTillNow += delayStep; - currentServers = this.getServerMethodsByFilterAndTarget(methodDef, target); - if (currentServers.length > 0) { - const streamInfo = currentServers[0].methods[0]; - callProtocolSubscribe(currentServers, streamInfo, successProxy, errorProxy); - } - else if (delayTillNow >= options.waitTimeoutMs) { - const def = typeof method === "string" ? { name: method } : method; - callProtocolSubscribe(currentServers, def, successProxy, errorProxy); - } - else { - setTimeout(retry, delayStep); - } - }; - setTimeout(retry, delayStep); - } - }); - return promisify(promise, successCallback, errorCallback); - } - servers(methodFilter) { - const filterCopy = methodFilter === undefined - ? undefined - : { ...methodFilter }; - return this.getServers(filterCopy).map((serverMethodMap) => { - return serverMethodMap.server.instance; - }); - } - methods(methodFilter) { - if (typeof methodFilter === "string") { - methodFilter = { name: methodFilter }; - } - else { - methodFilter = { ...methodFilter }; - } - return this.getMethods(methodFilter); - } - methodsForInstance(instance) { - return this.getMethodsForInstance(instance); - } - methodAdded(callback) { - return this.repo.onMethodAdded(callback); - } - methodRemoved(callback) { - return this.repo.onMethodRemoved(callback); - } - serverAdded(callback) { - return this.repo.onServerAdded(callback); - } - serverRemoved(callback) { - return this.repo.onServerRemoved((server, reason) => { - callback(server, reason); - }); - } - serverMethodAdded(callback) { - return this.repo.onServerMethodAdded((server, method) => { - callback({ server, method }); - }); - } - serverMethodRemoved(callback) { - return this.repo.onServerMethodRemoved((server, method) => { - callback({ server, method }); - }); - } - async invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - const getInvokePromise = async () => { - const methodDefinition = typeof methodFilter === "string" ? { name: methodFilter } : { ...methodFilter }; - if (!argumentObj) { - argumentObj = {}; - } - if (!target) { - target = "best"; - } - if (!additionalOptions) { - additionalOptions = {}; - } - const methodFilterDecoderResult = methodFilterDecoder.run(methodDefinition); - if (!methodFilterDecoderResult.ok) { - const message = `The provided 'method' argument is invalid. Error: ${JSON.stringify(methodFilterDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (typeof argumentObj !== "object") { - const message = "The provided 'argumentObj' argument is invalid. Error: The argumentObj should be an instance of an object"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const targetDecoderResult = targetDecoder.run(target); - if (!targetDecoderResult.ok) { - const message = `The provided 'target' argument is invalid. Error: ${JSON.stringify(targetDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - const invokeOptionsDecoderResult = invokeOptionsDecoder.run(additionalOptions); - if (!invokeOptionsDecoderResult.ok) { - const message = `The provided 'options' argument is invalid. Error: ${JSON.stringify(invokeOptionsDecoderResult.error)}.`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (success && typeof success !== "function") { - const message = "The provided 'success' function is invalid. Error: The success should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (error && typeof error !== "function") { - const message = "The provided 'error' function is invalid. Error: The error should be a valid function"; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = additionalOptions.method_response_timeout; - if (additionalOptions.methodResponseTimeoutMs === undefined) { - additionalOptions.methodResponseTimeoutMs = this.configuration.methodResponseTimeout; - } - } - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = additionalOptions.wait_for_method_timeout; - if (additionalOptions.waitTimeoutMs === undefined) { - additionalOptions.waitTimeoutMs = this.configuration.waitTimeoutMs; - } - } - let serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length === 0) { - try { - serversMethodMap = await this.tryToAwaitForMethods(methodDefinition, target, additionalOptions); - } - catch (err) { - const message = `Can not find a method matching ${JSON.stringify(methodFilter)} with server filter ${JSON.stringify(target)}`; - return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj)); - } - } - const timeout = additionalOptions.methodResponseTimeoutMs; - const additionalOptionsCopy = additionalOptions; - const invokePromises = serversMethodMap.map((serversMethodPair) => { - const invId = nanoid(10); - const method = serversMethodPair.methods[0]; - const server = serversMethodPair.server; - const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy); - return Promise.race([ - invokePromise, - rejectAfter(timeout, invokePromise, { - invocationId: invId, - message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`, - status: InvokeStatus.Error, - }) - ]); - }); - const invocationMessages = await Promise.all(invokePromises); - const results = this.getInvocationResultObj(invocationMessages, methodDefinition, argumentObj); - const allRejected = invocationMessages.every((result) => result.status === InvokeStatus.Error); - if (allRejected) { - return Promise.reject(results); - } - return results; - }; - return promisify(getInvokePromise(), success, error); - } - generateInvalidInputInvocationResult(message, methodDefinition, argumentObj) { - const method = { - ...methodDefinition, - getServers: () => [], - supportsStreaming: false, - objectTypes: methodDefinition.objectTypes ?? [], - flags: methodDefinition.flags?.metadata ?? {} - }; - const invokeResultMessage = { - invocationId: nanoid(10), - status: InvokeStatus.Error, - message - }; - return this.getInvocationResultObj([invokeResultMessage], method, argumentObj); - } - getInvocationResultObj(invocationResults, method, calledWith) { - const all_return_values = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Success) - .reduce((allValues, currentValue) => { - allValues = [ - ...allValues, - { - executed_by: currentValue.instance, - returned: currentValue.result, - called_with: calledWith, - method, - message: currentValue.message, - status: currentValue.status, - } - ]; - return allValues; - }, []); - const all_errors = invocationResults - .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Error) - .reduce((allErrors, currError) => { - allErrors = [ - ...allErrors, - { - executed_by: currError.instance, - called_with: calledWith, - name: method.name, - message: currError.message, - } - ]; - return allErrors; - }, []); - const invResult = invocationResults[0]; - const result = { - method, - called_with: calledWith, - returned: invResult.result, - executed_by: invResult.instance, - all_return_values, - all_errors, - message: invResult.message, - status: invResult.status - }; - return result; - } - tryToAwaitForMethods(methodDefinition, target, additionalOptions) { - return new Promise((resolve, reject) => { - if (additionalOptions.waitTimeoutMs === 0) { - reject(); - return; - } - const delayStep = 500; - let delayTillNow = 0; - const retry = () => { - delayTillNow += delayStep; - const serversMethodMap = this.getServerMethodsByFilterAndTarget(methodDefinition, target); - if (serversMethodMap.length > 0) { - clearInterval(interval); - resolve(serversMethodMap); - } - else if (delayTillNow >= (additionalOptions.waitTimeoutMs || 10000)) { - clearInterval(interval); - reject(); - return; - } - }; - const interval = setInterval(retry, delayStep); - }); - } - filterByTarget(target, serverMethodMap) { - if (typeof target === "string") { - if (target === "all") { - return [...serverMethodMap]; - } - else if (target === "best") { - const localMachine = serverMethodMap - .find((s) => s.server.instance.isLocal); - if (localMachine) { - return [localMachine]; - } - if (serverMethodMap[0] !== undefined) { - return [serverMethodMap[0]]; - } - } - else if (target === "skipMine") { - return serverMethodMap.filter(({ server }) => server.instance.peerId !== this.instance.peerId); - } - } - else { - let targetArray; - if (!Array.isArray(target)) { - targetArray = [target]; - } - else { - targetArray = target; - } - const allServersMatching = targetArray.reduce((matches, filter) => { - const myMatches = serverMethodMap.filter((serverMethodPair) => { - return this.instanceMatch(filter, serverMethodPair.server.instance); - }); - return matches.concat(myMatches); - }, []); - return allServersMatching; - } - return []; - } - instanceMatch(instanceFilter, instanceDefinition) { - if (instanceFilter?.peerId && instanceFilter?.instance) { - instanceFilter = { ...instanceFilter }; - delete instanceFilter.peerId; - } - return this.containsProps(instanceFilter, instanceDefinition); - } - methodMatch(methodFilter, methodDefinition) { - return this.containsProps(methodFilter, methodDefinition); - } - containsProps(filter, repoMethod) { - const filterProps = Object.keys(filter) - .filter((prop) => { - return filter[prop] !== undefined - && filter[prop] !== null - && typeof filter[prop] !== "function" - && prop !== "object_types" - && prop !== "display_name" - && prop !== "id" - && prop !== "gatewayId" - && prop !== "identifier" - && prop[0] !== "_"; - }); - return filterProps.every((prop) => { - let isMatch; - const filterValue = filter[prop]; - const repoMethodValue = repoMethod[prop]; - switch (prop) { - case "objectTypes": - isMatch = (filterValue || []).every((filterValueEl) => { - return (repoMethodValue || []).includes(filterValueEl); - }); - break; - case "flags": - isMatch = isSubset(repoMethodValue || {}, filterValue || {}); - break; - default: - isMatch = String(filterValue).toLowerCase() === String(repoMethodValue).toLowerCase(); - } - return isMatch; - }); - } - getMethods(methodFilter) { - if (methodFilter === undefined) { - return this.repo.getMethods(); - } - const methods = this.repo.getMethods().filter((method) => { - return this.methodMatch(methodFilter, method); - }); - return methods; - } - getMethodsForInstance(instanceFilter) { - const allServers = this.repo.getServers(); - const matchingServers = allServers.filter((server) => { - return this.instanceMatch(instanceFilter, server.instance); - }); - if (matchingServers.length === 0) { - return []; - } - let resultMethodsObject = {}; - if (matchingServers.length === 1) { - resultMethodsObject = matchingServers[0].methods; - } - else { - matchingServers.forEach((server) => { - Object.keys(server.methods).forEach((methodKey) => { - const method = server.methods[methodKey]; - resultMethodsObject[method.identifier] = method; - }); - }); - } - return Object.keys(resultMethodsObject) - .map((key) => { - return resultMethodsObject[key]; - }); - } - getServers(methodFilter) { - const servers = this.repo.getServers(); - if (methodFilter === undefined) { - return servers.map((server) => { - return { server, methods: [] }; - }); - } - return servers.reduce((prev, current) => { - const methodsForServer = Object.values(current.methods); - const matchingMethods = methodsForServer.filter((method) => { - return this.methodMatch(methodFilter, method); - }); - if (matchingMethods.length > 0) { - prev.push({ server: current, methods: matchingMethods }); - } - return prev; - }, []); - } - getServerMethodsByFilterAndTarget(methodFilter, target) { - const serversMethodMap = this.getServers(methodFilter); - return this.filterByTarget(target, serversMethodMap); - } - } - - class ServerSubscription { - protocol; - repoMethod; - subscription; - constructor(protocol, repoMethod, subscription) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.subscription = subscription; - } - get stream() { - if (!this.repoMethod.stream) { - throw new Error("no stream"); - } - return this.repoMethod.stream; - } - get arguments() { return this.subscription.arguments || {}; } - get branchKey() { return this.subscription.branchKey; } - get instance() { - if (!this.subscription.instance) { - throw new Error("no instance"); - } - return this.subscription.instance; - } - close() { - this.protocol.server.closeSingleSubscription(this.repoMethod, this.subscription); - } - push(data) { - this.protocol.server.pushDataToSingle(this.repoMethod, this.subscription, data); - } - } - - class Request { - protocol; - repoMethod; - requestContext; - arguments; - instance; - constructor(protocol, repoMethod, requestContext) { - this.protocol = protocol; - this.repoMethod = repoMethod; - this.requestContext = requestContext; - this.arguments = requestContext.arguments; - this.instance = requestContext.instance; - } - accept() { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, ""); - } - acceptOnBranch(branch) { - this.protocol.server.acceptRequestOnBranch(this.requestContext, this.repoMethod, branch); - } - reject(reason) { - this.protocol.server.rejectRequest(this.requestContext, this.repoMethod, reason); - } - } - - let ServerStreaming$1 = class ServerStreaming { - protocol; - server; - constructor(protocol, server) { - this.protocol = protocol; - this.server = server; - protocol.server.onSubRequest((rc, rm) => this.handleSubRequest(rc, rm)); - protocol.server.onSubAdded((sub, rm) => this.handleSubAdded(sub, rm)); - protocol.server.onSubRemoved((sub, rm) => this.handleSubRemoved(sub, rm)); - } - handleSubRequest(requestContext, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRequestHandler === "function")) { - return; - } - const request = new Request(this.protocol, repoMethod, requestContext); - repoMethod.streamCallbacks.subscriptionRequestHandler(request); - } - handleSubAdded(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionAddedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionAddedHandler(sub); - } - handleSubRemoved(subscription, repoMethod) { - if (!(repoMethod && - repoMethod.streamCallbacks && - typeof repoMethod.streamCallbacks.subscriptionRemovedHandler === "function")) { - return; - } - const sub = new ServerSubscription(this.protocol, repoMethod, subscription); - repoMethod.streamCallbacks.subscriptionRemovedHandler(sub); - } - }; - - class ServerBranch { - key; - protocol; - repoMethod; - constructor(key, protocol, repoMethod) { - this.key = key; - this.protocol = protocol; - this.repoMethod = repoMethod; - } - subscriptions() { - const subList = this.protocol.server.getSubscriptionList(this.repoMethod, this.key); - return subList.map((sub) => { - return new ServerSubscription(this.protocol, this.repoMethod, sub); - }); - } - close() { - this.protocol.server.closeAllSubscriptions(this.repoMethod, this.key); - } - push(data) { - this.protocol.server.pushData(this.repoMethod, data, [this.key]); - } - } - - class ServerStream { - _protocol; - _repoMethod; - _server; - name; - constructor(_protocol, _repoMethod, _server) { - this._protocol = _protocol; - this._repoMethod = _repoMethod; - this._server = _server; - this.name = this._repoMethod.definition.name; - } - branches(key) { - const bList = this._protocol.server.getBranchList(this._repoMethod); - if (key) { - if (bList.indexOf(key) > -1) { - return new ServerBranch(key, this._protocol, this._repoMethod); - } - return undefined; - } - else { - return bList.map((branchKey) => { - return new ServerBranch(branchKey, this._protocol, this._repoMethod); - }); - } - } - branch(key) { - return this.branches(key); - } - subscriptions() { - const subList = this._protocol.server.getSubscriptionList(this._repoMethod); - return subList.map((sub) => { - return new ServerSubscription(this._protocol, this._repoMethod, sub); - }); - } - get definition() { - const def2 = this._repoMethod.definition; - return { - accepts: def2.accepts, - description: def2.description, - displayName: def2.displayName, - name: def2.name, - objectTypes: def2.objectTypes, - returns: def2.returns, - supportsStreaming: def2.supportsStreaming, - flags: def2.flags?.metadata, - }; - } - close() { - this._protocol.server.closeAllSubscriptions(this._repoMethod); - this._server.unregister(this._repoMethod.definition, true); - } - push(data, branches) { - if (typeof branches !== "string" && !Array.isArray(branches) && branches !== undefined) { - throw new Error("invalid branches should be string or string array"); - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - this._protocol.server.pushData(this._repoMethod, data, branches); - } - updateRepoMethod(repoMethod) { - this._repoMethod = repoMethod; - } - } - - class Server { - protocol; - serverRepository; - streaming; - invocations = 0; - currentlyUnregistering = {}; - constructor(protocol, serverRepository) { - this.protocol = protocol; - this.serverRepository = serverRepository; - this.streaming = new ServerStreaming$1(protocol, this); - this.protocol.server.onInvoked(this.onMethodInvoked.bind(this)); - } - createStream(streamDef, callbacks, successCallback, errorCallback, existingStream) { - const promise = new Promise((resolve, reject) => { - if (!streamDef) { - reject("The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream."); - return; - } - let streamMethodDefinition; - if (typeof streamDef === "string") { - streamMethodDefinition = { name: "" + streamDef }; - } - else { - streamMethodDefinition = { ...streamDef }; - } - if (!streamMethodDefinition.name) { - return reject(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(streamMethodDefinition)}`); - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === streamMethodDefinition.name); - if (nameAlreadyExists) { - return reject(`A stream with the name "${streamMethodDefinition.name}" already exists! Please, provide a unique name for the stream.`); - } - streamMethodDefinition.supportsStreaming = true; - if (!callbacks) { - callbacks = {}; - } - if (typeof callbacks.subscriptionRequestHandler !== "function") { - callbacks.subscriptionRequestHandler = (request) => { - request.accept(); - }; - } - const repoMethod = this.serverRepository.add({ - definition: streamMethodDefinition, - streamCallbacks: callbacks, - protocolState: {}, - }); - this.protocol.server.createStream(repoMethod) - .then(() => { - let streamUserObject; - if (existingStream) { - streamUserObject = existingStream; - existingStream.updateRepoMethod(repoMethod); - } - else { - streamUserObject = new ServerStream(this.protocol, repoMethod, this); - } - repoMethod.stream = streamUserObject; - resolve(streamUserObject); - }) - .catch((err) => { - if (repoMethod.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - reject(err); - }); - }); - return promisify(promise, successCallback, errorCallback); - } - register(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallbackFunction = async (context, resultCallback) => { - try { - const result = callback(context.args, context.instance); - if (result && typeof result.then === "function") { - const resultValue = await result; - resultCallback(undefined, resultValue); - } - else { - resultCallback(undefined, result); - } - } - catch (e) { - resultCallback(e ?? "", e ?? ""); - } - }; - wrappedCallbackFunction.userCallback = callback; - return this.registerCore(methodDefinition, wrappedCallbackFunction); - } - registerAsync(methodDefinition, callback) { - if (!methodDefinition) { - return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property."); - } - if (typeof callback !== "function") { - return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); - } - const wrappedCallback = async (context, resultCallback) => { - try { - let resultCalled = false; - const success = (result) => { - if (!resultCalled) { - resultCallback(undefined, result); - } - resultCalled = true; - }; - const error = (e) => { - if (!resultCalled) { - if (!e) { - e = ""; - } - resultCallback(e, e); - } - resultCalled = true; - }; - const methodResult = callback(context.args, context.instance, success, error); - if (methodResult && typeof methodResult.then === "function") { - methodResult - .then(success) - .catch(error); - } - } - catch (e) { - resultCallback(e, undefined); - } - }; - wrappedCallback.userCallbackAsync = callback; - return this.registerCore(methodDefinition, wrappedCallback); - } - async unregister(methodFilter, forStream = false) { - if (methodFilter === undefined) { - return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property."); - } - if (typeof methodFilter === "function") { - await this.unregisterWithPredicate(methodFilter, forStream); - return; - } - let methodDefinition; - if (typeof methodFilter === "string") { - methodDefinition = { name: methodFilter }; - } - else { - methodDefinition = methodFilter; - } - if (methodDefinition.name === undefined) { - return Promise.reject("Method name is required. Cannot find a method if the method name is undefined!"); - } - const methodToBeRemoved = this.serverRepository.getList().find((serverMethod) => { - return serverMethod.definition.name === methodDefinition.name - && (serverMethod.definition.supportsStreaming || false) === forStream; - }); - if (!methodToBeRemoved) { - return Promise.reject(`Method with a name "${methodDefinition.name}" does not exist or is not registered by your application!`); - } - await this.removeMethodsOrStreams([methodToBeRemoved]); - } - async unregisterWithPredicate(filterPredicate, forStream) { - const methodsOrStreamsToRemove = this.serverRepository.getList() - .filter((sm) => filterPredicate(sm.definition)) - .filter((serverMethod) => (serverMethod.definition.supportsStreaming || false) === forStream); - if (!methodsOrStreamsToRemove || methodsOrStreamsToRemove.length === 0) { - return Promise.reject(`Could not find a ${forStream ? "stream" : "method"} matching the specified condition!`); - } - await this.removeMethodsOrStreams(methodsOrStreamsToRemove); - } - removeMethodsOrStreams(methodsToRemove) { - const methodUnregPromises = []; - methodsToRemove.forEach((method) => { - const promise = this.protocol.server.unregister(method) - .then(() => { - if (method.repoId) { - this.serverRepository.remove(method.repoId); - } - }); - methodUnregPromises.push(promise); - this.addAsCurrentlyUnregistering(method.definition.name, promise); - }); - return Promise.all(methodUnregPromises); - } - async addAsCurrentlyUnregistering(methodName, promise) { - const timeout = new Promise((resolve) => setTimeout(resolve, 5000)); - this.currentlyUnregistering[methodName] = Promise.race([promise, timeout]).then(() => { - delete this.currentlyUnregistering[methodName]; - }); - } - async registerCore(method, theFunction) { - let methodDefinition; - if (typeof method === "string") { - methodDefinition = { name: "" + method }; - } - else { - methodDefinition = { ...method }; - } - if (!methodDefinition.name) { - return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(method)}`); - } - const unregisterInProgress = this.currentlyUnregistering[methodDefinition.name]; - if (typeof unregisterInProgress !== "undefined") { - await unregisterInProgress; - } - const nameAlreadyExists = this.serverRepository.getList() - .some((serverMethod) => serverMethod.definition.name === methodDefinition.name); - if (nameAlreadyExists) { - return Promise.reject(`A method with the name "${methodDefinition.name}" already exists! Please, provide a unique name for the method.`); - } - if (methodDefinition.supportsStreaming) { - return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${methodDefinition.name}” to be a stream, please use the “glue.interop.createStream()” method.`); - } - const repoMethod = this.serverRepository.add({ - definition: methodDefinition, - theFunction, - protocolState: {}, - }); - return this.protocol.server.register(repoMethod) - .catch((err) => { - if (repoMethod?.repoId) { - this.serverRepository.remove(repoMethod.repoId); - } - throw err; - }); - } - onMethodInvoked(methodToExecute, invocationId, invocationArgs) { - if (!methodToExecute || !methodToExecute.theFunction) { - return; - } - methodToExecute.theFunction(invocationArgs, (err, result) => { - if (err !== undefined && err !== null) { - if (err.message && typeof err.message === "string") { - err = err.message; - } - else if (typeof err !== "string") { - try { - err = JSON.stringify(err); - } - catch (unStrException) { - err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`; - } - } - } - if (!result) { - result = {}; - } - else if (typeof result !== "object" || Array.isArray(result)) { - result = { _value: result }; - } - this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result); - }); - } - } - - class InstanceWrapper { - wrapped = {}; - constructor(API, instance, connection) { - this.wrapped.getMethods = function () { - return API.methodsForInstance(this); - }; - this.wrapped.getStreams = function () { - return API.methodsForInstance(this).filter((m) => m.supportsStreaming); - }; - if (instance) { - this.refreshWrappedObject(instance); - } - if (connection) { - connection.loggedIn(() => { - this.refresh(connection); - }); - this.refresh(connection); - } - } - unwrap() { - return this.wrapped; - } - refresh(connection) { - if (!connection) { - return; - } - const resolvedIdentity = connection?.resolvedIdentity; - const instance = Object.assign({}, resolvedIdentity ?? {}, { peerId: connection?.peerId }); - this.refreshWrappedObject(instance); - } - refreshWrappedObject(resolvedIdentity) { - Object.keys(resolvedIdentity).forEach((key) => { - this.wrapped[key] = resolvedIdentity[key]; - }); - this.wrapped.user = resolvedIdentity.user; - this.wrapped.instance = resolvedIdentity.instance; - this.wrapped.application = resolvedIdentity.application ?? nanoid(10); - this.wrapped.applicationName = resolvedIdentity.applicationName; - this.wrapped.pid = resolvedIdentity.pid ?? resolvedIdentity.process ?? Math.floor(Math.random() * 10000000000); - this.wrapped.machine = resolvedIdentity.machine; - this.wrapped.environment = resolvedIdentity.environment; - this.wrapped.region = resolvedIdentity.region; - this.wrapped.windowId = resolvedIdentity.windowId; - this.wrapped.isLocal = resolvedIdentity.isLocal ?? true; - this.wrapped.api = resolvedIdentity.api; - this.wrapped.service = resolvedIdentity.service; - this.wrapped.peerId = resolvedIdentity.peerId; - } - } - - const hideMethodSystemFlags = (method) => { - return { - ...method, - flags: method.flags.metadata || {} - }; - }; - class ClientRepository { - logger; - API; - servers = {}; - myServer; - methodsCount = {}; - callbacks = CallbackRegistryFactory(); - constructor(logger, API) { - this.logger = logger; - this.API = API; - const peerId = this.API.instance.peerId; - this.myServer = { - id: peerId, - methods: {}, - instance: this.API.instance, - wrapper: this.API.unwrappedInstance, - }; - this.servers[peerId] = this.myServer; - } - addServer(info, serverId) { - this.logger.debug(`adding server ${serverId}`); - const current = this.servers[serverId]; - if (current) { - return current.id; - } - const wrapper = new InstanceWrapper(this.API, info); - const serverEntry = { - id: serverId, - methods: {}, - instance: wrapper.unwrap(), - wrapper, - }; - this.servers[serverId] = serverEntry; - this.callbacks.execute("onServerAdded", serverEntry.instance); - return serverId; - } - removeServerById(id, reason) { - const server = this.servers[id]; - if (!server) { - this.logger.warn(`not aware of server ${id}, my state ${JSON.stringify(Object.keys(this.servers))}`); - return; - } - else { - this.logger.debug(`removing server ${id}`); - } - Object.keys(server.methods).forEach((methodId) => { - this.removeServerMethod(id, methodId); - }); - delete this.servers[id]; - this.callbacks.execute("onServerRemoved", server.instance, reason); - } - addServerMethod(serverId, method) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - if (server.methods[method.id]) { - return; - } - const identifier = this.createMethodIdentifier(method); - const that = this; - const methodDefinition = { - identifier, - gatewayId: method.id, - name: method.name, - displayName: method.display_name, - description: method.description, - version: method.version, - objectTypes: method.object_types || [], - accepts: method.input_signature, - returns: method.result_signature, - supportsStreaming: typeof method.flags !== "undefined" ? method.flags.streaming : false, - flags: method.flags ?? {}, - getServers: () => { - return that.getServersByMethod(identifier); - } - }; - methodDefinition.object_types = methodDefinition.objectTypes; - methodDefinition.display_name = methodDefinition.displayName; - methodDefinition.version = methodDefinition.version; - server.methods[method.id] = methodDefinition; - const clientMethodDefinition = hideMethodSystemFlags(methodDefinition); - if (!this.methodsCount[identifier]) { - this.methodsCount[identifier] = 0; - this.callbacks.execute("onMethodAdded", clientMethodDefinition); - } - this.methodsCount[identifier] = this.methodsCount[identifier] + 1; - this.callbacks.execute("onServerMethodAdded", server.instance, clientMethodDefinition); - return methodDefinition; - } - removeServerMethod(serverId, methodId) { - const server = this.servers[serverId]; - if (!server) { - throw new Error("server does not exists"); - } - const method = server.methods[methodId]; - delete server.methods[methodId]; - const clientMethodDefinition = hideMethodSystemFlags(method); - this.methodsCount[method.identifier] = this.methodsCount[method.identifier] - 1; - if (this.methodsCount[method.identifier] === 0) { - this.callbacks.execute("onMethodRemoved", clientMethodDefinition); - } - this.callbacks.execute("onServerMethodRemoved", server.instance, clientMethodDefinition); - } - getMethods() { - return this.extractMethodsFromServers(Object.values(this.servers)).map(hideMethodSystemFlags); - } - getServers() { - return Object.values(this.servers).map(this.hideServerMethodSystemFlags); - } - onServerAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerAdded", callback); - const serversWithMethodsToReplay = this.getServers().map((s) => s.instance); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, serversWithMethodsToReplay, callback); - } - onMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodAdded", callback); - const methodsToReplay = this.getMethods(); - return this.returnUnsubWithDelayedReplay(unsubscribeFunc, methodsToReplay, callback); - } - onServerMethodAdded(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodAdded", callback); - let unsubCalled = false; - const servers = this.getServers(); - setTimeout(() => { - servers.forEach((server) => { - const methods = server.methods; - Object.keys(methods).forEach((methodId) => { - if (!unsubCalled) { - callback(server.instance, methods[methodId]); - } - }); - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - onMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onMethodRemoved", callback); - return unsubscribeFunc; - } - onServerRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerRemoved", callback); - return unsubscribeFunc; - } - onServerMethodRemoved(callback) { - const unsubscribeFunc = this.callbacks.add("onServerMethodRemoved", callback); - return unsubscribeFunc; - } - getServerById(id) { - const server = this.servers[id]; - if (!server) { - return undefined; - } - return this.hideServerMethodSystemFlags(this.servers[id]); - } - reset() { - Object.keys(this.servers).forEach((key) => { - this.removeServerById(key, "reset"); - }); - this.servers = { - [this.myServer.id]: this.myServer - }; - this.methodsCount = {}; - } - createMethodIdentifier(methodInfo) { - const accepts = methodInfo.input_signature ?? ""; - const returns = methodInfo.result_signature ?? ""; - return (methodInfo.name + accepts + returns).toLowerCase(); - } - getServersByMethod(identifier) { - const allServers = []; - Object.values(this.servers).forEach((server) => { - Object.values(server.methods).forEach((method) => { - if (method.identifier === identifier) { - allServers.push(server.instance); - } - }); - }); - return allServers; - } - returnUnsubWithDelayedReplay(unsubscribeFunc, collectionToReplay, callback) { - let unsubCalled = false; - setTimeout(() => { - collectionToReplay.forEach((item) => { - if (!unsubCalled) { - callback(item); - } - }); - }, 0); - return () => { - unsubCalled = true; - unsubscribeFunc(); - }; - } - hideServerMethodSystemFlags(server) { - const clientMethods = {}; - Object.entries(server.methods).forEach(([name, method]) => { - clientMethods[name] = hideMethodSystemFlags(method); - }); - return { - ...server, - methods: clientMethods - }; - } - extractMethodsFromServers(servers) { - const methods = Object.values(servers).reduce((clientMethods, server) => { - return [...clientMethods, ...Object.values(server.methods)]; - }, []); - return methods; - } - } - - class ServerRepository { - nextId = 0; - methods = []; - add(method) { - method.repoId = String(this.nextId); - this.nextId += 1; - this.methods.push(method); - return method; - } - remove(repoId) { - if (typeof repoId !== "string") { - return new TypeError("Expecting a string"); - } - this.methods = this.methods.filter((m) => { - return m.repoId !== repoId; - }); - } - getById(id) { - if (typeof id !== "string") { - return undefined; - } - return this.methods.find((m) => { - return m.repoId === id; - }); - } - getList() { - return this.methods.map((m) => m); - } - length() { - return this.methods.length; - } - reset() { - this.methods = []; - } - } - - const SUBSCRIPTION_REQUEST = "onSubscriptionRequest"; - const SUBSCRIPTION_ADDED = "onSubscriptionAdded"; - const SUBSCRIPTION_REMOVED = "onSubscriptionRemoved"; - class ServerStreaming { - session; - repository; - serverRepository; - logger; - ERR_URI_SUBSCRIPTION_FAILED = "com.tick42.agm.errors.subscription.failure"; - callbacks = CallbackRegistryFactory(); - nextStreamId = 0; - constructor(session, repository, serverRepository, logger) { - this.session = session; - this.repository = repository; - this.serverRepository = serverRepository; - this.logger = logger; - session.on("add-interest", (msg) => { - this.handleAddInterest(msg); - }); - session.on("remove-interest", (msg) => { - this.handleRemoveInterest(msg); - }); - } - acceptRequestOnBranch(requestContext, streamingMethod, branch) { - if (typeof branch !== "string") { - branch = ""; - } - if (typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - throw new TypeError("The streaming method is missing its subscriptions."); - } - if (!Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - throw new TypeError("The streaming method is missing its branches."); - } - const streamId = this.getStreamId(streamingMethod, branch); - const key = requestContext.msg.subscription_id; - const subscription = { - id: key, - arguments: requestContext.arguments, - instance: requestContext.instance, - branchKey: branch, - streamId, - subscribeMsg: requestContext.msg, - }; - streamingMethod.protocolState.subscriptionsMap[key] = subscription; - this.session.sendFireAndForget({ - type: "accepted", - subscription_id: key, - stream_id: streamId, - }).catch((err) => { - this.logger.warn(`Failed to send accepted message for subscription ${key}: ${JSON.stringify(err)}`); - }); - this.callbacks.execute(SUBSCRIPTION_ADDED, subscription, streamingMethod); - } - rejectRequest(requestContext, streamingMethod, reason) { - if (typeof reason !== "string") { - reason = ""; - } - this.sendSubscriptionFailed("Subscription rejected by user. " + reason, requestContext.msg.subscription_id); - } - pushData(streamingMethod, data, branches) { - if (typeof streamingMethod !== "object" || !Array.isArray(streamingMethod.protocolState.branchKeyToStreamIdMap)) { - return; - } - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - if (typeof branches === "string") { - branches = [branches]; - } - else if (!Array.isArray(branches) || branches.length <= 0) { - branches = []; - } - const streamIdList = streamingMethod.protocolState.branchKeyToStreamIdMap - .filter((br) => { - if (!branches || branches.length === 0) { - return true; - } - return branches.indexOf(br.key) >= 0; - }).map((br) => { - return br.streamId; - }); - streamIdList.forEach((streamId) => { - const publishMessage = { - type: "publish", - stream_id: streamId, - data, - }; - this.session.sendFireAndForget(publishMessage) - .catch((err) => { - this.logger.warn(`Failed to send publish message for stream ${streamId}: ${JSON.stringify(err)}`); - }); - }); - } - pushDataToSingle(method, subscription, data) { - if (typeof data !== "object") { - throw new Error("Invalid arguments. Data must be an object."); - } - const postMessage = { - type: "post", - subscription_id: subscription.id, - data, - }; - this.session.sendFireAndForget(postMessage) - .catch((err) => { - this.logger.warn(`Failed to send post message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - } - closeSingleSubscription(streamingMethod, subscription) { - if (streamingMethod.protocolState.subscriptionsMap) { - delete streamingMethod.protocolState.subscriptionsMap[subscription.id]; - } - const dropSubscriptionMessage = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping a single subscription", - }; - this.session.sendFireAndForget(dropSubscriptionMessage) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - subscription.instance; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - closeMultipleSubscriptions(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object" || typeof streamingMethod.protocolState.subscriptionsMap !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - let subscriptionsToClose = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey === "string") { - subscriptionsToClose = subscriptionsToClose.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - subscriptionsToClose.forEach((subscription) => { - delete subscriptionsMap[subscription.id]; - const drop = { - type: "drop-subscription", - subscription_id: subscription.id, - reason: "Server dropping all subscriptions on stream_id: " + subscription.streamId, - }; - this.session.sendFireAndForget(drop) - .catch((err) => { - this.logger.warn(`Failed to send drop-subscription message for subscription ${subscription.id}: ${JSON.stringify(err)}`); - }); - }); - } - getSubscriptionList(streamingMethod, branchKey) { - if (typeof streamingMethod !== "object") { - return []; - } - let subscriptions = []; - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - if (typeof branchKey !== "string") { - subscriptions = allSubscriptions; - } - else { - subscriptions = allSubscriptions.filter((sub) => { - return sub.branchKey === branchKey; - }); - } - return subscriptions; - } - getBranchList(streamingMethod) { - if (typeof streamingMethod !== "object") { - return []; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return []; - } - const subscriptionsMap = streamingMethod.protocolState.subscriptionsMap; - const allSubscriptions = Object.keys(subscriptionsMap) - .map((key) => { - return subscriptionsMap[key]; - }); - const result = []; - allSubscriptions.forEach((sub) => { - let branch = ""; - if (typeof sub === "object" && typeof sub.branchKey === "string") { - branch = sub.branchKey; - } - if (result.indexOf(branch) === -1) { - result.push(branch); - } - }); - return result; - } - onSubAdded(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_ADDED, callback); - } - onSubRequest(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REQUEST, callback); - } - onSubRemoved(callback) { - this.onSubscriptionLifetimeEvent(SUBSCRIPTION_REMOVED, callback); - } - handleRemoveInterest(msg) { - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (typeof msg.subscription_id !== "string" || - typeof streamingMethod !== "object") { - return; - } - if (!streamingMethod.protocolState.subscriptionsMap) { - return; - } - if (typeof streamingMethod.protocolState.subscriptionsMap[msg.subscription_id] !== "object") { - return; - } - const subscription = streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - delete streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]; - this.callbacks.execute(SUBSCRIPTION_REMOVED, subscription, streamingMethod); - } - onSubscriptionLifetimeEvent(eventName, handlerFunc) { - this.callbacks.add(eventName, handlerFunc); - } - getNextStreamId() { - return this.nextStreamId++ + ""; - } - handleAddInterest(msg) { - const caller = this.repository.getServerById(msg.caller_id); - const instance = caller?.instance ?? {}; - const requestContext = { - msg, - arguments: msg.arguments_kv || {}, - instance, - }; - const streamingMethod = this.serverRepository.getById(msg.method_id); - if (streamingMethod === undefined) { - const errorMsg = "No method with id " + msg.method_id + " on this server."; - this.sendSubscriptionFailed(errorMsg, msg.subscription_id); - return; - } - if (streamingMethod.protocolState.subscriptionsMap && - streamingMethod.protocolState.subscriptionsMap[msg.subscription_id]) { - this.sendSubscriptionFailed("A subscription with id " + msg.subscription_id + " already exists.", msg.subscription_id); - return; - } - this.callbacks.execute(SUBSCRIPTION_REQUEST, requestContext, streamingMethod); - } - sendSubscriptionFailed(reason, subscriptionId) { - const errorMessage = { - type: "error", - reason_uri: this.ERR_URI_SUBSCRIPTION_FAILED, - reason, - request_id: subscriptionId, - }; - this.session.sendFireAndForget(errorMessage) - .catch((err) => { - this.logger.warn(`Failed to send subscription failed message for subscription ${subscriptionId}: ${JSON.stringify(err)}`); - }); - } - getStreamId(streamingMethod, branchKey) { - if (typeof branchKey !== "string") { - branchKey = ""; - } - if (!streamingMethod.protocolState.branchKeyToStreamIdMap) { - throw new Error(`streaming ${streamingMethod.definition.name} method without protocol state`); - } - const needleBranch = streamingMethod.protocolState.branchKeyToStreamIdMap.filter((branch) => { - return branch.key === branchKey; - })[0]; - let streamId = (needleBranch ? needleBranch.streamId : undefined); - if (typeof streamId !== "string" || streamId === "") { - streamId = this.getNextStreamId(); - streamingMethod.protocolState.branchKeyToStreamIdMap.push({ key: branchKey, streamId }); - } - return streamId; - } - } - - class ServerProtocol { - session; - clientRepository; - serverRepository; - logger; - callbacks = CallbackRegistryFactory(); - streaming; - constructor(session, clientRepository, serverRepository, logger) { - this.session = session; - this.clientRepository = clientRepository; - this.serverRepository = serverRepository; - this.logger = logger; - this.streaming = new ServerStreaming(session, clientRepository, serverRepository, logger.subLogger("streaming")); - this.session.on("invoke", (msg) => this.handleInvokeMessage(msg)); - } - createStream(repoMethod) { - repoMethod.protocolState.subscriptionsMap = {}; - repoMethod.protocolState.branchKeyToStreamIdMap = []; - return this.register(repoMethod, true); - } - register(repoMethod, isStreaming) { - const methodDef = repoMethod.definition; - const flags = Object.assign({}, { metadata: methodDef.flags ?? {} }, { streaming: isStreaming || false }); - const registerMsg = { - type: "register", - methods: [{ - id: repoMethod.repoId, - name: methodDef.name, - display_name: methodDef.displayName, - description: methodDef.description, - version: methodDef.version, - flags, - object_types: methodDef.objectTypes || methodDef.object_types, - input_signature: methodDef.accepts, - result_signature: methodDef.returns, - restrictions: undefined, - }], - }; - return this.session.send(registerMsg, { methodId: repoMethod.repoId }) - .then(() => { - this.logger.debug("registered method " + repoMethod.definition.name + " with id " + repoMethod.repoId); - }) - .catch((msg) => { - this.logger.warn(`failed to register method ${repoMethod.definition.name} with id ${repoMethod.repoId} - ${JSON.stringify(msg)}`); - throw msg; - }); - } - onInvoked(callback) { - this.callbacks.add("onInvoked", callback); - } - methodInvocationResult(method, invocationId, err, result) { - let msg; - if (err || err === "") { - msg = { - type: "error", - request_id: invocationId, - reason_uri: "agm.errors.client_error", - reason: err, - context: result, - peer_id: undefined, - }; - } - else { - msg = { - type: "yield", - invocation_id: invocationId, - peer_id: this.session.peerId, - result, - request_id: undefined, - }; - } - this.session.sendFireAndForget(msg) - .catch((error => { - this.logger.warn(`Failed to send method invocation result for method ${method.definition.name} invocation ${invocationId} - ${JSON.stringify(error)}`); - })); - } - async unregister(method) { - const msg = { - type: "unregister", - methods: [method.repoId], - }; - await this.session.send(msg); - } - getBranchList(method) { - return this.streaming.getBranchList(method); - } - getSubscriptionList(method, branchKey) { - return this.streaming.getSubscriptionList(method, branchKey); - } - closeAllSubscriptions(method, branchKey) { - this.streaming.closeMultipleSubscriptions(method, branchKey); - } - pushData(method, data, branches) { - this.streaming.pushData(method, data, branches); - } - pushDataToSingle(method, subscription, data) { - this.streaming.pushDataToSingle(method, subscription, data); - } - closeSingleSubscription(method, subscription) { - this.streaming.closeSingleSubscription(method, subscription); - } - acceptRequestOnBranch(requestContext, method, branch) { - this.streaming.acceptRequestOnBranch(requestContext, method, branch); - } - rejectRequest(requestContext, method, reason) { - this.streaming.rejectRequest(requestContext, method, reason); - } - onSubRequest(callback) { - this.streaming.onSubRequest(callback); - } - onSubAdded(callback) { - this.streaming.onSubAdded(callback); - } - onSubRemoved(callback) { - this.streaming.onSubRemoved(callback); - } - handleInvokeMessage(msg) { - const invocationId = msg.invocation_id; - const callerId = msg.caller_id; - const methodId = msg.method_id; - const args = msg.arguments_kv; - const methodList = this.serverRepository.getList(); - const method = methodList.filter((m) => { - return m.repoId === methodId; - })[0]; - if (method === undefined) { - return; - } - const client = this.clientRepository.getServerById(callerId)?.instance; - const invocationArgs = { args, instance: client }; - this.callbacks.execute("onInvoked", method, invocationId, invocationArgs); - } - } - - class UserSubscription { - repository; - subscriptionData; - get requestArguments() { - return this.subscriptionData.params.arguments || {}; - } - get servers() { - return this.subscriptionData.trackedServers.reduce((servers, pair) => { - if (pair.subscriptionId) { - const server = this.repository.getServerById(pair.serverId)?.instance; - if (server) { - servers.push(server); - } - } - return servers; - }, []); - } - get serverInstance() { - return this.servers[0]; - } - get stream() { - return this.subscriptionData.method; - } - constructor(repository, subscriptionData) { - this.repository = repository; - this.subscriptionData = subscriptionData; - } - onData(dataCallback) { - if (typeof dataCallback !== "function") { - throw new TypeError("The data callback must be a function."); - } - this.subscriptionData.handlers.onData.push(dataCallback); - if (this.subscriptionData.handlers.onData.length === 1 && this.subscriptionData.queued.data.length > 0) { - this.subscriptionData.queued.data.forEach((dataItem) => { - dataCallback(dataItem); - }); - } - } - onClosed(closedCallback) { - if (typeof closedCallback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onClosed.push(closedCallback); - } - onFailed(callback) { - } - onConnected(callback) { - if (typeof callback !== "function") { - throw new TypeError("The callback must be a function."); - } - this.subscriptionData.handlers.onConnected.push(callback); - } - close() { - this.subscriptionData.close(); - } - setNewSubscription(newSub) { - this.subscriptionData = newSub; - } - } - - class TimedCache { - config; - cache = []; - timeoutIds = []; - constructor(config) { - this.config = config; - } - add(element) { - const id = nanoid(10); - this.cache.push({ id, element }); - const timeoutId = setTimeout(() => { - const elementIdx = this.cache.findIndex((entry) => entry.id === id); - if (elementIdx < 0) { - return; - } - this.cache.splice(elementIdx, 1); - }, this.config.ELEMENT_TTL_MS); - this.timeoutIds.push(timeoutId); - } - flush() { - const elements = this.cache.map((entry) => entry.element); - this.timeoutIds.forEach((id) => clearInterval(id)); - this.cache = []; - this.timeoutIds = []; - return elements; - } - } - - const STATUS_AWAITING_ACCEPT = "awaitingAccept"; - const STATUS_SUBSCRIBED = "subscribed"; - const ERR_MSG_SUB_FAILED = "Subscription failed."; - const ERR_MSG_SUB_REJECTED = "Subscription rejected."; - const ON_CLOSE_MSG_SERVER_INIT = "ServerInitiated"; - const ON_CLOSE_MSG_CLIENT_INIT = "ClientInitiated"; - class ClientStreaming { - session; - repository; - logger; - subscriptionsList = {}; - timedCache = new TimedCache({ ELEMENT_TTL_MS: 10000 }); - subscriptionIdToLocalKeyMap = {}; - nextSubLocalKey = 0; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("subscribed", this.handleSubscribed); - session.on("event", this.handleEventData); - session.on("subscription-cancelled", this.handleSubscriptionCancelled); - } - subscribe(streamingMethod, params, targetServers, success, error, existingSub) { - if (targetServers.length === 0) { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " No available servers matched the target params.", - }); - return; - } - const subLocalKey = this.getNextSubscriptionLocalKey(); - const pendingSub = this.registerSubscription(subLocalKey, streamingMethod, params, success, error, params.methodResponseTimeout || 10000, existingSub); - if (typeof pendingSub !== "object") { - error({ - method: streamingMethod, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Unable to register the user callbacks.", - }); - return; - } - targetServers.forEach((target) => { - const serverId = target.server.id; - const method = target.methods.find((m) => m.name === streamingMethod.name); - if (!method) { - this.logger.error(`can not find method ${streamingMethod.name} for target ${target.server.id}`); - return; - } - pendingSub.trackedServers.push({ - serverId, - subscriptionId: undefined, - }); - const msg = { - type: "subscribe", - server_id: serverId, - method_id: method.gatewayId, - arguments_kv: params.arguments, - }; - this.session.send(msg, { serverId, subLocalKey }) - .then((m) => this.handleSubscribed(m)) - .catch((err) => this.handleErrorSubscribing(err)); - }); - } - drainSubscriptions() { - const existing = Object.values(this.subscriptionsList); - this.subscriptionsList = {}; - this.subscriptionIdToLocalKeyMap = {}; - return existing; - } - drainSubscriptionsCache() { - return this.timedCache.flush(); - } - getNextSubscriptionLocalKey() { - const current = this.nextSubLocalKey; - this.nextSubLocalKey += 1; - return current; - } - registerSubscription(subLocalKey, method, params, success, error, timeout, existingSub) { - const subsInfo = { - localKey: subLocalKey, - status: STATUS_AWAITING_ACCEPT, - method, - params, - success, - error, - trackedServers: [], - handlers: { - onData: existingSub?.handlers.onData || [], - onClosed: existingSub?.handlers.onClosed || [], - onConnected: existingSub?.handlers.onConnected || [], - }, - queued: { - data: [], - closers: [], - }, - timeoutId: undefined, - close: () => this.closeSubscription(subLocalKey), - subscription: existingSub?.subscription - }; - if (!existingSub) { - if (params.onData) { - subsInfo.handlers.onData.push(params.onData); - } - if (params.onClosed) { - subsInfo.handlers.onClosed.push(params.onClosed); - } - if (params.onConnected) { - subsInfo.handlers.onConnected.push(params.onConnected); - } - } - this.subscriptionsList[subLocalKey] = subsInfo; - subsInfo.timeoutId = setTimeout(() => { - if (this.subscriptionsList[subLocalKey] === undefined) { - return; - } - const pendingSub = this.subscriptionsList[subLocalKey]; - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - error({ - method, - called_with: params.arguments, - message: ERR_MSG_SUB_FAILED + " Subscription attempt timed out after " + timeout + " ms.", - }); - delete this.subscriptionsList[subLocalKey]; - } - else if (pendingSub.status === STATUS_SUBSCRIBED && pendingSub.trackedServers.length > 0) { - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return (typeof server.subscriptionId !== "undefined"); - }); - delete pendingSub.timeoutId; - if (pendingSub.trackedServers.length <= 0) { - this.callOnClosedHandlers(pendingSub); - delete this.subscriptionsList[subLocalKey]; - } - } - }, timeout); - return subsInfo; - } - handleErrorSubscribing = (errorResponse) => { - const tag = errorResponse._tag; - const subLocalKey = tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - pendingSub.trackedServers = pendingSub.trackedServers.filter((server) => { - return server.serverId !== tag.serverId; - }); - if (pendingSub.trackedServers.length <= 0) { - clearTimeout(pendingSub.timeoutId); - if (pendingSub.status === STATUS_AWAITING_ACCEPT) { - const reason = (typeof errorResponse.reason === "string" && errorResponse.reason !== "") ? - ' Publisher said "' + errorResponse.reason + '".' : - " No reason given."; - const callArgs = typeof pendingSub.params.arguments === "object" ? - JSON.stringify(pendingSub.params.arguments) : - "{}"; - pendingSub.error({ - message: ERR_MSG_SUB_REJECTED + reason + " Called with:" + callArgs, - called_with: pendingSub.params.arguments, - method: pendingSub.method, - }); - } - else if (pendingSub.status === STATUS_SUBSCRIBED) { - this.callOnClosedHandlers(pendingSub); - } - delete this.subscriptionsList[subLocalKey]; - } - }; - handleSubscribed = (msg) => { - const subLocalKey = msg._tag.subLocalKey; - const pendingSub = this.subscriptionsList[subLocalKey]; - if (typeof pendingSub !== "object") { - return; - } - const serverId = msg._tag.serverId; - const acceptingServer = pendingSub.trackedServers - .filter((server) => { - return server.serverId === serverId; - })[0]; - if (typeof acceptingServer !== "object") { - return; - } - acceptingServer.subscriptionId = msg.subscription_id; - this.subscriptionIdToLocalKeyMap[msg.subscription_id] = subLocalKey; - const isFirstResponse = (pendingSub.status === STATUS_AWAITING_ACCEPT); - pendingSub.status = STATUS_SUBSCRIBED; - if (isFirstResponse) { - let reconnect = false; - let sub = pendingSub.subscription; - if (sub) { - sub.setNewSubscription(pendingSub); - pendingSub.success(sub); - reconnect = true; - } - else { - sub = new UserSubscription(this.repository, pendingSub); - pendingSub.subscription = sub; - pendingSub.success(sub); - } - for (const handler of pendingSub.handlers.onConnected) { - try { - handler(sub.serverInstance, reconnect); - } - catch (e) { - } - } - } - }; - handleEventData = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const trackedServersFound = subscription.trackedServers.filter((s) => { - return s.subscriptionId === msg.subscription_id; - }); - if (trackedServersFound.length !== 1) { - return; - } - const isPrivateData = msg.oob; - const sendingServerId = trackedServersFound[0].serverId; - const server = this.repository.getServerById(sendingServerId); - const receivedStreamData = () => { - return { - data: msg.data, - server: server?.instance ?? {}, - requestArguments: subscription.params.arguments, - message: undefined, - private: isPrivateData, - }; - }; - const onDataHandlers = subscription.handlers.onData; - const queuedData = subscription.queued.data; - if (onDataHandlers.length > 0) { - onDataHandlers.forEach((callback) => { - if (typeof callback === "function") { - callback(receivedStreamData()); - } - }); - } - else { - queuedData.push(receivedStreamData()); - } - }; - handleSubscriptionCancelled = (msg) => { - const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - if (typeof subLocalKey === "undefined") { - return; - } - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - const expectedNewLength = subscription.trackedServers.length - 1; - subscription.trackedServers = subscription.trackedServers.filter((server) => { - if (server.subscriptionId === msg.subscription_id) { - subscription.queued.closers.push(server.serverId); - return false; - } - else { - return true; - } - }); - if (subscription.trackedServers.length !== expectedNewLength) { - return; - } - if (subscription.trackedServers.length <= 0) { - this.timedCache.add(subscription); - clearTimeout(subscription.timeoutId); - this.callOnClosedHandlers(subscription); - delete this.subscriptionsList[subLocalKey]; - } - delete this.subscriptionIdToLocalKeyMap[msg.subscription_id]; - }; - callOnClosedHandlers(subscription, reason) { - const closersCount = subscription.queued.closers.length; - const closingServerId = (closersCount > 0) ? subscription.queued.closers[closersCount - 1] : null; - let closingServer; - if (closingServerId !== undefined && typeof closingServerId === "string") { - closingServer = this.repository.getServerById(closingServerId)?.instance ?? {}; - } - subscription.handlers.onClosed.forEach((callback) => { - if (typeof callback !== "function") { - return; - } - callback({ - message: reason || ON_CLOSE_MSG_SERVER_INIT, - requestArguments: subscription.params.arguments || {}, - server: closingServer, - stream: subscription.method, - }); - }); - } - closeSubscription(subLocalKey) { - const subscription = this.subscriptionsList[subLocalKey]; - if (typeof subscription !== "object") { - return; - } - subscription.trackedServers.forEach((server) => { - if (typeof server.subscriptionId === "undefined") { - return; - } - subscription.queued.closers.push(server.serverId); - this.session.sendFireAndForget({ - type: "unsubscribe", - subscription_id: server.subscriptionId, - reason_uri: "", - reason: ON_CLOSE_MSG_CLIENT_INIT, - }).catch((err) => { - this.logger.warn(`Error sending unsubscribe for subscription id ${server.subscriptionId}: ${JSON.stringify(err)}`); - }); - delete this.subscriptionIdToLocalKeyMap[server.subscriptionId]; - }); - subscription.trackedServers = []; - this.callOnClosedHandlers(subscription, ON_CLOSE_MSG_CLIENT_INIT); - delete this.subscriptionsList[subLocalKey]; - } - } - - class ClientProtocol { - session; - repository; - logger; - streaming; - constructor(session, repository, logger) { - this.session = session; - this.repository = repository; - this.logger = logger; - session.on("peer-added", (msg) => this.handlePeerAdded(msg)); - session.on("peer-removed", (msg) => this.handlePeerRemoved(msg)); - session.on("methods-added", (msg) => this.handleMethodsAddedMessage(msg)); - session.on("methods-removed", (msg) => this.handleMethodsRemovedMessage(msg)); - this.streaming = new ClientStreaming(session, repository, logger); - } - subscribe(stream, options, targetServers, success, error, existingSub) { - this.streaming.subscribe(stream, options, targetServers, success, error, existingSub); - } - invoke(id, method, args, target) { - const serverId = target.id; - const methodId = method.gatewayId; - const msg = { - type: "call", - server_id: serverId, - method_id: methodId, - arguments_kv: args, - }; - return this.session.send(msg, { invocationId: id, serverId }) - .then((m) => this.handleResultMessage(m)) - .catch((err) => this.handleInvocationError(err)); - } - drainSubscriptions() { - return this.streaming.drainSubscriptions(); - } - drainSubscriptionsCache() { - return this.streaming.drainSubscriptionsCache(); - } - handlePeerAdded(msg) { - const newPeerId = msg.new_peer_id; - const remoteId = msg.identity; - const isLocal = msg.meta ? msg.meta.local : true; - const pid = Number(remoteId.process); - const serverInfo = { - machine: remoteId.machine, - pid: isNaN(pid) ? remoteId.process : pid, - instance: remoteId.instance, - application: remoteId.application, - applicationName: remoteId.applicationName, - environment: remoteId.environment, - region: remoteId.region, - user: remoteId.user, - windowId: remoteId.windowId, - peerId: newPeerId, - api: remoteId.api, - isLocal - }; - this.repository.addServer(serverInfo, newPeerId); - } - handlePeerRemoved(msg) { - const removedPeerId = msg.removed_id; - const reason = msg.reason; - this.repository.removeServerById(removedPeerId, reason); - } - handleMethodsAddedMessage(msg) { - const serverId = msg.server_id; - const methods = msg.methods; - methods.forEach((method) => { - this.repository.addServerMethod(serverId, method); - }); - } - handleMethodsRemovedMessage(msg) { - const serverId = msg.server_id; - const methodIdList = msg.methods; - const server = this.repository.getServerById(serverId); - if (server) { - const serverMethodKeys = Object.keys(server.methods); - serverMethodKeys.forEach((methodKey) => { - const method = server.methods[methodKey]; - if (methodIdList.indexOf(method.gatewayId) > -1) { - this.repository.removeServerMethod(serverId, methodKey); - } - }); - } - } - handleResultMessage(msg) { - const invocationId = msg._tag.invocationId; - const result = msg.result; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - return { - invocationId, - result, - instance: server?.instance, - status: InvokeStatus.Success, - message: "" - }; - } - handleInvocationError(msg) { - this.logger.debug(`handle invocation error ${JSON.stringify(msg)}`); - if ("_tag" in msg) { - const invocationId = msg._tag.invocationId; - const serverId = msg._tag.serverId; - const server = this.repository.getServerById(serverId); - const message = msg.reason; - const context = msg.context; - return { - invocationId, - result: context, - instance: server?.instance, - status: InvokeStatus.Error, - message - }; - } - else { - return { - invocationId: "", - message: msg.message, - status: InvokeStatus.Error, - error: msg - }; - } - } - } - - function gW3ProtocolFactory (instance, connection, clientRepository, serverRepository, libConfig, interop) { - const logger = libConfig.logger.subLogger("gw3-protocol"); - let resolveReadyPromise; - const readyPromise = new Promise((resolve) => { - resolveReadyPromise = resolve; - }); - const session = connection.domain("agm", ["subscribed"]); - const server = new ServerProtocol(session, clientRepository, serverRepository, logger.subLogger("server")); - const client = new ClientProtocol(session, clientRepository, logger.subLogger("client")); - async function handleReconnect() { - logger.info("reconnected - will replay registered methods and subscriptions"); - client.drainSubscriptionsCache().forEach((sub) => { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to soft-re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`soft-subscribing to method ${methodInfo.name} DONE`)).catch((error) => logger.warn(`subscribing to method ${methodInfo.name} failed: ${JSON.stringify(error)}}`)); - }); - const reconnectionPromises = []; - const existingSubscriptions = client.drainSubscriptions(); - for (const sub of existingSubscriptions) { - const methodInfo = sub.method; - const params = Object.assign({}, sub.params); - logger.info(`trying to re-subscribe to method ${methodInfo.name}, with params: ${JSON.stringify(params)}`); - reconnectionPromises.push(interop.client.subscribe(methodInfo, params, undefined, undefined, sub).then(() => logger.info(`subscribing to method ${methodInfo.name} DONE`))); - } - const registeredMethods = serverRepository.getList(); - serverRepository.reset(); - for (const method of registeredMethods) { - const def = method.definition; - if (method.stream) { - reconnectionPromises.push(interop.server.createStream(def, method.streamCallbacks, undefined, undefined, method.stream) - .then(() => logger.info(`subscribing to method ${def.name} DONE`)) - .catch(() => logger.warn(`subscribing to method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallback) { - reconnectionPromises.push(interop.register(def, method.theFunction.userCallback) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - else if (method?.theFunction?.userCallbackAsync) { - reconnectionPromises.push(interop.registerAsync(def, method.theFunction.userCallbackAsync) - .then(() => logger.info(`registering method ${def.name} DONE`)) - .catch(() => logger.warn(`registering method ${def.name} FAILED`))); - } - } - await Promise.all(reconnectionPromises); - logger.info("Interop is re-announced"); - } - function handleInitialJoin() { - if (resolveReadyPromise) { - resolveReadyPromise({ - client, - server, - }); - resolveReadyPromise = undefined; - } - } - session.onJoined((reconnect) => { - clientRepository.addServer(instance, connection.peerId); - if (reconnect) { - handleReconnect().then(() => connection.setLibReAnnounced({ name: "interop" })).catch((error) => logger.warn(`Error while re-announcing interop: ${JSON.stringify(error)}`)); - } - else { - handleInitialJoin(); - } - }); - session.onLeft(() => { - clientRepository.reset(); - }); - session.join(); - return readyPromise; - } - - class Interop { - instance; - readyPromise; - client; - server; - unwrappedInstance; - protocol; - clientRepository; - serverRepository; - constructor(configuration) { - if (typeof configuration === "undefined") { - throw new Error("configuration is required"); - } - if (typeof configuration.connection === "undefined") { - throw new Error("configuration.connections is required"); - } - const connection = configuration.connection; - if (typeof configuration.methodResponseTimeout !== "number") { - configuration.methodResponseTimeout = 30 * 1000; - } - if (typeof configuration.waitTimeoutMs !== "number") { - configuration.waitTimeoutMs = 30 * 1000; - } - this.unwrappedInstance = new InstanceWrapper(this, undefined, connection); - this.instance = this.unwrappedInstance.unwrap(); - this.clientRepository = new ClientRepository(configuration.logger.subLogger("cRep"), this); - this.serverRepository = new ServerRepository(); - let protocolPromise; - if (connection.protocolVersion === 3) { - protocolPromise = gW3ProtocolFactory(this.instance, connection, this.clientRepository, this.serverRepository, configuration, this); - } - else { - throw new Error(`protocol ${connection.protocolVersion} not supported`); - } - this.readyPromise = protocolPromise.then((protocol) => { - this.protocol = protocol; - this.client = new Client(this.protocol, this.clientRepository, this.instance, configuration); - this.server = new Server(this.protocol, this.serverRepository); - return this; - }); - } - ready() { - return this.readyPromise; - } - serverRemoved(callback) { - return this.client.serverRemoved(callback); - } - serverAdded(callback) { - return this.client.serverAdded(callback); - } - serverMethodRemoved(callback) { - return this.client.serverMethodRemoved(callback); - } - serverMethodAdded(callback) { - return this.client.serverMethodAdded(callback); - } - methodRemoved(callback) { - return this.client.methodRemoved(callback); - } - methodAdded(callback) { - return this.client.methodAdded(callback); - } - methodsForInstance(instance) { - return this.client.methodsForInstance(instance); - } - methods(methodFilter) { - return this.client.methods(methodFilter); - } - servers(methodFilter) { - return this.client.servers(methodFilter); - } - subscribe(method, options, successCallback, errorCallback) { - return this.client.subscribe(method, options, successCallback, errorCallback); - } - createStream(streamDef, callbacks, successCallback, errorCallback) { - return this.server.createStream(streamDef, callbacks, successCallback, errorCallback); - } - unregister(methodFilter) { - return this.server.unregister(methodFilter); - } - registerAsync(methodDefinition, callback) { - return this.server.registerAsync(methodDefinition, callback); - } - register(methodDefinition, callback) { - return this.server.register(methodDefinition, callback); - } - invoke(methodFilter, argumentObj, target, additionalOptions, success, error) { - return this.client.invoke(methodFilter, argumentObj, target, additionalOptions, success, error); - } - waitForMethod(name) { - const pw = new PromiseWrapper(); - const unsubscribe = this.client.methodAdded((m) => { - if (m.name === name) { - unsubscribe(); - pw.resolve(m); - } - }); - return pw.promise; - } - } - - const successMessages = ["subscribed", "success"]; - class MessageBus { - connection; - logger; - peerId; - session; - subscriptions; - readyPromise; - constructor(connection, logger) { - this.connection = connection; - this.logger = logger; - this.peerId = connection.peerId; - this.subscriptions = []; - this.session = connection.domain("bus", successMessages); - this.readyPromise = this.session.join(); - this.readyPromise.then(() => { - this.watchOnEvent(); - }); - } - ready() { - return this.readyPromise; - } - publish = (topic, data, options) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "publish", - topic, - data, - peer_id: this.peerId, - routing_key: routingKey, - target_identity: target - }); - this.session.send(args) - .catch((err) => { - this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`); - }); - }; - subscribe = (topic, callback, options) => { - return new Promise((resolve, reject) => { - const { routingKey, target } = options || {}; - const args = this.removeEmptyValues({ - type: "subscribe", - topic, - peer_id: this.peerId, - routing_key: routingKey, - source: target - }); - this.session.send(args) - .then((response) => { - const { subscription_id } = response; - this.subscriptions.push({ subscription_id, topic, callback, source: target }); - resolve({ - unsubscribe: () => { - this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId }) - .then(() => { - this.subscriptions = this.subscriptions.filter((s) => s.subscription_id !== subscription_id); - }).catch((err) => { - this.logger.warn(`Failed to send unsubscribe request for ${subscription_id}: ${JSON.stringify(err)}`); - }); - return Promise.resolve(); - } - }); - }) - .catch((error) => reject(error)); - }); - }; - watchOnEvent = () => { - this.session.on("event", (args) => { - const { data, subscription_id } = args; - const source = args["publisher-identity"]; - const subscription = this.subscriptions.find((s) => s.subscription_id === subscription_id); - if (subscription) { - if (!subscription.source) { - subscription.callback(data, subscription.topic, source); - } - else { - if (this.keysMatch(subscription.source, source)) { - subscription.callback(data, subscription.topic, source); - } - } - } - }); - }; - removeEmptyValues(obj) { - const cleaned = {}; - Object.keys(obj).forEach((key) => { - if (obj[key] !== undefined && obj[key] !== null) { - cleaned[key] = obj[key]; - } - }); - return cleaned; - } - keysMatch(obj1, obj2) { - const keysObj1 = Object.keys(obj1); - let allMatch = true; - keysObj1.forEach((key) => { - if (obj1[key] !== obj2[key]) { - allMatch = false; - } - }); - return allMatch; - } - } - - const IOConnectCoreFactory = (userConfig, ext) => { - const iodesktop = typeof window === "object" ? (window.iodesktop ?? window.glue42gd) : undefined; - const preloadPromise = typeof window === "object" ? (window.gdPreloadPromise ?? Promise.resolve()) : Promise.resolve(); - const glueInitTimer = timer("glue"); - userConfig = userConfig || {}; - ext = ext || {}; - const internalConfig = prepareConfig(userConfig, ext, iodesktop); - let _connection; - let _interop; - let _logger; - let _metrics; - let _contexts; - let _bus; - let _allowTrace; - const libs = {}; - function registerLib(name, inner, t) { - _allowTrace = _logger.canPublish("trace"); - if (_allowTrace) { - _logger.trace(`registering ${name} module`); - } - const done = (e) => { - inner.initTime = t.stop(); - inner.initEndTime = t.endTime; - inner.marks = t.marks; - if (!_allowTrace) { - return; - } - const traceMessage = e ? - `${name} failed - ${e.message}` : - `${name} is ready - ${t.endTime - t.startTime}`; - _logger.trace(traceMessage); - }; - inner.initStartTime = t.startTime; - if (inner.ready) { - inner.ready() - .then(() => { - done(); - }) - .catch((e) => { - const error = typeof e === "string" ? new Error(e) : e; - done(error); - }); - } - else { - done(); - } - if (!Array.isArray(name)) { - name = [name]; - } - name.forEach((n) => { - libs[n] = inner; - IOConnectCoreFactory[n] = inner; - }); - } - function setupConnection() { - const initTimer = timer("connection"); - _connection = new Connection(internalConfig.connection, _logger.subLogger("connection")); - let authPromise = Promise.resolve(internalConfig.auth); - if (internalConfig.connection && !internalConfig.auth) { - if (iodesktop) { - authPromise = iodesktop.getGWToken() - .then((token) => { - return { - gatewayToken: token - }; - }); - } - else if (typeof window !== "undefined" && window?.glue42electron) { - if (typeof window.glue42electron.gwToken === "string") { - authPromise = Promise.resolve({ - gatewayToken: window.glue42electron.gwToken - }); - } - } - else { - authPromise = Promise.reject("You need to provide auth information"); - } - } - return authPromise - .then((authConfig) => { - initTimer.mark("auth-promise-resolved"); - let authRequest; - if (Object.prototype.toString.call(authConfig) === "[object Object]") { - authRequest = authConfig; - } - else { - throw new Error("Invalid auth object - " + JSON.stringify(authConfig)); - } - return _connection.login(authRequest); - }) - .then(() => { - registerLib("connection", _connection, initTimer); - return internalConfig; - }) - .catch((e) => { - if (_connection) { - _connection.logout(); - } - throw e; - }); - } - function setupLogger() { - const initTimer = timer("logger"); - _logger = new Logger(`${internalConfig.connection.identity?.application}`, undefined, internalConfig.customLogger); - _logger.consoleLevel(internalConfig.logger.console); - _logger.publishLevel(internalConfig.logger.publish); - if (_logger.canPublish("debug")) { - _logger.debug("initializing glue..."); - } - registerLib("logger", _logger, initTimer); - return Promise.resolve(undefined); - } - function setupMetrics() { - const initTimer = timer("metrics"); - const config = internalConfig.metrics; - const metricsPublishingEnabledFunc = iodesktop?.getMetricsPublishingEnabled; - const identity = internalConfig.connection.identity; - const canUpdateMetric = metricsPublishingEnabledFunc ? metricsPublishingEnabledFunc : () => true; - const disableAutoAppSystem = (typeof config !== "boolean" && config.disableAutoAppSystem) ?? false; - _metrics = metrics({ - connection: config ? _connection : undefined, - logger: _logger.subLogger("metrics"), - canUpdateMetric, - system: "Glue42", - service: identity?.service ?? iodesktop?.applicationName ?? internalConfig.application, - instance: identity?.instance ?? identity?.windowId ?? nanoid(10), - disableAutoAppSystem, - pagePerformanceMetrics: typeof config !== "boolean" ? config?.pagePerformanceMetrics : undefined - }); - registerLib("metrics", _metrics, initTimer); - return Promise.resolve(); - } - function setupInterop() { - const initTimer = timer("interop"); - const agmConfig = { - connection: _connection, - logger: _logger.subLogger("interop"), - }; - _interop = new Interop(agmConfig); - Logger.Interop = _interop; - registerLib(["interop", "agm"], _interop, initTimer); - return Promise.resolve(); - } - function setupContexts() { - const hasActivities = (internalConfig.activities && _connection.protocolVersion === 3); - const needsContexts = internalConfig.contexts || hasActivities; - if (needsContexts) { - const initTimer = timer("contexts"); - _contexts = new ContextsModule({ - connection: _connection, - logger: _logger.subLogger("contexts"), - trackAllContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.trackAllContexts : false, - reAnnounceKnownContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.reAnnounceKnownContexts : false, - subscribeOnGet: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnGet : true, - subscribeOnUpdate: typeof internalConfig.contexts === "object" ? internalConfig.contexts.subscribeOnUpdate : true, - onlyReAnnounceSubscribedContexts: typeof internalConfig.contexts === "object" ? internalConfig.contexts.onlyReAnnounceSubscribedContexts : true - }); - registerLib("contexts", _contexts, initTimer); - } - else { - const replayer = _connection.replayer; - if (replayer) { - replayer.drain(ContextMessageReplaySpec.name); - } - } - return Promise.resolve(); - } - async function setupBus() { - if (!internalConfig.bus) { - return Promise.resolve(); - } - const initTimer = timer("bus"); - _bus = new MessageBus(_connection, _logger.subLogger("bus")); - registerLib("bus", _bus, initTimer); - return Promise.resolve(); - } - function setupExternalLibs(externalLibs) { - try { - externalLibs.forEach((lib) => { - setupExternalLib(lib.name, lib.create); - }); - return Promise.resolve(); - } - catch (e) { - return Promise.reject(e); - } - } - function setupExternalLib(name, createCallback) { - const initTimer = timer(name); - const lib = createCallback(libs); - if (lib) { - registerLib(name, lib, initTimer); - } - } - function waitForLibs() { - const libsReadyPromises = Object.keys(libs).map((key) => { - const lib = libs[key]; - return lib.ready ? - lib.ready() : Promise.resolve(); - }); - return Promise.all(libsReadyPromises); - } - function constructGlueObject() { - const feedbackFunc = (feedbackInfo) => { - if (!_interop) { - return; - } - _interop.invoke("T42.ACS.Feedback", feedbackInfo, "best"); - }; - const info = { - coreVersion: version, - version: internalConfig.version - }; - glueInitTimer.stop(); - const glue = { - feedback: feedbackFunc, - info, - logger: _logger, - interop: _interop, - agm: _interop, - connection: _connection, - metrics: _metrics, - contexts: _contexts, - bus: _bus, - version: internalConfig.version, - userConfig, - done: () => { - _logger?.info("done called by user..."); - return _connection.logout(); - } - }; - glue.performance = { - get glueVer() { - return internalConfig.version; - }, - get glueConfig() { - return JSON.stringify(userConfig); - }, - get browser() { - return window.performance.timing.toJSON(); - }, - get memory() { - return window.performance.memory; - }, - get initTimes() { - const all = getAllTimers(); - return Object.keys(all).map((key) => { - const t = all[key]; - return { - name: key, - duration: t.endTime - t.startTime, - marks: t.marks, - startTime: t.startTime, - endTime: t.endTime - }; - }); - } - }; - Object.keys(libs).forEach((key) => { - const lib = libs[key]; - glue[key] = lib; - }); - glue.config = {}; - Object.keys(internalConfig).forEach((k) => { - glue.config[k] = internalConfig[k]; - }); - if (ext && ext.extOptions) { - Object.keys(ext.extOptions).forEach((k) => { - glue.config[k] = ext?.extOptions[k]; - }); - } - if (ext?.enrichGlue) { - ext.enrichGlue(glue); - } - if (iodesktop && iodesktop.updatePerfData) { - iodesktop.updatePerfData(glue.performance); - } - if (glue.agm) { - const deprecatedDecorator = (fn, wrong, proper) => { - return function () { - glue.logger.warn(`glue.js - 'glue.agm.${wrong}' method is deprecated, use 'glue.interop.${proper}' instead.`); - return fn.apply(glue.agm, arguments); - }; - }; - const agmAny = glue.agm; - agmAny.method_added = deprecatedDecorator(glue.agm.methodAdded, "method_added", "methodAdded"); - agmAny.method_removed = deprecatedDecorator(glue.agm.methodRemoved, "method_removed", "methodRemoved"); - agmAny.server_added = deprecatedDecorator(glue.agm.serverAdded, "server_added", "serverAdded"); - agmAny.server_method_aded = deprecatedDecorator(glue.agm.serverMethodAdded, "server_method_aded", "serverMethodAdded"); - agmAny.server_method_removed = deprecatedDecorator(glue.agm.serverMethodRemoved, "server_method_removed", "serverMethodRemoved"); - } - return glue; - } - async function registerInstanceIfNeeded() { - const RegisterInstanceMethodName = "T42.ACS.RegisterInstance"; - if (Utils.isNode() && typeof process.env._GD_STARTING_CONTEXT_ === "undefined" && typeof userConfig?.application !== "undefined") { - const isMethodAvailable = _interop.methods({ name: RegisterInstanceMethodName }).length > 0; - if (isMethodAvailable) { - try { - await _interop.invoke(RegisterInstanceMethodName, { appName: userConfig?.application, pid: process.pid }); - } - catch (error) { - const typedError = error; - _logger.error(`Cannot register as an instance: ${JSON.stringify(typedError.message)}`); - } - } - } - } - return preloadPromise - .then(setupLogger) - .then(setupConnection) - .then(() => Promise.all([setupMetrics(), setupInterop(), setupContexts(), setupBus()])) - .then(() => _interop.readyPromise) - .then(() => registerInstanceIfNeeded()) - .then(() => { - return setupExternalLibs(internalConfig.libs || []); - }) - .then(waitForLibs) - .then(constructGlueObject) - .catch((err) => { - return Promise.reject({ - err, - libs - }); - }); - }; - if (typeof window !== "undefined") { - window.IOConnectCore = IOConnectCoreFactory; - } - IOConnectCoreFactory.version = version; - IOConnectCoreFactory.default = IOConnectCoreFactory; - - const iOConnectBrowserFactory = createFactoryFunction(IOConnectCoreFactory); - if (typeof window !== "undefined") { - const windowAny = window; - windowAny.IOBrowser = iOConnectBrowserFactory; - delete windowAny.GlueCore; - delete windowAny.IOConnectCore; - } - const legacyGlobal = window.glue42gd || window.glue42core; - const ioGlobal = window.iodesktop || window.iobrowser; - if (!legacyGlobal && !ioGlobal) { - window.iobrowser = { webStarted: false }; - } - if (!window.iodesktop && !window.iobrowser.system) { - window.iobrowser.system = setupGlobalSystem(); - } - iOConnectBrowserFactory.version = version$1; - - return iOConnectBrowserFactory; - -})); -//# sourceMappingURL=browser.umd.js.map diff --git a/javascript/start/stocks/lib/workspaces.umd.js b/javascript/start/stocks/lib/workspaces.umd.js deleted file mode 100644 index 8d833a0..0000000 --- a/javascript/start/stocks/lib/workspaces.umd.js +++ /dev/null @@ -1,5618 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.workspaces = factory()); -})(this, (function () { 'use strict'; - - function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createRegistry(options) { - if (options && options.errorHandling - && typeof options.errorHandling !== "function" - && options.errorHandling !== "log" - && options.errorHandling !== "silent" - && options.errorHandling !== "throw") { - throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed"); - } - var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling; - var callbacks = {}; - function add(key, callback, replayArgumentsArr) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - callbacksForKey = []; - callbacks[key] = callbacksForKey; - } - callbacksForKey.push(callback); - if (replayArgumentsArr) { - setTimeout(function () { - replayArgumentsArr.forEach(function (replayArgument) { - var _a; - if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) { - try { - if (Array.isArray(replayArgument)) { - callback.apply(undefined, replayArgument); - } - else { - callback.apply(undefined, [replayArgument]); - } - } - catch (err) { - _handleError(err, key); - } - } - }); - }, 0); - } - return function () { - var allForKey = callbacks[key]; - if (!allForKey) { - return; - } - allForKey = allForKey.reduce(function (acc, element, index) { - if (!(element === callback && acc.length === index)) { - acc.push(element); - } - return acc; - }, []); - if (allForKey.length === 0) { - delete callbacks[key]; - } - else { - callbacks[key] = allForKey; - } - }; - } - function execute(key) { - var argumentsArr = []; - for (var _i = 1; _i < arguments.length; _i++) { - argumentsArr[_i - 1] = arguments[_i]; - } - var callbacksForKey = callbacks[key]; - if (!callbacksForKey || callbacksForKey.length === 0) { - return []; - } - var results = []; - callbacksForKey.forEach(function (callback) { - try { - var result = callback.apply(undefined, argumentsArr); - results.push(result); - } - catch (err) { - results.push(undefined); - _handleError(err, key); - } - }); - return results; - } - function _handleError(exceptionArtifact, key) { - var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact); - if (_userErrorHandler) { - _userErrorHandler(errParam); - return; - } - var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack; - if (options) { - switch (options.errorHandling) { - case "log": - return console.error(msg); - case "silent": - return; - case "throw": - throw new Error(msg); - } - } - console.error(msg); - } - function clear() { - callbacks = {}; - } - function clearKey(key) { - var callbacksForKey = callbacks[key]; - if (!callbacksForKey) { - return; - } - delete callbacks[key]; - } - return { - add: add, - execute: execute, - clear: clear, - clearKey: clearKey - }; - } - createRegistry.default = createRegistry; - var lib = createRegistry; - - - var CallbackFactory = /*@__PURE__*/getDefaultExportFromCjs(lib); - - /** - * Wraps values in an `Ok` type. - * - * Example: `ok(5) // => {ok: true, result: 5}` - */ - var ok = function (result) { return ({ ok: true, result: result }); }; - /** - * Wraps errors in an `Err` type. - * - * Example: `err('on fire') // => {ok: false, error: 'on fire'}` - */ - var err = function (error) { return ({ ok: false, error: error }); }; - /** - * Create a `Promise` that either resolves with the result of `Ok` or rejects - * with the error of `Err`. - */ - var asPromise = function (r) { - return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error); - }; - /** - * Unwraps a `Result` and returns either the result of an `Ok`, or - * `defaultValue`. - * - * Example: - * ``` - * Result.withDefault(5, number().run(json)) - * ``` - * - * It would be nice if `Decoder` had an instance method that mirrored this - * function. Such a method would look something like this: - * ``` - * class Decoder { - * runWithDefault = (defaultValue: A, json: any): A => - * Result.withDefault(defaultValue, this.run(json)); - * } - * - * number().runWithDefault(5, json) - * ``` - * Unfortunately, the type of `defaultValue: A` on the method causes issues - * with type inference on the `object` decoder in some situations. While these - * inference issues can be solved by providing the optional type argument for - * `object`s, the extra trouble and confusion doesn't seem worth it. - */ - var withDefault = function (defaultValue, r) { - return r.ok === true ? r.result : defaultValue; - }; - /** - * Return the successful result, or throw an error. - */ - var withException = function (r) { - if (r.ok === true) { - return r.result; - } - else { - throw r.error; - } - }; - /** - * Apply `f` to the result of an `Ok`, or pass the error through. - */ - var map = function (f, r) { - return r.ok === true ? ok(f(r.result)) : r; - }; - /** - * Apply `f` to the result of two `Ok`s, or pass an error through. If both - * `Result`s are errors then the first one is returned. - */ - var map2 = function (f, ar, br) { - return ar.ok === false ? ar : - br.ok === false ? br : - ok(f(ar.result, br.result)); - }; - /** - * Apply `f` to the error of an `Err`, or pass the success through. - */ - var mapError = function (f, r) { - return r.ok === true ? r : err(f(r.error)); - }; - /** - * Chain together a sequence of computations that may fail, similar to a - * `Promise`. If the first computation fails then the error will propagate - * through. If it succeeds, then `f` will be applied to the value, returning a - * new `Result`. - */ - var andThen = function (f, r) { - return r.ok === true ? f(r.result) : r; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - /* global Reflect, Promise */ - - - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - } - - function isEqual(a, b) { - if (a === b) { - return true; - } - if (a === null && b === null) { - return true; - } - if (typeof (a) !== typeof (b)) { - return false; - } - if (typeof (a) === 'object') { - // Array - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (!isEqual(a[i], b[i])) { - return false; - } - } - return true; - } - // Hash table - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) { - return false; - } - for (var i = 0; i < keys.length; i++) { - if (!b.hasOwnProperty(keys[i])) { - return false; - } - if (!isEqual(a[keys[i]], b[keys[i]])) { - return false; - } - } - return true; - } - } - /* - * Helpers - */ - var isJsonArray = function (json) { return Array.isArray(json); }; - var isJsonObject = function (json) { - return typeof json === 'object' && json !== null && !isJsonArray(json); - }; - var typeString = function (json) { - switch (typeof json) { - case 'string': - return 'a string'; - case 'number': - return 'a number'; - case 'boolean': - return 'a boolean'; - case 'undefined': - return 'undefined'; - case 'object': - if (json instanceof Array) { - return 'an array'; - } - else if (json === null) { - return 'null'; - } - else { - return 'an object'; - } - default: - return JSON.stringify(json); - } - }; - var expectedGot = function (expected, got) { - return "expected " + expected + ", got " + typeString(got); - }; - var printPath = function (paths) { - return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join(''); - }; - var prependAt = function (newAt, _a) { - var at = _a.at, rest = __rest(_a, ["at"]); - return (__assign({ at: newAt + (at || '') }, rest)); - }; - /** - * Decoders transform json objects with unknown structure into known and - * verified forms. You can create objects of type `Decoder` with either the - * primitive decoder functions, such as `boolean()` and `string()`, or by - * applying higher-order decoders to the primitives, such as `array(boolean())` - * or `dict(string())`. - * - * Each of the decoder functions are available both as a static method on - * `Decoder` and as a function alias -- for example the string decoder is - * defined at `Decoder.string()`, but is also aliased to `string()`. Using the - * function aliases exported with the library is recommended. - * - * `Decoder` exposes a number of 'run' methods, which all decode json in the - * same way, but communicate success and failure in different ways. The `map` - * and `andThen` methods modify decoders without having to call a 'run' method. - * - * Alternatively, the main decoder `run()` method returns an object of type - * `Result`. This library provides a number of helper - * functions for dealing with the `Result` type, so you can do all the same - * things with a `Result` as with the decoder methods. - */ - var Decoder = /** @class */ (function () { - /** - * The Decoder class constructor is kept private to separate the internal - * `decode` function from the external `run` function. The distinction - * between the two functions is that `decode` returns a - * `Partial` on failure, which contains an unfinished error - * report. When `run` is called on a decoder, the relevant series of `decode` - * calls is made, and then on failure the resulting `Partial` - * is turned into a `DecoderError` by filling in the missing information. - * - * While hiding the constructor may seem restrictive, leveraging the - * provided decoder combinators and helper functions such as - * `andThen` and `map` should be enough to build specialized decoders as - * needed. - */ - function Decoder(decode) { - var _this = this; - this.decode = decode; - /** - * Run the decoder and return a `Result` with either the decoded value or a - * `DecoderError` containing the json input, the location of the error, and - * the error message. - * - * Examples: - * ``` - * number().run(12) - * // => {ok: true, result: 12} - * - * string().run(9001) - * // => - * // { - * // ok: false, - * // error: { - * // kind: 'DecoderError', - * // input: 9001, - * // at: 'input', - * // message: 'expected a string, got 9001' - * // } - * // } - * ``` - */ - this.run = function (json) { - return mapError(function (error) { return ({ - kind: 'DecoderError', - input: json, - at: 'input' + (error.at || ''), - message: error.message || '' - }); }, _this.decode(json)); - }; - /** - * Run the decoder as a `Promise`. - */ - this.runPromise = function (json) { return asPromise(_this.run(json)); }; - /** - * Run the decoder and return the value on success, or throw an exception - * with a formatted error string. - */ - this.runWithException = function (json) { return withException(_this.run(json)); }; - /** - * Construct a new decoder that applies a transformation to the decoded - * result. If the decoder succeeds then `f` will be applied to the value. If - * it fails the error will propagated through. - * - * Example: - * ``` - * number().map(x => x * 5).run(10) - * // => {ok: true, result: 50} - * ``` - */ - this.map = function (f) { - return new Decoder(function (json) { return map(f, _this.decode(json)); }); - }; - /** - * Chain together a sequence of decoders. The first decoder will run, and - * then the function will determine what decoder to run second. If the result - * of the first decoder succeeds then `f` will be applied to the decoded - * value. If it fails the error will propagate through. - * - * This is a very powerful method -- it can act as both the `map` and `where` - * methods, can improve error messages for edge cases, and can be used to - * make a decoder for custom types. - * - * Example of adding an error message: - * ``` - * const versionDecoder = valueAt(['version'], number()); - * const infoDecoder3 = object({a: boolean()}); - * - * const decoder = versionDecoder.andThen(version => { - * switch (version) { - * case 3: - * return infoDecoder3; - * default: - * return fail(`Unable to decode info, version ${version} is not supported.`); - * } - * }); - * - * decoder.run({version: 3, a: true}) - * // => {ok: true, result: {a: true}} - * - * decoder.run({version: 5, x: 'abc'}) - * // => - * // { - * // ok: false, - * // error: {... message: 'Unable to decode info, version 5 is not supported.'} - * // } - * ``` - * - * Example of decoding a custom type: - * ``` - * // nominal type for arrays with a length of at least one - * type NonEmptyArray = T[] & { __nonEmptyArrayBrand__: void }; - * - * const nonEmptyArrayDecoder = (values: Decoder): Decoder> => - * array(values).andThen(arr => - * arr.length > 0 - * ? succeed(createNonEmptyArray(arr)) - * : fail(`expected a non-empty array, got an empty array`) - * ); - * ``` - */ - this.andThen = function (f) { - return new Decoder(function (json) { - return andThen(function (value) { return f(value).decode(json); }, _this.decode(json)); - }); - }; - /** - * Add constraints to a decoder _without_ changing the resulting type. The - * `test` argument is a predicate function which returns true for valid - * inputs. When `test` fails on an input, the decoder fails with the given - * `errorMessage`. - * - * ``` - * const chars = (length: number): Decoder => - * string().where( - * (s: string) => s.length === length, - * `expected a string of length ${length}` - * ); - * - * chars(5).run('12345') - * // => {ok: true, result: '12345'} - * - * chars(2).run('HELLO') - * // => {ok: false, error: {... message: 'expected a string of length 2'}} - * - * chars(12).run(true) - * // => {ok: false, error: {... message: 'expected a string, got a boolean'}} - * ``` - */ - this.where = function (test, errorMessage) { - return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); }); - }; - } - /** - * Decoder primitive that validates strings, and fails on all other input. - */ - Decoder.string = function () { - return new Decoder(function (json) { - return typeof json === 'string' - ? ok(json) - : err({ message: expectedGot('a string', json) }); - }); - }; - /** - * Decoder primitive that validates numbers, and fails on all other input. - */ - Decoder.number = function () { - return new Decoder(function (json) { - return typeof json === 'number' - ? ok(json) - : err({ message: expectedGot('a number', json) }); - }); - }; - /** - * Decoder primitive that validates booleans, and fails on all other input. - */ - Decoder.boolean = function () { - return new Decoder(function (json) { - return typeof json === 'boolean' - ? ok(json) - : err({ message: expectedGot('a boolean', json) }); - }); - }; - Decoder.constant = function (value) { - return new Decoder(function (json) { - return isEqual(json, value) - ? ok(value) - : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) }); - }); - }; - Decoder.object = function (decoders) { - return new Decoder(function (json) { - if (isJsonObject(json) && decoders) { - var obj = {}; - for (var key in decoders) { - if (decoders.hasOwnProperty(key)) { - var r = decoders[key].decode(json[key]); - if (r.ok === true) { - // tslint:disable-next-line:strict-type-predicates - if (r.result !== undefined) { - obj[key] = r.result; - } - } - else if (json[key] === undefined) { - return err({ message: "the key '" + key + "' is required but was not present" }); - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else if (isJsonObject(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - Decoder.array = function (decoder) { - return new Decoder(function (json) { - if (isJsonArray(json) && decoder) { - var decodeValue_1 = function (v, i) { - return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v)); - }; - return json.reduce(function (acc, v, i) { - return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i)); - }, ok([])); - } - else if (isJsonArray(json)) { - return ok(json); - } - else { - return err({ message: expectedGot('an array', json) }); - } - }); - }; - Decoder.tuple = function (decoders) { - return new Decoder(function (json) { - if (isJsonArray(json)) { - if (json.length !== decoders.length) { - return err({ - message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length - }); - } - var result = []; - for (var i = 0; i < decoders.length; i++) { - var nth = decoders[i].decode(json[i]); - if (nth.ok) { - result[i] = nth.result; - } - else { - return err(prependAt("[" + i + "]", nth.error)); - } - } - return ok(result); - } - else { - return err({ message: expectedGot("a tuple of length " + decoders.length, json) }); - } - }); - }; - Decoder.union = function (ad, bd) { - var decoders = []; - for (var _i = 2; _i < arguments.length; _i++) { - decoders[_i - 2] = arguments[_i]; - } - return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders)); - }; - Decoder.intersection = function (ad, bd) { - var ds = []; - for (var _i = 2; _i < arguments.length; _i++) { - ds[_i - 2] = arguments[_i]; - } - return new Decoder(function (json) { - return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({})); - }); - }; - /** - * Escape hatch to bypass validation. Always succeeds and types the result as - * `any`. Useful for defining decoders incrementally, particularly for - * complex objects. - * - * Example: - * ``` - * interface User { - * name: string; - * complexUserData: ComplexType; - * } - * - * const userDecoder: Decoder = object({ - * name: string(), - * complexUserData: anyJson() - * }); - * ``` - */ - Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); }; - /** - * Decoder identity function which always succeeds and types the result as - * `unknown`. - */ - Decoder.unknownJson = function () { - return new Decoder(function (json) { return ok(json); }); - }; - /** - * Decoder for json objects where the keys are unknown strings, but the values - * should all be of the same type. - * - * Example: - * ``` - * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37}); - * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}} - * ``` - */ - Decoder.dict = function (decoder) { - return new Decoder(function (json) { - if (isJsonObject(json)) { - var obj = {}; - for (var key in json) { - if (json.hasOwnProperty(key)) { - var r = decoder.decode(json[key]); - if (r.ok === true) { - obj[key] = r.result; - } - else { - return err(prependAt("." + key, r.error)); - } - } - } - return ok(obj); - } - else { - return err({ message: expectedGot('an object', json) }); - } - }); - }; - /** - * Decoder for values that may be `undefined`. This is primarily helpful for - * decoding interfaces with optional fields. - * - * Example: - * ``` - * interface User { - * id: number; - * isOwner?: boolean; - * } - * - * const decoder: Decoder = object({ - * id: number(), - * isOwner: optional(boolean()) - * }); - * ``` - */ - Decoder.optional = function (decoder) { - return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); }); - }; - /** - * Decoder that attempts to run each decoder in `decoders` and either succeeds - * with the first successful decoder, or fails after all decoders have failed. - * - * Note that `oneOf` expects the decoders to all have the same return type, - * while `union` creates a decoder for the union type of all the input - * decoders. - * - * Examples: - * ``` - * oneOf(string(), number().map(String)) - * oneOf(constant('start'), constant('stop'), succeed('unknown')) - * ``` - */ - Decoder.oneOf = function () { - var decoders = []; - for (var _i = 0; _i < arguments.length; _i++) { - decoders[_i] = arguments[_i]; - } - return new Decoder(function (json) { - var errors = []; - for (var i = 0; i < decoders.length; i++) { - var r = decoders[i].decode(json); - if (r.ok === true) { - return r; - } - else { - errors[i] = r.error; - } - } - var errorsList = errors - .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; }) - .join('", "'); - return err({ - message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]" - }); - }); - }; - /** - * Decoder that always succeeds with either the decoded value, or a fallback - * default value. - */ - Decoder.withDefault = function (defaultValue, decoder) { - return new Decoder(function (json) { - return ok(withDefault(defaultValue, decoder.decode(json))); - }); - }; - /** - * Decoder that pulls a specific field out of a json structure, instead of - * decoding and returning the full structure. The `paths` array describes the - * object keys and array indices to traverse, so that values can be pulled out - * of a nested structure. - * - * Example: - * ``` - * const decoder = valueAt(['a', 'b', 0], string()); - * - * decoder.run({a: {b: ['surprise!']}}) - * // => {ok: true, result: 'surprise!'} - * - * decoder.run({a: {x: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}} - * ``` - * - * Note that the `decoder` is ran on the value found at the last key in the - * path, even if the last key is not found. This allows the `optional` - * decoder to succeed when appropriate. - * ``` - * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string())); - * - * optionalDecoder.run({a: {b: {c: 'surprise!'}}}) - * // => {ok: true, result: 'surprise!'} - * - * optionalDecoder.run({a: {b: 'cats'}}) - * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'} - * - * optionalDecoder.run({a: {b: {z: 1}}}) - * // => {ok: true, result: undefined} - * ``` - */ - Decoder.valueAt = function (paths, decoder) { - return new Decoder(function (json) { - var jsonAtPath = json; - for (var i = 0; i < paths.length; i++) { - if (jsonAtPath === undefined) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: 'path does not exist' - }); - } - else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an object', jsonAtPath) - }); - } - else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) { - return err({ - at: printPath(paths.slice(0, i + 1)), - message: expectedGot('an array', jsonAtPath) - }); - } - else { - jsonAtPath = jsonAtPath[paths[i]]; - } - } - return mapError(function (error) { - return jsonAtPath === undefined - ? { at: printPath(paths), message: 'path does not exist' } - : prependAt(printPath(paths), error); - }, decoder.decode(jsonAtPath)); - }); - }; - /** - * Decoder that ignores the input json and always succeeds with `fixedValue`. - */ - Decoder.succeed = function (fixedValue) { - return new Decoder(function (json) { return ok(fixedValue); }); - }; - /** - * Decoder that ignores the input json and always fails with `errorMessage`. - */ - Decoder.fail = function (errorMessage) { - return new Decoder(function (json) { return err({ message: errorMessage }); }); - }; - /** - * Decoder that allows for validating recursive data structures. Unlike with - * functions, decoders assigned to variables can't reference themselves - * before they are fully defined. We can avoid prematurely referencing the - * decoder by wrapping it in a function that won't be called until use, at - * which point the decoder has been defined. - * - * Example: - * ``` - * interface Comment { - * msg: string; - * replies: Comment[]; - * } - * - * const decoder: Decoder = object({ - * msg: string(), - * replies: lazy(() => array(decoder)) - * }); - * ``` - */ - Decoder.lazy = function (mkDecoder) { - return new Decoder(function (json) { return mkDecoder().decode(json); }); - }; - return Decoder; - }()); - - /* tslint:disable:variable-name */ - /** See `Decoder.string` */ - var string = Decoder.string; - /** See `Decoder.number` */ - var number = Decoder.number; - /** See `Decoder.boolean` */ - var boolean = Decoder.boolean; - /** See `Decoder.anyJson` */ - var anyJson = Decoder.anyJson; - /** See `Decoder.unknownJson` */ - Decoder.unknownJson; - /** See `Decoder.constant` */ - var constant = Decoder.constant; - /** See `Decoder.object` */ - var object = Decoder.object; - /** See `Decoder.array` */ - var array = Decoder.array; - /** See `Decoder.tuple` */ - Decoder.tuple; - /** See `Decoder.dict` */ - Decoder.dict; - /** See `Decoder.optional` */ - var optional = Decoder.optional; - /** See `Decoder.oneOf` */ - var oneOf = Decoder.oneOf; - /** See `Decoder.union` */ - Decoder.union; - /** See `Decoder.intersection` */ - var intersection = Decoder.intersection; - /** See `Decoder.withDefault` */ - Decoder.withDefault; - /** See `Decoder.valueAt` */ - Decoder.valueAt; - /** See `Decoder.succeed` */ - Decoder.succeed; - /** See `Decoder.fail` */ - Decoder.fail; - /** See `Decoder.lazy` */ - var lazy = Decoder.lazy; - - const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string"); - const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number"); - const positiveNumberDecoder = number().where((num) => num > 0, "Expected a positive number"); - const windowDragModeDecoder = oneOf(constant("keepInside"), constant("autoEject")); - const isWindowInSwimlaneResultDecoder = object({ - inWorkspace: boolean() - }); - const frameVisibilityResultDecoder = object({ - isVisible: boolean() - }); - const iconDecoder = object({ - base64Image: nonEmptyStringDecoder - }); - const setIconArgumentsDecoder = object({ - icon: iconDecoder, - frameId: nonEmptyStringDecoder - }); - const allParentDecoder = oneOf(constant("workspace"), constant("row"), constant("column"), constant("group")); - const subParentDecoder = oneOf(constant("row"), constant("column"), constant("group")); - const frameStateDecoder = oneOf(constant("maximized"), constant("minimized"), constant("normal")); - const loadingAnimationTypeDecoder = oneOf(constant("workspace")); - const checkThrowCallback = (callback, allowUndefined) => { - const argumentType = typeof callback; - if (allowUndefined && argumentType !== "function" && argumentType !== "undefined") { - throw new Error(`Provided argument must be either undefined or of type function, provided: ${argumentType}`); - } - if (!allowUndefined && argumentType !== "function") { - throw new Error(`Provided argument must be of type function, provided: ${argumentType}`); - } - }; - const workspaceBuilderCreateConfigDecoder = optional(object({ - saveLayout: optional(boolean()) - })); - const deleteLayoutConfigDecoder = object({ - name: nonEmptyStringDecoder - }); - const windowDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const groupDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropHeader: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()) - }); - const rowDefinitionConfigDecoder = object({ - minHeight: optional(number()), - maxHeight: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const columnDefinitionConfigDecoder = object({ - minWidth: optional(number()), - maxWidth: optional(number()), - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - isPinned: optional(boolean()), - maximizationBoundary: optional(boolean()) - }); - const swimlaneWindowDefinitionDecoder = object({ - type: optional(constant("window")), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const strictSwimlaneWindowDefinitionDecoder = object({ - type: constant("window"), - appName: optional(nonEmptyStringDecoder), - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - config: optional(windowDefinitionConfigDecoder) - }); - const parentDefinitionDecoder = optional(object({ - type: optional(subParentDecoder), - children: optional(lazy(() => array(oneOf(swimlaneWindowDefinitionDecoder, parentDefinitionDecoder)))), - config: optional(anyJson()) - })); - const strictColumnDefinitionDecoder = object({ - type: constant("column"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(columnDefinitionConfigDecoder) - }); - const strictRowDefinitionDecoder = object({ - type: constant("row"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(rowDefinitionConfigDecoder) - }); - const strictGroupDefinitionDecoder = object({ - type: constant("group"), - children: optional(lazy(() => array(oneOf(strictSwimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder)))), - config: optional(groupDefinitionConfigDecoder) - }); - const strictParentDefinitionDecoder = oneOf(strictGroupDefinitionDecoder, strictColumnDefinitionDecoder, strictRowDefinitionDecoder); - oneOf(string().where((s) => s.toLowerCase() === "maximized", "Expected a case insensitive variation of 'maximized'"), string().where((s) => s.toLowerCase() === "normal", "Expected a case insensitive variation of 'normal'")); - const newFrameConfigDecoder = object({ - bounds: optional(object({ - left: optional(number()), - top: optional(number()), - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - })), - isVisible: optional(boolean()), - frameId: optional(nonEmptyStringDecoder) - }); - const loadingStrategyDecoder = oneOf(constant("direct"), constant("delayed"), constant("lazy")); - const restoreWorkspaceConfigDecoder = optional(object({ - app: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - loadingStrategy: optional(loadingStrategyDecoder), - title: optional(nonEmptyStringDecoder), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - frameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - lockdown: optional(boolean()), - activateFrame: optional(boolean()), - newFrame: optional(oneOf(newFrameConfigDecoder, boolean())), - noTabHeader: optional(boolean()), - inMemoryLayout: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - allowSystemHibernation: optional(boolean()) - })); - const openWorkspaceConfigDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const workspaceDefinitionDecoder = object({ - children: optional(array(oneOf(swimlaneWindowDefinitionDecoder, strictParentDefinitionDecoder))), - context: optional(anyJson()), - config: optional(object({ - title: optional(nonEmptyStringDecoder), - position: optional(nonNegativeNumberDecoder), - isFocused: optional(boolean()), - noTabHeader: optional(boolean()), - reuseWorkspaceId: optional(nonEmptyStringDecoder), - loadingStrategy: optional(loadingStrategyDecoder), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showCloseButton: optional(boolean()), - allowSplitters: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - icon: optional(nonEmptyStringDecoder), - isPinned: optional(boolean()), - isSelected: optional(boolean()), - positionIndex: optional(nonNegativeNumberDecoder), - windowDragMode: optional(windowDragModeDecoder) - })), - frame: optional(object({ - activate: optional(boolean()), - reuseFrameId: optional(nonEmptyStringDecoder), - applicationName: optional(nonEmptyStringDecoder), - newFrame: optional(oneOf(boolean(), newFrameConfigDecoder)) - })) - }); - const workspaceSelectorDecoder = object({ - workspaceId: nonEmptyStringDecoder - }); - const restoreWorkspaceDefinitionDecoder = object({ - name: nonEmptyStringDecoder, - restoreOptions: optional(restoreWorkspaceConfigDecoder) - }); - const emptyFrameDefinitionDecoder = optional(object({ - applicationName: optional(string()), - frameConfig: optional(newFrameConfigDecoder), - context: optional(object()), - layoutComponentId: optional(nonEmptyStringDecoder) - })); - const frameInitConfigDecoder = object({ - workspaces: array(oneOf(optional(workspaceDefinitionDecoder), optional(restoreWorkspaceDefinitionDecoder))) - }); - const frameInitProtocolConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaces: array(oneOf(workspaceDefinitionDecoder, restoreWorkspaceDefinitionDecoder)) - }); - const builderConfigDecoder = object({ - type: allParentDecoder, - definition: optional(oneOf(workspaceDefinitionDecoder, parentDefinitionDecoder)) - }); - const workspaceCreateConfigDecoder = intersection(workspaceDefinitionDecoder, object({ - saveConfig: optional(object({ - saveLayout: optional(boolean()) - })) - })); - const getFrameSummaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const frameInitializationContextDecoder = object({ - context: optional(object()) - }); - const frameSummaryDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - object({ - type: subParentDecoder, - id: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number() - }); - const eventTypeDecoder = oneOf(constant("frame"), constant("workspace"), constant("container"), constant("window")); - const streamRequestArgumentsDecoder = object({ - type: eventTypeDecoder, - branch: nonEmptyStringDecoder - }); - const workspaceEventActionDecoder = oneOf(constant("opened"), constant("closing"), constant("closed"), constant("focus"), constant("added"), constant("loaded"), constant("removed"), constant("childrenUpdate"), constant("containerChange"), constant("maximized"), constant("restored"), constant("minimized"), constant("normal"), constant("selected"), constant("lock-configuration-changed"), constant("hibernated"), constant("resumed")); - const workspaceConfigResultDecoder = object({ - frameId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder, - positionIndex: nonNegativeNumberDecoder, - name: nonEmptyStringDecoder, - layoutName: optional(nonEmptyStringDecoder), - isHibernated: optional(boolean()), - isSelected: optional(boolean()), - allowDrop: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - widthInPx: optional(number()), - heightInPx: optional(number()), - isPinned: optional(boolean()), - windowDragMode: optional(windowDragModeDecoder), - loadingStrategy: optional(loadingStrategyDecoder) - }); - const baseChildSnapshotConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - positionIndex: number(), - minWidth: optional(number()), - maxWidth: optional(number()), - minHeight: optional(number()), - maxHeight: optional(number()) - }); - const parentSnapshotConfigDecoder = anyJson(); - const swimlaneWindowSnapshotConfigDecoder = intersection(baseChildSnapshotConfigDecoder, object({ - windowId: optional(nonEmptyStringDecoder), - isMaximized: optional(boolean()), - isFocused: boolean(), - isSelected: optional(boolean()), - title: optional(string()), - appName: optional(nonEmptyStringDecoder), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - widthInPx: optional(number()), - heightInPx: optional(number()), - context: optional(anyJson()) - })); - const customWorkspaceSubParentSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: parentSnapshotConfigDecoder, - children: optional(lazy(() => array(customWorkspaceChildSnapshotDecoder))), - type: oneOf(constant("row"), constant("column"), constant("group")) - }); - const customWorkspaceWindowSnapshotDecoder = object({ - id: optional(nonEmptyStringDecoder), - config: swimlaneWindowSnapshotConfigDecoder, - type: constant("window") - }); - const customWorkspaceChildSnapshotDecoder = oneOf(customWorkspaceWindowSnapshotDecoder, customWorkspaceSubParentSnapshotDecoder); - const childSnapshotResultDecoder = customWorkspaceChildSnapshotDecoder; - const workspaceSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder, - children: array(childSnapshotResultDecoder), - frameSummary: frameSummaryDecoder, - context: optional(anyJson()) - }); - const windowLayoutItemDecoder = object({ - type: constant("window"), - config: object({ - appName: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder), - context: optional(anyJson()), - url: optional(nonEmptyStringDecoder), - title: optional(string()), - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()), - minWidth: optional(number()), - minHeight: optional(number()), - maxWidth: optional(number()), - maxHeight: optional(number()), - isMaximized: optional(boolean()) - }) - }); - const groupLayoutItemDecoder = object({ - type: constant("group"), - config: anyJson(), - children: array(oneOf(windowLayoutItemDecoder)) - }); - const columnLayoutItemDecoder = object({ - type: constant("column"), - config: anyJson(), - children: array(oneOf(groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => columnLayoutItemDecoder), lazy(() => rowLayoutItemDecoder))) - }); - const rowLayoutItemDecoder = object({ - type: constant("row"), - config: anyJson(), - children: array(oneOf(columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder, lazy(() => rowLayoutItemDecoder))) - }); - const workspaceLayoutDecoder = object({ - name: nonEmptyStringDecoder, - type: constant("Workspace"), - metadata: optional(anyJson()), - components: array(object({ - type: constant("Workspace"), - application: optional(string()), - state: object({ - config: anyJson(), - context: anyJson(), - children: array(oneOf(rowLayoutItemDecoder, columnLayoutItemDecoder, groupLayoutItemDecoder, windowLayoutItemDecoder)) - }) - })) - }); - const workspacesImportLayoutDecoder = object({ - layout: workspaceLayoutDecoder, - mode: oneOf(constant("replace"), constant("merge")) - }); - const workspacesImportLayoutsDecoder = object({ - layouts: array(workspaceLayoutDecoder), - mode: oneOf(constant("replace"), constant("merge")) - }); - const exportedLayoutsResultDecoder = object({ - layouts: array(workspaceLayoutDecoder) - }); - const frameSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - isFocused: optional(boolean()), - isInitialized: optional(boolean()), - initializationContext: optional(frameInitializationContextDecoder) - }); - const frameSummariesResultDecoder = object({ - summaries: array(frameSummaryResultDecoder) - }); - const workspaceSummaryResultDecoder = object({ - id: nonEmptyStringDecoder, - config: workspaceConfigResultDecoder - }); - const workspaceSummariesResultDecoder = object({ - summaries: array(workspaceSummaryResultDecoder) - }); - const frameSnapshotResultDecoder = object({ - id: nonEmptyStringDecoder, - config: anyJson(), - workspaces: array(workspaceSnapshotResultDecoder) - }); - const layoutSummaryDecoder = object({ - name: nonEmptyStringDecoder, - applicationName: optional(string()) - }); - const layoutSummariesDecoder = object({ - summaries: array(layoutSummaryDecoder) - }); - const simpleWindowOperationSuccessResultDecoder = object({ - windowId: nonEmptyStringDecoder - }); - const voidResultDecoder = anyJson(); - const frameStateResultDecoder = object({ - state: frameStateDecoder - }); - const frameBoundsDecoder = object({ - top: number(), - left: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const frameBoundsResultDecoder = object({ - bounds: frameBoundsDecoder - }); - const getWorkspaceIconResultDecoder = object({ - icon: optional(nonEmptyStringDecoder) - }); - const getPlatformFrameIdResultDecoder = object({ - id: optional(nonEmptyStringDecoder) - }); - const operationCheckResultDecoder = object({ - isSupported: boolean() - }); - const resizeConfigDecoder = object({ - width: optional(positiveNumberDecoder), - height: optional(positiveNumberDecoder), - relative: optional(boolean()) - }); - const moveConfigDecoder = object({ - top: optional(number()), - left: optional(number()), - relative: optional(boolean()) - }); - const simpleItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder - }); - const closeOptionsDecoder = object({ - allowPrevent: optional(boolean()), - showDialog: optional(boolean()), - }); - const closeItemConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - closeOptions: optional(closeOptionsDecoder) - }); - const frameSnapshotConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - excludeIds: optional(boolean()) - }); - const frameStateConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - requestedState: frameStateDecoder - }); - const setItemTitleConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - title: nonEmptyStringDecoder - }); - const moveWindowConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - containerId: nonEmptyStringDecoder - }); - const resizeItemConfigDecoder = intersection(simpleItemConfigDecoder, resizeConfigDecoder); - const setMaximizationBoundaryConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - enabled: boolean() - }); - const moveFrameConfigDecoder = intersection(simpleItemConfigDecoder, moveConfigDecoder); - object({ - id: nonEmptyStringDecoder, - type: subParentDecoder - }); - const addWindowConfigDecoder = object({ - definition: swimlaneWindowDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addContainerConfigDecoder = object({ - definition: strictParentDefinitionDecoder, - parentId: nonEmptyStringDecoder, - parentType: allParentDecoder - }); - const addItemResultDecoder = object({ - itemId: nonEmptyStringDecoder, - windowId: optional(nonEmptyStringDecoder) - }); - const pingResultDecoder = object({ - live: boolean() - }); - const bundleWorkspaceConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - workspaceId: nonEmptyStringDecoder - }); - const bundleItemConfigDecoder = object({ - type: oneOf(constant("row"), constant("column")), - itemId: nonEmptyStringDecoder - }); - const containerSummaryResultDecoder = object({ - itemId: nonEmptyStringDecoder, - config: parentSnapshotConfigDecoder - }); - const frameStreamDataDecoder = object({ - frameSummary: frameSummaryDecoder, - frameBounds: optional(frameBoundsDecoder) - }); - const workspaceStreamDataDecoder = object({ - workspaceSummary: workspaceSummaryResultDecoder, - frameSummary: frameSummaryDecoder, - workspaceSnapshot: optional(workspaceSnapshotResultDecoder), - frameBounds: optional(frameBoundsDecoder) - }); - const containerStreamDataDecoder = object({ - containerSummary: containerSummaryResultDecoder - }); - const windowStreamDataDecoder = object({ - windowSummary: object({ - itemId: nonEmptyStringDecoder, - parentId: nonEmptyStringDecoder, - config: swimlaneWindowSnapshotConfigDecoder - }) - }); - const workspaceLayoutSaveConfigDecoder = object({ - name: nonEmptyStringDecoder, - workspaceId: nonEmptyStringDecoder, - saveContext: optional(boolean()), - allowMultiple: optional(boolean()), - metadata: optional(object()) - }); - const workspaceLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropBottom: optional(boolean()), - allowSystemHibernation: optional(boolean()), - allowExtract: optional(boolean()), - allowWindowReorder: optional(boolean()), - allowSplitters: optional(boolean()), - showCloseButton: optional(boolean()), - showSaveButton: optional(boolean()), - allowWorkspaceTabReorder: optional(boolean()), - allowWorkspaceTabExtract: optional(boolean()), - showWindowCloseButtons: optional(boolean()), - showAddWindowButtons: optional(boolean()), - showEjectButtons: optional(boolean()), - }); - const lockWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - config: optional(workspaceLockConfigDecoder) - }); - const windowLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - showCloseButton: optional(boolean()) - }); - const elementResizeConfigDecoder = object({ - width: optional(nonNegativeNumberDecoder), - height: optional(nonNegativeNumberDecoder) - }); - const lockWindowDecoder = object({ - windowPlacementId: nonEmptyStringDecoder, - config: optional(windowLockConfigDecoder) - }); - const rowLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const columnLockConfigDecoder = object({ - allowDrop: optional(boolean()), - allowSplitters: optional(boolean()), - }); - const groupLockConfigDecoder = object({ - allowExtract: optional(boolean()), - allowReorder: optional(boolean()), - allowDrop: optional(boolean()), - allowDropLeft: optional(boolean()), - allowDropRight: optional(boolean()), - allowDropTop: optional(boolean()), - allowDropBottom: optional(boolean()), - allowDropHeader: optional(boolean()), - showMaximizeButton: optional(boolean()), - showEjectButton: optional(boolean()), - showAddWindowButton: optional(boolean()), - }); - const lockRowDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("row"), - config: optional(rowLockConfigDecoder) - }); - const lockColumnDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("column"), - config: optional(columnLockConfigDecoder) - }); - const lockGroupDecoder = object({ - itemId: nonEmptyStringDecoder, - type: constant("group"), - config: optional(groupLockConfigDecoder) - }); - const lockContainerDecoder = oneOf(lockRowDecoder, lockColumnDecoder, lockGroupDecoder); - const pinWorkspaceDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const setWorkspaceIconDecoder = object({ - workspaceId: nonEmptyStringDecoder, - icon: optional(nonEmptyStringDecoder) - }); - const workspacePinOptionsDecoder = optional(object({ - icon: optional(nonEmptyStringDecoder) - })); - const frameShowConfigDecoder = optional(object({ - activate: optional(boolean()) - })); - const shortcutConfigDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const shortcutClickedDataDecoder = object({ - shortcut: nonEmptyStringDecoder, - frameId: nonEmptyStringDecoder - }); - const frameClosingDataDecoder = object({ - frameId: nonEmptyStringDecoder, - }); - const setMaximizationBoundaryAPIConfigDecoder = object({ - enabled: boolean() - }); - const loadingAnimationConfigDecoder = object({ - itemId: nonEmptyStringDecoder, - type: loadingAnimationTypeDecoder - }); - const operationCheckConfigDecoder = object({ - operation: nonEmptyStringDecoder - }); - const setWindowDragModeDecoder = object({ - itemId: nonEmptyStringDecoder, - dragMode: windowDragModeDecoder - }); - const setLoadingStrategyDecoder = object({ - itemId: nonEmptyStringDecoder, - strategy: loadingStrategyDecoder - }); - const frameClosingResultDecoder = object({ - prevent: boolean() - }); - const sizeDecoder = object({ - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const boundsDecoder = object({ - left: number(), - top: number(), - width: nonNegativeNumberDecoder, - height: nonNegativeNumberDecoder - }); - const popupTargetLocationDecoder = oneOf(constant("none"), constant("left"), constant("right"), constant("top"), constant("bottom")); - const popupConfigDecoder = object({ - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const ShowPopupConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - size: sizeDecoder, - targetBounds: boundsDecoder, - targetLocation: popupTargetLocationDecoder, - windowId: nonEmptyStringDecoder, - horizontalOffset: optional(number()), - verticalOffset: optional(number()), - focus: optional(boolean()), - }); - const changeFrameVisibilityConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - activate: optional(boolean()), - isVisible: boolean() - }); - const frameDialogOptionsDecoder = object({ - mode: optional(oneOf(constant("Global"), constant("WindowContainer"))), - type: string(), - size: optional(sizeDecoder), - message: nonEmptyStringDecoder, - messageTitle: optional(nonEmptyStringDecoder), - movable: optional(boolean()), - transparent: optional(boolean()), - title: nonEmptyStringDecoder, - context: optional(anyJson()), - affirmativeButtonName: optional(nonEmptyStringDecoder), - showAffirmativeButton: optional(boolean()), - cancelButtonName: optional(nonEmptyStringDecoder), - showCancelButton: optional(boolean()), - negativeButtonName: optional(nonEmptyStringDecoder), - showNegativeButton: optional(boolean()), - defaultAction: optional(oneOf(constant("affirmative"), constant("negative"), constant("cancel"))), - timerDuration: optional(positiveNumberDecoder), - showTimer: optional(boolean()), - inputMaxLength: optional(positiveNumberDecoder), - inputPattern: optional(nonEmptyStringDecoder), - inputPatternErrorMessage: optional(nonEmptyStringDecoder), - inputPlaceholder: optional(string()), - blur: optional(boolean()) - }); - const showFrameDialogConfigDecoder = object({ - frameId: nonEmptyStringDecoder, - options: frameDialogOptionsDecoder - }); - - const webPlatformMethodName = "T42.Web.Platform.Control"; - const webPlatformWspStreamName = "T42.Web.Platform.WSP.Stream"; - const OUTGOING_METHODS = { - control: { name: "T42.Workspaces.Control", isStream: false }, - frameStream: { name: "T42.Workspaces.Stream.Frame", isStream: true }, - workspaceStream: { name: "T42.Workspaces.Stream.Workspace", isStream: true }, - containerStream: { name: "T42.Workspaces.Stream.Container", isStream: true }, - windowStream: { name: "T42.Workspaces.Stream.Window", isStream: true } - }; - const INCOMING_METHODS = { - control: { name: "T42.Workspaces.Client.Control", isStream: false }, - }; - const STREAMS = { - frame: { name: "T42.Workspaces.Stream.Frame", payloadDecoder: frameStreamDataDecoder }, - workspace: { name: "T42.Workspaces.Stream.Workspace", payloadDecoder: workspaceStreamDataDecoder }, - container: { name: "T42.Workspaces.Stream.Container", payloadDecoder: containerStreamDataDecoder }, - window: { name: "T42.Workspaces.Stream.Window", payloadDecoder: windowStreamDataDecoder } - }; - const CLIENT_OPERATIONS = { - shortcutClicked: { name: "shortcutClicked", argsDecoder: shortcutClickedDataDecoder, resultDecoder: voidResultDecoder }, - frameClosing: { name: "frameClosing", argsDecoder: frameClosingDataDecoder, resultDecoder: frameClosingResultDecoder }, - }; - const OPERATIONS = { - ping: { name: "ping", resultDecoder: pingResultDecoder }, - isWindowInWorkspace: { name: "isWindowInWorkspace", argsDecoder: simpleItemConfigDecoder, resultDecoder: isWindowInSwimlaneResultDecoder }, - createWorkspace: { name: "createWorkspace", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: workspaceCreateConfigDecoder }, - createFrame: { name: "createFrame", resultDecoder: frameSummaryResultDecoder, argsDecoder: emptyFrameDefinitionDecoder }, - initFrame: { name: "initFrame", resultDecoder: voidResultDecoder, argsDecoder: frameInitProtocolConfigDecoder }, - getAllFramesSummaries: { name: "getAllFramesSummaries", resultDecoder: frameSummariesResultDecoder }, - getFrameSummary: { name: "getFrameSummary", resultDecoder: frameSummaryDecoder, argsDecoder: getFrameSummaryConfigDecoder }, - getAllWorkspacesSummaries: { name: "getAllWorkspacesSummaries", resultDecoder: workspaceSummariesResultDecoder }, - getWorkspaceSnapshot: { name: "getWorkspaceSnapshot", resultDecoder: workspaceSnapshotResultDecoder, argsDecoder: simpleItemConfigDecoder }, - getAllLayoutsSummaries: { name: "getAllLayoutsSummaries", resultDecoder: layoutSummariesDecoder }, - openWorkspace: { name: "openWorkspace", argsDecoder: openWorkspaceConfigDecoder, resultDecoder: workspaceSnapshotResultDecoder }, - deleteLayout: { name: "deleteLayout", resultDecoder: voidResultDecoder, argsDecoder: deleteLayoutConfigDecoder }, - saveLayout: { name: "saveLayout", resultDecoder: workspaceLayoutDecoder, argsDecoder: workspaceLayoutSaveConfigDecoder }, - importLayout: { name: "importLayout", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutDecoder }, - importLayouts: { name: "importLayouts", resultDecoder: voidResultDecoder, argsDecoder: workspacesImportLayoutsDecoder }, - exportAllLayouts: { name: "exportAllLayouts", resultDecoder: exportedLayoutsResultDecoder }, - restoreItem: { name: "restoreItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - maximizeItem: { name: "maximizeItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - focusItem: { name: "focusItem", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeItem: { name: "closeItem", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - closeWorkspace: { name: "closeWorkspace", argsDecoder: closeItemConfigDecoder, resultDecoder: voidResultDecoder }, - resizeItem: { name: "resizeItem", argsDecoder: resizeItemConfigDecoder, resultDecoder: voidResultDecoder }, - setMaximizationBoundary: { name: "setMaximizationBoundary", argsDecoder: setMaximizationBoundaryConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameState: { name: "changeFrameState", argsDecoder: frameStateConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameState: { name: "getFrameState", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameStateResultDecoder }, - getFrameBounds: { name: "getFrameBounds", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameBoundsResultDecoder }, - moveFrame: { name: "moveFrame", argsDecoder: moveFrameConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameSnapshot: { name: "getFrameSnapshot", argsDecoder: frameSnapshotConfigDecoder, resultDecoder: frameSnapshotResultDecoder }, - forceLoadWindow: { name: "forceLoadWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - ejectWindow: { name: "ejectWindow", argsDecoder: simpleItemConfigDecoder, resultDecoder: simpleWindowOperationSuccessResultDecoder }, - setItemTitle: { name: "setItemTitle", argsDecoder: setItemTitleConfigDecoder, resultDecoder: voidResultDecoder }, - moveWindowTo: { name: "moveWindowTo", argsDecoder: moveWindowConfigDecoder, resultDecoder: voidResultDecoder }, - addWindow: { name: "addWindow", argsDecoder: addWindowConfigDecoder, resultDecoder: addItemResultDecoder }, - addContainer: { name: "addContainer", argsDecoder: addContainerConfigDecoder, resultDecoder: addItemResultDecoder }, - bundleWorkspace: { name: "bundleWorkspace", argsDecoder: bundleWorkspaceConfigDecoder, resultDecoder: voidResultDecoder }, - bundleItem: { name: "bundleItem", argsDecoder: bundleItemConfigDecoder, resultDecoder: voidResultDecoder }, - hibernateWorkspace: { name: "hibernateWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - resumeWorkspace: { name: "resumeWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - lockWorkspace: { name: "lockWorkspace", argsDecoder: lockWorkspaceDecoder, resultDecoder: voidResultDecoder }, - lockWindow: { name: "lockWindow", argsDecoder: lockWindowDecoder, resultDecoder: voidResultDecoder }, - lockContainer: { name: "lockContainer", argsDecoder: lockContainerDecoder, resultDecoder: voidResultDecoder }, - pinWorkspace: { name: "pinWorkspace", argsDecoder: pinWorkspaceDecoder, resultDecoder: voidResultDecoder }, - unpinWorkspace: { name: "unpinWorkspace", argsDecoder: workspaceSelectorDecoder, resultDecoder: voidResultDecoder }, - getWorkspaceIcon: { name: "getWorkspaceIcon", argsDecoder: workspaceSelectorDecoder, resultDecoder: getWorkspaceIconResultDecoder }, - setWorkspaceIcon: { name: "setWorkspaceIcon", argsDecoder: setWorkspaceIconDecoder, resultDecoder: voidResultDecoder }, - registerShortcut: { name: "registerShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - unregisterShortcut: { name: "unregisterShortcut", argsDecoder: shortcutConfigDecoder, resultDecoder: voidResultDecoder }, - showLoadingAnimation: { name: "showLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - hideLoadingAnimation: { name: "hideLoadingAnimation", argsDecoder: loadingAnimationConfigDecoder, resultDecoder: voidResultDecoder }, - getPlatformFrameId: { name: "getPlatformFrameId", resultDecoder: getPlatformFrameIdResultDecoder }, - operationCheck: { name: "operationCheck", argsDecoder: operationCheckConfigDecoder, resultDecoder: operationCheckResultDecoder }, - setWindowDragMode: { name: "setWindowDragMode", argsDecoder: setWindowDragModeDecoder, resultDecoder: voidResultDecoder }, - setLoadingStrategy: { name: "setLoadingStrategy", argsDecoder: setLoadingStrategyDecoder, resultDecoder: voidResultDecoder }, - getTaskbarIcon: { name: "getTaskbarIcon", resultDecoder: iconDecoder }, - setTaskbarIcon: { name: "setTaskbarIcon", argsDecoder: setIconArgumentsDecoder, resultDecoder: voidResultDecoder }, - subscribeToFrameClosing: { name: "subscribeToFrameClosing", argsDecoder: simpleItemConfigDecoder, resultDecoder: voidResultDecoder }, - showPopup: { name: "showPopup", argsDecoder: ShowPopupConfigDecoder, resultDecoder: voidResultDecoder }, - changeFrameVisibility: { name: "changeFrameVisibility", argsDecoder: changeFrameVisibilityConfigDecoder, resultDecoder: voidResultDecoder }, - getFrameVisibility: { name: "getFrameVisibility", argsDecoder: simpleItemConfigDecoder, resultDecoder: frameVisibilityResultDecoder }, - showFrameDialog: { name: "showFrameDialog", argsDecoder: showFrameDialogConfigDecoder, resultDecoder: anyJson() } - }; - - class PromiseWrapper { - resolve; - reject; - promise; - constructor() { - this.promise = new Promise((res, rej) => { - this.resolve = res; - this.reject = rej; - }); - } - } - - class Bridge { - transport; - registry; - activeSubscriptions = []; - pendingSubScriptions = []; - constructor(transport, registry) { - this.transport = transport; - this.registry = registry; - } - async createCoreEventSubscription() { - await this.transport.coreSubscriptionReady(this.handleCoreEvent.bind(this)); - } - handleCoreSubscription(config) { - const registryKey = `${config.eventType}-${config.action}`; - const scope = config.scope; - const scopeId = config.scopeId; - return this.registry.add(registryKey, (args) => { - const scopeConfig = { - type: scope, - id: scopeId - }; - const receivedIds = { - frame: args.frameSummary?.id || args.windowSummary?.config.frameId, - workspace: args.workspaceSummary?.id || args.windowSummary?.config.workspaceId, - container: args.containerSummary?.itemId, - window: args.windowSummary?.itemId - }; - const shouldInvokeCallback = this.checkScopeMatch(scopeConfig, receivedIds); - if (!shouldInvokeCallback) { - return; - } - config.callback(args); - }); - } - async send(operationName, operationArgs, invocationOptions) { - const operationDefinition = Object.values(OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - try { - const operationResult = await this.transport.transmitControl(operationDefinition.name, operationArgs, invocationOptions); - operationDefinition.resultDecoder.runWithException(operationResult); - return operationResult; - } - catch (error) { - if (error.kind) { - throw new Error(`Unexpected internal incoming validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - throw new Error(error.message); - } - } - async subscribe(config) { - const pendingSub = this.getPendingSubscription(config); - if (pendingSub) { - await pendingSub.promise; - } - let activeSub = this.getActiveSubscription(config); - const registryKey = this.getRegistryKey(config); - if (!activeSub) { - const pendingPromise = new PromiseWrapper(); - const pendingSubscription = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - promise: pendingPromise.promise - }; - this.pendingSubScriptions.push(pendingSubscription); - try { - const stream = STREAMS[config.eventType]; - const gdSub = await this.transport.subscribe(stream.name, this.getBranchKey(config), config.eventType); - gdSub.onData((streamData) => { - const data = streamData.data; - const requestedArgumentsResult = streamRequestArgumentsDecoder.run(streamData.requestArguments); - const actionResult = workspaceEventActionDecoder.run(data.action); - if (!requestedArgumentsResult.ok || !actionResult.ok) { - return; - } - const streamType = requestedArgumentsResult.result.type; - const branch = requestedArgumentsResult.result.branch; - const keyToExecute = `${streamType}-${branch}-${actionResult.result}`; - const validatedPayload = STREAMS[streamType].payloadDecoder.run(data.payload); - if (!validatedPayload.ok) { - return; - } - this.registry.execute(keyToExecute, validatedPayload.result); - }); - activeSub = { - streamType: config.eventType, - level: config.scope, - levelId: config.scopeId, - callbacksCount: 0, - gdSub - }; - this.activeSubscriptions.push(activeSub); - pendingPromise.resolve(); - } - catch (error) { - pendingPromise.reject(error); - throw error; - } - finally { - this.removePendingSubscription(pendingSubscription); - } - } - const unsubscribe = this.registry.add(registryKey, config.callback); - ++activeSub.callbacksCount; - return () => { - unsubscribe(); - --activeSub.callbacksCount; - if (activeSub.callbacksCount === 0) { - activeSub.gdSub.close(); - this.activeSubscriptions.splice(this.activeSubscriptions.indexOf(activeSub), 1); - } - }; - } - onOperation(callback) { - const wrappedCallback = (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - callback(payload, caller); - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - onOperationWithResponse(callback) { - const wrappedCallback = async (payload, caller) => { - const operationName = payload.operation; - const operationArgs = payload.data; - const operationDefinition = Object.values(CLIENT_OPERATIONS).find((operation) => operation.name === operationName); - if (!operationDefinition) { - throw new Error(`Cannot find definition for operation name: ${operationName}`); - } - if (operationDefinition.argsDecoder) { - try { - operationDefinition.argsDecoder.runWithException(operationArgs); - } - catch (error) { - throw new Error(`Unexpected internal outgoing validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - const result = await callback(payload, caller); - if (operationDefinition.resultDecoder) { - try { - operationDefinition.resultDecoder.runWithException(result); - } - catch (error) { - throw new Error(`Unexpected internal outgoing result validation error: ${error.message}, for input: ${JSON.stringify(error.input)}, for operation ${operationName}`); - } - } - return result; - }; - return this.transport.onInternalMethodInvoked("control", wrappedCallback); - } - checkScopeMatch(scope, receivedIds) { - if (scope.type === "global") { - return true; - } - if (scope.type === "frame" && scope.id === receivedIds.frame) { - return true; - } - if (scope.type === "workspace" && scope.id === receivedIds.workspace) { - return true; - } - if (scope.type === "container" && scope.id === receivedIds.container) { - return true; - } - if (scope.type === "window" && scope.id === receivedIds.window) { - return true; - } - return false; - } - handleCoreEvent(args) { - const data = args.data; - try { - const verifiedAction = workspaceEventActionDecoder.runWithException(data.action); - const verifiedType = eventTypeDecoder.runWithException(data.type); - const verifiedPayload = STREAMS[verifiedType].payloadDecoder.runWithException(data.payload); - const registryKey = `${verifiedType}-${verifiedAction}`; - this.registry.execute(registryKey, verifiedPayload); - } - catch (error) { - console.warn(`Cannot handle event with data ${JSON.stringify(data)}, because of validation error: ${error.message}`); - } - } - getBranchKey(config) { - return config.scope === "global" ? config.scope : `${config.scope}_${config.scopeId}`; - } - getRegistryKey(config) { - return `${config.eventType}-${this.getBranchKey(config)}-${config.action}`; - } - getActiveSubscription(config) { - return this.activeSubscriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - getPendingSubscription(config) { - return this.pendingSubScriptions - .find((activeSub) => activeSub.streamType === config.eventType && - activeSub.level === config.scope && - activeSub.levelId === config.scopeId); - } - removePendingSubscription(pendingSubscription) { - const index = this.pendingSubScriptions.indexOf(pendingSubscription); - if (index >= 0) { - this.pendingSubScriptions.splice(index, 1); - } - } - } - - const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => { - return new Promise((resolve, reject) => { - let promiseActive = true; - const timeout = setTimeout(() => { - if (!promiseActive) { - return; - } - promiseActive = false; - const message = timeoutMessage; - reject(message); - }, timeoutMilliseconds); - promise() - .then((result) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - resolve(result); - }) - .catch((error) => { - if (!promiseActive) { - return; - } - promiseActive = false; - clearTimeout(timeout); - reject(error); - }); - }); - }; - - const isDesktop = () => { - return typeof window === "undefined" ? - true : - window.glue42gd || window.iodesktop; - }; - const browserGlobal = () => { - return typeof window === "undefined" ? null : - window.glue42core || window.iobrowser; - }; - - class InteropTransport { - agm; - registry; - defaultTransportTimeout = 120000; - coreEventMethodInitiated = false; - corePlatformSubPromise; - constructor(agm, registry) { - this.agm = agm; - this.registry = registry; - } - async initiate(actualWindowId) { - if (isDesktop()) { - await Promise.all(Object.values(OUTGOING_METHODS).map((method) => { - return this.verifyMethodLive(method.name); - })); - await Promise.all(Object.keys(INCOMING_METHODS).map((method) => { - return this.registerMethod(method); - })); - return; - } - const systemId = browserGlobal().communicationId; - await Promise.all([ - this.verifyMethodLive(webPlatformMethodName, systemId), - this.verifyMethodLive(webPlatformWspStreamName, systemId) - ]); - await this.transmitControl("frameHello", { windowId: actualWindowId }); - } - coreSubscriptionReady(eventCallback) { - if (!this.coreEventMethodInitiated) { - this.subscribePlatform(eventCallback); - } - return this.corePlatformSubPromise; - } - subscribePlatform(eventCallback) { - this.coreEventMethodInitiated = true; - const systemId = browserGlobal().communicationId; - this.corePlatformSubPromise = this.agm.subscribe(webPlatformWspStreamName, systemId ? { target: { instance: systemId } } : undefined); - this.corePlatformSubPromise - .then((sub) => { - sub.onData((data) => eventCallback(data.data)); - }); - } - async subscribe(streamName, streamBranch, streamType) { - const subscriptionArgs = { - branch: streamBranch, - type: streamType - }; - let subscription; - try { - subscription = await this.agm.subscribe(streamName, { arguments: subscriptionArgs }); - } - catch (error) { - const message = `Internal subscription error! Error details: stream - ${streamName}, branch: ${streamBranch}. Internal message: ${error.message}`; - throw new Error(message); - } - return subscription; - } - async transmitControl(operation, operationArguments, invocationOptions) { - const invocationArguments = isDesktop() ? { operation, operationArguments } : { operation, domain: "workspaces", data: operationArguments }; - const methodName = isDesktop() ? OUTGOING_METHODS.control.name : webPlatformMethodName; - const platformTarget = isDesktop() ? undefined : browserGlobal().communicationId; - let invocationResult; - const baseErrorMessage = `Internal Workspaces Communication Error. Attempted operation: ${JSON.stringify(invocationArguments)}. `; - try { - invocationResult = await this.agm.invoke(methodName, invocationArguments, platformTarget ? { instance: platformTarget } : "best", { methodResponseTimeoutMs: invocationOptions?.timeout ?? this.defaultTransportTimeout }); - if (!invocationResult) { - throw new Error("Received unsupported result from GD - empty result"); - } - if (!Array.isArray(invocationResult.all_return_values) || invocationResult.all_return_values.length === 0) { - throw new Error("Received unsupported result from GD - empty values collection"); - } - } - catch (error) { - if (error && error.all_errors && error.all_errors.length) { - const invocationErrorMessage = error.all_errors[0].message; - throw new Error(`${baseErrorMessage} -> Inner message: ${invocationErrorMessage}`); - } - throw new Error(`${baseErrorMessage} -> Inner message: ${error.message}`); - } - return invocationResult.all_return_values[0].returned; - } - onInternalMethodInvoked(key, callback) { - return this.registry.add(key, callback); - } - verifyMethodLive(name, systemId) { - return promisePlus(() => { - return new Promise((resolve) => { - const hasMethod = this.agm.methods().some((method) => { - const nameMatch = method.name === name; - const serverMatch = systemId ? - method.getServers().some((server) => server.instance === systemId) : - true; - return nameMatch && serverMatch; - }); - if (hasMethod) { - resolve(); - return; - } - const unSub = this.agm.serverMethodAdded((data) => { - const method = data.method; - const server = data.server; - const serverMatch = systemId ? - server.instance === systemId : - true; - if (method.name === name && serverMatch) { - unSub(); - resolve(); - } - }); - }); - }, 15000, "Timeout waiting for the Workspaces communication channels"); - } - registerMethod(key) { - const method = INCOMING_METHODS[key]; - return this.agm.register(method.name, (args, caller) => { - return Promise.all(this.registry.execute(key, args, caller)); - }); - } - } - - const privateData$4 = new WeakMap(); - class ParentBuilder { - constructor(definition, base) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$4.set(this, { base, children, definition }); - } - get type() { - return privateData$4.get(this).definition.type; - } - addColumn(definition) { - const base = privateData$4.get(this).base; - return base.add("column", privateData$4.get(this).children, definition); - } - addRow(definition) { - const base = privateData$4.get(this).base; - return base.add("row", privateData$4.get(this).children, definition); - } - addGroup(definition) { - const base = privateData$4.get(this).base; - return base.add("group", privateData$4.get(this).children, definition); - } - addWindow(definition) { - const base = privateData$4.get(this).base; - base.addWindow(privateData$4.get(this).children, definition); - return this; - } - serialize() { - const definition = privateData$4.get(this).definition; - definition.children = privateData$4.get(this).base.serializeChildren(privateData$4.get(this).children); - return definition; - } - } - - class BaseBuilder { - getBuilder; - constructor(getBuilder) { - this.getBuilder = getBuilder; - } - wrapChildren(children) { - return children.map((child) => { - if (child.type === "window") { - return child; - } - return this.getBuilder({ type: child.type, definition: child }); - }); - } - add(type, children, definition) { - const validatedDefinition = parentDefinitionDecoder.runWithException(definition); - const childBuilder = this.getBuilder({ type, definition: validatedDefinition }); - children.push(childBuilder); - return childBuilder; - } - addWindow(children, definition) { - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - validatedDefinition.type = "window"; - children.push(validatedDefinition); - } - serializeChildren(children) { - return children.map((child) => { - if (child instanceof ParentBuilder) { - return child.serialize(); - } - else { - return child; - } - }); - } - } - - const privateData$3 = new WeakMap(); - class WorkspaceBuilder { - constructor(definition, base, controller) { - const children = base.wrapChildren(definition.children); - delete definition.children; - privateData$3.set(this, { base, children, definition, controller }); - } - addColumn(definition) { - const children = privateData$3.get(this).children; - const areAllColumns = children.every((child) => child instanceof ParentBuilder && child.type === "column"); - if (!areAllColumns) { - throw new Error("Cannot add a column to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("column", children, definition); - } - addRow(definition) { - const children = privateData$3.get(this).children; - const areAllRows = children.every((child) => child instanceof ParentBuilder && child.type === "row"); - if (!areAllRows) { - throw new Error("Cannot add a row to this workspace, because there are already children of another type"); - } - const base = privateData$3.get(this).base; - return base.add("row", children, definition); - } - addGroup(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a group to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - return base.add("group", children, definition); - } - addWindow(definition) { - const children = privateData$3.get(this).children; - if (children.length !== 0) { - throw new Error("Cannot add a window to this workspace, because there are already defined children."); - } - const base = privateData$3.get(this).base; - base.addWindow(children, definition); - return this; - } - getChildAt(index) { - nonNegativeNumberDecoder.runWithException(index); - const data = privateData$3.get(this).children; - return data[index]; - } - async create(config) { - const saveConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - const definition = privateData$3.get(this).definition; - definition.children = privateData$3.get(this).base.serializeChildren(privateData$3.get(this).children); - const controller = privateData$3.get(this).controller; - return controller.createWorkspace(definition, saveConfig); - } - } - - const privateData$2 = new WeakMap(); - const getBase$2 = (model) => { - return privateData$2.get(model).base; - }; - class Row { - constructor(base) { - privateData$2.set(this, { base }); - } - get type() { - return "row"; - } - get id() { - return getBase$2(this).getId(this); - } - get frameId() { - return getBase$2(this).getFrameId(this); - } - get workspaceId() { - return getBase$2(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$2(this).getPositionIndex(this); - } - get children() { - return getBase$2(this).getAllChildren(this); - } - get parent() { - return getBase$2(this).getMyParent(this); - } - get frame() { - return getBase$2(this).getMyFrame(this); - } - get workspace() { - return getBase$2(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$2(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$2(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$2(this).getMinWidth(this); - } - get minHeight() { - return getBase$2(this).getMinHeight(this); - } - get maxWidth() { - return getBase$2(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$2(this).getMaxHeight(this); - } - get width() { - return getBase$2(this).getWidthInPx(this); - } - get height() { - return getBase$2(this).getHeightInPx(this); - } - get isPinned() { - return getBase$2(this).getIsPinned(this); - } - get isMaximized() { - return getBase$2(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$2(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$2(this).addWindow(this, definition, "row"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "group", "row", definition); - } - async addColumn(definition) { - if (definition?.type && definition.type !== "column") { - throw new Error(`Expected a column definition, but received ${definition.type}`); - } - return getBase$2(this).addParent(this, "column", "row", definition); - } - async addRow() { - throw new Error("Adding rows as row children is not supported"); - } - removeChild(predicate) { - return getBase$2(this).removeChild(this, predicate); - } - maximize() { - return getBase$2(this).maximize(this); - } - restore() { - return getBase$2(this).restore(this); - } - close() { - return getBase$2(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : rowLockConfigDecoder.runWithException(lockConfigResult); - return getBase$2(this).lockContainer(this, verifiedConfig); - } - async setHeight(height) { - nonNegativeNumberDecoder.runWithException(height); - return getBase$2(this).setHeight(this, height); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$2(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$2(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData$1 = new WeakMap(); - const getBase$1 = (model) => { - return privateData$1.get(model).base; - }; - class Column { - constructor(base) { - privateData$1.set(this, { base }); - } - get type() { - return "column"; - } - get id() { - return getBase$1(this).getId(this); - } - get frameId() { - return getBase$1(this).getFrameId(this); - } - get workspaceId() { - return getBase$1(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase$1(this).getPositionIndex(this); - } - get children() { - return getBase$1(this).getAllChildren(this); - } - get parent() { - return getBase$1(this).getMyParent(this); - } - get frame() { - return getBase$1(this).getMyFrame(this); - } - get workspace() { - return getBase$1(this).getMyWorkspace(this); - } - get allowDrop() { - return getBase$1(this).getAllowDrop(this); - } - get allowSplitters() { - return getBase$1(this).getAllowSplitters(this); - } - get minWidth() { - return getBase$1(this).getMinWidth(this); - } - get minHeight() { - return getBase$1(this).getMinHeight(this); - } - get maxWidth() { - return getBase$1(this).getMaxWidth(this); - } - get maxHeight() { - return getBase$1(this).getMaxHeight(this); - } - get width() { - return getBase$1(this).getWidthInPx(this); - } - get height() { - return getBase$1(this).getHeightInPx(this); - } - get isPinned() { - return getBase$1(this).getIsPinned(this); - } - get isMaximized() { - return getBase$1(this).getIsMaximized(this); - } - get maximizationBoundary() { - return getBase$1(this).getMaximizationBoundary(this); - } - addWindow(definition) { - return getBase$1(this).addWindow(this, definition, "column"); - } - async addGroup(definition) { - if (definition?.type && definition.type !== "group") { - throw new Error(`Expected a group definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "group", "column", definition); - } - async addColumn() { - throw new Error("Adding columns as column children is not supported"); - } - async addRow(definition) { - if (definition?.type && definition.type !== "row") { - throw new Error(`Expected a row definition, but received ${definition.type}`); - } - return getBase$1(this).addParent(this, "row", "column", definition); - } - removeChild(predicate) { - return getBase$1(this).removeChild(this, predicate); - } - maximize() { - return getBase$1(this).maximize(this); - } - restore() { - return getBase$1(this).restore(this); - } - close() { - return getBase$1(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : columnLockConfigDecoder.runWithException(lockConfigResult); - return getBase$1(this).lockContainer(this, verifiedConfig); - } - async setWidth(width) { - nonNegativeNumberDecoder.runWithException(width); - return getBase$1(this).setWidth(this, width); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowSplitters: this.allowSplitters - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase$1(this).processLocalSubscription(this, config); - return unsubscribe; - } - async setMaximizationBoundary(config) { - const validatedConfig = setMaximizationBoundaryAPIConfigDecoder.runWithException(config); - return getBase$1(this).setMaximizationBoundary(this, validatedConfig); - } - } - - const privateData = new WeakMap(); - const getBase = (model) => { - return privateData.get(model).base; - }; - class Group { - constructor(base) { - privateData.set(this, { base }); - } - get type() { - return "group"; - } - get id() { - return getBase(this).getId(this); - } - get frameId() { - return getBase(this).getFrameId(this); - } - get workspaceId() { - return getBase(this).getWorkspaceId(this); - } - get positionIndex() { - return getBase(this).getPositionIndex(this); - } - get children() { - return getBase(this).getAllChildren(this); - } - get parent() { - return getBase(this).getMyParent(this); - } - get frame() { - return getBase(this).getMyFrame(this); - } - get workspace() { - return getBase(this).getMyWorkspace(this); - } - get allowExtract() { - return getBase(this).getAllowExtract(this); - } - get allowReorder() { - return getBase(this).getAllowReorder(this); - } - get allowDropLeft() { - return getBase(this).getAllowDropLeft(this); - } - get allowDropRight() { - return getBase(this).getAllowDropRight(this); - } - get allowDropTop() { - return getBase(this).getAllowDropTop(this); - } - get allowDropBottom() { - return getBase(this).getAllowDropBottom(this); - } - get allowDropHeader() { - return getBase(this).getAllowDropHeader(this); - } - get allowDrop() { - return getBase(this).getAllowDrop(this); - } - get showMaximizeButton() { - return getBase(this).getShowMaximizeButton(this); - } - get showEjectButton() { - return getBase(this).getShowEjectButton(this); - } - get showAddWindowButton() { - return getBase(this).getShowAddWindowButton(this); - } - get minWidth() { - return getBase(this).getMinWidth(this); - } - get minHeight() { - return getBase(this).getMinHeight(this); - } - get maxWidth() { - return getBase(this).getMaxWidth(this); - } - get maxHeight() { - return getBase(this).getMaxHeight(this); - } - get width() { - return getBase(this).getWidthInPx(this); - } - get height() { - return getBase(this).getHeightInPx(this); - } - get isMaximized() { - return getBase(this).getIsMaximized(this); - } - addWindow(definition) { - return getBase(this).addWindow(this, definition, "group"); - } - async addGroup() { - throw new Error("Adding groups as group child is not supported"); - } - async addColumn() { - throw new Error("Adding columns as group child is not supported"); - } - async addRow() { - throw new Error("Adding rows as group child is not supported"); - } - removeChild(predicate) { - return getBase(this).removeChild(this, predicate); - } - maximize() { - return getBase(this).maximize(this); - } - restore() { - return getBase(this).restore(this); - } - close() { - return getBase(this).close(this); - } - lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropRight: this.allowDropRight, - allowDropTop: this.allowDropTop, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : groupLockConfigDecoder.runWithException(lockConfigResult); - return getBase(this).lockContainer(this, verifiedConfig); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - return getBase(this).setSize(this, config.width, config.height); - } - async bundleToRow() { - await getBase(this).bundleTo(this, "row"); - await this.workspace.refreshReference(); - } - async bundleToColumn() { - await getBase(this).bundleTo(this, "column"); - await this.workspace.refreshReference(); - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropHeader: this.allowDropHeader, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showAddWindowButton: this.showAddWindowButton, - showEjectButton: this.showEjectButton, - showMaximizeButton: this.showMaximizeButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "container", - scope: "container" - }; - const unsubscribe = await getBase(this).processLocalSubscription(this, config); - return unsubscribe; - } - } - - const DEFAULT_WINDOW_DRAG_MODE = "keepInside"; - const ONE_DAY_MS = 86_400_000; - - const data$3 = new WeakMap(); - const getData$3 = (model) => { - return data$3.get(model).manager.getWorkspaceData(model); - }; - const getDataManager = (model) => { - return data$3.get(model).manager; - }; - class Workspace { - constructor(dataManager) { - data$3.set(this, { manager: dataManager }); - } - get id() { - return getData$3(this).id; - } - get frameId() { - return getData$3(this).config.frameId; - } - get positionIndex() { - return getData$3(this).config.positionIndex; - } - get title() { - return getData$3(this).config.title; - } - get layoutName() { - return getData$3(this).config.layoutName; - } - get isHibernated() { - return getData$3(this).config.isHibernated; - } - get isSelected() { - return getData$3(this).config.isSelected; - } - get children() { - return getData$3(this).children; - } - get frame() { - return getData$3(this).frame; - } - get allowSplitters() { - return getData$3(this).config.allowSplitters; - } - get allowSystemHibernation() { - return getData$3(this).config.allowSystemHibernation; - } - get allowDrop() { - return getData$3(this).config.allowDrop; - } - get allowDropLeft() { - return getData$3(this).config.allowDropLeft; - } - get allowDropTop() { - return getData$3(this).config.allowDropTop; - } - get allowDropRight() { - return getData$3(this).config.allowDropRight; - } - get allowDropBottom() { - return getData$3(this).config.allowDropBottom; - } - get allowExtract() { - return getData$3(this).config.allowExtract; - } - get allowWindowReorder() { - return getData$3(this).config.allowWindowReorder; - } - get showCloseButton() { - return getData$3(this).config.showCloseButton; - } - get showSaveButton() { - return getData$3(this).config.showSaveButton; - } - get allowWorkspaceTabReorder() { - return getData$3(this).config.allowWorkspaceTabReorder; - } - get allowWorkspaceTabExtract() { - return getData$3(this).config.allowWorkspaceTabExtract; - } - get minWidth() { - return getData$3(this).config.minWidth; - } - get minHeight() { - return getData$3(this).config.minHeight; - } - get maxWidth() { - return getData$3(this).config.maxWidth; - } - get maxHeight() { - return getData$3(this).config.maxHeight; - } - get width() { - return getData$3(this).config.widthInPx; - } - get height() { - return getData$3(this).config.heightInPx; - } - get showWindowCloseButtons() { - return getData$3(this).config.showWindowCloseButtons; - } - get showEjectButtons() { - return getData$3(this).config.showEjectButtons; - } - get showAddWindowButtons() { - return getData$3(this).config.showAddWindowButtons; - } - get isPinned() { - return getData$3(this).config.isPinned; - } - get windowDragMode() { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - return DEFAULT_WINDOW_DRAG_MODE; - } - return getData$3(this).config.windowDragMode; - } - get loadingStrategy() { - if (!isDesktop()) { - console.warn("The workspace.loadingStrategy property is not supported in IO Connect Browser"); - } - return getData$3(this).config.loadingStrategy; - } - async setLoadingStrategy(strategy) { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - const controller = getData$3(this).controller; - await controller.setLoadingStrategy(this.id, strategy); - await this.refreshReference(); - } - async removeChild(predicate) { - checkThrowCallback(predicate); - const child = this.children.find(predicate); - if (!child) { - return; - } - await child.close(); - await this.refreshReference(); - } - async remove(predicate) { - checkThrowCallback(predicate); - const controller = getData$3(this).controller; - const child = controller.iterateFindChild(this.children, predicate); - await child.close(); - await this.refreshReference(); - } - async focus() { - await getData$3(this).controller.focusItem(this.id); - await this.refreshReference(); - } - async close() { - const controller = getData$3(this).controller; - await controller.closeWorkspace(this.id, this.frameId); - } - snapshot() { - return getData$3(this).controller.getSnapshot(this.id, "workspace"); - } - async saveLayout(name, config) { - nonEmptyStringDecoder.runWithException(name); - await getData$3(this).controller.saveLayout({ name, workspaceId: this.id, saveContext: config?.saveContext, metadata: config?.metadata, allowMultiple: config?.allowMultiple }); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const controller = getData$3(this).controller; - await controller.setItemTitle(this.id, title); - await this.refreshReference(); - } - getContext() { - const controller = getData$3(this).controller; - return controller.getWorkspaceContext(this.id); - } - setContext(data) { - const controller = getData$3(this).controller; - return controller.setWorkspaceContext(this.id, data); - } - updateContext(data) { - const controller = getData$3(this).controller; - return controller.updateWorkspaceContext(this.id, data); - } - onContextUpdated(callback) { - const controller = getData$3(this).controller; - return controller.subscribeWorkspaceContextUpdated(this.id, callback); - } - async refreshReference() { - const newSnapshot = (await getData$3(this).controller.getSnapshot(this.id, "workspace")); - const currentChildrenFlat = getData$3(this).controller.flatChildren(getData$3(this).children); - const newChildren = getData$3(this).controller.refreshChildren({ - existingChildren: currentChildrenFlat, - workspace: this, - parent: this, - children: newSnapshot.children - }); - const currentFrame = this.frame; - let actualFrame; - if (currentFrame.id === newSnapshot.config.frameId) { - getDataManager(this).remapFrame(currentFrame, newSnapshot.frameSummary); - actualFrame = currentFrame; - } - else { - const frameCreateConfig = { - summary: newSnapshot.frameSummary - }; - const newFrame = getData$3(this).ioc.getModel("frame", frameCreateConfig); - actualFrame = newFrame; - } - getDataManager(this).remapWorkspace(this, { - config: newSnapshot.config, - children: newChildren, - frame: actualFrame - }); - } - async getIcon() { - const controller = getData$3(this).controller; - return controller.getWorkspaceIcon(this.id); - } - async setIcon(icon) { - const controller = getData$3(this).controller; - return controller.setWorkspaceIcon(this.id, icon); - } - getBox(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type !== "window" && predicate(child)); - } - getAllBoxes(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allParents = controller.iterateFilterChildren(children, (child) => child.type !== "window"); - if (!predicate) { - return allParents; - } - return allParents.filter(predicate); - } - getRow(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "row" && predicate(parent)); - } - getAllRows(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "row" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "row"); - } - getColumn(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "column" && predicate(parent)); - } - getAllColumns(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "column" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "column"); - } - getGroup(predicate) { - checkThrowCallback(predicate); - return this.getBox((parent) => parent.type === "group" && predicate(parent)); - } - getAllGroups(predicate) { - checkThrowCallback(predicate, true); - if (predicate) { - return this.getAllBoxes((parent) => parent.type === "group" && predicate(parent)); - } - return this.getAllBoxes((parent) => parent.type === "group"); - } - getWindow(predicate) { - checkThrowCallback(predicate); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - return controller.iterateFindChild(children, (child) => child.type === "window" && predicate(child)); - } - getAllWindows(predicate) { - checkThrowCallback(predicate, true); - const children = getData$3(this).children; - const controller = getData$3(this).controller; - const allWindows = controller.iterateFilterChildren(children, (child) => child.type === "window"); - if (!predicate) { - return allWindows; - } - return allWindows.filter(predicate); - } - addRow(definition) { - return getData$3(this).base.addParent(this, "row", "workspace", definition); - } - addColumn(definition) { - return getData$3(this).base.addParent(this, "column", "workspace", definition); - } - addGroup(definition) { - return getData$3(this).base.addParent(this, "group", "workspace", definition); - } - addWindow(definition) { - return getData$3(this).base.addWindow(this, definition, "workspace"); - } - async bundleToRow() { - await getData$3(this).controller.bundleWorkspaceTo("row", this.id); - await this.refreshReference(); - } - async bundleToColumn() { - await getData$3(this).controller.bundleWorkspaceTo("column", this.id); - await this.refreshReference(); - } - async hibernate() { - await getData$3(this).controller.hibernateWorkspace(this.id); - await this.refreshReference(); - } - async resume() { - await getData$3(this).controller.resumeWorkspace(this.id); - await this.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowWindowReorder: this.allowWindowReorder, - allowSplitters: this.allowSplitters, - showCloseButton: this.showCloseButton, - showSaveButton: this.showSaveButton, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - showAddWindowButtons: this.showAddWindowButtons, - showEjectButtons: this.showEjectButtons, - showWindowCloseButtons: this.showWindowCloseButtons - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : workspaceLockConfigDecoder.runWithException(lockConfigResult); - await getData$3(this).controller.lockWorkspace(this.id, verifiedConfig); - await this.refreshReference(); - } - async pin(options) { - workspacePinOptionsDecoder.runWithException(options); - await getData$3(this).controller.pinWorkspace(this.id, options?.icon); - await this.refreshReference(); - } - async unpin() { - await getData$3(this).controller.unpinWorkspace(this.id); - await this.refreshReference(); - } - async showLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.showWorkspaceLoadingAnimation(this.id); - } - async hideLoadingAnimation() { - if (!isDesktop()) { - throw new Error("Not supported in IO Connect Browser"); - } - await getData$3(this).controller.hideWorkspaceLoadingAnimation(this.id); - } - async setWindowDragMode(mode) { - const desktopGlobal = isDesktop(); - if (!desktopGlobal) { - throw new Error("Not supported in IO Connect Browser"); - } - windowDragModeDecoder.runWithException(mode); - await getData$3(this).controller.setWindowDragMode(this.id, mode); - await this.refreshReference(); - } - async onClosed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - action: "closed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onHibernated(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "hibernated", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onResumed(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback(); - }; - const config = { - action: "resumed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "added", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - action: "removed", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const foundWindow = this.getWindow((win) => { - return win.id && win.id === payload.windowSummary.config.windowId; - }); - callback(foundWindow); - }; - const config = { - action: "loaded", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowMaximized(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "maximized", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowRestored(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "restored", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onWindowSelected(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async (payload) => { - await this.refreshReference(); - const windowParent = this.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => { - return child.type === "window" && child.elementId === payload.windowSummary.itemId; - }); - callback(foundWindow); - }; - const config = { - action: "selected", - eventType: "window", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$3(this).id; - const wrappedCallback = async () => { - await this.refreshReference(); - callback({ - allowDrop: this.allowDrop, - allowDropLeft: this.allowDropLeft, - allowDropTop: this.allowDropTop, - allowDropRight: this.allowDropRight, - allowDropBottom: this.allowDropBottom, - allowSystemHibernation: this.allowSystemHibernation, - allowExtract: this.allowExtract, - allowSplitters: this.allowSplitters, - allowWindowReorder: this.allowWindowReorder, - allowWorkspaceTabExtract: this.allowWorkspaceTabExtract, - allowWorkspaceTabReorder: this.allowWorkspaceTabReorder, - showAddWindowButtons: this.showAddWindowButtons, - showCloseButton: this.showCloseButton, - showEjectButtons: this.showEjectButtons, - showSaveButton: this.showSaveButton, - showWindowCloseButtons: this.showWindowCloseButtons - }); - }; - const config = { - action: "lock-configuration-changed", - eventType: "workspace", - scope: "workspace", - scopeId: id, - callback: wrappedCallback - }; - const unsubscribe = await getData$3(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$2 = new WeakMap(); - const getData$2 = (model) => { - return data$2.get(model).manager.getWindowData(model); - }; - class Window { - constructor(dataManager) { - data$2.set(this, { manager: dataManager }); - } - get id() { - return getData$2(this).config.windowId; - } - get elementId() { - return getData$2(this).id; - } - get type() { - return "window"; - } - get frameId() { - return getData$2(this).frame.id; - } - get workspaceId() { - return getData$2(this).workspace.id; - } - get positionIndex() { - return getData$2(this).config.positionIndex; - } - get isMaximized() { - return getData$2(this).config.isMaximized; - } - get isLoaded() { - return getData$2(this).controller.checkIsWindowLoaded(this.id); - } - get isSelected() { - return getData$2(this).config.isSelected; - } - get focused() { - return this.getGdWindow().isFocused; - } - get title() { - return getData$2(this).config.title; - } - get allowExtract() { - return getData$2(this).config.allowExtract; - } - get allowReorder() { - return getData$2(this).config.allowReorder; - } - get showCloseButton() { - return getData$2(this).config.showCloseButton; - } - get width() { - return getData$2(this).config.widthInPx; - } - get height() { - return getData$2(this).config.heightInPx; - } - get minWidth() { - return getData$2(this).config.minWidth; - } - get minHeight() { - return getData$2(this).config.minHeight; - } - get maxWidth() { - return getData$2(this).config.maxWidth; - } - get maxHeight() { - return getData$2(this).config.maxHeight; - } - get workspace() { - return getData$2(this).workspace; - } - get frame() { - return getData$2(this).frame; - } - get parent() { - return getData$2(this).parent; - } - get appName() { - return getData$2(this).config.appName; - } - async forceLoad() { - if (this.isLoaded) { - return; - } - const controller = getData$2(this).controller; - const itemId = getData$2(this).id; - const windowId = await controller.forceLoadWindow(itemId); - getData$2(this).config.windowId = windowId; - await this.workspace.refreshReference(); - } - async focus() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.focusItem(id); - await this.workspace.refreshReference(); - } - async close() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.closeItem(id); - await getData$2(this) - .parent - .removeChild((child) => child.id === id); - await this.workspace.refreshReference(); - } - async setTitle(title) { - nonEmptyStringDecoder.runWithException(title); - const itemId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.setItemTitle(itemId, title); - await this.workspace.refreshReference(); - } - async maximize() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.maximizeItem(id); - await this.workspace.refreshReference(); - } - async restore() { - const id = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.restoreItem(id); - await this.workspace.refreshReference(); - } - async eject() { - if (!this.isLoaded) { - throw new Error("Cannot eject this window, because it is not loaded yet"); - } - const itemId = getData$2(this).id; - const windowId = getData$2(this).config.windowId; - const newWindowId = await getData$2(this).controller.ejectWindow(itemId, windowId); - getData$2(this).config.windowId = newWindowId; - await this.workspace.refreshReference(); - return this.getGdWindow(); - } - getGdWindow() { - if (!this.isLoaded) { - throw new Error("Cannot fetch this GD window, because the window is not yet loaded"); - } - const myId = getData$2(this).config.windowId; - const controller = getData$2(this).controller; - return controller.getGDWindow(myId); - } - async moveTo(parent) { - if (!(parent instanceof Row || parent instanceof Column || parent instanceof Group)) { - throw new Error("Cannot add to the provided parent, because the provided parent is not an instance of Row, Column or Group"); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - const foundParent = await controller.getParent((p) => p.id === parent.id); - if (!foundParent) { - throw new Error("Cannot move the window to the selected parent, because this parent does not exist."); - } - await controller.moveWindowTo(myId, parent.id); - await this.workspace.refreshReference(); - } - async lock(config) { - let lockConfigResult = undefined; - if (typeof config === "function") { - const currentLockConfig = { - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }; - lockConfigResult = config(currentLockConfig); - } - else { - lockConfigResult = config; - } - const verifiedConfig = lockConfigResult === undefined ? undefined : windowLockConfigDecoder.runWithException(lockConfigResult); - const windowPlacementId = getData$2(this).id; - await getData$2(this).controller.lockWindow(windowPlacementId, verifiedConfig); - await this.workspace.refreshReference(); - } - async setSize(config) { - const verifiedConfig = elementResizeConfigDecoder.runWithException(config); - if (!verifiedConfig.width && !verifiedConfig.height) { - throw new Error("Expected either width or height to be passed."); - } - const myId = getData$2(this).id; - const controller = getData$2(this).controller; - await controller.resizeItem(myId, { - height: verifiedConfig.height, - width: verifiedConfig.width, - relative: false - }); - await this.workspace.refreshReference(); - } - async onRemoved(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback(); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - async onLockConfigurationChanged(callback) { - checkThrowCallback(callback); - const id = getData$2(this).id; - const wrappedCallback = async () => { - await this.workspace.refreshReference(); - callback({ - allowExtract: this.allowExtract, - allowReorder: this.allowReorder, - showCloseButton: this.showCloseButton - }); - }; - const config = { - callback: wrappedCallback, - action: "lock-configuration-changed", - eventType: "window", - scope: "window" - }; - const unsubscribe = await getData$2(this).controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - const data$1 = new WeakMap(); - const getData$1 = (model) => { - return data$1.get(model).manager.getFrameData(model); - }; - class Frame { - constructor(dataManager) { - data$1.set(this, { manager: dataManager }); - } - async registerShortcut(shortcut, callback) { - nonEmptyStringDecoder.runWithException(shortcut); - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const unsubscribe = await getData$1(this).controller.registerShortcut(shortcut, myId, callback); - return unsubscribe; - } - get id() { - return getData$1(this).summary.id; - } - get isInitialized() { - return getData$1(this).summary.isInitialized; - } - getBounds() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameBounds(myId); - } - async resize(config) { - const validatedConfig = resizeConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.resizeItem(myId, validatedConfig); - } - async move(config) { - const validatedConfig = moveConfigDecoder.runWithException(config); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.moveFrame(myId, validatedConfig); - } - focus() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.focusItem(myId); - } - async state() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getFrameState(myId); - } - setIcon(icon) { - if (!isDesktop()) { - throw new Error("frame.setIcon() is not supported in IO Connect Browser"); - } - iconDecoder.runWithException(icon); - const frameId = this.id; - return getData$1(this).controller.setTaskbarIcon(icon, frameId); - } - getIcon() { - if (!isDesktop()) { - throw new Error("frame.getIcon() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getTaskbarIcon(frameId); - } - isVisible() { - if (!isDesktop()) { - throw new Error("frame.isVisible() is not supported in IO Connect Browser"); - } - const frameId = this.id; - return getData$1(this).controller.getFrameVisibility(frameId); - } - async minimize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "minimized"); - } - async maximize() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "maximized"); - } - async restore() { - if (!isDesktop()) { - throw new Error("State operations are not supported in IO Connect Browser"); - } - const myId = getData$1(this).summary.id; - return getData$1(this).controller.changeFrameState(myId, "normal"); - } - close(options) { - const validatedOptions = optional(closeOptionsDecoder).runWithException(options); - const myId = getData$1(this).summary.id; - return getData$1(this).controller.closeFrame(myId, validatedOptions); - } - snapshot() { - const myId = getData$1(this).summary.id; - return getData$1(this).controller.getSnapshot(myId, "frame"); - } - async workspaces() { - const controller = getData$1(this).controller; - return controller.getWorkspacesByFrameId(this.id); - } - async getConstraints() { - const controller = getData$1(this).controller; - const myId = getData$1(this).summary.id; - return controller.getFrameConstraints(myId); - } - async restoreWorkspace(name, options) { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return getData$1(this).controller.restoreWorkspace(name, validatedOptions); - } - createWorkspace(definition, config) { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(config); - return getData$1(this).controller.createWorkspace(validatedDefinition, validatedConfig); - } - async init(config) { - frameInitConfigDecoder.runWithException(config); - if (getData$1(this).summary.isInitialized) { - throw new Error("The frame has already been initialized"); - } - return getData$1(this).controller.initFrame(this.id, config); - } - async showPopup(config) { - if (!isDesktop()) { - throw new Error("Popup operations are not supported in IO Connect Browser"); - } - const validatedConfig = popupConfigDecoder.runWithException(config); - const controller = getData$1(this).controller; - await controller.showPopup(validatedConfig, this.id); - return controller.getGDWindow(validatedConfig.windowId); - } - async show(config) { - if (!isDesktop()) { - throw new Error("The show operation is not supported in IO Connect Browser"); - } - const validatedConfig = frameShowConfigDecoder.runWithException(config); - return getData$1(this).controller.showFrame(this.id, validatedConfig); - } - async hide() { - if (!isDesktop()) { - throw new Error("The hide operation is not supported in IO Connect Browser"); - } - return getData$1(this).controller.hideFrame(this.id); - } - async showDialog(options) { - if (!isDesktop()) { - throw new Error("The showModal operation is not supported in IO Connect Browser"); - } - frameDialogOptionsDecoder.runWithException(options); - return getData$1(this).controller.showFrameDialog(this.id, options); - } - async onClosing(callback) { - if (!isDesktop()) { - throw new Error("Frame closing operations are not supported in io.Connect Browser"); - } - checkThrowCallback(callback); - const wrappedCallback = async () => { - let shouldPrevent = false; - const preventClose = () => shouldPrevent = true; - await callback({ prevent: preventClose }); - return { prevent: shouldPrevent }; - }; - const unsubscribe = await getData$1(this).controller.registerFrameOnClosing(this.id, wrappedCallback); - return unsubscribe; - } - async onClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMaximized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "maximized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onMinimized(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "minimized", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onNormal(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = () => { - callback(); - }; - const config = { - callback: wrappedCallback, - action: "normal", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceOpened(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "opened", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceSelected(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const workspace = await getData$1(this).controller.getWorkspaceById(payload.workspaceSummary.id); - callback(workspace); - }; - const config = { - callback: wrappedCallback, - action: "selected", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWorkspaceClosed(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const config = { - callback: wrappedCallback, - action: "closed", - eventType: "workspace", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowAdded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "added", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowRemoved(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const config = { - callback: wrappedCallback, - action: "removed", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onWindowLoaded(callback) { - checkThrowCallback(callback); - const myId = getData$1(this).summary.id; - const wrappedCallback = async (payload) => { - const foundParent = await getData$1(this).controller.getParent((parent) => { - return parent.id === payload.windowSummary.parentId; - }); - const foundWindow = foundParent.children.find((child) => child.type === "window" && child.positionIndex === payload.windowSummary.config.positionIndex); - callback(foundWindow); - }; - const config = { - callback: wrappedCallback, - action: "loaded", - eventType: "window", - scope: "frame" - }; - const unsubscribe = await getData$1(this).controller.processLocalSubscription(config, myId); - return unsubscribe; - } - async onInitializationRequested(callback) { - checkThrowCallback(callback); - if (!this.isInitialized) { - callback(getData$1(this).summary.initializationContext); - } - return () => { }; - } - async onFocusChanged(callback) { - checkThrowCallback(callback); - const myData = getData$1(this); - const { id } = myData.summary; - const wrappedCallback = (args) => { - callback({ isFocused: args.frameSummary.isFocused }); - }; - const config = { - callback: wrappedCallback, - action: "focus", - eventType: "frame", - scope: "frame" - }; - const unsubscribe = await myData.controller.processLocalSubscription(config, id); - return unsubscribe; - } - } - - class PrivateDataManager { - parentsData = new WeakMap(); - workspacesData = new WeakMap(); - windowsData = new WeakMap(); - framesData = new WeakMap(); - deleteData(model) { - if (model instanceof Window) { - this.windowsData.delete(model); - } - if (model instanceof Workspace) { - this.workspacesData.delete(model); - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - this.parentsData.delete(model); - } - if (model instanceof Frame) { - this.framesData.delete(model); - } - } - setWindowData(model, data) { - this.windowsData.set(model, data); - } - setWorkspaceData(model, data) { - this.workspacesData.set(model, data); - } - setParentData(model, data) { - this.parentsData.set(model, data); - } - setFrameData(model, data) { - this.framesData.set(model, data); - } - getWindowData(model) { - return this.windowsData.get(model); - } - getWorkspaceData(model) { - return this.workspacesData.get(model); - } - getParentData(model) { - return this.parentsData.get(model); - } - getFrameData(model) { - return this.framesData.get(model); - } - remapChild(model, newData) { - if (model instanceof Window) { - const data = this.windowsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - } - if (model instanceof Row || model instanceof Column || model instanceof Group) { - const data = this.parentsData.get(model); - data.parent = newData.parent || data.parent; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - remapFrame(model, newData) { - const data = this.framesData.get(model); - data.summary = newData; - } - remapWorkspace(model, newData) { - const data = this.workspacesData.get(model); - data.frame = newData.frame || data.frame; - data.config = newData.config || data.config; - data.children = newData.children || data.children; - } - } - - const data = new WeakMap(); - const getData = (base, model) => { - const manager = data.get(base).manager; - if (model instanceof Workspace) { - return manager.getWorkspaceData(model); - } - return data.get(base).manager.getParentData(model); - }; - class Base { - frameId; - workspaceId; - positionIndex; - constructor(dataManager) { - data.set(this, { manager: dataManager }); - } - getId(model) { - return getData(this, model).id; - } - getPositionIndex(model) { - return getData(this, model).config.positionIndex; - } - getWorkspaceId(model) { - const privateData = getData(this, model); - return privateData.config.workspaceId || privateData.workspace.id; - } - getFrameId(model) { - return getData(this, model).frame.id; - } - getAllChildren(model, predicate) { - checkThrowCallback(predicate, true); - const children = getData(this, model).children; - if (typeof predicate === "undefined") { - return children; - } - return children.filter(predicate); - } - getMyParent(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).parent; - } - getMyFrame(model) { - return getData(this, model).frame; - } - getMyWorkspace(model) { - if (model instanceof Workspace) { - return model; - } - return getData(this, model).workspace; - } - async addWindow(model, definition, parentType) { - if (!definition.appName && !definition.windowId) { - throw new Error("The window definition should contain either an appName or a windowId"); - } - const validatedDefinition = swimlaneWindowDefinitionDecoder.runWithException(definition); - const controller = getData(this, model).controller; - const operationResult = await controller.add("window", getData(this, model).id, parentType, validatedDefinition); - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getWindow(w => w.elementId === operationResult.itemId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getWindow(w => w.elementId === operationResult.itemId); - } - async addParent(model, typeToAdd, parentType, definition) { - const parentDefinition = this.transformDefinition(typeToAdd, definition); - const controller = getData(this, model).controller; - const newParentId = (await controller.add("container", getData(this, model).id, parentType, parentDefinition)).itemId; - if (model instanceof Workspace) { - await model.refreshReference(); - return model.getBox((parent) => parent.id === newParentId); - } - const myWorkspace = this.getMyWorkspace(model); - await myWorkspace.refreshReference(); - return myWorkspace.getBox((parent) => parent.id === newParentId); - } - async removeChild(model, predicate) { - checkThrowCallback(predicate); - const child = this.getAllChildren(model).find(predicate); - if (!child) { - return; - } - await child.close(); - if (model instanceof Workspace) { - await model.refreshReference(); - return; - } - await this.getMyWorkspace(model).refreshReference(); - } - async maximize(model) { - const { controller, id } = getData(this, model); - await controller.maximizeItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async restore(model) { - const { controller, id } = getData(this, model); - await controller.restoreItem(id); - await this.getMyWorkspace(model.parent).refreshReference(); - } - async close(model) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.closeItem(modelData.id); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async lockContainer(model, config) { - const modelData = getData(this, model); - const controller = getData(this, model).controller; - await controller.lockContainer(modelData.id, model.type, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - getAllowDrop(model) { - return getData(this, model).config.allowDrop; - } - getAllowDropLeft(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropLeft is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropLeft; - } - getAllowDropRight(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropRight is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropRight; - } - getAllowDropTop(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropTop is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropTop; - } - getAllowDropBottom(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropBottom is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropBottom; - } - getAllowDropHeader(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Property allowDropHeader is available only for groups and not on ${model.type} ${model.id}`); - } - return privateData.config.allowDropHeader; - } - getAllowSplitters(model) { - const privateData = getData(this, model); - if (privateData.type === "group") { - throw new Error(`Cannot get allow splitters from private data ${privateData.type}`); - } - return privateData.config.allowSplitters; - } - getAllowExtract(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowExtract; - } - getAllowReorder(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get allow extract from private data ${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.allowReorder; - } - getShowMaximizeButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show maximize button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showMaximizeButton; - } - getShowEjectButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get show eject button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showEjectButton; - } - getShowAddWindowButton(model) { - const privateData = getData(this, model); - if (privateData.type !== "group") { - throw new Error(`Cannot get add window button from private data${privateData.type} with config ${privateData.type !== "workspace" ? privateData.config.type : ""}`); - } - return privateData.config.showAddWindowButton; - } - getMinWidth(model) { - const privateData = getData(this, model); - return privateData.config.minWidth; - } - getMaxWidth(model) { - const privateData = getData(this, model); - return privateData.config.maxWidth; - } - getMinHeight(model) { - const privateData = getData(this, model); - return privateData.config.minHeight; - } - getMaxHeight(model) { - const privateData = getData(this, model); - return privateData.config.maxHeight; - } - getWidthInPx(model) { - const privateData = getData(this, model); - return privateData.config.widthInPx; - } - getHeightInPx(model) { - const privateData = getData(this, model); - return privateData.config.heightInPx; - } - getIsPinned(model) { - const privateData = getData(this, model); - return privateData.config.isPinned; - } - getIsMaximized(model) { - const privateData = getData(this, model); - return privateData.config.isMaximized; - } - getMaximizationBoundary(model) { - const privateData = getData(this, model); - return privateData.config.maximizationBoundary; - } - async setHeight(model, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setWidth(model, width) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setSize(model, width, height) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.resizeItem(id, { - width, - height - }); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async setMaximizationBoundary(model, config) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.setMaximizationBoundary(id, config); - await this.getMyWorkspace(modelData.parent).refreshReference(); - } - async bundleTo(model, type) { - const modelData = getData(this, model); - const { controller, id } = modelData; - await controller.bundleItemTo(type, id); - } - async processLocalSubscription(model, subscriptionConfig) { - return getData(this, model).controller.processLocalSubscription(subscriptionConfig, this.getId(model)); - } - transformDefinition(type, definition) { - let parentDefinition; - if (typeof definition === "undefined") { - parentDefinition = { type, children: [] }; - } - else if (definition instanceof ParentBuilder) { - parentDefinition = definition.serialize(); - } - else { - if (typeof definition.type === "undefined") { - definition.type = type; - } - parentDefinition = strictParentDefinitionDecoder.runWithException(definition); - parentDefinition.children = parentDefinition.children || []; - } - return parentDefinition; - } - } - - class BaseController { - ioc; - windows; - contexts; - layouts; - constructor(ioc, windows, contexts, layouts) { - this.ioc = ioc; - this.windows = windows; - this.contexts = contexts; - this.layouts = layouts; - } - get bridge() { - return this.ioc.bridge; - } - get privateDataManager() { - return this.ioc.privateDataManager; - } - checkIsWindowLoaded(windowId) { - return (!!windowId) && this.windows.list().some((win) => win.id === windowId); - } - async createWorkspace(createConfig) { - const snapshot = await this.bridge.send(OPERATIONS.createWorkspace.name, createConfig); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async createEmptyFrame(definition) { - const frameSummary = await this.bridge.send(OPERATIONS.createFrame.name, definition); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - async initFrame(frameId, config) { - await this.bridge.send(OPERATIONS.initFrame.name, { frameId, ...config }); - } - async restoreWorkspace(name, options) { - const snapshot = await this.bridge.send(OPERATIONS.openWorkspace.name, { name, restoreOptions: options }); - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: snapshot.config.frameId }); - const frameConfig = { - summary: frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async add(type, parentId, parentType, definition) { - let operationName; - const operationArgs = { definition, parentId, parentType }; - if (type === "window") { - operationName = OPERATIONS.addWindow.name; - } - else if (type === "container") { - operationName = OPERATIONS.addContainer.name; - } - else { - throw new Error(`Unrecognized add type: ${type}`); - } - return await this.bridge.send(operationName, operationArgs); - } - async getFrame(windowId) { - const frameSummary = await this.bridge.send(OPERATIONS.getFrameSummary.name, { itemId: windowId }); - const frameConfig = { - summary: frameSummary - }; - return this.ioc.getModel("frame", frameConfig); - } - getFrames(allFrameSummaries, predicate) { - return allFrameSummaries.reduce((frames, frameSummary) => { - const frameConfig = { - summary: frameSummary - }; - const frameToCheck = this.ioc.getModel("frame", frameConfig); - if (!predicate || predicate(frameToCheck)) { - frames.push(frameToCheck); - } - return frames; - }, []); - } - getAllWorkspaceSummaries(...bridgeResults) { - const allSummaries = bridgeResults.reduce((summaries, summaryResult) => { - summaries.push(...summaryResult.summaries); - return summaries; - }, []); - return allSummaries.map((summary) => { - return Object.assign({}, { id: summary.id, width: summary.config.widthInPx, height: summary.config.heightInPx }, summary.config); - }); - } - handleOnSaved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - const addedUnSub = this.layouts.onAdded(wrappedCallback); - const changedUnSub = this.layouts.onChanged(wrappedCallback); - return () => { - addedUnSub(); - changedUnSub(); - }; - } - handleOnRemoved(callback) { - const wrappedCallback = (layout) => { - if (layout.type !== "Workspace") { - return; - } - callback(layout); - }; - return this.layouts.onRemoved(wrappedCallback); - } - async importLayouts(layouts, mode) { - await this.layouts.import(layouts, mode); - } - async transformStreamPayloadToWorkspace(payload) { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const snapshot = payload.workspaceSnapshot || (await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId: payload.workspaceSummary.id })); - const workspaceConfig = { frame, snapshot }; - const workspace = this.ioc.getModel("workspace", workspaceConfig); - return workspace; - } - async fetchWorkspace(itemId) { - const snapshot = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = this.ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - return this.ioc.getModel("workspace", workspaceConfig); - } - async bundleWorkspaceTo(type, workspaceId) { - await this.bridge.send(OPERATIONS.bundleWorkspace.name, { type, workspaceId }); - } - async bundleItemTo(type, itemId) { - const isSupported = await this.isOperationSupported(OPERATIONS.bundleItem.name); - if (!isSupported) { - throw new Error(`Operation ${OPERATIONS.bundleItem.name} is not supported. Ensure that you are running the latest version of all packages`); - } - await this.bridge.send(OPERATIONS.bundleItem.name, { type, itemId }); - } - async getTaskbarIcon(frameId) { - return await this.bridge.send(OPERATIONS.getTaskbarIcon.name, { frameId }); - } - async setTaskbarIcon(icon, frameId) { - await this.bridge.send(OPERATIONS.setTaskbarIcon.name, { icon, frameId }); - } - getWorkspaceContext(workspaceId) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.get(contextName); - } - setWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.set(contextName, data); - } - updateWorkspaceContext(workspaceId, data) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.update(contextName, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - const contextName = `___workspace___${workspaceId}`; - return this.contexts.subscribe(contextName, callback); - } - async restoreItem(itemId) { - await this.bridge.send(OPERATIONS.restoreItem.name, { itemId }); - } - async maximizeItem(itemId) { - await this.bridge.send(OPERATIONS.maximizeItem.name, { itemId }); - } - async focusItem(itemId) { - await this.bridge.send(OPERATIONS.focusItem.name, { itemId }); - } - async closeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.closeWorkspace.name, { itemId: workspaceId }); - } - async closeItem(itemId) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId }); - } - async closeFrame(itemId, closeOptions) { - await this.bridge.send(OPERATIONS.closeItem.name, { itemId, closeOptions }); - } - async resizeItem(itemId, config) { - await this.bridge.send(OPERATIONS.resizeItem.name, Object.assign({}, { itemId }, config)); - } - async setMaximizationBoundary(itemId, config) { - await this.bridge.send(OPERATIONS.setMaximizationBoundary.name, Object.assign({}, { itemId }, config)); - } - async showWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.showLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - await this.bridge.send(OPERATIONS.hideLoadingAnimation.name, { itemId: workspaceId, type: "workspace" }); - } - async setWindowDragMode(workspaceId, dragMode) { - await this.bridge.send(OPERATIONS.setWindowDragMode.name, { itemId: workspaceId, dragMode }); - } - async moveFrame(itemId, config) { - await this.bridge.send(OPERATIONS.moveFrame.name, Object.assign({}, { itemId }, config)); - } - getGDWindow(itemId) { - return this.windows.list().find((gdWindow) => gdWindow.id === itemId); - } - async forceLoadWindow(itemId) { - const controlResult = await this.bridge.send(OPERATIONS.forceLoadWindow.name, { itemId }); - return controlResult.windowId; - } - async ejectWindow(itemId, windowId) { - return await this.bridge.send(OPERATIONS.ejectWindow.name, { itemId, windowId }); - } - async moveWindowTo(itemId, newParentId) { - await this.bridge.send(OPERATIONS.moveWindowTo.name, { itemId, containerId: newParentId }); - } - async getSnapshot(itemId, type) { - let result; - if (type === "workspace") { - result = await this.bridge.send(OPERATIONS.getWorkspaceSnapshot.name, { itemId }); - } - else if (type === "frame") { - result = await this.bridge.send(OPERATIONS.getFrameSnapshot.name, { itemId }); - } - return result; - } - async setItemTitle(itemId, title) { - await this.bridge.send(OPERATIONS.setItemTitle.name, { itemId, title }); - } - refreshChildren(config) { - const { parent, children, existingChildren, workspace } = config; - if (parent instanceof Window || parent.type === "window") { - return; - } - const newChildren = children.map((newChildSnapshot) => { - let childToAdd = existingChildren.find((child) => { - return child.type === "window" ? child.elementId === newChildSnapshot.id : child.id === newChildSnapshot.id; - }); - if (childToAdd) { - this.privateDataManager.remapChild(childToAdd, { - parent: parent, - children: [], - config: newChildSnapshot.config - }); - } - else { - let createConfig; - if (newChildSnapshot.type === "window") { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - }; - } - else { - createConfig = { - id: newChildSnapshot.id, - parent: parent, - frame: workspace.frame, - workspace, - config: newChildSnapshot.config, - children: [] - }; - } - childToAdd = this.ioc.getModel(newChildSnapshot.type, createConfig); - } - if (newChildSnapshot.type !== "window") { - this.refreshChildren({ - workspace, existingChildren, - children: newChildSnapshot.children, - parent: childToAdd - }); - } - return childToAdd; - }); - if (parent instanceof Workspace) { - return newChildren; - } - else { - this.privateDataManager.remapChild(parent, { children: newChildren }); - return newChildren; - } - } - iterateFindChild(children, predicate) { - let foundChild = children.find((child) => predicate(child)); - if (foundChild) { - return foundChild; - } - children.some((child) => { - if (child instanceof Window) { - return false; - } - foundChild = this.iterateFindChild(child.children, predicate); - if (foundChild) { - return true; - } - }); - return foundChild; - } - iterateFilterChildren(children, predicate) { - const foundChildren = children.filter((child) => predicate(child)); - const grandChildren = children.reduce((innerFound, child) => { - if (child instanceof Window) { - return innerFound; - } - innerFound.push(...this.iterateFilterChildren(child.children, predicate)); - return innerFound; - }, []); - foundChildren.push(...grandChildren); - return foundChildren; - } - notifyWindowAdded(windowId) { - return new Promise((resolve) => { - const alreadyPresent = this.windows.list().some((win) => win.id === windowId); - if (alreadyPresent) { - return resolve(); - } - const unsubscribe = this.windows.onWindowAdded((win) => { - if (win.id !== windowId) { - return; - } - if (unsubscribe) { - unsubscribe(); - } - resolve(); - }); - }); - } - async hibernateWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.hibernateWorkspace.name, { workspaceId }); - } - async resumeWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.resumeWorkspace.name, { workspaceId }); - } - async lockWorkspace(workspaceId, config) { - await this.bridge.send(OPERATIONS.lockWorkspace.name, { workspaceId, config }); - } - async lockWindow(windowPlacementId, config) { - await this.bridge.send(OPERATIONS.lockWindow.name, { windowPlacementId, config }); - } - async lockContainer(itemId, type, config) { - await this.bridge.send(OPERATIONS.lockContainer.name, { itemId, type, config }); - } - async pinWorkspace(workspaceId, icon) { - await this.bridge.send(OPERATIONS.pinWorkspace.name, { workspaceId, icon }); - } - async unpinWorkspace(workspaceId) { - await this.bridge.send(OPERATIONS.unpinWorkspace.name, { workspaceId }); - } - async getWorkspaceIcon(workspaceId) { - const result = await this.bridge.send(OPERATIONS.getWorkspaceIcon.name, { workspaceId }); - return result.icon; - } - setWorkspaceIcon(workspaceId, icon) { - return this.bridge.send(OPERATIONS.setWorkspaceIcon.name, { workspaceId, icon }); - } - async getPlatformFrameId() { - try { - const result = await this.bridge.send(OPERATIONS.getPlatformFrameId.name, {}); - return result; - } - catch (error) { - return {}; - } - } - async setLoadingStrategy(workspaceId, strategy) { - await this.isOperationSupported(OPERATIONS.setLoadingStrategy.name); - return this.bridge.send(OPERATIONS.setLoadingStrategy.name, { itemId: workspaceId, strategy }); - } - async showFrame(frameId, config) { - const payload = { frameId, isVisible: true, ...config }; - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, payload); - } - async hideFrame(frameId) { - return this.bridge.send(OPERATIONS.changeFrameVisibility.name, { frameId, isVisible: false }); - } - async getFrameVisibility(frameId) { - const result = await this.bridge.send(OPERATIONS.getFrameVisibility.name, { itemId: frameId }); - return result.isVisible; - } - async showFrameDialog(frameId, options) { - const result = await this.bridge.send(OPERATIONS.showFrameDialog.name, { frameId, options }, { timeout: ONE_DAY_MS }); - return result; - } - async isOperationSupported(operation) { - if (isDesktop()) { - return { isSupported: true }; - } - return await this.bridge.send(OPERATIONS.operationCheck.name, { operation }); - } - async showPopup(config, frameId) { - return this.bridge.send(OPERATIONS.showPopup.name, { ...config, frameId }); - } - } - - class MainController { - bridge; - base; - shortcutsController; - closingController; - constructor(bridge, base, shortcutsController, closingController) { - this.bridge = bridge; - this.base = base; - this.shortcutsController = shortcutsController; - this.closingController = closingController; - } - setTaskbarIcon(icon, frameId) { - return this.base.setTaskbarIcon(icon, frameId); - } - getTaskbarIcon(frameId) { - return this.base.getTaskbarIcon(frameId); - } - checkIsWindowLoaded(windowId) { - return this.base.checkIsWindowLoaded(windowId); - } - async checkIsInSwimlane(windowId) { - const controlResult = await this.bridge.send(OPERATIONS.isWindowInWorkspace.name, { itemId: windowId }); - return controlResult.inWorkspace; - } - async createWorkspace(definition, saveConfig) { - const createConfig = Object.assign({}, definition, { saveConfig }); - return await this.base.createWorkspace(createConfig); - } - async createEmptyFrame(definition) { - return await this.base.createEmptyFrame(definition); - } - async initFrame(frameId, config) { - return this.base.initFrame(frameId, config); - } - async restoreWorkspace(name, options) { - const allLayouts = await this.getLayoutSummaries(); - const layoutExists = allLayouts.some((summary) => summary.name === name); - if (!layoutExists) { - throw new Error(`This layout: ${name} cannot be restored, because it doesn't exist.`); - } - if (options?.frameId) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - const foundMatchingFrame = allFrameSummaries.summaries.some((summary) => summary.id === options.frameId); - if (!foundMatchingFrame) { - throw new Error(`Cannot reuse the frame with id: ${options.frameId}, because there is no frame with that ID found`); - } - } - return await this.base.restoreWorkspace(name, options); - } - async add(type, parentId, parentType, definition) { - return await this.base.add(type, parentId, parentType, definition); - } - processLocalSubscription(config, levelId) { - return isDesktop() ? - this.handleEnterpriseLocalSubscription(config, levelId) : - this.handleCoreLocalSubscription(config, levelId); - } - processGlobalSubscription(callback, eventType, action) { - return isDesktop() ? - this.handleEnterpriseGlobalSubscription(callback, eventType, action) : - this.handleCoreGlobalSubscription(callback, eventType, action); - } - async getFrame(selector) { - if (selector.windowId) { - return await this.base.getFrame(selector.windowId); - } - if (selector.predicate) { - return (await this.getFrames(selector.predicate))[0]; - } - throw new Error(`The provided selector is not valid: ${JSON.stringify(selector)}`); - } - async getFrames(predicate) { - const allFrameSummaries = await this.bridge.send(OPERATIONS.getAllFramesSummaries.name); - return this.base.getFrames(allFrameSummaries.summaries, predicate); - } - getWorkspaceById(workspaceId) { - return this.base.fetchWorkspace(workspaceId); - } - async getWorkspaceByWindowId(itemId) { - if (!isDesktop()) { - return (await this.getWorkspaces((wsp) => !!wsp.getWindow((w) => w.id === itemId)))[0]; - } - return this.base.fetchWorkspace(itemId); - } - transformStreamPayloadToWorkspace(payload) { - return this.base.transformStreamPayloadToWorkspace(payload); - } - async getWorkspace(predicate) { - let foundWorkspace; - await this.iterateWorkspaces((wsp, end) => { - if (predicate(wsp)) { - foundWorkspace = wsp; - end(); - } - }); - return foundWorkspace; - } - async getWorkspaces(predicate) { - const matchingWorkspaces = []; - await this.iterateWorkspaces((wsp) => { - if (!predicate || predicate(wsp)) { - matchingWorkspaces.push(wsp); - } - }); - return matchingWorkspaces; - } - async getWorkspacesByFrameId(frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - const workspacesForFrame = await Promise.all(summariesForFrame.map((summary) => { - return this.base.fetchWorkspace(summary.id); - })); - return workspacesForFrame; - } - async isLastWorkspaceInFrame(workspaceId, frameId) { - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - const summariesForFrame = workspaceSummaries.filter((s) => s.frameId === frameId); - return summariesForFrame.length === 1 && summariesForFrame[0].id === workspaceId; - } - async getAllWorkspaceSummaries() { - const allSummariesResult = await this.bridge.send(OPERATIONS.getAllWorkspacesSummaries.name, {}); - return this.base.getAllWorkspaceSummaries(allSummariesResult); - } - async getWindow(predicate) { - let resultWindow; - await this.iterateWorkspaces((wsp, end) => { - const foundWindow = wsp.getWindow(predicate); - if (foundWindow) { - resultWindow = foundWindow; - end(); - } - }); - return resultWindow; - } - async getParent(predicate) { - let resultParent; - await this.iterateWorkspaces((wsp, end) => { - const foundParent = wsp.getBox(predicate); - if (foundParent) { - resultParent = foundParent; - end(); - } - }); - return resultParent; - } - async getLayoutSummaries() { - const allLayouts = await this.bridge.send(OPERATIONS.getAllLayoutsSummaries.name); - return allLayouts.summaries; - } - async deleteLayout(name) { - await this.bridge.send(OPERATIONS.deleteLayout.name, { name }); - } - async exportLayout(predicate) { - const allLayoutsResult = await this.bridge.send(OPERATIONS.exportAllLayouts.name); - return allLayoutsResult.layouts.reduce((matchingLayouts, layout) => { - if (!predicate || predicate(layout)) { - matchingLayouts.push(layout); - } - return matchingLayouts; - }, []); - } - async saveLayout(config) { - return await this.bridge.send(OPERATIONS.saveLayout.name, config); - } - async importLayouts(layouts, mode) { - if (isDesktop()) { - try { - await this.bridge.send(OPERATIONS.importLayouts.name, { layouts, mode }); - } - catch (error) { - await Promise.all(layouts.map((layout) => this.bridge.send(OPERATIONS.importLayout.name, { layout, mode }))); - } - return; - } - await this.base.importLayouts(layouts, mode); - } - handleOnSaved(callback) { - return this.base.handleOnSaved(callback); - } - handleOnRemoved(callback) { - return this.base.handleOnRemoved(callback); - } - async bundleWorkspaceTo(type, workspaceId) { - return await this.base.bundleWorkspaceTo(type, workspaceId); - } - async bundleItemTo(type, id) { - return await this.base.bundleItemTo(type, id); - } - getWorkspaceContext(workspaceId) { - return this.base.getWorkspaceContext(workspaceId); - } - setWorkspaceContext(workspaceId, data) { - return this.base.setWorkspaceContext(workspaceId, data); - } - updateWorkspaceContext(workspaceId, data) { - return this.base.updateWorkspaceContext(workspaceId, data); - } - subscribeWorkspaceContextUpdated(workspaceId, callback) { - return this.base.subscribeWorkspaceContextUpdated(workspaceId, callback); - } - async restoreItem(itemId) { - return await this.base.restoreItem(itemId); - } - async maximizeItem(itemId) { - return await this.base.maximizeItem(itemId); - } - async focusItem(itemId) { - return await this.base.focusItem(itemId); - } - async changeFrameState(frameId, state) { - await this.bridge.send(OPERATIONS.changeFrameState.name, { frameId, requestedState: state }); - } - async getFrameBounds(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameBounds.name, { itemId: frameId }); - return frameResult.bounds; - } - async getFrameState(frameId) { - const frameResult = await this.bridge.send(OPERATIONS.getFrameState.name, { itemId: frameId }); - return frameResult.state; - } - async closeWorkspace(workspaceId, frameId) { - if (isDesktop()) { - return await this.closeItem(workspaceId); - } - let closeWorkspaceCommandExists = false; - try { - const { isSupported } = await this.base.isOperationSupported(OPERATIONS.closeWorkspace.name); - closeWorkspaceCommandExists = isSupported; - } - catch (error) { - closeWorkspaceCommandExists = false; - } - if (closeWorkspaceCommandExists) { - return await this.base.closeWorkspace(workspaceId); - } - return await this.legacyCloseWorkspace(workspaceId, frameId); - } - async closeItem(itemId) { - return await this.base.closeItem(itemId); - } - async closeFrame(itemId, closeOptions) { - return await this.base.closeFrame(itemId, closeOptions); - } - async resizeItem(itemId, config) { - return await this.base.resizeItem(itemId, config); - } - async setMaximizationBoundary(itemId, config) { - return await this.base.setMaximizationBoundary(itemId, config); - } - async showWorkspaceLoadingAnimation(workspaceId) { - return await this.base.showWorkspaceLoadingAnimation(workspaceId); - } - async hideWorkspaceLoadingAnimation(workspaceId) { - return await this.base.hideWorkspaceLoadingAnimation(workspaceId); - } - async setWindowDragMode(workspaceId, dragMode) { - return await this.base.setWindowDragMode(workspaceId, dragMode); - } - async moveFrame(itemId, config) { - return await this.base.moveFrame(itemId, config); - } - getGDWindow(itemId) { - return this.base.getGDWindow(itemId); - } - async forceLoadWindow(itemId) { - const windowId = await this.base.forceLoadWindow(itemId); - await this.base.notifyWindowAdded(windowId); - return windowId; - } - async ejectWindow(itemId, windowId) { - const id = (await this.base.ejectWindow(itemId, windowId)).windowId; - await this.base.notifyWindowAdded(id); - return id; - } - async moveWindowTo(itemId, newParentId) { - return await this.base.moveWindowTo(itemId, newParentId); - } - async getSnapshot(itemId, type) { - return await this.base.getSnapshot(itemId, type); - } - async setItemTitle(itemId, title) { - return await this.base.setItemTitle(itemId, title); - } - flatChildren(children) { - return children.reduce((soFar, child) => { - soFar.push(child); - if (child.type !== "window") { - soFar.push(...this.flatChildren(child.children)); - } - return soFar; - }, []); - } - refreshChildren(config) { - return this.base.refreshChildren(config); - } - iterateFindChild(children, predicate) { - return this.base.iterateFindChild(children, predicate); - } - iterateFilterChildren(children, predicate) { - return this.base.iterateFilterChildren(children, predicate); - } - hibernateWorkspace(workspaceId) { - return this.base.hibernateWorkspace(workspaceId); - } - resumeWorkspace(workspaceId) { - return this.base.resumeWorkspace(workspaceId); - } - lockWorkspace(workspaceId, config) { - return this.base.lockWorkspace(workspaceId, config); - } - lockWindow(windowPlacementId, config) { - return this.base.lockWindow(windowPlacementId, config); - } - lockContainer(itemId, type, config) { - return this.base.lockContainer(itemId, type, config); - } - pinWorkspace(workspaceId, icon) { - return this.base.pinWorkspace(workspaceId, icon); - } - unpinWorkspace(workspaceId) { - return this.base.unpinWorkspace(workspaceId); - } - getWorkspaceIcon(workspaceId) { - return this.base.getWorkspaceIcon(workspaceId); - } - setWorkspaceIcon(workspaceId, icon) { - return this.base.setWorkspaceIcon(workspaceId, icon); - } - async getFrameConstraints(frameId) { - const frameSnapshot = await this.getSnapshot(frameId, "frame"); - return { - minWidth: frameSnapshot.config.minWidth, - maxWidth: frameSnapshot.config.maxWidth, - minHeight: frameSnapshot.config.minHeight, - maxHeight: frameSnapshot.config.maxHeight, - }; - } - registerShortcut(shortcut, frameId, callback) { - return this.shortcutsController.registerShortcut(shortcut, frameId, callback); - } - getPlatformFrameId() { - return this.base.getPlatformFrameId(); - } - setLoadingStrategy(workspaceId, strategy) { - return this.base.setLoadingStrategy(workspaceId, strategy); - } - registerFrameOnClosing(frameId, callback) { - return this.closingController.registerFrameOnClosing(frameId, callback); - } - showPopup(config, frameId) { - return this.base.showPopup(config, frameId); - } - async showFrame(frameId, config) { - return this.base.showFrame(frameId, config); - } - async hideFrame(frameId) { - return this.base.hideFrame(frameId); - } - async getFrameVisibility(frameId) { - return this.base.getFrameVisibility(frameId); - } - async showFrameDialog(frameId, options) { - return this.base.showFrameDialog(frameId, options); - } - async handleCoreLocalSubscription(config, levelId) { - await this.bridge.createCoreEventSubscription(); - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseLocalSubscription(config, levelId) { - config.scopeId = config.scopeId || levelId; - if (config.eventType === "window" && config.action === "loaded") { - const originalCB = config.callback; - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - originalCB(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async handleCoreGlobalSubscription(callback, eventType, action) { - await this.bridge.createCoreEventSubscription(); - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.handleCoreSubscription(config); - } - handleEnterpriseGlobalSubscription(callback, eventType, action) { - const config = { - eventType, callback, action, - scope: "global", - }; - if (eventType === "window" && action === "loaded") { - const wrappedCB = async (callbackData) => { - await this.base.notifyWindowAdded(callbackData.windowSummary.config.windowId); - callback(callbackData); - }; - config.callback = wrappedCB; - } - return this.bridge.subscribe(config); - } - async iterateWorkspaces(callback) { - let ended = false; - const end = () => { ended = true; }; - const workspaceSummaries = await this.getAllWorkspaceSummaries(); - for (const summary of workspaceSummaries) { - if (ended) { - return; - } - const wsp = await this.base.fetchWorkspace(summary.id); - callback(wsp, end); - } - } - async legacyCloseWorkspace(workspaceId, frameId) { - const isLastWorkspaceInFrame = await this.isLastWorkspaceInFrame(workspaceId, frameId); - const platformFrameId = (await this.getPlatformFrameId()).id; - const shouldCloseFrame = isLastWorkspaceInFrame && - platformFrameId !== frameId; - if (shouldCloseFrame) { - return await this.closeFrame(frameId, {}); - } - await this.closeItem(workspaceId); - } - } - - class ShortcutsController { - bridge; - _shortcuts = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.bridge.onOperation((payload) => { - if (payload.operation === CLIENT_OPERATIONS.shortcutClicked.name) { - const data = payload.data; - this._shortcuts.execute(`${data.frameId}-${data.shortcut}`); - } - }); - } - async registerShortcut(shortcut, frameId, callback) { - await this.bridge.send(OPERATIONS.registerShortcut.name, { shortcut, frameId }); - const un = this._shortcuts.add(`${frameId}-${shortcut}`, callback); - return () => { - un(); - this.bridge.send(OPERATIONS.unregisterShortcut.name, { shortcut, frameId }); - }; - } - } - - class ClosingController { - bridge; - registry = CallbackFactory(); - constructor(bridge) { - this.bridge = bridge; - this.subscribeToFrameClosing(); - } - async registerFrameOnClosing(frameId, callback) { - await this.bridge.send(OPERATIONS.subscribeToFrameClosing.name, { itemId: frameId }); - return this.registry.add(frameId, callback); - } - subscribeToFrameClosing() { - this.bridge.onOperationWithResponse(async (payload) => { - if (payload.operation !== CLIENT_OPERATIONS.frameClosing.name) { - return; - } - const data = payload.data; - const frameClosingResult = await Promise.all(this.registry.execute(data.frameId)); - return this.aggregateFrameClosingResult(frameClosingResult); - }); - } - aggregateFrameClosingResult(results) { - return { - prevent: results.some((result) => result?.prevent) - }; - } - } - - class IoC { - agm; - windows; - layouts; - contexts; - _controllerInstance; - _bridgeInstance; - _transportInstance; - _privateDataManagerInstance; - _parentBaseInstance; - _baseController; - _shortcutsController; - _closingController; - constructor(agm, windows, layouts, contexts) { - this.agm = agm; - this.windows = windows; - this.layouts = layouts; - this.contexts = contexts; - } - get baseController() { - if (!this._baseController) { - this._baseController = new BaseController(this, this.windows, this.contexts, this.layouts); - } - return this._baseController; - } - get controller() { - if (!this._controllerInstance) { - this._controllerInstance = new MainController(this.bridge, this.baseController, this.shortcutsController, this.closingController); - } - return this._controllerInstance; - } - get shortcutsController() { - if (!this._shortcutsController) { - this._shortcutsController = new ShortcutsController(this.bridge); - } - return this._shortcutsController; - } - get closingController() { - if (!this._closingController) { - this._closingController = new ClosingController(this.bridge); - } - return this._closingController; - } - get bridge() { - if (!this._bridgeInstance) { - this._bridgeInstance = new Bridge(this.transport, CallbackFactory()); - } - return this._bridgeInstance; - } - get transport() { - if (!this._transportInstance) { - this._transportInstance = new InteropTransport(this.agm, CallbackFactory()); - } - return this._transportInstance; - } - get privateDataManager() { - if (!this._privateDataManagerInstance) { - this._privateDataManagerInstance = new PrivateDataManager(); - } - return this._privateDataManagerInstance; - } - get parentBase() { - if (!this._parentBaseInstance) { - this._parentBaseInstance = new Base(this.privateDataManager); - } - return this._parentBaseInstance; - } - async initiate(actualWindowId) { - await this.transport.initiate(actualWindowId); - } - getModel(type, createConfig) { - switch (type) { - case "frame": { - const newFrame = new Frame(this.privateDataManager); - const { summary } = createConfig; - const frameData = { summary, controller: this.controller }; - this.privateDataManager.setFrameData(newFrame, frameData); - return newFrame; - } - case "window": { - const { id, parent, frame, workspace, config } = createConfig; - const windowPrivateData = { - type: "window", - controller: this.controller, - config, id, parent, frame, workspace - }; - const newWindow = new Window(this.privateDataManager); - this.privateDataManager.setWindowData(newWindow, windowPrivateData); - return newWindow; - } - case "row": - case "column": - case "group": { - const { id, children, parent, frame, workspace, config } = createConfig; - const newParent = type === "column" ? new Column(this.parentBase) : - type === "row" ? new Row(this.parentBase) : new Group(this.parentBase); - const builtChildren = this.buildChildren(children, frame, workspace, newParent); - const parentPrivateData = { - id, parent, frame, workspace, - config, - type, - controller: this.controller, - children: builtChildren, - }; - this.privateDataManager.setParentData(newParent, parentPrivateData); - return newParent; - } - case "workspace": { - const { snapshot, frame } = createConfig; - const newWorkspace = new Workspace(this.privateDataManager); - const children = this.buildChildren(snapshot.children, frame, newWorkspace, newWorkspace); - const workspacePrivateData = { - id: snapshot.id, - type: "workspace", - config: snapshot.config, - base: this.parentBase, - controller: this.controller, - children, frame, ioc: this - }; - this.privateDataManager.setWorkspaceData(newWorkspace, workspacePrivateData); - return newWorkspace; - } - default: throw new Error(`Unrecognized type: ${type}`); - } - } - getBuilder(config) { - config.definition = config.definition || {}; - if (!Array.isArray(config.definition.children)) { - config.definition.children = []; - } - const baseBuilder = new BaseBuilder(this.getBuilder.bind(this)); - switch (config.type) { - case "workspace": { - return new WorkspaceBuilder(config.definition, baseBuilder, this.controller); - } - case "row": - case "column": - case "group": { - config.definition.type = config.type; - return new ParentBuilder(config.definition, baseBuilder); - } - default: throw new Error(`Unexpected Builder creation error, provided config: ${JSON.stringify(config)}`); - } - } - buildChildren(children, frame, workspace, parent) { - return children.map((child) => { - switch (child.type) { - case "window": return this.getModel("window", { - id: child.id, - config: child.config, - frame, workspace, parent - }); - case "column": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "row": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - case "group": return this.getModel(child.type, { - id: child.id, - config: child.config, - children: child.children, - frame, workspace, parent - }); - default: throw new Error(`Unsupported child type: ${child.type}`); - } - }); - } - } - - var version = "4.2.3"; - - const composeAPI = (glue, ioc) => { - const controller = ioc.controller; - const inWorkspace = () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - return controller.checkIsInSwimlane(myId); - }; - const getBuilder = (config) => { - const validatedConfig = builderConfigDecoder.runWithException(config); - return ioc.getBuilder(validatedConfig); - }; - const getMyFrame = async () => { - const windowId = glue.windows.my().id; - if (!windowId) { - throw new Error("Cannot get my frame, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(windowId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your frame, because this window is not in a workspace"); - } - return controller.getFrame({ windowId }); - }; - const getFrame = async (predicate) => { - checkThrowCallback(predicate); - return controller.getFrame({ predicate }); - }; - const getAllFrames = async (predicate) => { - checkThrowCallback(predicate, true); - return controller.getFrames(predicate); - }; - const getAllWorkspacesSummaries = () => { - return controller.getAllWorkspaceSummaries(); - }; - const getMyWorkspace = async () => { - const myId = glue.windows.my().id; - if (!myId) { - throw new Error("Cannot get my workspace, because my id is undefined."); - } - const isInSwimlane = await controller.checkIsInSwimlane(myId); - if (!isInSwimlane) { - throw new Error("Cannot fetch your workspace, because this window is not in a workspace"); - } - return await controller.getWorkspaceByWindowId(myId); - }; - const getWorkspace = async (predicate) => { - checkThrowCallback(predicate); - return (await controller.getWorkspaces(predicate))[0]; - }; - const getWorkspaceById = async (workspaceId) => { - nonEmptyStringDecoder.runWithException(workspaceId); - return controller.getWorkspaceById(workspaceId); - }; - const getAllWorkspaces = (predicate) => { - checkThrowCallback(predicate, true); - return controller.getWorkspaces(predicate); - }; - const getWindow = async (predicate) => { - checkThrowCallback(predicate); - return controller.getWindow(predicate); - }; - const getParent = async (predicate) => { - checkThrowCallback(predicate); - return controller.getParent(predicate); - }; - const restoreWorkspace = async (name, options) => { - nonEmptyStringDecoder.runWithException(name); - const validatedOptions = restoreWorkspaceConfigDecoder.runWithException(options); - return controller.restoreWorkspace(name, validatedOptions); - }; - const createWorkspace = async (definition, saveConfig) => { - const validatedDefinition = workspaceDefinitionDecoder.runWithException(definition); - const validatedConfig = workspaceBuilderCreateConfigDecoder.runWithException(saveConfig); - return controller.createWorkspace(validatedDefinition, validatedConfig); - }; - const createEmptyFrame = async (definition) => { - const validatedDefinition = emptyFrameDefinitionDecoder.runWithException(definition); - return controller.createEmptyFrame(validatedDefinition ?? {}); - }; - const layouts = { - getSummaries: () => { - return controller.getLayoutSummaries(); - }, - delete: async (name) => { - nonEmptyStringDecoder.runWithException(name); - return controller.deleteLayout(name); - }, - export: async (predicate) => { - checkThrowCallback(predicate, true); - return controller.exportLayout(predicate); - }, - import: async (layouts, mode = "replace") => { - if (!Array.isArray(layouts)) { - throw new Error(`The provided layouts argument is not an array: ${JSON.stringify(layouts)}`); - } - layouts.forEach((layout) => workspaceLayoutDecoder.runWithException(layout)); - return controller.importLayouts(layouts, mode); - }, - save: async (config) => { - const verifiedConfig = workspaceLayoutSaveConfigDecoder.runWithException(config); - return controller.saveLayout(verifiedConfig); - }, - onSaved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnSaved(callback); - }, - onRemoved: async (callback) => { - checkThrowCallback(callback); - return controller.handleOnRemoved(callback); - } - }; - const onFrameOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const frameConfig = { - summary: payload.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - callback(frame); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "opened"); - return unsubscribe; - }; - const onFrameClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "frame", "closed"); - return unsubscribe; - }; - const onWorkspaceOpened = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "opened"); - return unsubscribe; - }; - const onWorkspaceClosed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - callback({ frameId: payload.frameSummary.id, workspaceId: payload.workspaceSummary.id, frameBounds: payload.frameBounds }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "closed"); - return unsubscribe; - }; - const onWorkspaceHibernated = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "hibernated"); - return unsubscribe; - }; - const onWorkspaceResumed = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const workspace = await controller.transformStreamPayloadToWorkspace(payload); - callback(workspace); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "workspace", "resumed"); - return unsubscribe; - }; - const onWindowAdded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "added"); - return unsubscribe; - }; - const onWindowLoaded = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const foundWindow = workspace.getWindow((win) => win.id && win.id === payload.windowSummary.config.windowId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "loaded"); - return unsubscribe; - }; - const onWindowRemoved = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = (payload) => { - const { windowId, workspaceId, frameId } = payload.windowSummary.config; - callback({ windowId, workspaceId, frameId }); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "removed"); - return unsubscribe; - }; - const onWindowMaximized = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "maximized"); - return unsubscribe; - }; - const onWindowRestored = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "restored"); - return unsubscribe; - }; - const onWindowSelected = async (callback) => { - checkThrowCallback(callback); - const wrappedCallback = async (payload) => { - const snapshot = (await controller.getSnapshot(payload.windowSummary.config.workspaceId, "workspace")); - const frameConfig = { - summary: snapshot.frameSummary - }; - const frame = ioc.getModel("frame", frameConfig); - const workspaceConfig = { frame, snapshot }; - const workspace = ioc.getModel("workspace", workspaceConfig); - const windowParent = workspace.getBox((parent) => parent.id === payload.windowSummary.parentId); - const foundWindow = windowParent.children.find((child) => child.type === "window" && child.elementId === payload.windowSummary.itemId); - callback(foundWindow); - }; - const unsubscribe = await controller.processGlobalSubscription(wrappedCallback, "window", "selected"); - return unsubscribe; - }; - const waitForFrame = async (id) => { - nonEmptyStringDecoder.runWithException(id); - return new Promise((res, rej) => { - let unsub = () => { - }; - onFrameOpened((f) => { - if (f.id === id) { - res(f); - unsub(); - } - }).then((u) => { - unsub = u; - return getAllFrames(); - }).then((frames) => { - const myFrame = frames.find((f) => f.id === id); - if (myFrame) { - res(myFrame); - unsub(); - } - }).catch(rej); - }); - }; - return { - inWorkspace, - getBuilder, - getMyFrame, - getFrame, - getAllFrames, - getAllWorkspacesSummaries, - getMyWorkspace, - getWorkspace, - getWorkspaceById, - getAllWorkspaces, - getWindow, - getBox: getParent, - restoreWorkspace, - createWorkspace, - createEmptyFrame, - waitForFrame, - layouts, - onFrameOpened, - onFrameClosed, - onWorkspaceOpened, - onWorkspaceClosed, - onWorkspaceHibernated, - onWorkspaceResumed, - onWindowAdded, - onWindowLoaded, - onWindowRemoved, - onWindowMaximized, - onWindowRestored, - onWindowSelected, - version - }; - }; - - const factoryFunction = async (io) => { - const ioc = new IoC(io.agm, io.windows, io.layouts, io.contexts); - const actualWindowId = io.interop.instance.windowId; - await ioc.initiate(actualWindowId); - io.workspaces = composeAPI(io, ioc); - }; - if (typeof window !== "undefined") { - window.IOWorkspaces = factoryFunction; - } - - return factoryFunction; - -})); -//# sourceMappingURL=workspaces.umd.js.map diff --git a/javascript/start/stocks/package-lock.json b/javascript/start/stocks/package-lock.json new file mode 100644 index 0000000..525a164 --- /dev/null +++ b/javascript/start/stocks/package-lock.json @@ -0,0 +1,1280 @@ +{ + "name": "stocks", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "stocks", + "version": "1.0.0", + "dependencies": { + "@interopio/browser": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@interopio/browser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/@interopio/browser/-/browser-4.2.4.tgz", + "integrity": "sha512-BPgkwH6N8HyGf7st99ZJwQ7arijz9j1bGu7pUAXBrtbv6cu4zH5GR7JKPGANZmFl0uefNPQyAQ4hc7C/i1i++A==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/desktop": "^6.14.0", + "@interopio/search-api": "^3.2.1", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.2" + } + }, + "node_modules/@interopio/core": { + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/@interopio/core/-/core-6.8.1.tgz", + "integrity": "sha512-WFWIV8JilNuAcxXaB+81IjL9j82sU73ABMUUEOWpvWoyqxhPlneOS+rSYViFX5gdk5pLH3fM6T/MmRGn3UFLwQ==", + "license": "MIT", + "dependencies": { + "callback-registry": "^2.7.2", + "ws": "^8.18.0" + } + }, + "node_modules/@interopio/desktop": { + "version": "6.18.0", + "resolved": "https://registry.npmjs.org/@interopio/desktop/-/desktop-6.18.0.tgz", + "integrity": "sha512-YqRHRiCymbY2fOCT2HHJnLY4780JSRI1fUtaWEoIa5Z3djZk/3xRgVxIjOVw9Y/TAFGCwyIeW142a7HYnSGD5Q==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1", + "@interopio/schemas": "^10.1.0", + "@interopio/utils": "^1.4.2", + "@interopio/workspaces-api": "^4.2.3", + "callback-registry": "^2.7.1" + } + }, + "node_modules/@interopio/schemas": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@interopio/schemas/-/schemas-10.1.0.tgz", + "integrity": "sha512-8uDEoOAZenTr4a3O8vLq6JyS/LutkT/gh9EjuOrS9fOmHEUfJaS2u+qPo5em9/8MtjKgblZEJStSsW1gr34CtQ==", + "license": "ISC", + "dependencies": { + "ajv": "^6.12.6", + "ajv-keywords": "^3.4.1" + }, + "peerDependencies": { + "log4js": "^6.4.2" + }, + "peerDependenciesMeta": { + "log4js": { + "optional": true + } + } + }, + "node_modules/@interopio/search-api": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/@interopio/search-api/-/search-api-3.2.1.tgz", + "integrity": "sha512-raUZzqBQoidm/6Mvgao2wFWlTDu9D4jghiX1dqor1LdsIfUpelJkkuFGeDl0z/3DWneaxDF8Vc/uoBtLz7qJLw==", + "license": "MIT", + "dependencies": { + "@interopio/core": "^6.8.1" + } + }, + "node_modules/@interopio/utils": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/@interopio/utils/-/utils-1.4.2.tgz", + "integrity": "sha512-14Bb2WI9Cwf9zjhTurP4qP9AVY4cxR1AOrwrOtHrTGAeeHp88mALFWfMEv1QnRhlQ06To2vQcRgebNrPlHDZ8Q==", + "license": "ISC", + "dependencies": { + "decoder-validate": "^0.0.2" + } + }, + "node_modules/@interopio/workspaces-api": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/@interopio/workspaces-api/-/workspaces-api-4.2.3.tgz", + "integrity": "sha512-5wrR1yhETKuX4txVrmS5q3G+8KI6GW4yOxsrVdf5qErO2HxN938XUdiAHIesarwlQoncrgnVx7uTn6IeOWUoXg==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.59.0.tgz", + "integrity": "sha512-upnNBkA6ZH2VKGcBj9Fyl9IGNPULcjXRlg0LLeaioQWueH30p6IXtJEbKAgvyv+mJaMxSm1l6xwDXYjpEMiLMg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.59.0.tgz", + "integrity": "sha512-hZ+Zxj3SySm4A/DylsDKZAeVg0mvi++0PYVceVyX7hemkw7OreKdCvW2oQ3T1FMZvCaQXqOTHb8qmBShoqk69Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.59.0.tgz", + "integrity": "sha512-W2Psnbh1J8ZJw0xKAd8zdNgF9HRLkdWwwdWqubSVk0pUuQkoHnv7rx4GiF9rT4t5DIZGAsConRE3AxCdJ4m8rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.59.0.tgz", + "integrity": "sha512-ZW2KkwlS4lwTv7ZVsYDiARfFCnSGhzYPdiOU4IM2fDbL+QGlyAbjgSFuqNRbSthybLbIJ915UtZBtmuLrQAT/w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.59.0.tgz", + "integrity": "sha512-EsKaJ5ytAu9jI3lonzn3BgG8iRBjV4LxZexygcQbpiU0wU0ATxhNVEpXKfUa0pS05gTcSDMKpn3Sx+QB9RlTTA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.59.0.tgz", + "integrity": "sha512-d3DuZi2KzTMjImrxoHIAODUZYoUUMsuUiY4SRRcJy6NJoZ6iIqWnJu9IScV9jXysyGMVuW+KNzZvBLOcpdl3Vg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.59.0.tgz", + "integrity": "sha512-t4ONHboXi/3E0rT6OZl1pKbl2Vgxf9vJfWgmUoCEVQVxhW6Cw/c8I6hbbu7DAvgp82RKiH7TpLwxnJeKv2pbsw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.59.0.tgz", + "integrity": "sha512-CikFT7aYPA2ufMD086cVORBYGHffBo4K8MQ4uPS/ZnY54GKj36i196u8U+aDVT2LX4eSMbyHtyOh7D7Zvk2VvA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.59.0.tgz", + "integrity": "sha512-jYgUGk5aLd1nUb1CtQ8E+t5JhLc9x5WdBKew9ZgAXg7DBk0ZHErLHdXM24rfX+bKrFe+Xp5YuJo54I5HFjGDAA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.59.0.tgz", + "integrity": "sha512-peZRVEdnFWZ5Bh2KeumKG9ty7aCXzzEsHShOZEFiCQlDEepP1dpUl/SrUNXNg13UmZl+gzVDPsiCwnV1uI0RUA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.59.0.tgz", + "integrity": "sha512-gbUSW/97f7+r4gHy3Jlup8zDG190AuodsWnNiXErp9mT90iCy9NKKU0Xwx5k8VlRAIV2uU9CsMnEFg/xXaOfXg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.59.0.tgz", + "integrity": "sha512-yTRONe79E+o0FWFijasoTjtzG9EBedFXJMl888NBEDCDV9I2wGbFFfJQQe63OijbFCUZqxpHz1GzpbtSFikJ4Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.59.0.tgz", + "integrity": "sha512-sw1o3tfyk12k3OEpRddF68a1unZ5VCN7zoTNtSn2KndUE+ea3m3ROOKRCZxEpmT9nsGnogpFP9x6mnLTCaoLkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.59.0.tgz", + "integrity": "sha512-+2kLtQ4xT3AiIxkzFVFXfsmlZiG5FXYW7ZyIIvGA7Bdeuh9Z0aN4hVyXS/G1E9bTP/vqszNIN/pUKCk/BTHsKA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.59.0.tgz", + "integrity": "sha512-NDYMpsXYJJaj+I7UdwIuHHNxXZ/b/N2hR15NyH3m2qAtb/hHPA4g4SuuvrdxetTdndfj9b1WOmy73kcPRoERUg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.59.0.tgz", + "integrity": "sha512-nLckB8WOqHIf1bhymk+oHxvM9D3tyPndZH8i8+35p/1YiVoVswPid2yLzgX7ZJP0KQvnkhM4H6QZ5m0LzbyIAg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.59.0.tgz", + "integrity": "sha512-oF87Ie3uAIvORFBpwnCvUzdeYUqi2wY6jRFWJAy1qus/udHFYIkplYRW+wo+GRUP4sKzYdmE1Y3+rY5Gc4ZO+w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.59.0.tgz", + "integrity": "sha512-3AHmtQq/ppNuUspKAlvA8HtLybkDflkMuLK4DPo77DfthRb71V84/c4MlWJXixZz4uruIH4uaa07IqoAkG64fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.59.0.tgz", + "integrity": "sha512-2UdiwS/9cTAx7qIUZB/fWtToJwvt0Vbo0zmnYt7ED35KPg13Q0ym1g442THLC7VyI6JfYTP4PiSOWyoMdV2/xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.59.0.tgz", + "integrity": "sha512-M3bLRAVk6GOwFlPTIxVBSYKUaqfLrn8l0psKinkCFxl4lQvOSz8ZrKDz2gxcBwHFpci0B6rttydI4IpS4IS/jQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.59.0.tgz", + "integrity": "sha512-tt9KBJqaqp5i5HUZzoafHZX8b5Q2Fe7UjYERADll83O4fGqJ49O1FsL6LpdzVFQcpwvnyd0i+K/VSwu/o/nWlA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.59.0.tgz", + "integrity": "sha512-V5B6mG7OrGTwnxaNUzZTDTjDS7F75PO1ae6MJYdiMu60sq0CqN5CVeVsbhPxalupvTX8gXVSU9gq+Rx1/hvu6A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.59.0.tgz", + "integrity": "sha512-UKFMHPuM9R0iBegwzKF4y0C4J9u8C6MEJgFuXTBerMk7EJ92GFVFYBfOZaSGLu6COf7FxpQNqhNS4c4icUPqxA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.59.0.tgz", + "integrity": "sha512-laBkYlSS1n2L8fSo1thDNGrCTQMmxjYY5G0WFWjFFYZkKPjsMBsgJfGf4TLxXrF6RyhI60L8TMOjBMvXiTcxeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.59.0.tgz", + "integrity": "sha512-2HRCml6OztYXyJXAvdDXPKcawukWY2GpR5/nxKp4iBgiO3wcoEGkAaqctIbZcNB6KlUQBIqt8VYkNSj2397EfA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-keywords": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", + "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", + "license": "MIT", + "peerDependencies": { + "ajv": "^6.9.1" + } + }, + "node_modules/callback-registry": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/callback-registry/-/callback-registry-2.7.2.tgz", + "integrity": "sha512-VVrtF21DaH0VHeNMkLDd4VGuxsYM3V3l3lwYneKVMU/6X3TRtcQszUwlAcqj2HrLcbP1NyS12LsanUwCykaz/Q==", + "license": "ISC" + }, + "node_modules/decoder-validate": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/decoder-validate/-/decoder-validate-0.0.2.tgz", + "integrity": "sha512-9BsqAH9Zq6CvlxKHkSrZrH2iYlhuhHcrh6uTnDvcsa9P5YEweEzt1ci+X/9STgSCE7b9BA7/QIiwhfUDDWmjxw==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.8", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", + "integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rollup": { + "version": "4.59.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz", + "integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.59.0", + "@rollup/rollup-android-arm64": "4.59.0", + "@rollup/rollup-darwin-arm64": "4.59.0", + "@rollup/rollup-darwin-x64": "4.59.0", + "@rollup/rollup-freebsd-arm64": "4.59.0", + "@rollup/rollup-freebsd-x64": "4.59.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.59.0", + "@rollup/rollup-linux-arm-musleabihf": "4.59.0", + "@rollup/rollup-linux-arm64-gnu": "4.59.0", + "@rollup/rollup-linux-arm64-musl": "4.59.0", + "@rollup/rollup-linux-loong64-gnu": "4.59.0", + "@rollup/rollup-linux-loong64-musl": "4.59.0", + "@rollup/rollup-linux-ppc64-gnu": "4.59.0", + "@rollup/rollup-linux-ppc64-musl": "4.59.0", + "@rollup/rollup-linux-riscv64-gnu": "4.59.0", + "@rollup/rollup-linux-riscv64-musl": "4.59.0", + "@rollup/rollup-linux-s390x-gnu": "4.59.0", + "@rollup/rollup-linux-x64-gnu": "4.59.0", + "@rollup/rollup-linux-x64-musl": "4.59.0", + "@rollup/rollup-openbsd-x64": "4.59.0", + "@rollup/rollup-openharmony-arm64": "4.59.0", + "@rollup/rollup-win32-arm64-msvc": "4.59.0", + "@rollup/rollup-win32-ia32-msvc": "4.59.0", + "@rollup/rollup-win32-x64-gnu": "4.59.0", + "@rollup/rollup-win32-x64-msvc": "4.59.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/javascript/start/stocks/package.json b/javascript/start/stocks/package.json new file mode 100644 index 0000000..1ccc6d9 --- /dev/null +++ b/javascript/start/stocks/package.json @@ -0,0 +1,14 @@ +{ + "name": "stocks", + "version": "1.0.0", + "scripts": { + "start": "vite --port 9100" + }, + "dependencies": { + "@interopio/browser": "^4.0.0", + "@interopio/workspaces-api": "^4.0.0" + }, + "devDependencies": { + "vite": "^6.0.0" + } +} diff --git a/javascript/start/workspace/package-lock.json b/javascript/start/workspace/package-lock.json new file mode 100644 index 0000000..5e7b5c3 --- /dev/null +++ b/javascript/start/workspace/package-lock.json @@ -0,0 +1,496 @@ +{ + "name": "workspace", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "workspace", + "version": "1.0.0", + "dependencies": { + "http-server": "^0.12.3" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, + "node_modules/basic-auth": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-1.1.0.tgz", + "integrity": "sha512-CtGuTyWf3ig+sgRyC7uP6DM3N+5ur/p8L+FPfsd+BbIfIs74TFfCajZTHnCw6K5dqM0bZEbRIqRy1fAdiUJhTA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "license": "MIT", + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/corser": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", + "integrity": "sha512-utCYNzRSQIZNPIcGZdQc92UVJYAhtGAteCFg0yRaFm8f0P+CPtyGyHXJcGXnffjCybUCEx3FQ2G7U3/o9eIkVQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecstatic": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/ecstatic/-/ecstatic-3.3.2.tgz", + "integrity": "sha512-fLf9l1hnwrHI2xn9mEDT7KIi22UDqA2jaCwyCbSUJh9a1V+LEUSL/JO/6TIz/QyuBURWUHrFL5Kg2TtO1bkkog==", + "deprecated": "This package is unmaintained and deprecated. See the GH Issue 259.", + "license": "MIT", + "dependencies": { + "he": "^1.1.1", + "mime": "^1.6.0", + "minimist": "^1.1.0", + "url-join": "^2.0.5" + }, + "bin": { + "ecstatic": "lib/ecstatic.js" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "license": "MIT" + }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-server": { + "version": "0.12.3", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-0.12.3.tgz", + "integrity": "sha512-be0dKG6pni92bRjq0kvExtj/NrrAd28/8fCXkaI/4piTwQMSDSLMhWyW0NI1V+DBI3aa1HMlQu46/HjVLfmugA==", + "license": "MIT", + "dependencies": { + "basic-auth": "^1.0.3", + "colors": "^1.4.0", + "corser": "^2.0.1", + "ecstatic": "^3.3.2", + "http-proxy": "^1.18.0", + "minimist": "^1.2.5", + "opener": "^1.5.1", + "portfinder": "^1.0.25", + "secure-compare": "3.0.1", + "union": "~0.5.0" + }, + "bin": { + "hs": "bin/http-server", + "http-server": "bin/http-server" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/opener": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", + "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", + "license": "(WTFPL OR MIT)", + "bin": { + "opener": "bin/opener-bin.js" + } + }, + "node_modules/portfinder": { + "version": "1.0.38", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.38.tgz", + "integrity": "sha512-rEwq/ZHlJIKw++XtLAO8PPuOQA/zaPJOZJ37BVuN97nLpMJeuDVLVGRwbFoBgLudgdTMP2hdRJP++H+8QOA3vg==", + "license": "MIT", + "dependencies": { + "async": "^3.2.6", + "debug": "^4.3.6" + }, + "engines": { + "node": ">= 10.12" + } + }, + "node_modules/qs": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz", + "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "license": "MIT" + }, + "node_modules/secure-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/secure-compare/-/secure-compare-3.0.1.tgz", + "integrity": "sha512-AckIIV90rPDcBcglUwXPF3kg0P0qmPsPXAj6BBEENQE1p5yA1xfmDJzfi1Tappj37Pv2mVbKpL3Z1T+Nn7k1Qw==", + "license": "MIT" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/union": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/union/-/union-0.5.0.tgz", + "integrity": "sha512-N6uOhuW6zO95P3Mel2I2zMsbsanvvtgn6jVqJv4vbVcz/JN0OkL9suomjQGmWtxJQXOCqUJvquc1sMeNz/IwlA==", + "dependencies": { + "qs": "^6.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/url-join": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-2.0.5.tgz", + "integrity": "sha512-c2H1fIgpUdwFRIru9HFno5DT73Ok8hg5oOb5AT3ayIgvCRfxgs2jyt5Slw8kEB7j3QUr6yJmMPDT/odjk7jXow==", + "license": "MIT" + } + } +} diff --git a/javascript/start/workspace/package.json b/javascript/start/workspace/package.json new file mode 100644 index 0000000..aab41ea --- /dev/null +++ b/javascript/start/workspace/package.json @@ -0,0 +1,10 @@ +{ + "name": "workspace", + "version": "1.0.0", + "scripts": { + "start": "http-server . -p 9300 -c-1" + }, + "dependencies": { + "http-server": "^0.12.3" + } +}